<?php

#############################################################################
#                                 Site@School
# Site@School is a website management system designed for primary schools.
#
# About Site@School:
# Comissioned by: City District 'de Baarsjes', Amsterdam, Netherlands
# Original idea, coding (version 1.0) and design : Mark de Haan (mark@starwave.nl)
# Ideas, improvements, expansions (version 1.1 - 2.4): Fred Stuurman
# Current coder & maintainer: Fred Stuurman (fc.stuurman@hccnet.nl)
############################################################################
# last change 2006-10-04, version 2.4.10 Fred Stuurman <fc.stuurman@hccnet.nl>
# index.php - last changed 2006-06-14, version: 2.4.01 - Peter Fokker <peter@berestijn.nl>
# $Id: index.php,v 1.2 2006/10/15 19:08:55 fstuurman Exp $
#
# History
#
# 2006-06-14 - Peter Fokker <peter@berestijn.nl>
# - The function error_exit() is back from starnet/core/common.inc.php
# - We now do include starnet/core/common.inc.php but only after sanity check #3
# - Rearranged the history of modifications; added a CVS tag near the top
#
# 2006-06-13 - Peter Fokker <peter@berestijn.nl>
# - Some code was lost in the main program when Fred incorporated my
#   patches from May 31, 2006 into fixpac 01 (dated 2006-06-11).
#   I added the code again: it was a version check also against the
#   patch level, not just the bare version).
#
# 2006-06-?? - Fred Stuurman <fc.stuurman@hccnet.nl>
# - Added another sanity check on the existence of the theme, generates error 050
#   (replaces existing logic "error message 1")
# - Rearranged code; moved error_exit() to starnet/core/common.inc.php
#
# 2006-05-31 - Peter Fokker <peter@berestijn.nl>
# - Suppress all error reporting during the sanity checks to prevent information leaks
#
# 2006-05-30 - Peter Fokker <peter@berestijn.nl>
# - Added sanity checks, we now do a gentle exit in each of these cases:
#   . database.inc.php cannot be found (error 010) => must install S@S first
#   . cannot connect to MySQL (error 020) => database server down?
#   . cannot open our database (error 030) => configuration error?
#   . database version doesn't match PHP-code (error 040) => must migrate S@S
#
############################################################################
#                        LICENSE INFORMATION
#
# 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.
##############################################################################
//error_reporting(E_ALL);

$old_error_reporting = error_reporting(0); // switch off error reporting during sanity checks

define('IN_SAS', true);
define('SAS_VERSION', '2.4.10'); // this version number is checked against the database lateron

//initialize variables
$page = 0;
$section = 0;
$category = "";
$themelocation = "";
$cmsdir = 'starnet';

function error_exit($conditioncode, $ttl = "Error")
{
	/*---------------------------------
	 * Show a 'cryptic' condition code + exit
	 */
	echo "<html>\n<head>\n<title>$ttl</title>\n</head>\n<body>\n" .
	"<h1>$ttl</h1>\n" .
	"<b>There is a problem with this site.</b>\n<p>\n" .
	"Please contact the site owner mentioning the " .
	"following condition code:\n<p>\n<b>" .
	SAS_VERSION . '/' . $conditioncode . "</b>\n<p>\n" .
	"Thank you for your cooperation!\n</body>\n</html>\n";
	exit;
} /* error_exit() */

// SANITY CHECK #1 - is there an existing installation at the location we expect?
if (!file_exists($cmsdir . '/configuration/database.inc.php'))
{
	error_exit('010');
}

// SANITY CHECK #2 - do we have a connection to a working database?
include ($cmsdir . '/configuration/database.inc.php');
if (!($db = mysql_connect($db_server, $db_username, $db_password)))
{
	error_exit('020');
}

// SANITY CHECK #3 - do we have access to our own database?
if (!mysql_select_db($db_name))
{
	error_exit('030');
}

/*
 * Still here? Must have valid database in our hands then. Carry on...
 */
error_reporting($old_error_reporting); // switch on error reporting after sanity checks

include ($cmsdir . "/core/common.inc.php"); //include common functions

require ($cmsdir . "/core/session.php");
//build a session

unset ($sas_config);
$query = "SELECT config_key,config_value FROM $table_configuration WHERE config_key NOT LIKE 'agenda%'";
//read all the configuration items
$result = mysql_query($query);

