Location: PHPKode > projects > Community Learning Network > cln/index.php
<?php
/*
 * PageLoader for CLN
 *
 * Copyright (c) 2003-4 St. Christopher House
 *
 * Developed by The Working Group Inc.
 *
 * 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.
 *
 * @version $Id: index.php,v 1.76 2005/01/25 02:03:19 darcy Exp $
 *
 */

// ****************************************************************************
// The CLN_FILE_BASE is usually ./ unless it is a PAGETYPE=Admin
if (!defined('CLN_FILE_BASE')) {
	define('CLN_FILE_BASE', './');
}

// ****************************************************************************
// Set up the PHP environment

// Set the include path
if (!setIncludePath()) {
	print 'The include path couldn\'t be set';
	exit;
}

// Turn session auto start off, so that we have time to load the libraries
ini_set('session.auto_start','Off');

// Fix missing _SERVER vars on windows
if(!isset($_SERVER['REQUEST_URI'])) {
   $_SERVER['REQUEST_URI'] = $_SERVER['PHP_SELF'] .'?'. $_SERVER['QUERY_STRING'];
}


// ****************************************************************************
// Load the site configuration, this includes loading the local one first if it's there
if(file_exists(CLN_FILE_BASE . 'config/CLN/config-local.php')) {
	require_once('config/CLN/config-local.php');
}
require_once('config/CLN/config.php');


// ****************************************************************************
// This is used to catch bad url requests.  they need to end with a / or a filename
// do it here before all the libraries, so it does load too much before refreshing
if(isset($_GET['p']) && substr($_GET['p'],-4) != '.php' && substr($_GET['p'],-1) != '/') {
	Header('Location: ' . cleanURL($_GET['p'].'/'));
	exit;
}

// ****************************************************************************
// Set up PHP's error handling
register_shutdown_function('clnErrorShutdown');
error_reporting(CLN_ERROR_REPORTING_LEVEL);
require_once('PEAR.php');
require_once('Cln_Error_Handler.php');
set_error_handler('clnErrorHandler');
PEAR::setErrorHandling(PEAR_ERROR_CALLBACK, 'clnErrorHandler');


// ****************************************************************************
// Load all libraries
// Base PEAR classes
require_once('Log.php');
require_once('DB.php');
require_once('File.php');
require_once('Benchmark/Timer.php');

// CLN Custom classes and functions
require_once($GLOBALS['classes']['module_loader']['library']);
require_once('Cln_Module.php');

require_once($GLOBALS['classes']['db']['library']);
require_once($GLOBALS['classes']['ko']['library']);
require_once($GLOBALS['classes']['metadata']['library']);

require_once($GLOBALS['classes']['user']['library']);
require_once($GLOBALS['classes']['group']['library']);

require_once($GLOBALS['classes']['process_manager']['library']);

require_once('Cln_Room.php');
require_once('Cln_Page.php');


// ****************************************************************************
// Start the timer to measure how long the pages take to render
$GLOBALS['pageTimer'] = new Benchmark_Timer();
$GLOBALS['pageTimer']->start();


// ****************************************************************************
// Strip slashes from all incoming variables right away.
Cln_stripSlashes($_REQUEST);
Cln_stripSlashes($_POST);
Cln_stripSlashes($_GET);
Cln_stripSlashes($_COOKIE);


// ****************************************************************************
// Prime required variables
if(!defined('MAIN_CLN_DSN') || !defined('CLN_BASE_URL')) {
	print <<<EOF
<p>CLN_BASE_URL must be set in your local configuration file.</p>
<p>While you are setting up your CLN_BASE_URL, you can also setup your database connection (MAIN_CLN_DSN), so you can run your own version of the system.  See config.php for examples.</p>
<p>copy what is below into config/CLN/config-local.php.</p>
<pre>
&lt;?php

# main database configuration
define('MAIN_CLN_DSN', 'mysql://username:hide@address.com/database');

# base url
define('CLN_BASE_URL','http://domain.com/cln/');

# required to send password emails when registering
define('CLN_SERVER_EMAIL_ADDRESS', 'hide@address.com');

# and if you would like clean url support (requires apache mod_rewrite):
define('CLN_CLEAN_URLS',1);

?&gt;
</pre>
<p>Please see docs/INSTALL for more information.</p>
EOF;

	exit;
}
primeTemplateVariables();


