<?php

/*
 *	W-AGORA 4.0
 *	-----------
 *	$Id: init.inc,v 1.119 2006/07/11 21:31:32 mdruilhe Exp $
 *	Usage:		Initialization file
 *	Author:		Marc Druilhe <mdruilhe@w-agora.com>
 */

require ("globals.inc");

# display the headers and include the header file if required
# ----------------------------------------------------------
function display_header ($title='', $include_header) {
	global $WA_SELF, $lang, $bn_action, $site, $bn, $bn_dir, $bn_dir_default, $bn_header, $bn_body, $frameset;
	global $cat_id, $cat_title, $site_title, $bn_title, $bn_descr, $bn_style, $bn_frames, $bn_popup, $bn_browse_server, $lynx, $bn_charset;
	global $icon_dir, $img_dir;
	global $bn_search, $main_page, $bn_base_url, $ext, $auth, $is_authenticated, $db, $bn_date_format;
	global $login_string, $login_user;
	global $admin_url, $admin_text, $admin_link;
	global $list_url, $list_text, $list_link;
	global $post_url, $post_text, $post_link, $post_button;
	global $search_url, $search_text, $search_link;
	global $login_url, $login_text, $login_link;
	global $logout_url, $logout_text, $logout_link;
	global $register_url, $register_text, $register_link;
	global $profile_url, $profile_text, $profile_link;
	global $subscribe_url, $subscribe_text, $subscribe_link;
	global $download_forum_url, $download_forum_text, $download_forum_link;
	global $forum_list_url, $forum_list_text, $forum_list_link;
	global $choose_forum_box, $choose_forum_form;
	global $bn_win_width, $bn_win_height;
	global $forum, $site_stats, $totalthreads, $totalnotes;

	if (empty($frameset)) {
		if (empty($GLOBALS['bn_doctype'])) {
			echo "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">\n";
		} else {
			echo $GLOBALS['bn_doctype'];
		}
			
		$dir = (isset($GLOBALS['bn_html_dir']) ) ? $GLOBALS['bn_html_dir'] : 'ltr';
		echo "<html lang=\"$lang\" dir=\"$dir\">\n<head>\n";
		printf("<title>%s%s%s</title>\n", strip_tags($bn_title),
			(empty($bn_title) || empty($title)) ? '' : " - ", strip_tags($title));
		printf ("<meta name=\"GENERATOR\" Content=\"%s\"/>\n", wa_version() );

		if (!empty($bn_charset)) {
			printf ("<meta http-equiv=\"Content-Type\" Content=\"text/html;charset=%s\"/>\n", $bn_charset);
		}

		if ( ($bn_popup == 1) || ($bn_browse_server==1) ):
?>
<script type="text/javascript">
<!-- // Hide for old browsers
  var newWindow = null;
 function OpenWindow (Url,Title, Width, Height) {
  var win_opt= "toolbar=0,location=0,directories=0,status=0,menubar=0,";
  win_opt += "scrollbars=1,resizable=1,copyhistory=0,";
  win_opt += "width=" + Width + ",height=" + Height;
  newWindow = window.open('',Title,win_opt);
  if (newWindow != null) {
    if (newWindow.opener == null)
      newWindow.opener = self;
    newWindow.location.href = Url;
    if (newWindow.focus) newWindow.focus();
  }
 }
 // End of script -->
</script>
<?php
		endif;

		echo "<link rel=\"stylesheet\" href=\"style.css\" type=\"text/css\">\n";
		if (!empty($bn_style) && file_exists ("$bn_dir/$bn_style")) {
			include "$bn_dir/$bn_style";
		} elseif (file_exists ("$bn_dir_default/style.$ext") ) {
			include "$bn_dir_default/style.$ext";
		}

		echo "<link rel=\"alternate\" type=\"application/rss+xml\" title=\"$bn_title\" href=\"$bn_base_url/rss.$ext?site=$site&bn=$bn\" />";
		printf ("</head>\n<body %s>\n", $bn_body);
	}

	if ($include_header) {
		if (!empty($bn_header) && file_exists ("$bn_dir/$bn_header") ) {
			include "$bn_dir/$bn_header";
		} elseif (file_exists ("$bn_dir_default/header.$ext")) {
			include ("$bn_dir_default/header.$ext");
		}
	}
}

