<?PHP

/***********************************************************************
** Title.........:	Image Manager, draws the thumbnails and directories
** Version.......:	1.01
** Author........:	Xiang Wei ZHUO <wei@zhuo.org>
** Filename......:	images.php
** Last changed..:	8 Mar 2003 

                    Functions
                     - create a new folder,
                     - upload new image
                     
                    Last changed by Fred Stuurman (fc.stuurman@hccnet.nl)
#$Id: images.php,v 1.1 2006/10/03 12:27:15 fstuurman Exp $
                    04-07-2006 , to make it work with Site@School 2.4.02
***********************************************************************/
include ("../../../configuration/database.inc.php"); // connecting to database
mysql_connect("$db_server", "$db_username", "$db_password");
mysql_select_db("$db_name");

require ("../../../core/session.php"); //build a session
require ("../../../core/common.inc.php"); //common fuctions

$query = "SELECT config_value FROM $table_configuration WHERE config_key='sessioncode'";
if ($result = mysql_query($query))
{
	$check_sessioncode = mysql_result($result, 0);
	unset ($query);
	unset ($result);
}
if ($_SESSION['sessioncode'] != "$check_sessioncode")
{
	//if we don't have a session present the login screen
	Header("Location: ../../../index.php");
	exit;
}

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

$query = "SELECT config_value FROM $table_configuration WHERE config_key='serverpath'";
$result = mysql_query($query) or die_script(mysql_error());
$server_path = mysql_result($result, 0);
if (strrpos($server_path, '/') != strlen($server_path) - 1)
{
	$server_path .= '/';
} //add last slash if not present
unset ($query);
unset ($result);

$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);

$query = "SELECT config_value FROM $table_configuration WHERE config_key='media_dir'";
$result = mysql_query($query) or die_script(mysql_error());
$media = mysql_result($result, 0);
unset ($query);
unset ($result);
//print "Serverpath: ".$server_path." Userpath: ".$user_path ;

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

$BASE_DIR = $server_path;
$BASE_ROOT = $user_path . '/' . $media;
$BASE_URL .= '/';
$IMG_ROOT = $BASE_ROOT;

if (isset ($_GET['dir']))
{
	$dirParam = $_GET['dir'];

	if (strlen($dirParam) > 0)
	{
		if (substr($dirParam, 0, 1) == '/')
			$IMG_ROOT .= $dirParam;
		else
			$IMG_ROOT = $dirParam;
	}
}

$refresh_dirs = false;
$clearUploads = false;

if (strrpos($IMG_ROOT, '/') != strlen($IMG_ROOT) - 1)
	$IMG_ROOT .= '/';

if (isset ($_GET['create']) && isset ($_GET['dir']))
{
	create_folder();
}

if (isset ($_FILES['upload']) && is_array($_FILES['upload']) && isset ($_POST['dirPath']))
{

	$dirPathPost = $_POST['dirPath'];
	if (strlen($dirPathPost) > 0)
	{
		if (substr($dirPathPost, 0, 1) == '/')
		{
			$IMG_ROOT .= $dirPathPost;
		}
		else
			$IMG_ROOT = $dirPathPost;
	}

	if (strrpos($IMG_ROOT, '/') != strlen($IMG_ROOT) - 1)
		$IMG_ROOT .= '/';

	do_upload($_FILES['upload'], $media . $dirPathPost);
}

function dir_name($dir)
{
	$lastSlash = intval(strrpos($dir, '/'));
	if ($lastSlash == strlen($dir) - 1)
	{
		return substr($dir, 0, $lastSlash);
	}
	else
		return dirname($dir);
}

function do_upload($file, $dest_dir)
{
	global $clearUploads;

	if (is_file($file['tmp_name']))
	{
		$file_name = $file['name'];
		sas_move_uploaded_file($dest_dir, $file_name, $file['tmp_name']);
		//move_uploaded_file($file['tmp_name'], $dest_dir.$file_name);
	}

	$clearUploads = true;
}