// ****************************************************************************
// Start the session and load/prime session objects

session_name(CLN_COOKIE_NAME);
session_start();

// The Module Loader
// NOTE: This must be loaded first, before any other session variables
if(!isset($_SESSION['Module_Loader'])) {
	session_register('Module_Loader');
	$_SESSION['Module_Loader'] = new $GLOBALS['classes']['module_loader']['classname']();
}

// The Process Manager
if (!isset($_SESSION['ProcessManager'])) {
	session_register('ProcessManager');
	$_SESSION['ProcessManager'] = & new $GLOBALS['classes']['process_manager']['classname']();
}

// The User Object
if(!isset($_SESSION['User'])) {
	session_register('User');
	$_SESSION['User'] = new $GLOBALS['classes']['user']['classname']();
}

// The Edit Mode
if (!isset($_SESSION['editMode'])) {
	session_register('editMode');
	$_SESSION['editMode'] = 'browse';
}


d('REQUEST_URI: '.$_SERVER['REQUEST_URI'], 5);

// ****************************************************************************
// Clean up the passed path stuff

// Figure out the path being sent
if(!empty($_GET['p'])) {
	$GLOBALS['path'] = $_GET['p'];
} else {
	$GLOBALS['path'] = '';
}

// Add index.php or /index.php if needed
if(substr($GLOBALS['path'],-4) != '.php') {
	if(substr($GLOBALS['path'],-1) != '/') {
		$GLOBALS['path'] .= '/';
	}
	$GLOBALS['path'] .= 'index.php';
}

// Strip off early /'s
if (substr($GLOBALS['path'], 0, 1) == '/') {
	$GLOBALS['path'] = substr($GLOBALS['path'], 1);
}

d('-------------------> loading '.$GLOBALS['path'],1);

// ***************************************************************************
// See if the user is logging in or out
if(isset($_POST['CLN_login_submit'])) {
	$_SESSION['User']->email = $_POST['CLN_login_email'];
	$_SESSION['User']->password = $_POST['CLN_login_password'];

	$_SESSION['User']->login();
}
else if(isset($_GET['Cln_logout'])) {	// the user is logging out
	$_SESSION['User']->logout();
} else {
	//print 'checking authentication for user<br />';
	$_SESSION['User']->isLoggedIn();
}


// ***************************************************************************
// See if the user is trying to switch languages
if(isset($_POST['setLanguage'])) {
	if($_POST['setLanguage'] == $_SESSION['User']->preferredLanguages[0]) {
		unset($_SESSION['User']->lang);
	} else {
		$_SESSION['User']->lang = $_POST['setLanguage'];
	}
	$language = $_POST['setLanguage'];
	PEAR::raiseError("Your viewing language has been switched to <b>{$GLOBALS['languages'][$language]}</b>. <br /><br />This doesn't mean that you will see everything in <b>{$GLOBALS['languages'][$language]}</b> - the system does not do automatic translation. However, you will see content in  <b>{$GLOBALS['languages'][$language]}</b> whenever a translation exists in that language.", E_USER_NOTICE);
}

// ***************************************************************************
// See if the user is trying to switch edit mode
if(isset($_GET['editMode'])) $_SESSION['editMode'] = $_GET['editMode'];


// ***************************************************************************
// Display the Page

// If it's PAGETYPE Admin, then don't load the normal content

if ((isset($PAGETYPE) && $PAGETYPE == 'Admin')) {
	// Do nothing now, content will be handled directly
}

