<?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)
############################################################################
# images.php: last changed 04/10/2006  , version: 2.4.10
#            by Fred Stuurman  (fc.stuurman@hccnet.nl)
#$Id: images.php,v 1.2 2006/10/15 19:08:54 fstuurman Exp $
# this file is part of the FCK filemanager created for S@S
############################################################################
#                        LICENSE INFORMATION
# Copyright (C) 2002 - 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.
##############################################################################
define('IN_SAS', true);

//config of the script
$hide_files = array (
	"^\zz_"
); //hide the thumbnails
$create_thumbs = TRUE; //if you don't want thumbs change to FALSE

include ("../../../../../configuration/database.inc.php"); // connecting to database
mysql_connect("$db_server", "$db_username", "$db_password");
mysql_select_db("$db_name");

include ("../../../../../core/common.inc.php");
include ("../../../../../core/session.php");

if ($_SESSION['type'] == "flash")
{
	$allowed_extensions = array (
		"swf",
		"fla"
	);
}
elseif ($_SESSION['type'] == "link")
{
	$allowed_extensions = array (
		"zip",
		"doc",
		"xls",
		"pdf",
		"rtf",
		"csv",
		"jpg",
		"gif",
		"jpeg",
		"png",
		"avi",
		"mpg",
		"mpeg",
		"swf",
		"fla",
		"mp3",
		"txt",
		"htm",
		"html",
		"csv"
	);
}
elseif ($_SESSION['type'] == "image")
{
	$allowed_extensions = array (
		"jpg",
		"gif",
		"jpeg",
		"png",
		"tiff",
		"tif",
		"bmp"
	);
}
else
{
	$allowed_extensions = "";
}

$query = "SELECT config_value FROM $table_configuration WHERE config_key='serverpath'";
$result = mysql_query($query) or die_script(mysql_error());
$sas_basedir = mysql_result($result, 0);

$query = "SELECT config_value FROM $table_configuration WHERE config_key='user_path'";
$result = mysql_query($query) or die_script(mysql_error());
$user_path = mysql_result($result, 0);
if (substr($user_path, 0, 1) == "/")
{
	$user_path = substr($user_path, 1); //strip first slash
}
unset ($query);
unset ($result);

if (IsSet ($_SESSION['editpage']))
{
	//when editpage is set we are a pupil or teacher coming using the studenteditor
	//give him/her personal directory

	$query = "SELECT config_value FROM $table_configuration WHERE config_key='studentpages_dir'";
	$result = mysql_query($query) or die_script(mysql_error());
	$studentpages = mysql_result($result, 0);
	unset ($query);
	unset ($result);
	$query = "SELECT dir_number FROM $table_studentpages WHERE studentid = '$_SESSION[editpage]'";
	$result = mysql_query($query) or die_script(mysql_error());
	if (mysql_num_rows($result) > 0)
	{
		$dir_number = mysql_result($result, 0); //directory number for the project or pupil
		unset ($query);
		unset ($result);
		// Path to user files relative to the document root.
		$user_path .= "/" . $studentpages . "/" . $dir_number;
		$_SESSION['user_media_path'] = $studentpages . "/" . $dir_number;
	}
}
elseif (($_SESSION['user_type'] == '20') OR ($_SESSION['user_type'] == '22') OR ($_SESSION['user_type'] == '21'))
{
	//we have admin users in S@S admin , present the media directory.
	$user_path .= "/media";
	$_SESSION['user_media_path'] = "media";
}
else
{
	exit; //we don't have a session 
}

$query = "SELECT name FROM $table_users WHERE id = '$_SESSION[userid]'";
$result = mysql_query($query) or die_script(mysql_error());
$user_name = mysql_result($result, 0);

//load language file
$query = "SELECT config_value FROM $table_configuration WHERE config_key = 'language'";
$result = mysql_query($query) or die_script(mysql_error());
$language = mysql_result($result, 0);
include ("../../../../../languages/$language/$language.php");

if (IsSet ($_GET['opendir']))
{
	$user_path = $user_path . $_GET['opendir'] . "/";
	$opendir = $_GET['opendir'];

	if (strpos($opendir, "../") !== false)
	{
		die("Hacking attempt");
	}

	$prev_opendir = dir_name($opendir); //previous opened directory
	$_SESSION['opendir'] = $_GET['opendir']; //this session var is used by browser.php
}
else
{
	$opendir = ""; //make sure its cleared 
}