function create_folder()
{
	global $BASE_DIR, $IMG_ROOT, $refresh_dirs;

	$folder_name = $_GET['foldername'];

	if (strlen($folder_name) > 0)
	{
		$folder = $BASE_DIR . $IMG_ROOT . $folder_name;

		if (!is_dir($folder) && !is_file($folder))
		{
			mkdir($folder, 0755);
			$refresh_dirs = true;
		}
	}
}

function num_files($dir)
{
	$total = 0;

	if (is_dir($dir))
	{
		$d = @ dir($dir);

		while (false !== ($entry = $d->read()))
		{
			//echo $entry."<br>";
			if (substr($entry, 0, 1) != '.')
			{
				$total++;
			}
		}
		$d->close();
	}
	return $total;
}

function dirs($dir, $abs_path)
{
	$d = dir($dir);
	//echo "Handle: ".$d->handle."<br>\n";
	//echo "Path: ".$d->path."<br>\n";
	$dirs = array ();
	while (false !== ($entry = $d->read()))
	{
		if (is_dir($dir . '/' . $entry) && substr($entry, 0, 1) != '.')
		{
			//dirs($dir.'/'.$entry, $prefix.$prefix);
			//echo $prefix.$entry."<br>\n";
			$path['path'] = $dir . '/' . $entry;
			$path['name'] = $entry;
			$dirs[$entry] = $path;
		}
	}
	$d->close();

	ksort($dirs);
	for ($i = 0; $i < count($dirs); $i++)
	{
		$name = key($dirs);
		$current_dir = $abs_path . '/' . $dirs[$name]['name'];
		echo ", \"$current_dir\"\n";
		dirs($dirs[$name]['path'], $current_dir);
		next($dirs);
	}
}

function parse_size($size)
{
	if ($size < 1024)
		return $size . ' btyes';
	else
		if ($size >= 1024 && $size < 1024 * 1024)
		{
			return sprintf('%01.2f', $size / 1024.0) . ' Kb';
		}
		else
		{
			return sprintf('%01.2f', $size / (1024.0 * 1024)) . ' Mb';
		}
}

function show_image($img, $file, $info, $size)
{
	global $BASE_DIR, $BASE_URL, $newPath;

	$img_path = dir_name($img);
	$img_file = basename($img);

	$img_url = $BASE_URL . $img_path . '/' . $img_file;

	$filesize = parse_size($size);
?> 
<td>
<table width="102" border="0" cellpadding="0" cellspacing="2">
  <tr> 
    <td align="center" class="imgBorder" onMouseOver="pviiClassNew(this,'imgBorderHover')" onMouseOut="pviiClassNew(this,'imgBorder')">
	<a href="javascript:;" onClick="javascript:imageSelected('<?PHP echo $img_url; ?>');"><img src="<?PHP echo $img_url; ?>" width="50" height="50" alt="<?PHP echo $file; ?> - <?PHP echo $filesize; ?>" border="0"></a>
  <br><font size="2"><?PHP echo $file; ?></font></td>
  </tr>
</table>
</td>
<?PHP

}

function show_dir($path, $dir)
{
	global $newPath, $BASE_DIR, $BASE_URL;

	$num_files = num_files($BASE_DIR . $path);
?>
<td>
<table width="102" border="0" cellpadding="0" cellspacing="2">
  <tr> 
    <td align="center" class="imgBorder" onMouseOver="pviiClassNew(this,'imgBorderHover')" onMouseOut="pviiClassNew(this,'imgBorder')">
	  <a href="images.php?dir=<?PHP echo $path; ?>" onClick="changeLoadingStatus('load')">
		<img src="../graphics/folder.gif" width="50" height="50" border=0 alt="<?PHP echo $dir; ?>"></a><br><font size="2"><?PHP echo $dir; ?></font>
	</td>
  </tr>

</table>
</td>
<?PHP

}