// Otherwise load the normal content
else {
	// ***************************************************************************
	// Initialize the appropriate room and page session objects


	// ***************************************************************************
	// Set the location information, based on the path
	setLocation();
	//d("SetLocation - ROOMID $ROOMID, PAGEID $PAGEID");
	//d("Current Session Objects - Room: {$_SESSION['Room']->koId} Page: {$_SESSION['Page']->koId} KO: {$_SESSION['KO']->koId}");
	
	
	if(isset($_GET['koId'])) {
		$content = getKO($_GET['koId']);
		
		// create simple room - someday could be special template - dwc
		$aRoom =& new $GLOBALS['classes']['ko']['classname']($GLOBALS['ROOMID']);
		$aRoom->loadPartObject(0);
		echo "<html><head>";
		echo $aRoom->currentPart['object']->loadHeader();
		echo "</head><body>".$content."</body></html>";
	} else {
		if (isset($_SESSION['Room']) && isset($ROOMID)) {
			reinitializeSessionObject('Room', $ROOMID);
		}
		else if (!isset($_SESSION['Room'])) {
			session_register('Room');
			if (isset($ROOMID)) {
				$_SESSION['Room'] =& new $GLOBALS['classes']['ko']['classname']($ROOMID);
			}
			else {
				// when does this get called? - dwc
				$_SESSION['Room'] =& new $GLOBALS['classes']['ko']['classname']('NEW', 1);
			}
		}
	
		// initialize Page
		if (isset($_SESSION['Page']) && isset($PAGEID)) {
			reinitializeSessionObject('Page', $PAGEID);
		}
		else if (!isset($_SESSION['Page'])) {
			session_register('Page');
			if (isset($PAGEID)) {
				$_SESSION['Page'] =& new $GLOBALS['classes']['ko']['classname']($PAGEID);
			}
			else {
				// when does this get called? - dwc
				$_SESSION['Page'] =& new $GLOBALS['classes']['ko']['classname']('NEW', 2);
			}
		}
	
		echo $_SESSION['Room']->getContent();
	}
}

// write out log all at once
clnWriteLog();

/*
 **********************************************************************
 **********************************************************************
 * Functions used on this page
 **********************************************************************
 **********************************************************************
 */

/*
 *
 * Function: setIncludePath()
 *
 * To set the include path
 *
 * @access public
 * @return bool	  TRUE on success or FALSE on failure
 *
 */
function setIncludePath()
{
	$INCLUDE_PATH = array(
		CLN_FILE_BASE,
		CLN_FILE_BASE . 'config',
		CLN_FILE_BASE . 'lib',
		CLN_FILE_BASE . 'lib/CLN',
		CLN_FILE_BASE . 'lib/pear'
	);

	// Set the separator based on the OS
	$separator = ':';
	if(preg_match('/^win/i', PHP_OS)) {
		$separator = ';';
	}

	// Set the include path
	$current_include_path = ini_get('include_path');
	$new_include_path = join($separator, $INCLUDE_PATH) . $separator . $current_include_path;

	return ini_set('include_path',$new_include_path);
}


/*
 *
 * Function: primeTemplateVariables()
 *
 * Sets the initial values of the Template Variables (to blank)
 *
 * @access public
 * @return bool	  TRUE on success or FALSE on failure
 *
 */
function primeTemplateVariables()
{
	if (!isset($GLOBALS['CLN_HEADER'])) $GLOBALS['CLN_HEADER'] = '';
	if (!isset($GLOBALS['CLN_FOOTER'])) $GLOBALS['CLN_FOOTER'] = '';
	if (!isset($GLOBALS['CLN_LOGIN'])) $GLOBALS['CLN_LOGIN'] = '';
	if (!isset($GLOBALS['CLN_NAVBAR'])) $GLOBALS['CLN_NAVBAR'] = '';
	if (!isset($GLOBALS['CLN_MAINNAV'])) $GLOBALS['CLN_MAINNAV'] = '';
	if (!isset($GLOBALS['CLN_TITLE'])) $GLOBALS['CLN_TITLE'] = '';
	if (!isset($GLOBALS['CLN_PAGE_TITLE'])) $GLOBALS['CLN_PAGE_TITLE'] = '';
	if (!isset($GLOBALS['CLN_CONTENT'])) $GLOBALS['CLN_CONTENT'] = '';
	if (!isset($GLOBALS['CLN_USER_ERROR'])) $GLOBALS['CLN_USER_ERROR'] = '';
	if (!isset($GLOBALS['CLN_USER_MESSAGE'])) $GLOBALS['CLN_USER_MESSAGE'] = '';
	if (!isset($GLOBALS['CLN_ROOM_BORT'])) $GLOBALS['CLN_ROOM_BORT'] = '';
	if (!isset($GLOBALS['CLN_PAGE_BORT'])) $GLOBALS['CLN_PAGE_BORT'] = '';
}


