Location: PHPKode > projects > Lame Node System > lns-0.6-11/index.php
<?php

/************************************************************************
 *																		*
 * Copyright (C) 2001 Stuart Reeves										*
 *																		*
 * 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.							*
 * 																		*
 * The GNU General Public License is available from:					*
 * http://www.gnu.org/copyleft/gpl.html									*
 *																		*
 ************************************************************************/

/* Stuart's lns (lame node system)
 *
 *
 * General
 * -------
 *
 * HTTP GET variables passed to this script (index.php):
 *		node						- The requested nodename
 *		lastnodes					- Number of recent nodes to display on the front page
 * 		ts
 *		_search
 *		_username
 *		_metatype
 *		
 *
 * Syntax:
 *		node=<nodename>[&lastnodes=<number>][&_username=<username>]
 *			 LIST_NODE[&listmode=<display option>,<...>,...][$_username=<username>]
 *			 FINGER_NODE[&_username=<username>]
 *			 SUBMIT_NODE[&_nodename=<nodename>][&ts=<timestamp>]
 *		
 *
 *
 * Form Data (all vars have underscores before them)
 * ---------
 *
 * Create node form data:
 *		Actions:   		_submitnode, _deletenode, _previewnode
 * 		Variables: 		_nodename, _link, _author, _contact, _text, 
 *				   		_protected, _metatype, _silentupdate
 *
 * Search form data:
 *		_search, _searchrange, _searchtype
 *
 * Preferences form data:
 *		Actions: 		_savesiteprefs, _savepersonalprefs
 *		Variables: 		_relatednodes, _homenodes, _recentnodes, 
 *						_nodesinsubmit, _theme, _lastnodes,
 *						_currpassword, _newpassord, _email
 *						_website, _profile
 *
 * Login/out form data:
 *		Actions:		_login / _logout
 *		Variables:		_username, _password
 *
 * New user form data:
 *		Actions:		_newuser
 *		Variables:		_username
 *
 *
 * Database Information (see header.php.inc)
 * --------------------
 *
 * NODE_TABLE db table format:
 * 		nodename 	VARCHAR(200)	(non-unique)
 * 		link 		VARCHAR(255)
 *		ts  		TIMESTAMP		(NULL)
 * 		author  	VARCHAR(20)
 * 		contact 	VARCHAR(80)
 *		text 		MEDIUMTEXT
 *		protected 	CHAR			(true when set to "t")
 *		hidden		CHAR			(true when set to "t")
 *		username	VARCHAR(50)		(unique)
 *		rawtype		VARCHAR(10)
 *		metatype	VARCHAR(10)
 *
 * AUTHINFO_TABLE db table format
 *		ts			TIMESTAMP		(NULL)
 *		created		TIMESTAMP
 *		username 	VARCHAR(50) 	(unique)
 *		password 	VARCHAR(50)
 *		email		VARCHAR(100)
 *		website 	VARCHAR(150)
 *		profile 	TEXT
 *		superuser	CHAR			(true when set to "t")
 *		loginstate	CHAR			(true when set to "t")
 *
 *
 * Notes
 * -----
 * Session data uses a variable called "sessionUsername" to store the current user's identity.
 * This script sets a cookie "lns_prefs" that expires on my birthday in about 10 years :)
 *
 * There are two session variables registered:
 *		sessionUsername		- The username of the currently logged in user
 *		homeNode			- The home node of the logged in user (if any)
 */



/************************************************
 * Set/retrieve preferences cookie				*
 ************************************************/

$expire = mktime(0, 0, 0, 6, 9, 2012);
 
// The variables that will be referenced later on in the script. Note that these are the
// default values, therefore.
$currTheme 		   = "";
$showRelatedNodes  = false;
$showHomeNodes	   = false;
$showRecentNodes   = false;
$showNodesInSubmit = false;