# include the footer file if required and display the HTML footer
# ---------------------------------------------------------------
function display_footer($include_footer) {
	global $WA_SELF, $bn_action, $site, $bn, $bn_dir, $bn_dir_default, $bn_footer, $bn_body, $frameset;
	global $cat_id, $cat_title, $site_title, $bn_title, $bn_style, $bn_frames, $bn_popup, $lynx;
	global $bn_search, $main_page, $ext, $auth, $is_authenticated, $db, $bn_date_format;
	global $list_url, $list_text, $list_link;
	global $post_url, $post_text, $post_link, $post_button;
	global $search_url, $search_text, $search_link;
	global $login_url, $login_text, $login_link;
	global $register_url, $register_text, $register_link;
	global $profile_url, $profile_text, $profile_link;
	global $subscribe_url, $subscribe_text, $subscribe_link;
	global $choose_forum_box, $choose_forum_form;
	global $icon_dir, $img_dir;

	if ($include_footer) {
		$bn_dir_default = (empty($bn_dir_default) ) 
			? ( (is_dir("$bn_dir_forums/$site/default")) ? ("$bn_dir_forums/$site/default") : $bn_dir ) 
			: $bn_dir_default;
		if (!empty($bn_footer) && file_exists("$bn_dir/$bn_footer") ) {
			include "$bn_dir/$bn_footer";
		} elseif (file_exists ("$bn_dir_default/footer.$ext")) {
			include ("$bn_dir_default/footer.$ext");
		}
	}


	if (!isset($frameset)) {
		echo "</body>\n</html>\n";
		$db->closeDB();
		exit;
	}
}

# include general purpose functions
# ---------------------------------
	require ("$inc_dir/misc_func.$ext");

# --------------------------------------
# Initialize configuration file and site
# --------------------------------------
	if (empty($bn)) {
# No forum selected -> default to 'site' configuration
		$site = empty($site) ? 'agora' : trim(basename($site));
		$site_cfg_file = "${cfg_dir}/site_${site}.$ext";
		$cfg_file = $site_cfg_file;
		$expnd = 'all';
		$bn = '';
	} else {
		$bn=trim(basename($bn));
		$site = strtok($bn, "_");
		$forum_name = strtok('_');
		$site_cfg_file = "${cfg_dir}/site_${site}.$ext";
		$cfg_file = "${cfg_dir}/${bn}.${ext}";
	}

# read configuration for this forum
# ---------------------------------
	if (file_exists ("$cfg_file") && file_exists ("$site_cfg_file")) {
		include ("$site_cfg_file");
		include ("$cfg_file");
	} elseif (file_exists ("$site_cfg_file")) {
		@header("Location: $bn_base_url/$main_page?site=$site");
		exit;
	} elseif ($site == "agora") {
		@header("Location: $bn_base_url/setup.$ext");
		exit;
	} elseif (empty($bn) ) {
		@header("Location: $bn_base_url/$main_page");
		exit;
	} else {
		msgWarning ("Forum <b>$forum_name</b> does not exist<br>Could not access configuration file: <b>$cfg_file</b>", "$main_page?site=$site&bn=");
		exit;
	}

# Change default directory if $theme variable is set
# --------------------------------------------------
	if (isset($_GET['theme']) ) {
		$theme = $_GET['theme'];
	} elseif (isset($_COOKIE['theme'])) {
		$theme = $_COOKIE['theme'];
	}

	if (isset($theme) && is_dir("$bn_dir_default/$theme") ) {
	    $bn_dir_default = "$bn_dir_default/$theme";
		if (!isset($_COOKIE['theme']) || ($theme != $_COOKIE['theme']) ) {
			setcookie ('theme', $theme, 0, '/');
		}
	}

	if ($lynx==1) {
		$bn_frames = 0;
		$bn_popup = 0;
	}