/*
 *
 * Function: includeLangeFile()
 *
 * Grabs a language specific file based on the user's lang prefs, and
 * also based on what files already exist.
 *
 * @access public
 * @return string	last page in history or default (ie. homepage)
 *
 */
function includeLangFile($file)
{
	// If this file has been loaded already, just return TRUE
	if (isset($GLOBALS['langFilesLoaded'][$file])) {
		return TRUE;
	}

	// Figure out what languages do exist
	$langdir = CLN_FILE_BASE . dirname($file);
	$langfilename = basename($file);
	if (is_dir($langdir)) {
	   if ($dh = opendir($langdir)) {
		   while (($thisfile = readdir($dh)) !== false) {
			   if(substr($thisfile,0,-7) == $langfilename) {
			     	$availableLanguages[] = substr($thisfile,-6,-4);
			   }
		   }
		   closedir($dh);
	   }
	} else {
		PEAR::raiseError('Unable to include lang file for '.$file, E_ERROR);
		return FALSE;
	}

	$langToUse = whichLanguage($availableLanguages);

	if (file_exists(CLN_FILE_BASE . $file . '.' . $langToUse . '.php')) {
		include_once (CLN_FILE_BASE . $file . '.' . $langToUse . '.php');
		$GLOBALS['langFilesLoaded'][$file] = TRUE;
		return TRUE;
	} else {
		PEAR::raiseError("Attempted to include a non-existent language file: $file", E_WARNING);
		return FALSE;
	}
}


/*
 *
 * Function: whichLanguage()
 *
 * 		is passed an array of available languages for a particular ko
 *		it expects the first code to be the original, which will be
 * 		returned if nothing else matches
 *
 * @access public
 * @return string		language code (ie. en, fr etc.)
 *
 */
function whichLanguage($availableLanguages)
{
	if(!is_array($availableLanguages)) {
		PEAR::raiseError('Available languages is not an array', E_ERROR);
	}

	// 1. user defined language
	if (isset($_SESSION['User']->lang)) {
		foreach($availableLanguages as $lang) {
			if($_SESSION['User']->lang == $lang) {
				return $lang;
			}
		}
	}

	// 2. user default language(s)
	if(isset($_SESSION['User']->preferredLanguages)) {
		reset($availableLanguages);
		foreach($availableLanguages as $lang) {
			foreach($_SESSION['User']->preferredLanguages as $thisLang) {
				if($thisLang == $lang) {
					return $lang;
				}
			}
		}
	}

	// 3. system default language
	reset($availableLanguages);
	foreach($availableLanguages as $lang) {
		if(CLN_DEFAULT_LANGUAGE == $lang) {
			return $lang;
		}
	}

	return $availableLanguages[0];
}


/*
 *
 * Function: setLocation()
 *
 * 		used to get the roomId and pageId based on the the path
 *
 * @access public
 * @return array		roomId, pageId
 *
 */
