<?php

#############################################################################
#                              Site@School
# Site@School is a website management system designed for 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)
############################################################################
# common.inc.php: last changed 24/08/2006  , version: 2.4.10
#            by Fred Stuurman  (fc.stuurman@hccnet.nl)
#$Id: common.inc.php,v 1.2 2006/10/15 19:08:53 fstuurman Exp $
############################################################################
#                        LICENSE INFORMATION
# Copyright (C) 2006 Municipality of Amsterdam, City District
#  'de Baarsjes', Amsterdam, the Netherlands.
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
# See the GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
##############################################################################

if (!defined('IN_SAS'))
{
	die("Hacking attempt");
}

//function which will check magic quotes to be on, if not add slashes to input string.
function sql_addslashes($a_string = '')
{
	if (!get_magic_quotes_gpc())
	{
		$a_string = addslashes($a_string);
	}
	return $a_string;
} // end of the 'sql_addslashes()' function

# Function to verify user logon.
# $user is the usernname , $pass is password and $type_of_user is type of user

function verify_logon($user, $pass, $type_of_user)
{
	global $check_sessioncode, $sas_config, $table_users, $page, $section, $sas_lang, $cmsdir;

	if ($sas_config['use_encryption'] == 1) //passwords are encrypted
	{
		$pass = md5($pass);
	}

	$login = anti_injection(strip_tags($user), strip_tags($pass));

	if ($type_of_user == "admin") //admin type users
	{
		$result = mysql_query("SELECT username, password FROM $table_users 
				WHERE username = '" . $login['user'] . "' AND password = '" . $login['pass'] . "' AND type > 19 LIMIT 1"); //usertypes higher as 19 have access
	}
	else //pupils and teachers
		{
		$result = mysql_query("SELECT username, password FROM $table_users 
			WHERE type != '20' AND type != '0' AND username = '" . $login['user'] . "' AND password = '" . $login['pass'] . "' LIMIT 1");
	}

	$results = mysql_num_rows($result);

	if ($results == '1')
	{
		$query = "SELECT id, type, initial, invalid_logins FROM $table_users WHERE username = '" . $login['user'] . "' LIMIT 1";
		$result = mysql_query($query) or die_script($query, mysql_error());
		$_SESSION['userid'] = mysql_result($result, 0, 'id');
		$_SESSION['user_type'] = mysql_result($result, 0, 'type');
		$is_initial_logon = mysql_result($result, 0, 'initial');
		$invalid_logins = mysql_result($result, 0, 'invalid_logins');
		unset ($query);
		unset ($result);

		if (($invalid_logins > 9) AND ($sas_config['use_encryption'] == 1))
		{
			print "<script language=\"Javascript\">
						   <!--
						   alert (\"" . $sas_lang['user_revoked'] . "\");
						   window.location = '$sas_config[url]$cmsdir/sendpw.php' ;
						   //-->
						   </script>";
			exit;
			return FALSE;
		}

		if (($is_initial_logon == 1) AND (!IsSet ($_POST['option'])))
		{ //force a new password
			session_unset();
			session_destroy();
			if ($type_of_user == "admin") //admin type users
			{
				header("Location: index.php?option=new_password&username=$login[user]");
			}
			else //teacher and pupils
				{
				print "<script language='javascript'>
								window.location = 'index.php?page=$page&section=$section&option=new_password&username=$login[user]'
								</script>";
			}
		}

		if ($_POST['option'] == "save_new_password")
		{
			if (($_POST['password_new1'] == $_POST['password_new2']) AND (strlen($_POST['password_new1']) > 3))
			{ //check if both password given are equal
				$password = md5($_POST[password_new1]);
				mysql_query("UPDATE $table_users SET password = '$password', invalid_logins = 0,
																 initial = 0 WHERE username = '" . $login['user'] . "'");
				print "<script language=\"Javascript\">
							   <!--
							   alert (\"" . $sas_lang['password_has_changed'] . "\");
							   //-->
							   </script>";
			}
			else //not equal return to renew password form.
				{
				session_unset();
				session_destroy();
				if ($type_of_user == "admin") //admin type users
				{
					header("Location: index.php?option=new_password&username=$login[user]&error=true");
				}
				else //teacher and pupils
					{
					print "<script language='javascript'>
										window.location = 'index.php?page=$page&section=$section&option=new_password&username=$login[user]&error=true'
										</script>";
				}
			}
		}

		if (($_SESSION['user_type'] == 2) or ($_SESSION['user_type'] == 22))
		{
			$_SESSION['usertype'] = "teacher";
		}

		if (($_SESSION['user_type'] == 1) or ($_SESSION['user_type'] == 21))
		{
			$_SESSION['usertype'] = "student";
		}

		$_SESSION['sessioncode'] = $check_sessioncode;
		mysql_query("UPDATE $table_users SET invalid_logins = 0 WHERE username = '" . $login['user'] . "'");

		return TRUE;
	}
	else // username and password don't match
		{
		mysql_query("UPDATE $table_users SET invalid_logins = invalid_logins + 1 WHERE username = '" . $login['user'] . "'");
		return FALSE;
	}
} // end of the 'verify_logon()' function

function anti_injection($user, $pass)
{
	global $sas_lang;
	# We'll first get rid of any special characters using a simple regex statement.
	# After that, we'll get rid of any SQL command words using a string replacment.
	$banlist = array (
		"insert",
		"select",
		"update",
		"delete",
		"distinct",
		"having",
		"truncate",
		"replace",
		"handler",
		"like",
		" as",
		" or",
		"procedure",
		"limit",
		"order by",
		"group by",
		" asc",
		"desc"
	);
	if (eregi("[a-zA-Z0-9]+", $user))
	{
		$user = trim(str_replace($banlist, '', strtolower($user)));
	}
	else
	{
		$user = NULL;
	}
	# Now to make sure the given password is an alphanumerical string
	# devoid of any special characters. 
	if (eregi("[a-zA-Z0-9]+", $pass))
	{
		$pass = trim(str_replace($banlist, '', strtolower($pass)));
	}
	else
	{
		$pass = NULL;
	}
	# Now to make an array so we can dump these variables into the SQL query.
	# If either user or pass is NULL (because of inclusion of illegal characters),
	# the whole script will stop dead in its tracks.
	$array = array (
		'user' => $user,
		'pass' => $pass
	);

	if (!in_array(NULL, $array))
	{
		return $array;
	}
}

function die_script($query, $error_message)
//function to display mysql error meesage
{
	//sometimes mysql gives back a blank error message and nothing is wrong
	//so ignore those.
	if (trim($error_message) != '')
	{
		print "<p><font color=\"red\">Mysql returned following error: </font><b>" . $error_message . "</b>
		         <font color=\"red\"><br>Query: </font><b>" . $query . "</b><p>";
	}
}

function is_empty_folder($dir)
//function to see if a given directory is empty
{
	if (is_dir($dir))
	{
		$dl = opendir($dir);
		if ($dl)
		{
			while ($name = readdir($dl))
			{
				if (!is_dir("$dir/$name"))
				{
					return false;
					break;
				}
			}
			closedir($dl);
		}
		return true;
	}
	else
		return true;
}

function random_code($size)
{
	// generate an random alphanumeric code $size positions long.
	$final_rand = "";
	srand((double) microtime() * 10000000);
	$alpha = array (
		"A",
		"B",
		"C",
		"D",
		"E",
		"F",
		"G",
		"H",
		"I",
		"J",
		"K",
		"L",
		"M",
		"N",
		"O",
		"P",
		"Q",
		"R",
		"S",
		"T",
		"U",
		"V",
		"X",
		"Y",
		"Z",
		"1",
		"2",
		"3",
		"4",
		"5",
		"6",
		"7",
		"8",
		"9",
		"0"
	);
	$rand_keys = array_rand($alpha, $size);
	for ($i = 0; $i <= $size -1; $i++)
	{
		$final_rand .= $alpha[$rand_keys[$i]];
	}
	return $final_rand;
}

function load_language($cmsdir, $path)
//function which load language file, first try if a changed by user
//language file exists, if not load the standard delivered S@S one.
{
	global $sas_lang, $sas_config;

	$lang_path = $cmsdir . "languages/" . $sas_config['language'] . "/" . $path . "/" . $sas_config['language'];

	if (file_exists($lang_path . "_user.php"))
	{
		include ($lang_path . "_user.php");
	}
	elseif (file_exists($lang_path . ".php"))
	{
		include ($lang_path . ".php");
	}
	else
	{
		include ("languages/EN/" . $path . "/EN.php");
	}

	return $sas_lang;
} // end of the 'load_language()' function

function remove_special_characters($string)
{
	# Remove spaces, apostrophe, exclamation marks  and replace them with underscore
	$str_from = " \'@!,\t\*?`\"";
	$str_to = str_repeat("_", strlen($str_from));
	return strtr(stripslashes($string), $str_from, $str_to);
} // end of the 'remove_special_characters()' function

function sas_move_uploaded_file($write_path, $file_name, $temp_file)
{
	# this function is called when move_uploaded_file() function is needed for a file upload
	# parameters: 
	# $write_path: path relative to the starnet directory eg. media/gallery
	# $file_name : the filename to be stored
	# $temp_file : the temporary filename of the upload.
	# check if $write_path contains ../ if so exit.
	# check if the file type is allowed to be uploaded.
	# remove special characters from filename.
	# upload file in the $write_path directory

	if (strpos($write_path, "../") === FALSE) //check if someone is trying to fool us.
	{
		global $db_server, $db_username, $db_password, $db_name, $table_configuration;
		mysql_connect("$db_server", "$db_username", "$db_password");
		mysql_select_db("$db_name");

		$query = "SELECT config_value FROM $table_configuration WHERE config_key='serverpath'";
		$result = mysql_query($query); //get the document root of the site
		$serverpath = mysql_result($result, 0);
		unset ($query);
		unset ($result);

		$query = "SELECT config_value FROM $table_configuration WHERE config_key='user_path'";
		$result = mysql_query($query); //get the directoryname of the cms
		$userpath = mysql_result($result, 0);
		unset ($query);
		unset ($result);

		// this array contains the allowed file type we allow to be uploaded.
		$valid_types = array (
			".jpg",
			".gif",
			".png",
			".bmp",
			".doc",
			".txt",
			".html",
			".htm",
			".mp3",
			".avi",
			".zip",
			".xls",
			".pdf",
			".rtf",
			".csv",
			".jpeg",
			".mpg",
			".mpeg",
			".swf",
			".fla",
			".ppt",
			".rar",
			""
		);

		//$file_type = strtolower(strstr($file_name, '.'));
		$pos = strrpos($file_name, "."); //get lst position of point
		$file_type = strtolower(substr($file_name, $pos)); //get the file extion from that point on.

		if (!in_array($file_type, $valid_types)) //check if file type is allowed.
		{
			print "<script language=\"Javascript\">
						   <!--
						   alert (\"This file type: $file_type is not allowed!\");
						   //-->
						   </script>";
			return FALSE;
		}
		$file_name = remove_special_characters($file_name); //we remove special characters from filename						

		if (strrpos($serverpath, '/') != strlen($serverpath) - 1)
		{
			$serverpath .= '/'; //add last slash if not present
		}

		if (substr($userpath, 0, 1) == "/")
		{
			$userpath = substr($userpath, 1); //strip first slash
		}

		$serverpath = $serverpath . $userpath . "/" . $write_path; //add the write_path to the serverpath		

		if (move_uploaded_file($temp_file, $serverpath . "/" . $file_name))
		{
			// set permission  file bits
			@ chmod($serverpath . "/" . $file_name, 0644);
			return TRUE;
		}
		else
		{
			print "<script language=\"Javascript\">
						   <!--
						   alert (\"File upload error!\");
						   //-->
						   </script>";
			return FALSE;
		}
	}
} // end of the 'sas_move_uploaded()' function

function delete_files($target)
{
	//function which deletes files and directories from the pupils directory
	//is called when a pupil, project or teacher is deleted from the system

	global $sas_config;

	$exceptions = array (
		".",
		".."
	); //skip those

	$sas_path = $sas_config['serverpath'] . $sas_config['user_path'] . "/studentpages/";
	$dh = opendir($sas_path . $target);

	while (false !== ($file_name = readdir($dh)))
	{
		if (!in_array($file_name, $exceptions))
		{
			if (is_dir($sas_path . $target . "/" . $file_name))
			{
				// recurse subdirectory; call of function recursive
				delete_files($target . "/" . $file_name, $exceptions);
				rmdir($sas_path . $target . "/" . $file_name);
			}
			else
				if (is_file($sas_path . $target . "/" . $file_name))
				{
					// unlink file
					unlink($sas_path . $target . "/" . $file_name);
				}
		}
	}

	closedir($dh);
	return true;
} // end of the 'delete_files()' function
?>