<?php // $Id: fileDisplay.lib.php,v 1.9.2.2 2005/08/09 08:08:11 bmol Exp $ 
/*
vim: set expandtab tabstop=4 shiftwidth=4:
============================================================================== 
	Dokeos - elearning and course management software
	
	Copyright (c) 2004 Dokeos S.A.
	Copyright (c) 2003 University of Ghent (UGent)
	Copyright (c) 2001 Universite catholique de Louvain (UCL)
	
	For a full list of contributors, see "credits.txt".
	The full license can be read in "license.txt".
	
	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.
	
	See the GNU General Public License for more details.
	
	Contact: Dokeos, 181 rue Royale, B-1000 Brussels, Belgium, info@dokeos.com
============================================================================== 
*/
/**
============================================================================== 
*	This is the file display library for Dokeos.
*	Include/require it in your code to use its functionality.
*
*	@package dokeos.library
============================================================================== 
*/


/*
============================================================================== 
		GENERIC FUNCTIONS : FOR OLDER PHP VERSIONS
============================================================================== 
*/

if ( ! function_exists('array_search') )
{
	/**
	 * Searches haystack for needle and returns the key
	 * if it is found in the array, FALSE otherwise
	 *
	 * Natively implemented in PHP since 4.0.5 version.
	 * This function is intended for previous version.
	 *
	 * @author - Hugues Peeters <peeters@ipm.ucl.ac.be>
	 * @param   - needle (mixed)
	 * @param   - haystack (array)
	 * @return  - array key or FALSE
	 *
	 * @see     - http://www.php.net/array_search
	 */

	function array_search($needle, $haystack)
	{
		while (list ($key, $val) = each ($haystack))
			if ($val == $needle )
				return $key;
		return false;
	}
}

/*
============================================================================== 
		FILE DISPLAY FUNCTIONS
============================================================================== 
*/ 

/**
 * Define the image to display for each file extension
 * This needs an existing image repository to works
 *
 * @author - Hugues Peeters <peeters@ipm.ucl.ac.be>
 * @param  - fileName (string) - name of a file
 * @retrun - the gif image to chose
 */

function choose_image($fileName)
{
	static $type, $image;

	/* TABLES INITILIASATION */

	if (!$type || !$image)
	{
		$type['word'      ] = array("doc", "dot", "rtf", "mcw", "wps");
		$type['web'       ] = array("htm", "html", "htx", "xml", "xsl", "php");
		$type['image'     ] = array("gif", "jpg", "png", "bmp", "jpeg");
		$type['audio'     ] = array("wav", "mid", "mp2", "mp3", "midi", "sib");
		$type['video'     ] = array("mp4", "mov", "rm", "pls", "mpg", "mpeg", "au");
		$type['excel'     ] = array("xls", "xlt", "xls", "xlt");
		$type['compressed'] = array("zip", "tar", "rar", "gz");
		$type['code'      ] = array("js", "cpp", "c", "java");
		$type['acrobat'   ] = array("pdf");
		$type['powerpoint'] = array("ppt");
		$type['flash'] = array("fla","swf");
		$type['texte'] = array("txt");


		$image['word'      ] = "doc.gif";
		$image['web'       ] = "html.gif";
		$image['image'     ] = "gif.gif";
		$image['audio'     ] = "wav.gif";
		$image['video'     ] = "video.gif";
		$image['excel'     ] = "xls.gif";
		$image['compressed'] = "zip.gif";
		$image['code'      ] = "txt.gif";
		$image['acrobat'   ] = "pdf.gif";
		$image['powerpoint'] = "ppt.gif";
		$image['flash'] = "flash.gif";
		$image['texte'] = "txt.gif";

	}

	/* FUNCTION CORE */

	if (ereg("\.([[:alnum:]]+)$", $fileName, $extension))
	{
		$extension[1] = strtolower ($extension[1]);

		foreach( $type as $genericType => $typeList)
		{
			if (in_array($extension[1], $typeList))
			{
				return$image[$genericType];
			}
		}
	}

	return "defaut.gif";
}

//------------------------------------------------------------------------------

/**
 * Transform the file size in a human readable format
 *
 * @author - ???
 * @param  - fileSize (int) - size of the file in bytes
 */