function setLocation()
{
	$path = '/' . $GLOBALS['path']; // We need to add a / in front of it
	$pathParts = split('/',$path);

	// Check if they're in myhouse
	if ($pathParts[1] == 'MyHouse') {
		$GLOBALS['MYHOUSE'] = TRUE; // :ONEDAY: The name of myhouse should be a config variable

		// shift two levels off
		array_shift($pathParts);
		array_shift($pathParts);

		if($_SESSION['User']->userId && $_SESSION['User']->confirmed) {
			array_unshift($pathParts,'','Users','User'.$_SESSION['User']->userId);
			$GLOBALS['MYHOUSE_ROOT'] = 'Users/User'.$_SESSION['User']->userId;
		} else {
			array_unshift($pathParts,'','Users','Guest');
			$GLOBALS['MYHOUSE_ROOT'] = 'Users/Guest';
		}
		d('real path in my house: '.join('/',$pathParts),3);
	}

	$currentThisId = 1; // The starting ID is 1

	$cln_db = &Cln_Db::singleton(MAIN_CLN_DSN);

	$relativePath = array();

	while(count($pathParts) > 1) {
		$currentParentId = $currentThisId;

		$status = $_SESSION['editMode'] == 'edit' ? 0 : 1;

		$sql = sprintf("SELECT child.koId, child.nodeName FROM %s AS child, %s AS parent
						WHERE child.parentId = parent.koId AND parent.koId = '%s'
						AND parent.nodeName = '%s' AND child.nodeName = '%s'
						AND child.status = %d AND child.status = parent.status",
						ROOM_NODE_TABLE, ROOM_NODE_TABLE, $currentParentId, $pathParts[0],
						$pathParts[1], $status);

		$result = $cln_db->query($sql);

		if (PEAR::isError($result)) {
			PEAR::raiseError('Unable to select from '.ROOM_NODE_TABLE.' table: '.$sql, E_ERROR);
			return FALSE;
		}

		$row = $result->fetchRow(DB_FETCHMODE_OBJECT);

		if(!isset($row)) {
			PEAR::raiseError('Unable to find page '.cleanURL($GLOBALS['path']), E_USER_ERROR);
			if($GLOBALS['path'] == CLN_ERROR_PAGE) {
				PEAR::raiseError('CLN_ERROR_PAGE has not been set yet.', E_USER_ERROR);
				clnRedirect(CLN_BASE_URL);
			} else {
				clnRedirect(cleanURL(CLN_ERROR_PAGE));
			}
		}

		$currentThisId = $row->koId;

		// used to construct breadcrumb
		$GLOBALS['breadcrumb'][] = array('koId' => $row->koId,'nodeName' => $row->nodeName);

		array_shift($pathParts);

		// Do the file base stuff
		$relativePath[] = '../';
	}

	// To do the relative path, knock one ../ off the end
	array_pop($relativePath);

	// override relative path, as My House is only one level deep
	if(isset($GLOBALS['MYHOUSE'])) {
		array_pop($relativePath);
	}

	// Setup CLN_CLEAN_URL_BASE constant used throughout system
	if (CLN_CLEAN_URLS && count($relativePath) > 0) {
		define('CLN_CLEAN_URL_BASE', join('',$relativePath));
	}
	else {
		define('CLN_CLEAN_URL_BASE','./');
	}

	$GLOBALS['ROOMID'] = $currentParentId;
	$GLOBALS['PAGEID'] = $currentThisId;

	return TRUE;
}


/*
 *
 * Function: cleanURL()
 *
 * 	  returns url based upon CLN_CLEAN_URLS configuration constant
 *
 * @access public
 * @return string	$var or stripslashes($var)
 *
 */
 function cleanURL($path, $url = CLN_BASE_URL) {
 	if(defined('CLN_CLEAN_URLS') && CLN_CLEAN_URLS) {
 		return $url . $path;
 	} else {
 		return appendToURL($url,'p='.$path);
 	}
 }


/*
 *
 * Function:  appendToURL()
 *
 * 		adds params to an existing url, formatting it properly
 *
 * @access public
 * @return string 	URL
 *
 */
function appendToURL($url,$newParams, $redirect = FALSE) {
	$urlParts = parse_url($url);
	$newParams = str_replace('&amp;', '&', $newParams);

	// If we're appending this to an already existing query
	if(isset($urlParts['query'])) {
		$newParamParts = split('&',$newParams);
		$params = split('&',$urlParts['query']);
		foreach($params as $nameValuePair) {
			$skipParam = false;
			list($name,$value) = split('=',$nameValuePair);
			foreach($newParamParts as $newParam) {
				list($newname, $newvalue) = split('=',$newParam);
				//print $name.' != '.$newname.'<br />';
				if($name == $newname) {
					$skipParam = true;
				}
			}
			if(!$skipParam) {
				$oldParams[] = $name.'='.$value;
			}
		}
		if(isset($oldParams)) {
			$oldParamsString = join('&amp;',$oldParams);
			$newUrl = '?'.$oldParamsString.'&amp;'.$newParams;
		} else {
			$newUrl = '?'.$newParams;
		}
	}
	// Else if this is the first query being appended
	else {
		$newParamParts = split('&', $newParams);
		$newParams = join('&amp;', $newParamParts);
		$newUrl = '?'.$newParams;
	}

	$finalURL = unparse_url($urlParts).$newUrl;
	if ($redirect) {
		return str_replace('&amp;', '&', $finalURL);
	}
	else {
		return $finalURL;
	}
}