# Set current date
# ----------------
	$formated_date = formated_date ($now);

# ------------------------------------------
# Include forum specific configuration files
# ------------------------------------------

# --------
# messages
# --------
	if (empty($bn_msgs) ) {
		// override cookie (take out $lang from URL)
		if (isset($lang) && file_exists("$bn_dir_default/msgs_${lang}.$ext") ) {
			include ("$bn_dir_default/msgs_${lang}.$ext");
		} else {
			include ("$bn_dir_default/msgs.$ext");
		}
	} else {
		if (isset($lang) && file_exists("$bn_dir/msgs_${lang}.$ext") ) {
			include "$bn_dir/msgs_${lang}.$ext";
		} else {
			include "$bn_dir/$bn_msgs";
		}
	}

# -----------------
# fields definition
# -----------------

# loads customized fields
# --------------------------
	if (empty($bn_fields) ) {
		include ("$bn_dir_default/fields.$ext");
	} else {
		include "$bn_dir/$bn_fields";
	}

# Set core variables (managed by w-agora)
# ---------------------------------------
	if(!empty($bn)) {
		if (isset($bn_var)) {
			unset ($bn_var);
		}

		$bn_var = array (
			'unixdate',		// timestamp (creation date)
			'userid',		// user ID
			'mod_date',		// modification date
			'mod_userid',	// userid of modifier
			'password',		// MD5 encoded password
			'filename',		// name of HTML note
			'att_size',		// total attachments size
			'mail_reply',	// set to '1' if replies to this note must be sent by email
			'hidden',		// set to 1 if note must be approved by the moderator
			'hits',			// hits count
			'closed',		// closed thread (RFU)
			'ip'			// logged IP address of sender
		);

		// force w-agora variables to be listed
		foreach($bn_var as $var) {
			$list_var[$var] = 1;
		}
	}

# listing outline
# ---------------
	if (empty($bn_list_vars) ) {
		include ("$bn_dir_default/list.$ext");
	} else {
		include "$bn_dir/$bn_list_vars";
	}
	$bn_hot_threshold = (isset($bn_hot_threshold) ) ? (integer) $bn_hot_threshold : 15;

# Note template
# -------------
	if (!empty($bn)) {
		if (!empty($bn_template) ) {
			include "$bn_dir/$bn_template";
		} elseif (file_exists ("$bn_dir_default/template.$ext") ) {
			include ("$bn_dir_default/template.$ext");
		}	
	}

# set the before_access file
# ----------------------
	if (!empty($bn_before_access)) {
		if (file_exists ("$bn_dir/$bn_before_access") ) {
			$before_access = "$bn_dir/$bn_before_access";
		} else {
			$before_access = "$bn_dir_default/$bn_before_access";
		}
	} elseif (file_exists ("$bn_dir_default/before_access.$ext") ) {
		$before_access = "$bn_dir_default/before_access.$ext";
	} else {
		$before_access = "";
	}

# Define labels associated with the different values
# --------------------------------------------------
	$user_states =array(
		'0' => USER_STATE_LOCKED,
		'1' => USER_STATE_ACTIVE,
		'P' => USER_STATE_PENDING
	);

	$forum_types['pub'] = FORUM_TYPE_PUBLIC;
	$forum_types['reg'] = FORUM_TYPE_REGISTERED;
	$forum_types['rest'] = FORUM_TYPE_RESTRICTED;
	$forum_types['priv'] = FORUM_TYPE_PRIVATE;

	$forum_states = array (
		'0' => FORUM_STATE_INACTIVE,
		'1' => FORUM_STATE_ACTIVE,
		'L' => FORUM_STATE_LOCKED,
		'C' => FORUM_STATE_CLOSED
	);