if (IsSet ($_GET['delete_file']))
{

	$delete_file = $_GET['delete_file'];
	if (strpos($delete_file, "../") !== false)
	{
		die("Hacking attempt");
	}

	$file = $sas_basedir . $user_path . $delete_file;

	if (file_exists($file)) //if file exists, delete it.
	{
		unlink($file);
	}

	$thumbfile = $sas_basedir . $user_path . 'zz_thumb_' . $delete_file;

	if (file_exists($thumbfile)) //if thumb exists, delete it.
	{
		unlink($thumbfile);
	}
}

if (substr($user_path, -2) == "//") //prevent double slash
{
	$user_path = substr($user_path, 0, -1);
}
?>
<html>
	<head>
		<title><?PHP echo $sas_lang['insert_picture'] ?></title>

<style type="text/css">
<!--
body, td, input, select
{
	margin:0px; padding:0px;
	font-size: 11px;
	font-family: 'Microsoft Sans Serif' , Arial, Helvetica, Verdana;
}

A:link {color: #000000; text-decoration: none}

A:active {color: #000000; text-decoration: none}

A:visited {color: #000000; text-decoration: none}

A:hover {color: #07367a; text-decoration: none}

.imgBorder {
	height: 110px;
	border: 1px solid threedface;
	vertical-align: middle;
}

.imgBorderHover {
	height: 110px;
	border: 1px solid threedface;
	vertical-align: middle;
	background: #FFFFCC;
	cursor: hand;
}

.title { background: #ddf; color: #000; font-weight: bold; font-size: 120%; padding: 3px 10px; margin-bottom: 10px;
border-bottom: 1px solid black; letter-spacing: 2px;

}
-->
</style>
</head>
<body>
<script type="text/javascript">
        
function SelectFile( fileUrl )
{
        parent.window.opener.SetUrl( fileUrl ) ;
        parent.window.close() ;
}

</script>
<?php

print "<table cellspacing=\"2\" cellpadding=\"0\" width=\"100%\" border=\"0\">
		<tr><td colspan=\"6\">" . $sas_lang['username'] . ": <b>" . $user_name . "</b> - " . $sas_lang['directory'] . "&nbsp;<b>" . $user_path . "</b></td></tr><tr>\n";

//define arrays were file and directories are stored
$files = array ();
$dirs = array ();

if ($dh = opendir($sas_basedir . $user_path))
{
	while (($filename = readdir($dh)) !== false) //read the directory via file handle
	{
		if (($filename != ".") && ($filename != "..")) //skip those
		{
			if (is_dir($sas_basedir . $user_path . "$filename")) //is entry a directory
			{
				array_push($dirs, $filename);
			}
			else //entry is a file 
				{
				$lastdot = strrpos($filename, ".");
				$ext = (($lastdot !== false) ? (substr($filename, $lastdot +1)) : "");
				$hide = false;

				for ($j = 0; $j < sizeof($hide_files); $j++)
					$hide = (ereg($hide_files[$j], $filename) ? true : $hide);

				if ((in_array(strtolower($ext), $allowed_extensions)) AND (!$hide)) //allowed file type and not hidden
				{
					array_push($files, $filename);
				}
			}
		}
	}
	closedir($dh);
}
//sort the dirs and files arrays
$array_lowercase = array_map('strtolower', $dirs);
array_multisort($array_lowercase, SORT_ASC, SORT_STRING, $dirs);
$array_lowercase = array_map('strtolower', $files);
array_multisort($array_lowercase, SORT_ASC, SORT_STRING, $files);

//list the directories
$i = 0;
if (($_GET['opendir'] != "/") AND ($_GET['opendir'] != ""))
{
	//create a return icon for previous directory
	print "<td width=\"20%\" align=\"center\" class=\"imgBorder\">
			<a href=\"images.php?opendir=" . $prev_opendir . "\"><img src=\"graphics/previous.png\" border=\"0\"><br>" . $sas_lang['goback'] . " ..</a></td>\n";
	$i++;
}

foreach ($dirs as $value) //list the directory array
{
	if ($_GET['opendir'] != "/")
	{
		$path = $_GET[opendir] . "/" . $value;
	}
	else
	{
		$path = $value;
	}
	if (substr($path, 0, 1) != "/") //check if first pos is a slash, if not add it.
	{
		$path = "/" . $path;
	}
	print "<td width=\"20%\" align=\"center\" class=\"imgBorder\">
			<a href=\"images.php?opendir=$path\"><img src=\"graphics/folder.gif\" border=\"0\"><br>" . $value . "</a></td>\n";
	$i++;

	if ($i == 5)
	{
		print "</tr><tr>";
		$i = 0;
	}

}

// print empty cells if needed.
for ($k = $i; $k <= 4; $k++)
{
	echo "<td width=\"20%\">&nbsp;</td>";
}

if ($i < 4)
{
	print "</tr>";
}

//list the files
$i = 0;

print "<tr>";
foreach ($files as $value) //list the files array
{
	$tmp = explode(".", $value); //get the picture extention.
	$ext = array_pop($tmp);
	$thumb = FALSE;

	if ((strtoupper($ext) == "PNG") or (strtoupper($ext) == "GIF") or (strtoupper($ext) == "JPG"))
	{
		$image_array = makethumb($value);
		$image_file = "/" . $user_path . $image_array[0];
		$thumb = $image_array[1];
	}
	elseif ((strtoupper($ext) == "DOC") or (strtoupper($ext) == "TXT"))
	{
		$image_file = "graphics/document.jpg";
	}
	elseif (strtoupper($ext) == "XLS")
	{
		$image_file = "graphics/spreadsheet.jpg";
	}
	elseif ((strtoupper($ext) == "SWF") or (strtoupper($ext) == "FLA") or (strtoupper($ext) == "MPG") or (strtoupper($ext) == "AVI") or (strtoupper($ext) == "MPEG"))
	{
		$image_file = "graphics/video.jpg";
	}
	elseif (strtoupper($ext) == "PDF")
	{
		$image_file = "graphics/pdf.jpg";
	}
	elseif (strtoupper($ext) == "MP3")
	{
		$image_file = "graphics/sound.jpg";
	}
	elseif ((strtoupper($ext) == "HTML") or (strtoupper($ext) == "HTM"))
	{
		$image_file = "graphics/html.jpg";
	}
	elseif (strtoupper($ext) == "ZIP")
	{
		$image_file = "graphics/tar.jpg";
	}
	else
	{
		$image_file = "graphics/binary.jpg";
	}

	print "<td align=\"center\" class=\"imgBorder\" width=\"96\" height=\"96\"><a href=\"javascript:SelectFile('/" . $user_path . $value . "');\">";

	if ($thumb == TRUE)
	{
		print "<img src=\"" . $image_file . "\" border=\"0\" alt=\"$value\" title=\"$value\"></a><br>\n" . $value . "<br>";
	}
	else
	{
		print "<img src=\"" . $image_file . "\" width=\"96\" height=\"96\" border=\"0\" alt=\"$value\" title=\"$value\"></a><br>\n" . $value . "<br>";
	}

	if (IsSet ($_GET['opendir'])) //if we are in a subdirectory we need to add it to the link
	{
		$delete_link = "images.php?opendir=" . $_GET['opendir'] . "&delete_file=" . $value;
	}
	else
	{
		$delete_link = "images.php?delete_file=" . $value;
	}

	print "<img border=\"0\" src=\"graphics/delete.gif\" width=\"16\" height=\"16\" alt=\"" . $sas_lang['delete'] . "\" title=\"" . $sas_lang['delete'] . "\"
				onClick=\"if(confirm('" . $sas_lang['delete_file_confirmation'] . "')) parent.images.location='$delete_link';\"></a></td>\n";
	$i++;
	if ($i == 5)
	{
		print "</tr><tr>";
		$i = 0;
	}
}

if ($i > 0)
{
	for ($k = $i; $k <= 4; $k++)
	{
		echo "<td width=\"20%\">&nbsp;</td>";
	}
}

if ($i < 4)
{
	print "</tr>";
}

print "</table>";
print "</body>
</html>";

function MakeThumb($image)
{
	#function to create a thumbnail for faster loading.
	global $create_thumbs, $user_path, $sas_basedir;

	$thumbfile = $sas_basedir . $user_path . "zz_thumb_" . $image;

	if (file_exists($thumbfile))
	{
		// thumbnail exists just return its name, $thumb is TRUE
		return array (
			"zz_thumb_" . $image,
			TRUE
		);
	}

	if ($create_thumbs == TRUE)
	{
		if (function_exists('imagecreatetruecolor'))
		{
			// use gdlib to resize images      
			$size = getimagesize($sas_basedir . $user_path . $image);
			$x = $size[0];
			$y = $size[1];

			if (($x < 150) AND ($y < 150)) //only make thumb when bigger then 150 pixels
			{
				return array (
					$image,
					TRUE
				);
			}

			if ($x < $y)
			{
				$newy = 96;
				$newx = $x / ($y / 96);
			}
			else
			{
				$newx = 96;
				$newy = $y / ($x / 96);
			}

			$tmp = explode(".", $image); //get the picture extention.
			$ext = array_pop($tmp);

			if (strtoupper($ext) == "JPG")
			{
				$src_img = @imagecreatefromjpeg($sas_basedir . $user_path . $image);
				$dst_img = @ImageCreateTrueColor($newx, $newy);
				@ imagecopyresampled($dst_img, $src_img, 0, 0, 0, 0, $newx, $newy, $x, $y);
				@ imagejpeg($dst_img, $thumbfile, "100");
				@ imagedestroy($src_img);
				@ imagedestroy($dst_img);
				if (file_exists($thumbfile))
				{
					//we have a thumb, $thumb is TRUE
					return array (
						"zz_thumb_" . $image,
						TRUE
					);
				}
				else
				{
					//we don't have a thumb, $thumb is FALSE
					return array (
						$image,
						FALSE
					);
				}
			}
			elseif (strtoupper($ext) == "PNG")
			{
				$src_img = @imagecreatefrompng($sas_basedir . $user_path . $image);
				$dst_img = @ImageCreateTrueColor($newx, $newy);
				@ imagecopyresampled($dst_img, $src_img, 0, 0, 0, 0, $newx, $newy, $x, $y);
				@ imagepng($dst_img, $thumbfile, "9"); //changed for php 5.x from 100 -> 9
				@ imagedestroy($src_img);
				@ imagedestroy($dst_img);
				if (file_exists($thumbfile))
				{
					//we have a thumb, $thumb is TRUE
					return array (
						"zz_thumb_" . $image,
						TRUE
					);
				}
				else
				{
					//we don't have a thumb, $thumb is FALSE
					return array (
						$image,
						FALSE
					);
				}
			}
			elseif (strtoupper($ext) == "GIF")
			{
				if (function_exists('imagecreatefromgif'))
				{
					$src_img = @imagecreatefromgif($sas_basedir . $user_path . $image);
					$dst_img = @ImageCreateTrueColor($newx, $newy);
					@ imagecopyresampled($dst_img, $src_img, 0, 0, 0, 0, $newx, $newy, $x, $y);
					@ imagegif($dst_img, $thumbfile, "100");
					@ imagedestroy($src_img);
					@ imagedestroy($dst_img);
					if (file_exists($thumbfile))
					{
						//we have a thumb, $thumb is TRUE
						return array (
							"zz_thumb_" . $image,
							TRUE
						);
					}
					else
					{
						//we don't have a thumb, $thumb is FALSE
						return array (
							$image,
							FALSE
						);
					}
				}
			}
			else
			{
				//we don't have a thumb, $thumb is FALSE
				return array (
					$image,
					FALSE
				);
			}
		}
		else
		{
			//we don't have a thumb, $thumb is FALSE
			return array (
				$image,
				FALSE
			);
		}
	}
	else
	{
		return array (
				$image,
				FALSE
			);
	}
}

function dir_name($dir)
{
	# strip the last directory to be able to jump back to the previous directory.
	$lastSlash = intval(strrpos($dir, '/'));

	if ($lastSlash == 0)
	{
		return "/";
	}
	else
		return dirname($dir);
}
?>