/*
 *
 * Function:  removeUrlValue()
 *
 * 		removes a parameter from the URL
 *
 * @access public
 * @return string 	URL
 *
 */
function removeUrlValue($url, $removeParam) {
	d("removing $removeParam from $url");
	$urlParts = parse_url($url);

	if (isset($urlParts['query'])) {
		$params = split('&', $urlParts['query']);
		foreach ($params as $nameValuePair) {
			list($name, $value) = split('=', $nameValuePair);
			$splitParams[$name] = $value;
		}
		unset($splitParams[$removeParam]);

		foreach ($splitParams as $name => $value) {
			$newUrlParamsArray[] = "{$name}={$value}";
		}
		$newUrlParams = join('&amp;', $newUrlParamsArray);

		d('now url is: ' .  unparse_url($urlParts) . '?' . $newUrlParams);
		return unparse_url($urlParts) . '?' . $newUrlParams;
	}

}


/*
 *
 * Function:  unparse_url()
 *
 *
 *
 * @access public
 * @return string 	URL
 *
 */
function unparse_url($parts_arr) {
	$ret_url = '';

	if(isset($parts_arr['scheme']) && strcmp($parts_arr['scheme'], '') != 0) {
		$ret_url = $parts_arr['scheme'] . '://';
	}

	if(isset($parts_arr['user'])) {
		$ret_url .= $parts_arr['user'];
	}

	if(isset($parts_arr['pass'])) {
		if (strcmp($parts_arr['pass'], '') != 0) {
			$ret_url .= ':' . $parts_arr['pass'];
		}
		if ((strcmp($parts_arr['user'], '') != 0) || (strcmp($parts_arr['pass'], '') != 0)) {
			$ret_url .= '@';
		}
	}

	if(isset($parts_arr['host'])) {
		$ret_url .= $parts_arr['host'];
	}

	if(isset($parts_arr['port']) && strcmp($parts_arr['port'], '') != 0) {
		$ret_url .= ':' . $parts_arr['port'];
	}

	if(isset($parts_arr['path'])) {
		$ret_url .= $parts_arr['path'];
	}

	/*if(isset($parts_arr['query']) && strcmp($parts_arr['query'], '') != 0) {
			$ret_url .= '?' . $parts_arr['query'];
	}*/

	if(isset($parts_arr['fragment']) && strcmp($parts_arr['fragment'], '') != 0) {
			$ret_url .= '#' . $parts_arr['fragment'];
	}

	return $ret_url;
}


/*
 *
 * Function: Cln_stripSlashes()
 *
 * 	  checks to see if magic_quotes_qpc is set and if it is, strips slashes directly from the variable
 *
 * @access public
 * @return string	$var or stripslashes($var)
 *
 */
function Cln_stripSlashes(&$var)
{
	if (get_magic_quotes_gpc()) {
		if (is_array($var)) {
			foreach ($var as $key => $value) {
			   Cln_stripSlashes($var[$key]);
			}
		}
		else if (is_string($var)) {
			$var = stripslashes($var);
		}
	}
}


/*
 *
 * Function: stripslashesArray()
 *
 * 	  strips the slashes of an array. Currently, this doesn't pass anything back, it just
 *
 * @access public
 * @return string	$var or stripslashes($var)
 *
 */
function stripslashesArray($thisArray)
{
	if (is_array($thisArray)) {
		foreach ($thisArray as $key => $value) {
		   $thisArray[$key] = stripslashes($value);
		}
	}
	return $thisArray;
}