while ($config_list = mysql_fetch_array($result))
{
	$sas_config[$config_list[0]] = $config_list[1];
	//put them in the config array
}

// SANITY CHECK #4 - do we have the correct version of the database?
$old_error_reporting = error_reporting(0); // switch off error reporting during sanity check

if ($sas_config['sas_version'] . '.' . $sas_config['sas_patch_version'] != SAS_VERSION)
{
	error_exit('040');
}

// SANITY CHECK #5 - do we have a template value?
if ($sas_config['theme'] == "") //if theme config value is empty, there is a problem with the site.
{
	error_exit('050');
}

error_reporting($old_error_reporting); // switch on error reporting after sanity check

// setting variables to global
if (IsSet ($_GET['page']))
{
	$page = intval($_GET['page']);
}
if (IsSet ($_GET['section']))
{
	$section = intval($_GET['section']);
}
if (IsSet ($_GET['category']))
{
	$category = $_GET['category'];
}
if (IsSet ($_GET['logout']))
{
	$logout = $_GET['logout'];
}
if (IsSet ($_GET['site']))
	// we get protected or public via the URL link
{
	$website = $_GET['site'];
	// unset session variable in case we want to go to public area
	unset ($_SESSION['site']);
	if ($website == "protected")
	{
		//if user wants to go to protected area set it in the session variable.
		$_SESSION['site'] = $website;
	}
}
elseif (IsSet ($_SESSION['site']))
{
	$website = $_SESSION['site'];
}
else
{
	$website = "";
}

if (IsSet ($logout)) // logging out, destroying session data
{
	mysql_query("UPDATE $table_studentpages SET approved = '' WHERE approved = $_SESSION[userid]");
	//clear approved for pages which might be in use by pupil/teacher
	session_unset();
	session_destroy();

	if ($website == "protected")
	{
		//if we go back to normal site we don't know page and section
		header("Location: index.php");
	}
}

if (IsSet ($_SESSION['usertype']))
{
	$sas_usertype = $_SESSION['usertype'];
}
else
{
	$sas_usertype = "";
}

if (IsSet ($_SESSION['userid']) AND ($sas_usertype == "teacher" OR $_SESSION['user_type'] > 19) AND $_SESSION['site'] == "protected")
	//are we allowed to get intranet access, then switch to the protected tables
{
	$table_sections = $dbprefix . "prot_sections";
	$table_pages = $dbprefix . "prot_pages";
	$_SESSION['site'] = $website;
	$themelocation = $sas_config['protected_theme'];
	//set the protected theme
}
else
{
	$themelocation = $sas_config['theme'];
	//set normal theme
}

$sitename = $sas_config['sitename'];
//selecting the title of the site

$check_sessioncode = $sas_config['sessioncode'];
//selecting the sessioncode, can be used for security
$userpath = $sas_config['user_path'];
//get the directoryname of the cms
if (substr($userpath, 0, 1) == "/")
{
	$userpath = substr($userpath, 1);
	//strip first slash
}
$serverpath = $sas_config['serverpath'];
//get the document root of the site
$media = $sas_config['media_dir'];
//media directory
$studentpages = $sas_config['studentpages_dir'];
//pupilpages directory
if (strrpos($serverpath, '/') != strlen($serverpath) - 1)
{
	$serverpath .= '/';
	//add last slash if not present
}
$serverpath = $serverpath . $userpath;

$site_url = $sas_config['url'];
//select the URL, used for images, downloads, links etc.

$language = $sas_config['language'];
//select the language, used for module language files
load_language($cmsdir . '/', '/'); //load language file

if ((!IsSet ($section)) OR ($section == 0)) //select startsection if no section was selected
{
	if ($website == "protected")
	{
		$section = $sas_config['protected_startsection'];
	}
	else
	{
		$section = $sas_config['startsection'];
	}
}

if ((!IsSet ($page)) OR ($page == 0)) //select startpage of section if no page was selected
{
	$query = "SELECT frontpage FROM $table_sections WHERE id = '" . $section . "'";
	$result = mysql_query($query) or die_script($query, mysql_error());
	$page = mysql_result($result, 0);
	unset ($query);
	unset ($result);
}