// Record the cookie if the site prefs have been submitted
if ($_POST["_savesiteprefs"]) {

	$cleanThemeStr    = "";
	$relatedNodesStr  = "0";
	$homeNodesStr	  = "0";
	$recentNodesStr	  = "0";
	$nodesInSubmitStr = "0";
	$lastNodesStr	  = "";

	// Clean up the theme variable
	if (isset($_POST["_theme"])) {
		$cleanThemeStr = strrchr($_POST["_theme"], "/");
		if ($cleanThemeStr)
			$cleanThemeStr = substr($cleanThemeStr, 1);
		else
			$cleanThemeStr = $_POST["_theme"];
		
		$currTheme = $cleanThemeStr;
	}
	
	// Get the checkbox options
	if (isset($_POST["_relatednodes"])) {
		$relatedNodesStr  = "1";
		$showRelatedNodes = true;
	}
	if (isset($_POST["_homenodes"])) {
		$homeNodesStr  = "1";
		$showHomeNodes = true;
	}
	if (isset($_POST["_recentnodes"])) {
		$recentNodesStr  = "1";
		$showRecentNodes = true;
	}
	if (isset($_POST["_nodesinsubmit"])) {
		$nodesInSubmitStr  = "1";
		$showNodesInSubmit = true;
	}

	// Set the number of nodes to be displayed on the front page if the number is not passed
	// in the URL
	if (isset($_POST["_lastnodes"]) && is_numeric($_POST["_lastnodes"])) {
		if ($_POST["_lastnodes"] > 0 && $_POST["_lastnodes"] < 100) {
			$lastNodesStr = $_POST["_lastnodes"];
			$lastNodes    = $_POST["_lastnodes"];
		}
	}

	// Construct the cookie. Note that order is important when retrieving the tokenised
	// results.
	$prefsStr = "$cleanThemeStr $relatedNodesStr " . 
				"$homeNodesStr $recentNodesStr " . 
				"$nodesInSubmitStr $lastNodesStr";
				
	setcookie("lns_prefs", $prefsStr, $expire);
	
} else { 
	
	// Load the preferences from the cookie
	$currTheme = strtok($_COOKIE["lns_prefs"], " ");

	// Get the checkbox values (NOTE: order is important)
	if (strtok(" ") == "1")
		$showRelatedNodes = true;
	if (strtok(" ") == "1")
		$showHomeNodes = true;
	if (strtok(" ") == "1")
		$showRecentNodes = true;
	if (strtok(" ") == "1")
		$showNodesInSubmit = true;

	$savedLastNodes = strtok(" ");

	// Check for GET variable
	if (!isset($_GET["lastnodes"]))
		$lastNodes = $savedLastNodes;
	else if (is_numeric($_GET["lastnodes"]) && $_GET["lastnodes"] > 0 && $_GET["lastnodes"] < 100)
		$lastNodes = $_GET["lastnodes"];
}


// Start session for authentication
session_name("lns_auth");
session_start();


/************************************************
 * Constants and includes						*
 ************************************************/
 
require_once("include/header.php.inc");
require_once("include/Util.php");
require_once("include/NodeInterface.php");
require_once("include/UserInput.php");
require_once("include/Auth.php");
require_once("include/HTMLFactory.php");

if (REPORT_GEN_TIME)
	$start_time = Util::getMicroSeconds();


/************************************************
 * Variables passed to this script				*
 ***********************************************/

// Handle "./index.php?<nodename>" type requests and POSTed node requests
if (!isset($_GET["node"])) {
	if (isset($argv[0]))
		$_GET["node"] = $argv[0];
	else if (isset($_POST["node"]))
		$_GET["node"] = $_POST["node"];
}


// Make the nodename ``safe''
if ($_GET["node"] != "")
	$_GET["node"] = htmlentities($_GET["node"], ENT_QUOTES);

// Preferences defaults
if ($currTheme == "")
	$currTheme = DEFAULT_THEME;

if ($lastNodes == 0)
	$lastNodes = LAST_NODES_CREATED;



// This array holds the posted node listing options
$displayListMode = array(SHOW_EXTERNAL_LINKS => false,
					 	 SHOW_DISTINCT_NODES => false,
					 	 SHOW_LATEST_NODES	 => false,
						 SHOW_NODES_BY_TS	 => false,
						 SHOW_METATYPE		 => null);

// Sort out the listmode variable and parse for associated meanings
if (isset($_GET["listmode"])) {
	
	global $NODE_METATYPES;
	$token = strtok($_GET["listmode"], ",");
	
	while ($token) {
		// Process each token and set flags in the array accordingly
		switch ($token) {
			case SHOW_EXTERNAL_LINKS: $displayListMode[SHOW_EXTERNAL_LINKS] = true;
				break;
			case SHOW_DISTINCT_NODES: $displayListMode[SHOW_DISTINCT_NODES] = true;
				break;
			case SHOW_LATEST_NODES:	  $displayListMode[SHOW_LATEST_NODES]   = true;
				break;
			case SHOW_NODES_BY_TS:	  $displayListMode[SHOW_NODES_BY_TS]	= true;
				break;
			default:
				// Search for a meta-type to display (if any)
				foreach ($NODE_METATYPES as $metaType) {
					if ($token == $metaType)
						$displayListMode[SHOW_METATYPE] = $metaType;
				}
				break;
		}
		
		$token = strtok(",");
	}
}