# Include Database access then connect
# ------------------------------------
	$_dbparam = getDBaccess($site);
	extract($_dbparam);
	require ("$inc_dir/$bn_access.$ext");
	$db_class = "${bn_access}_access";
	$db =& new $db_class;
	$db->setDebug($debug);
	$ret = $db->openDB($dbhost, $dbport, $dbuser, $dbpassword, $dbname, $site);
	if ($ret < 0) {
		$err = sprintf(ERROR_DATABASE, $ret);
		if (!empty($before_access)) include $before_access;
		display_header ($err, $header_footer);
		msgForm ($err, "$main_page", '');
		display_footer ($header_footer);
		exit;
	}

# -----------------------
# gets forum informations
# -----------------------
	if (empty($bn)) {
		// default site parameters
		if ($site=="agora" ) {
			$forum = array ( 'state' =>'1', 'type' => 'pub', 'bn_title' => 'agora sites database', 'cat_id' => '0');
		} else {
			$agora_dbparam = getDBaccess("agora");
			$agora_access = $agora_dbparam["bn_access"];
			$agora_dbhost = $agora_dbparam["dbhost"];
			$agora_dbname = $agora_dbparam["dbname"];
			if ($agora_access!= $bn_access) {
				include ("$inc_dir/$agora_access.$ext");
			}
			if ( ($agora_access != $bn_access) || ($agora_dbname != $dbname) || ($agora_dbhost != $dbhost) ) {
				$db_class = "${agora_access}_access";
				$agora_db =& new $db_class;
				$agora_db->setDebug($debug);
			
				if ($agora_access == $bn_access) {
					$db->closeDB();
				}
			
				$ret = $agora_db->openDB($agora_dbhost, $agora_dbparam["dbport"], $agora_dbparam["dbuser"], $agora_dbparam["dbpassword"], $agora_dbname, "agora");
				$forum = $agora_db->getSite($site);
				$agora_db->closeDB();
				if ($agora_access == $bn_access) {
					$ret = $db->openDB($dbhost, $dbport, $dbuser, $dbpassword, $dbname, $site);
				}

			} else {
				$forum = $db->getSite($site);
			}

			if (!is_array($forum)) {
				// bypass the error if "agora" not found in the site database
				$forum = array ( 'state'=>'1', 'type'=>'rest', 'bn_title'=>"$site");
			}
		}
	} else {
		$forum = $db->getForum($site, $bn);
		if (!is_array($forum)) {
			$err = sprintf(ERROR_DATABASE, $forum);
			if (!empty($before_access)) include $before_access;
			display_header ($err, $header_footer);
			msgForm ($err, "$main_page", '');
			display_footer ($header_footer);
			exit;
		}
	}

# extract useful variables from forum infos read from the database
# ----------------------------------------------------------------
	if (empty($bn) ) {
		$bn_title = & $forum['bn_title'];
	} else {
		extract ($forum, EXTR_PREFIX_ALL, 'forum');
		$owneraddress = & $forum_owneraddress;
		$ownername = & $forum_ownername;
		$bn_title = & $forum_bn_title;
		$bn_descr = & $forum_descr;
		$bn_db = & $forum_bn_db;
		$totalthreads = & $forum_totalthreads;
		$totalnotes = & $forum_totalnotes;
	}

	if (isset($cat)) {
	    $cat_id = $cat;
	} else {
	    $cat_id = $forum['cat_id'];
		$cat = '';
	}

	if ($site!='agora') {
		$categories = $db->getCategories($site);
		$site_title = (empty($bn) ) ? $bn_title :  $categories[0];
		$cat_title = $categories[$cat_id];
	}

# don't display header and footer in frameless mode, nor in the popup
# -------------------------------------------------------------------
	$header_footer = ( empty($bn_frames) && (empty($bn_popup) || empty($popup)) ) ? true : false;

# We authenticate the user in all cases in order to set the $auth object
#   (so that we can later know if he is a moderator)
# ----------------------------------------------------------------------
	$usersource = (empty($bn_usersource) )  ? 'agora_user' : $bn_usersource;
	include ("$user_dir/$usersource.$ext");
	$auth_class = "${usersource}_source";
	$auth =& new $auth_class;