$query = "SELECT name FROM $table_sections WHERE id = '" . $section . "'"; //selecting the title of the section
$result = mysql_query($query) or die_script($query, mysql_error());
$sectiontitle = mysql_result($result, 0);
unset ($query);
unset ($result);

$query = "SELECT name FROM $table_pages WHERE id = '" . $page . "'";
//selecting the title of the page
$result = mysql_query($query) or die_script($query, mysql_error());
if (!@ $pagetitle = mysql_result($result, 0))
{
	print "No page was set as startpage for this section of the site";
	exit;
}

$ip = $_SERVER["REMOTE_ADDR"];
//log the ip address
$d = date("Y-m-d");
$ipfilter = explode(",", $sas_config['stats_ip_filter']);

$table_stats = $dbprefix . "stats";
//update or insert into the stats table
if (IsSet ($site) AND ($site == "protected"))
{
	$table_pages = $dbprefix . "prot_pages";
	mysql_query("UPDATE $table_pages SET count=count+1, lastvisitdate='$d' WHERE id = '" . $page . "'");

	$query2 = "SELECT ip FROM $table_stats WHERE ip = '$ip' AND pageid = '" . $page . "' AND sectionid = $section AND public = 1";
	$result2 = mysql_query($query2) or die_script($query, mysql_error());
	$RecordCount = mysql_num_rows($result2);
	if ($RecordCount > 0)
	{
		$results = mysql_query("UPDATE $table_stats 
												 SET count = count + 1,
													public = 1
												 WHERE ip = '$ip' AND pageid = $page AND sectionid = '" . $section . "' AND public = 1");
	}
	else
	{
		$results = mysql_query("INSERT INTO $table_stats(ip,received,pageid,sectionid,count,public) 
												 VALUES('$ip',now(),$page,$section,'1','1')");
	}
}
else
{
	//if (array_search($ip, $ipfilter) === FALSE)
	//{
	mysql_query("UPDATE $table_pages SET count=count+1, lastvisitdate='$d' WHERE id = $page");
	//}
	$query2 = "SELECT ip FROM $table_stats WHERE ip = '$ip' AND pageid = $page AND sectionid = '" . $section . "' AND public = 0";
	$result2 = mysql_query($query2) or die_script($query, mysql_error());
	$RecordCount = mysql_num_rows($result2);
	if ($RecordCount > 0)
	{
		$results = mysql_query("UPDATE $table_stats 
												 SET count = count + 1, public = 0
												 WHERE ip = '$ip' AND pageid = $page AND sectionid = '" . $section . "' AND public = 0");
	}
	else
	{
		$results = mysql_query("INSERT INTO $table_stats(ip,received,pageid,sectionid,count,public) 
												 VALUES('$ip',now(),$page,$section,'1','0')");
	}
}

unset ($query);
unset ($result);

//do we have print flag on?
if (isset ($_GET['print']) AND ($_GET['print'] == "yes"))
{
	print "
	<html>
	<body>
	<center><INPUT TYPE=\"BUTTON\" VALUE=\"print\" ONCLICK=\"if (window.print) window.print();\"></center>";

	$query = "SELECT module FROM $table_pages WHERE id = '" . $page . "'";
	$result = mysql_query($query);
	$module = mysql_result($result, 0);
	unset ($query);
	unset ($result);

	if ($module != '')
	{
		print "<table height=\"490\" border=\"0\" cellpadding=\"10\" cellspacing=\"0\" width=\"100%\"><tr><td valign=\"top\" width=\"100%\">";
		include ($cmsdir . "/modules/$module");
	}
	else
	{
		print "<table height=\"490\" border=\"0\" cellpadding=\"10\" cellspacing=\"0\" width=\"100%\"><tr><td valign=\"top\" width=\"100%\">";
		$query = "SELECT content FROM $table_pages WHERE id = '" . $page . "'";
		$result = mysql_query($query);
		$content = mysql_result($result, 0);
		unset ($query);
		unset ($result);
		$content = str_replace("../", "", $content);
		print "$content";
	}

	print "</td></tr>
			</table>
			</body>
			</html>";
}
else // including the theme file
	{
	include ($cmsdir . "/themes/$themelocation/main.inc.php");
}
?>