/****************************************************
 * Main page generation 							*
 ****************************************************/


// Create Auth object for the currently logged in user
$auth = null;
if (isset($_SESSION["sessionUsername"])) {
	$auth = new Auth(HOSTNAME, USERNAME, PASSWORD, DB_NAME, AUTHINFO_TABLE);
	$auth->setUsername($_SESSION["sessionUsername"]);
} 


// Select the HTML theme to be used
$HTMLFactory = new HTMLFactory($currTheme, $_GET["node"]);
$HTMLFactory->setUsername($_SESSION["sessionUsername"]);


// Set the user's home node if it exists

if (isset($_SESSION["sessionUsername"])) {
	
	if (isset($_SESSION["homeNode"])) {
		// Update the HTMLFactory variables
		$HTMLFactory->setHomeNode($_SESSION["homeNode"]);
		if ($_GET["node"] == "") {
			$_GET["node"] = $_SESSION["homeNode"];
			$HTMLFactory->setNodename($_GET["node"]);
		}
	}
	
}

// If "node" is still empty (due to no user logged in, or no home node for a logged in user),
// revert to HOME_NODE
if ($_GET["node"] == "") {
	$_GET["node"] = HOME_NODE;
	$HTMLFactory->setNodename($_GET["node"]);
}


$bodyHTML = ""; // To store the HTML between the <body> tags


/* Node query structure. The switch looks for the following predefined nodes:
 *
 *		SUBMIT_NODE 		- Node submit form
 *		SEARCH_NODE 		- Search for words in node titles and text bodies
 *		SHOW_ALL_NODE		- Displays all the nodes in the database
 *		SHOW_LATEST_NODE	- Displays the last nodes newer than SHOW_LATEST_NODE_MAXAGE
 *		HELP_NODE
 *		PREFERENCES_NODE	- Allows the user to choose sitewide/personal preferences
 *		NEW_USER_NODE		- 
 *		LOGIN_NODE
 *		LOGOUT_NODE
 *		FINGER_NODE			- Display a user's information
 *
 *		default 			- Displays the requested nodename (can be default/user home)
 *
 * We generate the node's body so that the HTMLFactory object can be informed of any last-minute
 * data before the HTML is actually sent to the browser. */