/*
 *
 * Function: validateString()
 *
 * 	  Validates string $string against type $type
 *
 * @access public
 * @return strinh
 *
 */
function validateString($string, $type)
{
	if ($type == 'username') {
		$expression = '(^[A-Za-z0-9]{4,12}$)';
	}

	elseif ($type == 'email') {
		// Is it of the hide@address.com type?
		$expression = '^[_A-Za-z0-9-]+(\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\.[A-Za-z0-9-]+)+$';
	}

	elseif ($type == 'password') {
		$expression = '(^[A-Za-z0-9]{4,12}$)';
	}

	elseif ($type == 'name') {
		$expression = '(^[A-Za-z]([[:space:]]*[A-Za-z]*)*$)';
	}

	elseif ($type == 'CanadaPostalCode') {
		$expression = '^[A-Za-z][0-9][A-Za-z][[:space:]]*[0-9][A-Za-z][0-9]$';
	}

	elseif ($type == 'USPostalCode') {
		$expression = '(^[0-9]{5}$)';
	}

	elseif ($type == 'phone') {
		// Does it just contain numbers and dashes and parentheses
		// 	$expression = '(^[(]*[0-9]{3}[)]*[-]*[0-9]{3}[-]*[0-9]{4}$)';
		$expression = '(^[()x0-9-]*$)';
		$string = ereg_replace('([ 	]+)','',$string);;
	}

	elseif ($type == 'safetext') {
		$expression= '^[A-Za-z0-9#\-\.[:space:]]+$';
	}

	elseif ($type == 'DB_ID') {
		$expression = '^[0-9]{5}$';
	}

	elseif ($type == 'URL') {
		$expression = '^http://[^[:space:]]+$';
	}

	elseif ($type == 'phpFilename') {
		$expression = '^[A-Za-z0-9-]+$';
	}

	$answer = ereg($expression, $string);

	return $answer;
}


/*
 *
 * Function:  reinitializeSessionObject()
 *
 * 		Attempts to reinitialize the session object passed to it. If it already
 *		exists with the same koId then it just returns that, otherwise it
 *		unsets that variable, and returns a new one
 *
 * @access public
 * @return reference 	instance of Cln_KO
 *
 */
function reinitializeSessionObject($object, $koId)
{
	// Shouldn't be reinitializing while editing objects!
	if (!isset($_GET['editKoId']) && $_SESSION[$object]->koId != $koId) {
		unset($_SESSION[$object]);
		$_SESSION[$object] =& new $GLOBALS['classes']['ko']['classname']($koId);
	}
}


/*
 *
 * Function:  formatDate()
 *
 * 		returns a formatted date
 *
 * @access public
 * @return string 	Date
 *
 */
function formatDate($timestamp) {
	if($timestamp < 0) return 'unavailable';

	return strftime('%D %T',$timestamp);
}


/*
 *
 * Function:  convertCreated()
 *
 * 		used to convert the created date from mysql datetime into a unix timestamp
 *
 * @access public
 * @return string 	URL
 *
 */
function convertCreated($mysqlDatetime) {
    if(empty($mysqlDatetime)) return '';

	list($date,$time) = split(' ',$mysqlDatetime);
	list($year,$month,$day) = split('-',$date);
	list($hour,$min,$sec) = split(':',$time);

	return mktime($hour,$min,$sec,$month,$day,$year);
}


/*
 *
 * Function:  convertModified()
 *
 * 		used to convert the created date from mysql timestamp into a unix timestamp
 *
 * @access public
 * @return string 	URL
 *
 */
function convertModified($mysqlTimestamp) {
	list($year,$month,$day,$hour,$min,$sec) = sscanf($mysqlTimestamp,'%4s%2s%2s%2s%2s%2s');

	return mktime($hour,$min,$sec,$month,$day,$year);
}


/*
 *
 * Function:  clearRecordLocks()
 *
 * 		Clears any record locks if there are any
 *
 * @access public
 * @return string 	URL
 *
 */