# force user to re-login if required
# ----------------------------------
	if (isset($force_login)) {
		if (!empty($before_access)) include $before_access;
		$auth->logout($site);
		display_header (LABEL_PLEASE_LOGIN, $header_footer);
		$auth->login($site);
		exit;
	}

# -------------------------------------------
# Authenticate the user and check permissions
# -------------------------------------------
	$is_authenticated = $auth->authenticate();
	$login_user = $auth->userid;
	$check_perm = false; 
	if (!empty($bn)) {
		$check_perm = $auth->havePermission ($bn, $bn_action_mode); 
	}

# -----------------------------------------------------------------------------------
#	Now we check the type access to this forum and authenticate the user
# -----------------------------------------------------------------------------------
	$check_auth = (defined('auth_required')) ? true : false;
	$haveperm = true;

	if (!defined('no_auth_required')) {
		switch ($forum['type']) {

		  // registered forum : need to be authenticated to post
		  case 'reg':
			if ($bn_action_mode=='W') {
				$check_auth=true;
				$haveperm = $is_authenticated;
			}
			break;

		  // restricted forum : check permission on this forum for this user
		  case 'rest':
			if ($bn_action_mode=='W') {
				$check_auth=true;
				$haveperm = $check_perm;
			}
			break;

		  // private forum : must be authenticated to access (read/write/list)
		  case 'priv':
			$check_auth=true;
			$haveperm = $check_perm;
			break;

		  default:
			$check_auth=false;
			break;
		}
	}

# Check if the current user is logged in as moderator for later usage
# -------------------------------------------------------------------
	$is_root = ($auth->level > ADMIN) ? true : false;
	$is_administrator = ($auth->level >= ADMIN) ? true : false;
	$is_moderator = ($is_administrator || (is_array($auth->privs) && ($auth->privs['modpriv'] == 1))) ? true : false;

# Allowed options for a moderator
# -------------------------------
	if ($is_moderator) {
		$bn_modify = 1;
		$bn_delete = 1;
		$bn_file_upload = 1;
		if (is_array($bn_html_var) ) {
			$bn_allow_html = 1;
		}
	}

	if ($is_root) {
		$bn_browse_server = 1;
	}