function draw_no_results($emptydir)
{
?>
<table width="100%" height="100%" border="0" cellpadding="0" cellspacing="0">
  <tr>
    <td><div align="center" style="font-size:large;font-weight:bold;color:#CCCCCC;font-family: Helvetica, sans-serif;"><?PHP echo $emptydir ?></div></td>
  </tr>
</table>
<?PHP
}

function draw_no_dir()
{
	global $BASE_DIR, $BASE_ROOT;
?>
<table width="100%" height="100%" border="0" cellpadding="0" cellspacing="0">
  <tr>
    <td><div align="center" style="font-size:small;font-weight:bold;color:#CC0000;font-family: Helvetica, sans-serif;">Configuration Problem: &quot;<?PHP echo $BASE_DIR.$BASE_ROOT; ?>&quot; does not exist.</div></td>
  </tr>
</table>
<?PHP

}

function draw_table_header()
{
	echo '<table border="0" cellpadding="0" cellspacing="2">';
	echo '<tr>';
}

function draw_table_footer()
{
	echo '</tr>';
	echo '</table>';
}
?>
<html>
<head>
<title>Untitled Document</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<style type="text/css">
<!--
.imgBorder {
	height: 96px;
	border: 1px solid threedface;
	vertical-align: middle;
}
.imgBorderHover {
	height: 96px;
	border: 1px solid threedface;
	vertical-align: middle;
	background: #FFFFCC;
	cursor: hand;
}

.buttonHover {
	border: 1px solid;
	border-color: ButtonHighlight ButtonShadow ButtonShadow ButtonHighlight;
	cursor: hand;
	background: #FFFFCC;
}
.buttonOut
{
 border: 1px solid;
 border-color: white;
}

.imgCaption {
	font-size: 9pt;
	font-family: "MS Shell Dlg", Helvetica, sans-serif;
	text-align: center;
}
.dirField {
	font-size: 9pt;
	font-family: "MS Shell Dlg", Helvetica, sans-serif;
	width:110px;
}

-->
</style>
<?PHP

$dirPath = eregi_replace($BASE_ROOT, '', $IMG_ROOT);
$paths = explode('/', $dirPath);
$upDirPath = '/';
for ($i = 0; $i < count($paths) - 2; $i++)
{
	$path = $paths[$i];
	if (strlen($path) > 0)
	{
		$upDirPath .= $path . '/';
	}
}

$slashIndex = strlen($dirPath);
$newPath = $dirPath;

if ($slashIndex > 1 && substr($dirPath, $slashIndex -1, $slashIndex) == '/')
{
	$newPath = substr($dirPath, 0, $slashIndex -1);
}
?>

<script language="JavaScript" type="text/JavaScript">
<!--
function pviiClassNew(obj, new_style) { //v2.6 by PVII
  obj.className=new_style;
}

function goUp() 
{
	location.href = "images.php?dir=<?PHP echo $upDirPath; ?>";
}

function changeDir(newDir) 
{
	location.href = "images.php?dir="+newDir;
}

function newFolder(oldDir, newFolder) 
{
	location.href = "images.php?dir="+oldDir+'&create=folder&foldername='+newFolder;
}

function updateDir() 
{
	var newPath = "<?PHP echo $newPath; ?>";
	var allPaths = window.top.document.forms[0].dirPath.options;
	if(newPath.substr(0,2) == '//')         //strip one slash
  {
  newPath = newPath.substr(1,newPath.length) ;
  }
	//alert("new:"+newPath);
	for(i=0; i<allPaths.length; i++) 
	{
		//alert(allPaths.item(i).value);
		allPaths.item(i).selected = false;
		if((allPaths.item(i).value)==newPath) 
		{
			allPaths.item(i).selected = true;
		}
	}

<?PHP

if ($clearUploads)
{
?>
	var topDoc = window.top.document.forms[0];
	topDoc.upload.value = null;
	//topDoc.upload.disabled = true;
<?PHP
}
?>

}