switch ($_GET["node"]) {


	// Submit or preview node 
	case SUBMIT_NODE:
	
		// Bit of fiddling to get the HTTP GET vars detected if a user is adding to or editing 
		// a node
		if (isset($_GET["_nodename"]))
			$_POST["_nodename"] = $_GET["_nodename"];
		if (isset($_GET["_metatype"]))
			$_POST["_metatype"] = $_GET["_metatype"];
		
		$userInput = new UserInput($_POST["_nodename"], 
								   $_POST["_author"], 
								   $_POST["_contact"], 
								   $_POST["_link"], 
								   $_POST["_text"], 
								   $_POST["_protected"], 
								   $_POST["_metatype"],
								   $_POST["_silentupdate"]);

		$userInput->setUsername($_SESSION["sessionUsername"]);
		
		// If the user is logged in then their details are automatically ``filled in''. They may
		// also perform edits to existing nodes.
		if (isset($_SESSION["sessionUsername"])) {
			
			$nodeInterface = new NodeInterface(HOSTNAME, 
											   USERNAME, 
											   PASSWORD, 
											   DB_NAME, 
											   NODE_TABLE);

			// Find out if the current user is a superuser or not and then inform the HTML forms
			// and user input handler accordingly
			if ($auth->isSuperuser() == 1) {
				$userInput->setSuperuser(true);
				$HTMLFactory->setSuperuser(true);
				$nodeInterface->setSuperuser(true);
			}


			// Set the timestamp (for new nodes, $ts will not be set). A set timestamp will imply
			// that this node is currently being edited.
			$userInput->setTimestamp($_GET["ts"]);

			// If this is the first edit session (i.e. user has just clicked on ``edit this node'')
			// then we need to retrieve the node textbody from the database and reverse parse it.
			if (!isset($_POST["_text"]) && !isset($_POST["_link"])) {
				
				$nodeInterface->setUsername($_SESSION["sessionUsername"]);
				
				// Get the current field values for this node (e.g. the node text)
				if (isset($_GET["ts"])) {
					// Retrieve the data for the node we want to edit
					$nodeInterface->editNode($_GET["ts"]);
					$userInput->setText($nodeInterface->getUnparsedText());
					$userInput->setLink($nodeInterface->getLink());
					$userInput->setMetatype($nodeInterface->getMetatype());
					$HTMLFactory->setSilentUpdate(false);
					// If this is not a superuser, then the following will have no effect
					$HTMLFactory->setProtected($nodeInterface->isProtected());
				}
				
			} else {
				// Carry through values for edits
				$HTMLFactory->setProtected($_POST["_protected"]); // Note: Check security here
				if (isset($_GET["ts"]))
					$HTMLFactory->setSilentUpdate($_POST["_silentupdate"]);
			}
		}
		
		if ($_POST["_deletenode"]) {
			switch ($userInput->deleteNode(HOSTNAME, 
										   USERNAME, 
										   PASSWORD, 
										   DB_NAME, 
										   NODE_TABLE)) {
											   
				case 1:
					$HTMLFactory->setNodeContent("Successfully nuked node.");
					break;
				case 0:
					$HTMLFactory->setNodeContent("This node is not yours. Leave it alone.");
					break;
				case -1:
					$HTMLFactory->setNodeContent("You can't kill a node that doesn't exist!");
					break;
			}

		} else if ($userInput->check()) {
			
						
			// Display the preview or submit the node
			if ($_POST["_previewnode"]) {
	
				$html = "";
				
				if ($userInput->getLink() != "")
					$html .= "<span class=\"warning\">This node links externally to the URL: " . 
							 $userInput->getLink() . "</span><br />";
				
				$html .= $userInput->getParsedText() . "<br /><br /><small>[" . 
						 $userInput->getMetatype() . " node created by ";
			
				if ($userInput->contactExists())
					$html .= "<a href=\"" . $userInput->getContact() . "\">" . 
							 $userInput->getAuthor() . "</a>";
				else
					$html .= $userInput->getAuthor();
			
				$html .= " on (no date)]</small>";

				$HTMLFactory->appendNodeContent(
								$HTMLFactory->createNodeMiniView($html,
																 $userInput->getNodename(), 
												 				 0,
												 				 $userInput->getMetatype()));
				$HTMLFactory->appendNodeContent("<br /><br />"); 

		
			} else if ($_POST["_submitnode"]) {
				switch($userInput->createNode(HOSTNAME, USERNAME, PASSWORD, DB_NAME, NODE_TABLE)) {
					case 1:
						$HTMLFactory->setNodeContent("Your node <a href=\"?node=" . 
													 $userInput->getNodename() . 
									 				 "\">" . $userInput->getNodename() . 
							 		 				 "</a> was submitted! Now go tell the world.");
						break;
					case 0:
						$HTMLFactory->setNodeContent("You do not own this node.");
						break;
					case -1:
						if ($userInput->getMetatype() == METATYPE_HOME) {
							$HTMLFactory->setNodeContent("You are not allowed to create more " . 
														 "than one home node. Stop being greedy.");
						} else {
							$HTMLFactory->setNodeContent("This node is <a href=\"?node=" . 
														 HELP_NODE . "#protectednodes\">" . 
														 "protected</a>. Hit \"back\" on " . 
										 				 "your browser, or <a href=\"?node=" . 
										 				 SUBMIT_NODE . "\">create</a> a " . 
														 "differently named one!");
						}
						break;
				}
			}
			
			
		} else
			$HTMLFactory->appendNodeContent("<span class=\"warning\">You must enter a nodename " . 
											"and text into the main textbox or the external " .
											"link box.</span>");
	
		if (!$_POST["_submitnode"] && !$_POST["_deletenode"]) {
			
			// Carry over the timestamp if we are in edit
			$tsText = "";
			if (isset($_GET["ts"]))
				$tsText = "&ts=" . $_GET["ts"];
			
			$HTMLFactory->createSubmitForm("?node=" . SUBMIT_NODE . $tsText, 
										   $userInput->getNodename(),
										   $userInput->getAuthor(), 
										   $userInput->getContact(), 
										   $userInput->getLink(), 
										   $userInput->getText(),
										   $userInput->getMetatype());
		}
	
		if ($showNodesInSubmit && !$_POST["_submitnode"] && !$_POST["_deletenode"]) {
		
			$nodeInterface = new NodeInterface(HOSTNAME, USERNAME, PASSWORD, DB_NAME, NODE_TABLE);
			//$nodeInterface->setShowNodenameHeader(true);
			$html = $nodeInterface->getNode(htmlentities($_POST["_nodename"], ENT_QUOTES), 
											&$HTMLFactory);
			
			if (!$html)
				$html .= "There are no other entries for this node.<br/><br/>\n";
		
			$html = "<dl><dt><div class=\"subtitle\">Existing Node Entries</div>" . 
					"<br /></dt><dd>$html</dd></dl>";

			$HTMLFactory->appendNodeContent($HTMLFactory->createNodeMiniView($html));
		}
	
		break;
		

	case WHO_NODE:
		if ($auth == null)
			$auth = new Auth(HOSTNAME, USERNAME, PASSWORD, DB_NAME, AUTHINFO_TABLE);
			
		if ($userList = $auth->getUserList(false)) {
			/*$userScopeText = "";
			if (false)
				$userScopeText = "currently logged in users";
			else
				$userScopeText = "all users";
				
			//echo "<div class=\"subtitle\">Who query for <em>$userScopeText</em></div>" . 
			//			 "<br />";*/

			$HTMLFactory->createWhoPage($userList);
			
		} else {
			$HTMLFactory->setNodeContent("No users");
		}
		
		break;
		
	
	// Search for a node, phrase etc.
	case SEARCH_NODE:

		// A HTTP GET value for _search overrides a POSTed search
		if (isset($_GET["_search"]))
			$_POST["_search"] = $_GET["_search"];

		if ($_POST["_search"] != "") {

			$nodeInterface = new NodeInterface(HOSTNAME, USERNAME, PASSWORD, DB_NAME, NODE_TABLE);
			$nodeInterface->setShowNodenameHeader(true);
			$nodeInterface->setTruncateNodes(true);
			
			$html = $nodeInterface->search($_POST["_search"], &$HTMLFactory);
			if ($html)
				$HTMLFactory->setNodeContent($html);
			else 
				$HTMLFactory->setNodeContent("I could not find the node you want. " .
					  		 				 "<a href=\"?node=" . SEARCH_NODE . 
											 "\">Try again</a>.");
		} else			
			$HTMLFactory->createSearchForm("$PHP_SELF?node=".SEARCH_NODE);
	
		break;

	
	case LIST_NODE:
	
		$nodeInterface = new NodeInterface(HOSTNAME, USERNAME, PASSWORD, DB_NAME, NODE_TABLE);
		$nodeInterface->setUsername($_SESSION["sessionUsername"]);
		$nodeInterface->setShowExtLinks($displayListMode[SHOW_EXTERNAL_LINKS]);
		$nodeInterface->setShowDistinct($displayListMode[SHOW_DISTINCT_NODES]);
		$nodeInterface->setShowByTS($displayListMode[SHOW_NODES_BY_TS]);
		$nodeInterface->setShowHomeNodes(true);
	
		$age = 0;
		if ($displayListMode[SHOW_LATEST_NODES])
			$age = SHOW_LATEST_NODES_MAXAGE;
		
		// Display some info about the requested list options
		if ($displayListMode[SHOW_METATYPE] != "") {
			$HTMLFactory->appendNodeContent("Displaying <em>" . $displayListMode[SHOW_METATYPE] . 
											"</em> nodes");
			if (isset($_GET["_username"]))
				$HTMLFactory->appendNodeContent(" created by user <em>" . $_GET["_username"] . 
												"</em>");
			
			$HTMLFactory->appendNodeContent(":<br /><br />");
		}
		
		$usernameStr = "";
		
		if (isset($_GET["_username"]))
			$usernameStr = "&_username=" . $_GET["_username"];
		
		$metatypeStr1 = "";
		$metatypeStr2 = "";
		
		if (isset($displayListMode[SHOW_METATYPE])) {
			$metatypeStr1 = "&listmode=" . $displayListMode[SHOW_METATYPE];
			$metatypeStr2 = "," . $displayListMode[SHOW_METATYPE];
		}
		
		
		$HTMLFactory->appendNodeContent(
						$nodeInterface->getNodeList($age, 
													0, 
													$_GET["_username"], 
									    			$displayListMode[SHOW_METATYPE]));
		
		if ($displayListMode[SHOW_EXTERNAL_LINKS]) {
			
			// Alter the $listmode POSTed variable by removing the ``extlinks'' option. Note
			// that this will carry forward to the distinct listing options as well.
			$listOpts = preg_replace("/" . SHOW_EXTERNAL_LINKS . ",?/", "", $_GET["listmode"]);
			if ($metatypeStr1 == "")
				$listOpts = "&listmode=$listOpts";
	
			$HTMLFactory->appendNodeContent("<br/><br/><a href=\"?node=" . $_GET["node"] .
						 					$metatypeStr1 . $listOpts . $usernameStr . 
						 					"\">show normal nodes</a>");
						 
		} else {
			$HTMLFactory->appendNodeContent("<br/><br/><a href=\"?node=" . $_GET["node"] . 
											$usernameStr . "&listmode=" . SHOW_EXTERNAL_LINKS . 
											"," . $_GET["listmode"] . $metatypeStr2 . 
											"\">show external links</a>");
		}
	
	
		if ($displayListMode[SHOW_DISTINCT_NODES]) { 
		
			$listOpts = preg_replace("/" . SHOW_DISTINCT_NODES . ",?/", "", $_GET["listmode"]);
			if ($metatypeStr1 == "")
				$listOpts = "&listmode=$listOpts";

			$HTMLFactory->appendNodeContent("<br/><br/><a href=\"?node=" . $_GET["node"] . 
											$metatypeStr1 . $listOpts . $usernameStr . 
						 					"\">show duplicates</a>");
		} else {
			$HTMLFactory->appendNodeContent("<br/><br/><a href=\"?node=" . $_GET["node"] . 
											$usernameStr . "&listmode=" . SHOW_DISTINCT_NODES . 
											"," . $_GET["listmode"] . $metatypeStr2 . 
											"\">show distinct nodes</a>");
		}
	
		if ($displayListMode[SHOW_LATEST_NODES]) {
			$HTMLFactory->appendNodeContent("<br/><div class=\"small\" align=\"center\">nodes " . 
											"less than <i>$age</i> days old</div>");
		}

		break;
	
	
	case HELP_NODE:
		$HTMLFactory->createHelpPage();
		break;


	case PREFERENCES_NODE:

		// Display the basic preferences form (cookie-based)
		
		$HTMLFactory->createSitePrefsForm("$PHP_SELF?node=" . PREFERENCES_NODE, 
										  $currTheme, 
										  $showRelatedNodes,
										  $showHomeNodes,
										  $showRecentNodes,
										  $showNodesInSubmit,
										  $lastNodes);
		
		// Display the user-specific preferences
		if (isset($_SESSION["sessionUsername"])) {
			
			$updated = false;
			
			if (isset($_POST["_savepersonalprefs"])) {
				
				$auth->setUserData(UserInput::getCleanContact($_POST["_email"]), 
								   UserInput::getCleanLink($_POST["_website"]), 
								   UserInput::getParsedText($_POST["_profile"]));
				$updated = true;
				
				// Test that the user has actually typed something for the passwords and update
				// if necessary.
				if (strlen($_POST["_currpassword"]) > 0 && strlen($_POST["_newpassword"]) > 0) {
				
					switch ($auth->updatePassword($_POST["_currpassword"], 
												  $_POST["_newpassword"])) {
												  
						case -1;
							$HTMLFactory->appendNodeContent("<div align=\"center\" " . 
														 	"class=\"warning\">Incorrect " .
										 				 	"length for new password</div>");
							$updated = false;
							break;
							
						case 0:
							$HTMLFactory->appendNodeContent("<div align=\"center\" " . 
														 	"class=\"warning\">Incorrect " .
										 				 	"current password.</div>");
							$updated = false;
							break;
							
						default:
							break;
					}
				
				}
				
			}
			
			
			$userData = $auth->getUserData();
			
			$HTMLFactory->createUserPrefsForm("$PHP_SELF?node=" . PREFERENCES_NODE,
														   $userData["email"],
														   $userData["website"], 
														   $userData["profile"]);
			if ($updated)
				$HTMLFactory->appendNodeContent("<div align=\"center\"><strong>Preferences " . 
											 	"updated</strong></div>");
		}
		
		break;

	
	case NEW_USER_NODE:

		if (ENABLE_AUTHENTICATION) {
			if ($_POST["_newuser"]) {
				$auth 			= new Auth(HOSTNAME, USERNAME, PASSWORD, DB_NAME, AUTHINFO_TABLE);
				$newUserAttempt = $auth->createUser($_POST["_username"], false);
				
				if (is_string($newUserAttempt)) {
					$HTMLFactory->setNodeContent("Your password is: <em>$newUserAttempt</em>" . 
												 "<br /><br />You must <a href=\"?node=" . 
												 LOGIN_NODE . "\">login</a> before changing " .
												 "your password (in the <a href=\"?node=" . 
								 				 PREFERENCES_NODE . "\">preferences</a> page).");
				} else {
				
					switch ($newUserAttempt) {
						case 0:
							$HTMLFactory->setNodeContent("Cannot register this username. Try " . 
														 "a <a href=\"?node=" . NEW_USER_NODE . 
														 "\">different username</a>.");
							break;
						case -1:
							$HTMLFactory->setNodeContent("Too many results; database may be " .
														 "corrupt.");
							break;
						default:
							break;
					}
				}
			
			} else {
				$HTMLFactory->createNewUserForm("$PHP_SELF?node=" . NEW_USER_NODE);
			}
		}

		break;


	// Displays the login form
	case LOGIN_NODE:
	
		if (ENABLE_AUTHENTICATION) {
		
			if (isset($_POST["_login"])) {
								
				$auth = new Auth(HOSTNAME, USERNAME, PASSWORD, DB_NAME, AUTHINFO_TABLE);
				$auth->setUsername($_POST["_username"]);

				// Attempt the login and report any errors
				$loginAttempt = $auth->authUser($_POST["_password"], true);
				switch ($loginAttempt) {
				
					case -1: 
						$HTMLFactory->setNodeContent("Too many results; database may be corrupt.");
						break;
				
					case 0: 
						$HTMLFactory->setNodeContent("Username and/or password invalid. Please ".
							 		 				 "<a href=\"?node=" . LOGIN_NODE . 
													 "\">try again</a>.");
						break;	
				
					default:
						$_SESSION["sessionUsername"] = $_POST["_username"];

						$nodeInterface = new NodeInterface(HOSTNAME, 
														   USERNAME, 
														   PASSWORD, 
														   DB_NAME, 
														   NODE_TABLE);
														   
						$nodeInterface->setUsername($_POST["_username"]);
						$userHomeNode = $nodeInterface->getHomeNode();
	
						$homePageText = "";
						
						if (is_string($userHomeNode)) {
							$_SESSION["homeNode"] = $userHomeNode;
							$homePageText = " Go to your <a href=\"?node=$userHomeNode\">" . 
											"home page</a>.";
						} else {
							$homePageTest = " Create your <a href=\"?node=" . SUBMIT_NODE . 
											"&_metatype=" . METATYPE_HOME . "\">home page</a>";
						}

						session_write_close();
						
						$HTMLFactory->setUsername($_POST["_username"]);
						$HTMLFactory->setNodeContent("Welcome <em>" . $_POST["_username"] . 
													 "</em>, you have " . 
													 "logged in successfully.$homePageText<br/>" .
													 "<br/>Last login time: " . 
							 		 				 Util::fmtTimestamp($loginAttempt));
						break;
				}
				
							
			} else {

				if (!isset($_SESSION["sessionUsername"]))
					$HTMLFactory->createLoginForm("$PHP_SELF?node=" . LOGIN_NODE);
				else
					$HTMLFactory->setNodeContent("You are already logged in.");
			}
		} else
			$HTMLFactory->setNodeContent("User authentication has been disabled.");
		
		break;


	case LOGOUT_NODE:

		if (ENABLE_AUTHENTICATION) {
		
			if (isset($_POST["_logout"])) {
				
				if (isset($_SESSION["sessionUsername"]) || isset($_SESSION["homeNode"])) {
				
					unset($_SESSION["sessionUsername"]);
					unset($_SESSION["homeNode"]);
					if (session_destroy()) {
						session_write_close();
						$HTMLFactory->setUsername(null);
						$HTMLFactory->setNodeContent("You have successfully logged out.");
					} else
						$HTMLFactory->setNodeContent("Failed to close session.");
						
				} else {
					$HTMLFactory->setNodeContent("You are not <a href=\"?node=" .
												 LOGIN_NODE . "\">logged in</a>.");
				}
			} else 
				$HTMLFactory->createLogoutForm("$PHP_SELF?node=" . LOGOUT_NODE);
		
		} else
			$HTMLFactory->setNodeContent("User authentication has been disabled.");
	
		break;


	case FINGER_NODE:
		$auth = new Auth(HOSTNAME, USERNAME, PASSWORD, DB_NAME, AUTHINFO_TABLE);
		if ($userData = $auth->getUserData($_GET["_username"]))
			$HTMLFactory->createFingerPage($userData);
		else
			$HTMLFactory->setNodeContent("No such user <em>" . $_GET["_username"] . "</em>");
		break;



	// Display the requested default home node, user home node or the requested node
	default:
	
		$nodeInterface = new NodeInterface(HOSTNAME, USERNAME, PASSWORD, DB_NAME, NODE_TABLE);
		$nodeInterface->setUsername($_SESSION["sessionUsername"]);	
		$auth = new Auth(HOSTNAME, USERNAME, PASSWORD, DB_NAME, AUTHINFO_TABLE);
		$auth->setUsername($_SESSION["sessionUsername"]);
		if ($auth->isSuperuser() == 1)
			$nodeInterface->setSuperuser(true);

		/* Based on the previous resolution of the nodename, we will display home node options
		 * for the default home node or the user's home node. Otherwise we get the node as 
		 * usual. */
		 
		if ($_GET["node"] == HOME_NODE || 
			(isset($_SESSION["homeNode"]) && 
			 $_SESSION["homeNode"] == stripslashes($_GET["node"]))) {
			 
			$HTMLFactory->setNodeContent($nodeInterface->getNode($_GET["node"], &$HTMLFactory));
			$HTMLFactory->setNodename($nodeInterface->getNodename());
			
			$nodeInterface->setShowDistinct(true);
			$nodeInterface->setShowHomeNodes(true);
	
			$bodyHTML = "";
	
			if ($showHomeNodes) {
				$bodyHTML .= "<hr width=\"50%\" /><div class=\"subtitle\">Home Nodes</div>" . 
							 "<table  width=\"90%\" align=\"center\" cellspacing=\"0\" " .
							 "cellpadding=\"0\" border=\"0\"><tr><td width=\"10\">&nbsp;</td><td>";

				$bodyHTML .= $nodeInterface->getNodeList(0, 0, null, METATYPE_HOME);

				$bodyHTML .= "</td></tr></table>";
				
			}
	
			if ($showRecentNodes) {
				$nodeInterface->setShowHomeNodes(false);
				$bodyHTML .= "<hr width=\"50%\" />" . 
					 		 "<div class=\"subtitle\">Recent Nodes (last $lastNodes)</div>" . 
					 		 "<table  width=\"90%\" align=\"center\" cellspacing=\"0\" " .
							 "cellpadding=\"0\" border=\"0\"><tr><td width=\"10\">&nbsp;</td><td>";
		
				$bodyHTML .= $nodeInterface->getNodeList(0, $lastNodes, null, null);
				$moreNodes = $lastNodes + 5;
				$bodyHTML .= "</td></tr></table><a href=\"?node=" . HOME_NODE . "&lastnodes=" . 
							 $moreNodes . "\">show more</a>";
			}
			$HTMLFactory->appendNodeContent($bodyHTML);
			$HTMLFactory->setTypes($nodeInterface->getRawtype(), $nodeInterface->getMetatype());

		} else {

			// Display this node as normal
			$nodeInterface->setShowRelatedNodes($showRelatedNodes);
			$html = $nodeInterface->getNode($_GET["node"], &$HTMLFactory);
			$HTMLFactory->setNodeContent($html);
			$HTMLFactory->setNodename($nodeInterface->getNodename());
			$HTMLFactory->setFirstEditor($nodeInterface->getFirstEditor());
			$HTMLFactory->setTypes($nodeInterface->getRawtype(), $nodeInterface->getMetatype());
			$external = $nodeInterface->isExternal();
				
		}

}



// Redirect if necessary, otherwise output the HTML stream
if($external) {
	echo "<script language=\"JavaScript\">window.location = \"$external\"</script>";
} else {
	echo $HTMLFactory->createHeader();
	echo $HTMLFactory->createNodeContent();
	echo $HTMLFactory->createFooter();

	// Display the time it took to make the page
	if (REPORT_GEN_TIME) {
		$gen_time = round(Util::getMicroSeconds() - $start_time, 3);
		echo "<small>page generation time: $gen_time seconds</small>";
	}
}

?>
Return current item: Lame Node System