# set the URL variables
# ---------------------

	$target_frame = ($bn_frames && ($bn_action=='header') ) ? 'main' : '';
	$parent_frame = ($bn_frames==1 ) ? '_parent' : '';

	// LIST
	$list_url = "list.$ext?site=$site&bn=$bn";
	$list_text = LABEL_LIST;
	$list_link = anchor ($list_url, $target_frame, $list_text, ALT_LIST_NOTES);

	// POST
	$post_text = LABEL_POST;
	$post_link = '';
	$post_button = '';

	if ( ($bn_action=='list') && $bn_list_post && ($forum['type']=='pub' || $auth->havePermission($bn, 'W')) ) {
		$post_url = '#FORM';
		if ($forum['state'] == '1') {
			$post_link = anchor ($post_url, '', $post_text, ALT_POST_NOTE);
			$post_button = getButton('post', $post_text, "location.href='$post_url';");
		}
	} elseif ($bn_popup) {
		$post_url = "post.$ext?bn=$bn";
		if ($forum['state'] == '1') {
			$post_link = anchorWindow ($post_url, $post_text, ALT_POST_NOTE, $bn_win_width, $bn_win_height);
			$post_button = getButton('post', $post_text, "OpenWindow('$post_url','${bn}_post',$bn_win_width,$bn_win_height)");
		}
	} else {
		$post_url = "post.$ext?bn=$bn";
		if ($forum['state'] == '1') {
			$post_link = anchor ($post_url, $target_frame, $post_text, ALT_POST_NOTE);
			$post_button = getButton('post', $post_text, ( (empty($target_frame)) ? "" : "parent.$target_frame." ) . "location.href='$post_url';");
		}
	}

	// SEARCH
	$search_url = (empty($bn)) ? "search.$ext?site=$site" : "search.$ext?bn=$bn";
	$search_text = LABEL_SEARCH;
	$search_link = ($bn_search==1) ? anchor ($search_url, $target_frame, $search_text, sprintf(ALT_SEARCH_FORUM, $msg[1]) ) : '';

	// DOWNLOAD
	$download_forum_url = "download_forum.$ext?bn=$bn";
	$download_forum_text = LABEL_DOWNLOAD_FORUM;
	$download_forum_link = anchor ($download_forum_url, $target_frame, $download_forum_text, ALT_DOWNLOAD_FORUM);

	// FORUM LIST
	$forum_list_url = "$main_page?site=$site&bn=";
	$forum_list_text = LABEL_FORUMS_LIST;
	$forum_list_link = anchor ($forum_list_url, $parent_frame, $forum_list_text, ALT_FORUMS_LIST );

	// LOGIN
	$login_url = "login.$ext?site=$site&bn=$bn";
	$login_text = LABEL_LOGIN;
	$login_link = anchor ($login_url, $target_frame, $login_text, sprintf(ALT_LOGIN_INTO, $site) );

	// LOGOUT
	$logout_url = "logout.$ext?site=$site&bn=$bn";
	$logout_text = LABEL_LOGOUT;
	$logout_link = anchor ($logout_url, $target_frame, $logout_text, sprintf(ALT_LOGOUT_FROM, $site) );

	// REGISTER
	$register_url = "register.$ext?site=$site&bn=$bn";
	$register_text = LABEL_REGISTER;
	$register_link = anchor ($register_url, $target_frame, $register_text, ALT_REGISTER_USER );

	// PROFILE + SUBSCRIBE
	$profile_url = "profile.$ext?site=$site&bn=$bn";
	$profile_text = LABEL_PROFILE;
	$profile_link = '';
	$subscribe_url = "subscribe.$ext?site=$site&bn=$bn";
	$subscribe_text = LABEL_SUBSCRIBE_FORUM;
	$subscribe_link = '';
	if ( $is_authenticated || ($bn_action=='header') ) {
		$profile_link = anchor ($profile_url, $target_frame, $profile_text, ALT_CHANGE_PROFILE );
		if ($bn_user_mail) {
			$subscribe_link = anchor ($subscribe_url, $target_frame, $subscribe_text, ALT_SUBSCRIBE_FORUM );
		}
	}

	// ADMIN ACCESS
	$admin_url = "admin.$ext?site=$site&bn=$bn";
	$admin_text = LABEL_ADMIN;
	if ($auth->level >= MODER) {
		$admin_link = anchor ($admin_url, $parent_frame, $admin_text, ALT_ADMIN_SITE );
	}

# Get newest user and site statistics
# -----------------------------------
	if (empty($bn) ) {
		$newestuser = $db->getNewestUser($site);
		if (is_array($newestuser)) {
			// extract $site_newest_userid, $site_newest_username, $site_newest_useraddress
			extract ($newestuser, EXTR_PREFIX_ALL, 'site_newest');

			// make blanks unbreakable to ease formatting
			$site_newest_username = str_replace (' ', '&nbsp;', $site_newest_username);

			// for compatibility
			$site_newestuser = $site_newest_userid;
		}
		$site_stats = $db->getSiteStats ($site);
		$site_totalforums = $site_stats['totalforums'];
		$site_totalthreads = $site_stats['totalthreads'];
		$site_totalnotes = $site_stats['totalnotes'];
		$site_totalusers = $site_stats['totalusers'];
		$site_totalfiles = $site_stats['totalfiles'];
		$site_totalfilesize = $site_stats['totalfilesize'];
	}

# set Select box with forums
# --------------------------
	$forums = $db->getForums($site);
	if (is_array($forums) && count ($forums)>1) {
		$forums[''] = ITEM_FORUMS_LIST;
		$choose_forum_box = getListBox ('bn', $forums, $bn, 0, "window.location=('list.$ext?site=$site&bn='+this.options[this.selectedIndex].value)");
		$choose_forum_form = "<form action='list.$ext'><input type='hidden' name='site' value='$site'>".LABEL_JUMP_TO.": $choose_forum_box <input type=\"submit\" value=\"".LABEL_GO."\"></form>";
	}