<?PHP if ($refresh_dirs) { ?>
function refreshDirs() 
{
	var allPaths = window.top.document.forms[0].dirPath.options;
	var fields = ["/" <?PHPdirs($BASE_DIR.$BASE_ROOT,'');?>];

	var newPath = "<?PHP echo $newPath; ?>";

	while(allPaths.length > 0) 
	{
		for(i=0; i<allPaths.length; i++) 
		{
			allPaths.remove(i);	
		}		
	}

	for(i=0; i<fields.length; i++) 
	{
		var newElem =	document.createElement("OPTION");
		var newValue = fields[i];
		newElem.text = newValue;
		newElem.value = newValue;

		if(newValue == newPath) 
			newElem.selected = true;	
		else
			newElem.selected = false;

		allPaths.add(newElem);
	}
}
refreshDirs();
<?PHP } ?>

function imageSelected(filename) 
{
	var topDoc = window.top.document.forms[0];
	topDoc.f_url.value = filename;	
}

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_showHideLayers() { //v6.0
  var i,p,v,obj,args=MM_showHideLayers.arguments;
  for (i=0; i<(args.length-2); i+=3) if ((obj=MM_findObj(args[i],window.top.document))!=null) { v=args[i+2];
    if (obj.style) { obj=obj.style; v=(v=='show')?'visible':(v=='hide')?'hidden':v; }
    obj.visibility=v; }
}

function changeLoadingStatus(state) 
{
	var statusText = null;
	if(state == 'load') {
		statusText = '<?PHP echo $sas_lang['load_images'] ?>';
	}
	else if(state == 'upload') {
		statusText = '<?PHP echo $sas_lang['upload_images'] ?>';
	}
	if(statusText != null) {
		var obj = MM_findObj('loadingStatus', window.top.document);
		obj.innerHTML = statusText;
		MM_showHideLayers('loading','','show')		
	}
}

//-->
</script>
</head>
<body onLoad="updateDir();" bgcolor="white">

<?PHP

//var_dump($_GET);
//echo $dirParam.':'.$upDirPath;
//echo '<br>';
$IMG_ROOT = ereg_replace("//", "/", $IMG_ROOT); // strip an extra slash from the image root
$d = @ dir($BASE_DIR . $IMG_ROOT);

if ($d)
{
	//var_dump($d);
	$images = array ();
	$folders = array ();
	while (false !== ($entry = $d->read()))
	{
		$img_file = $IMG_ROOT . $entry;

		if (is_file($BASE_DIR . $img_file))
		{
			$image_info = @ getimagesize($BASE_DIR . $img_file);
			if (is_array($image_info))
			{
				$file_details['file'] = $img_file;
				$file_details['img_info'] = $image_info;
				$file_details['size'] = filesize($BASE_DIR . $img_file);
				$images[$entry] = $file_details;
				//show_image($img_file, $entry, $image_info);
			}
		}
		else
			if (is_dir($BASE_DIR . $img_file) && substr($entry, 0, 1) != '.')
			{
				$folders[$entry] = $img_file;
				//show_dir($img_file, $entry);	
			}
	}
	$d->close();
	$counter = 1;
	if (count($images) > 0 || count($folders) > 0)
	{
		//now sort the folders and images by name.
		ksort($images);
		ksort($folders);

		draw_table_header();

		for ($i = 0; $i < count($folders); $i++)
		{
			if ($counter == 6) //next row
			{
				print "</tr><tr>";
				$counter = 1;
			}
			$folder_name = key($folders);
			show_dir($folders[$folder_name], $folder_name);
			next($folders);
			$counter++;
		}

		for ($i = 0; $i < count($images); $i++)
		{
			if ($counter == 6) //next row
			{
				print "</tr><tr>";
				$counter = 1;
			}
			$image_name = key($images);

			show_image($images[$image_name]['file'], $image_name, $images[$image_name]['img_info'], $images[$image_name]['size']);
			next($images);
			$counter++;
		}
		draw_table_footer();
	}
	else
	{
		draw_no_results($sas_lang['emptydir']);
	}
}
else
{
	draw_no_dir();
}
?>
<script language="JavaScript" type="text/JavaScript">
MM_showHideLayers('loading','','hide')
</script>
</body>
</html>