function clearRecordLocks() {
	if (isset($_SESSION['recordsLocked']) && $_SESSION['recordsLocked']) {
		// If the user has a userId
		if (isset($_SESSION['User']) && $_SESSION['User']->isLoggedIn()) {
			// Remove any locks
			$cln_db = &Cln_Db::singleton(MAIN_CLN_DSN);
			$sql = sprintf('DELETE FROM `%s` WHERE userId = %d', RECORD_LOCK_TABLE, $_SESSION['User']->userId);
			$cln_db->query($sql);
		}
		// Reset the session variable
		$_SESSION['recordsLocked'] = FALSE;
	}
	else {
		$_SESSION['recordsLocked'] = FALSE;
	}
}


/*
 *
 * Function: getNodePath()
 *
 * 		gets full node path for url (based upon breadcrumb)
 *
 * @access public
 * @return String		url
 *
 */
function getNodePath($koId, $ignorePage = FALSE)
{
	d("getNodePath() - koId: $koId", 3);

	$cln_db = &Cln_Db::singleton(MAIN_CLN_DSN);

	if($ignorePage) {
		$numberOfNodes = count($GLOBALS['breadcrumb'])-1;
	} else {
		$numberOfNodes = count($GLOBALS['breadcrumb']);
	}

	if($numberOfNodes > 0) {
		for($i=0;$i<$numberOfNodes;$i++) {
			$koId = $GLOBALS['breadcrumb'][$i]['koId'];
			if(isset($GLOBALS['breadcrumb'][$i-1]['koId'])) {
				$parentId = $GLOBALS['breadcrumb'][$i-1]['koId'];
			} else {
				$parentId = 1;
			}
			$status = $_SESSION['editMode'] == 'edit' ? 0 : 1;
			$sql = sprintf('SELECT nodeName FROM %s WHERE koId = %d AND parentId = %d AND status = %d',
							ROOM_NODE_TABLE, $koId, $parentId, $status);

			$result = $cln_db->query($sql);
			if (PEAR::isError($result)) {
				PEAR::raiseError('Unable to select from '.ROOM_NODE_TABLE.' table: '.$sql, E_ERROR);
				return FALSE;
			}

			$row = $result->fetchRow(DB_FETCHMODE_OBJECT);
			$nodes[] = $row->nodeName;
		}
		$nodePath = join('/',$nodes);
	} else {
		$nodePath = '';
	}

	if(isset($GLOBALS['MYHOUSE_ROOT'])) $nodePath = ereg_replace($GLOBALS['MYHOUSE_ROOT'],'MyHouse',$nodePath);

	return $nodePath;
}


/*
 *
 * Function:  clnRedirect()
 *
 * 		redirects to the passed URL
 *
 * @access public
 * @return string 	URL
 *
 */
function clnRedirect($url) {
	clnWriteLog();
	header('Location: '. $url);
	exit;
}


/*
 *
 * Function:  getKO()
 *
 * 		gets a KO from it's koId.  it's a good shortcut, especially within templates.
 *
 * @access public
 * @return string 	URL
 *
 */
function getKO($koId) {
	$thisKO =& new $GLOBALS['classes']['ko']['classname']($koId);
	$thisKO->loadPartObject(0);

	return $thisKO->getContent();
}


/*
 *
 * Function:  loadClass()
 *
 * 		load the class from a modId
 *
 * @access public
 * @return string 	URL
 *
 */
function loadClass($thisModId) {
	if (isset($_SESSION['Module_Loader'])) {
		$thisClassPath = $_SESSION['Module_Loader']->getModulePath($thisModId);
		include_once(CLN_FILE_BASE.$thisClassPath);
	}
	return TRUE;
}


/*
 *
 * Function:  d()
 *
 * 		a debugging function that you turn on with TRUE in the first IF
 *
 * @access public
 * @return string 	URL
 *
 */
function d($message,$level = 1) {
	if (defined('CLN_DEBUG') && CLN_DEBUG >= $level && !empty($message)) {
		if (is_array($message) || is_object($message)) {
			ob_start();
			print_r($message);
			$message = ob_get_contents();
			ob_end_clean();
		}
		PEAR::raiseError($message, E_ERROR);
	}
}

?>
Return current item: Community Learning Network