# Logout user if not active in the site
# -------------------------------------
	if ($is_authenticated && !$is_root && $auth->state!=1) {
		$auth->logout($site);
		if (!empty($before_access)) include $before_access;
		display_header ('authentication', $header_footer);
		msgForm ( ERROR_ACCOUNT_NOT_ACTIVE, "list.$ext?site=$site&bn=$bn", 'close');
		display_footer ($header_footer);
		exit;
	}

# Check if this forum is active so we can read/post
# ----------------------------------------------------
	if (!$is_moderator) {
		if ($forum['state']=='0') {
			if (!empty($before_access)) include $before_access;
			display_header ('', $header_footer);
			unset ($bn);
		 	msgForm (str_replace('{FORUM}', $msg[1], ERROR_FORUM_DOWN), "$main_page?site=$site&bn=", 'close');
			display_footer ($header_footer);
		} elseif ( (($forum['state'] =='C') || ($forum['state']=='L')) && ($bn_action_mode=='W')) {
			if (!empty($before_access)) include $before_access;
			display_header ('', $header_footer);
			if ($forum['state'] =='C')	
				msgForm (str_replace('{MSG}', $msg[0], str_replace('{FORUM}', $msg[1], ERROR_FORUM_CLOSED)), $main_page, 'close');
			else
				msgForm (str_replace('{FORUM}', $msg[1], ERROR_FORUM_LOCKED), $main_page, 'close');

			display_footer ($header_footer);
		}
	}

	
# Check authentication if required
# --------------------------------
	if ($check_auth) {
		if ($is_authenticated) {
# user is authenticated, we check permissions & exit if is not authorized
			if (!$haveperm ) {
				if (!empty($before_access)) include $before_access;
				display_header ('authentication', $header_footer);
				msgForm (str_replace('{FORUM}', $msg[1], ERROR_ACCESS_DENIED), "list.$ext?site=$site&bn=", 'close');
				display_footer ($header_footer);
			} elseif ($auth->privs['state'] == "P") {
				if (!empty($before_access)) include $before_access;
				display_header ('authentication', $header_footer);
				msgForm (str_replace('{FORUM}', $msg[1], str_replace('{MOD_EMAIL}', $owneraddress, ERROR_ACCOUNT_PENDING)), "list.$ext?site=$site&bn=", 'close');
				display_footer ($header_footer);
			} elseif ($auth->privs['state'] == "L") {
				if (!empty($before_access)) include $before_access;
				display_header ('authentication', $header_footer);
				msgForm (str_replace('{FORUM}', $msg[1], str_replace('{MOD_EMAIL}', $owneraddress, ERROR_ACCOUNT_LOCKED)), "list.$ext?site=$site&bn=", 'close');
				display_footer ($header_footer);
			}
		} else {
# user is not authenticated
			$loginURL = $auth->getLoginURL();
			if (is_string($loginURL)) {
				header("Location: $loginURL");
			} else {
				if (!empty($before_access)) include $before_access;
				display_header (LABEL_MUST_LOGIN, $header_footer);
				$auth->login($site, LABEL_MUST_LOGIN);
				display_footer ($header_footer);
			}
		}
	}
	
	if ($is_authenticated) {
		$login_string = sprintf (LABEL_LOGGED_AS_SINCE, $auth->user['username'], formated_date($auth->user['lastlogin']) );
	} else {
		$login_string = LABEL_NOT_LOGGED_IN;
	}

# initialize and send cookies if cookies option is set
# ----------------------------------------------------
	if (($bn_cookies==1) && !isset($no_cookie)) {
		include ("$inc_dir/cookies.$ext");
	}


# force browser, proxies to refresh the page if required
# ------------------------------------------------------
	if (isset($force_refresh)) {
		// send headers to force expiration
		header("Expires: Mon, 2 Aug 1999 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
	}

?>