function format_file_size($fileSize)
{
	if($fileSize >= 1073741824)
	{
		$fileSize = round($fileSize / 1073741824 * 100) / 100 . "g";
	}
	elseif($fileSize >= 1048576)
	{
		$fileSize = round($fileSize / 1048576 * 100) / 100 . "m";
	}
	elseif($fileSize >= 1024)
	{
		$fileSize = round($fileSize / 1024 * 100) / 100 . "k";
	}
	else
	{
		$fileSize = $fileSize . "b";
	}

	return $fileSize;
}

//------------------------------------------------------------------------------


/**
 * Transform a UNIX time stamp in human readable format date
 *
 * @author - Hugues Peeters <peeters@ipm.ucl.ac.be>
 * @param - date - UNIX time stamp
 */

function format_date($fileDate)
{
	return date("d.m.Y", $fileDate);
}

//------------------------------------------------------------------------------


/**
 * Transform the file path in a url
 *
 * @param - filePaht (string) - relative local path of the file on the Hard disk
 * @return - relative url
 */

function format_url($filePath)
{
	$stringArray = explode("/", $filePath);

	for ($i = 0; $i < sizeof($stringArray); $i++)
	{
		$stringArray[$i] = rawurlencode($stringArray[$i]);
	}

	return implode("/",$stringArray);
}

/**
 * Get the most recent time the content of a folder was changed
 *
 * @param - $dirName (string) - path of the dir on the Hard disk
 * @param - $dorecursive (bool) - transverse all folders in the folder?
 * @return - time the content of the folder was changed
 */
function recent_modified_file_time($dirName,$doRecursive=1) {
   $d = dir($dirName);
   $lastModified = 0;
   while($entry = $d->read()) {
       if ($entry != "." && $entry != "..") {
           if (!is_dir($dirName."/".$entry)) {
               $currentModified = filemtime($dirName."/".$entry);
           } else if ($doRecursive && is_dir($dirName."/".$entry)) {
               $currentModified = recent_modified_file_time($dirName."/".$entry,true);
           }
           if ($currentModified > $lastModified){
               $lastModified = $currentModified;
           }
       }
   }
   $d->close();
   //prevents returning 0 (for empty directories)
   return ($lastModified==0)?filemtime($dirName):$lastModified;
} 
//------------------------------------------------------------------------------

/**
 * Get the total size of a directory
 *
 * @param - $dirName (string) - path of the dir on the HD
 * @return - size in bytes
 */
function folder_size($dirName)
{
	if ($dh = opendir($dirName))
	{
		while (($filecnt = readdir($dh)) !== false) 
		{
			if($filecnt == "." || $filecnt == "..") 
			{
				continue;
			}
        	if(is_dir($dirName."/".$filecnt))
        	{
        		$size += folder_size($dirName."/".$filecnt);
        	}
        	else
        	{
        		$size += filesize($dirName."/".$filecnt);
        	}
		}
    }
	else
	{
	$size = 0;
	}
	//return 0 if empty.
    return ($size)?$size:0;
}

/**
 * Calculates the total size of a directory by adding the sizes (that
 * are stored in the DBase) of all files & folders in this directory
 *
 * @param array $_course
 * @param string $path
 * @param boolean $can_see_invisible
 * @return total size
 * @todo expand the query so people who can't see invisible files only get the
 *       total size of all visible files in the given directory
 */
function get_total_folder_size($path, $can_see_invisible)
{	
	$TABLE_ITEMPROPERTY = Database::get_course_table(LAST_TOOL_EDIT_TABLE);
	$TABLE_DOCUMENT = Database::get_course_table(DOCUMENT_TABLE);

	$sql = "SELECT SUM(size) 
	FROM  ".$TABLE_ITEMPROPERTY."  AS props, ".$TABLE_DOCUMENT."  AS docs
	WHERE docs.id = props.ref 
	AND props.tool = '".TOOL_DOCUMENT."'
	AND path LIKE '".$path."/%'
	AND props.visibility <> 2";

	$result = api_sql_query($sql,__FILE__,__LINE__);
		
	if($result && mysql_num_rows($result)!=0)
	{	
		$row = mysql_fetch_row($result);
		return $row[0] == null ? 0 : $row[0];
	}
	else
	{
		return 0;
	} 
}
?>