Feature #272 - fileManage.lib.php and text.lib.php: Revision, coding conventions, cleaning.

skala
Ivan Tcholakov 16 years ago
parent 589e5e7d51
commit be4fd4c1eb
  1. 575
      main/inc/lib/fileManage.lib.php
  2. 30
      main/inc/lib/text.lib.php

@ -1,12 +1,11 @@
<?php <?php
/* For licensing terms, see /license.txt */ /* For licensing terms, see /license.txt */
/** /**
============================================================================== * This is the file manage library for Chamilo.
* This is the file manage library for Dokeos.
* Include/require it in your code to use its functionality. * Include/require it in your code to use its functionality.
* *
* @package chamilo.library * @package chamilo.library
==============================================================================
*/ */
/** /**
@ -14,41 +13,37 @@
* *
* @author - Hugues Peeters <peeters@ipm.ucl.ac.be> * @author - Hugues Peeters <peeters@ipm.ucl.ac.be>
* @param - action (string) - action type require : 'delete' or 'update' * @param - action (string) - action type require : 'delete' or 'update'
* @param - oldPath (string) - old path info stored to change * @param - old_path (string) - old path info stored to change
* @param - newPath (string) - new path info to substitute * @param - new_path (string) - new path info to substitute
* @desc Update the file or directory path in the document db document table * @desc Update the file or directory path in the document db document table
* *
*/ */
function update_db_info($action, $old_path, $new_path = '') {
function update_db_info($action, $oldPath, $newPath="") global $dbTable; // Table 'document'
{
global $dbTable; // table 'document' // RH: see below
/* DELETE */ /* DELETE */
if ($action == "delete") if ($action == 'delete') {
{
/* // RH: metadata, update 2004/08/23 /* // RH: metadata, update 2004/08/23
these two lines replaced by new code below: these two lines replaced by new code below:
$query = "DELETE FROM `$dbTable` $query = "DELETE FROM `$dbTable`
WHERE path='".$oldPath."' OR path LIKE '".$oldPath."/%'"; WHERE path='".$old_path."' OR path LIKE '".$old_path."/%'";
*/ */
$to_delete = "WHERE path LIKE BINARY '".$oldPath."' OR path LIKE BINARY '".$oldPath."/%'"; $to_delete = "WHERE path LIKE BINARY '".$old_path."' OR path LIKE BINARY '".$old_path."/%'";
$query = "DELETE FROM $dbTable " . $to_delete; $query = "DELETE FROM $dbTable " . $to_delete;
$result = Database::query("SELECT id FROM $dbTable " . $to_delete); $result = Database::query("SELECT id FROM $dbTable " . $to_delete);
if (Database::num_rows($result)) if (Database::num_rows($result)) {
{
require_once(api_get_path(INCLUDE_PATH) . "../metadata/md_funcs.php"); require_once api_get_path(INCLUDE_PATH).'../metadata/md_funcs.php';
$mdStore = new mdstore(TRUE); // create if needed $mdStore = new mdstore(TRUE); // create if needed
$mdType = (substr($dbTable, -13) == 'scormdocument') ? $md_type = (substr($dbTable, -13) == 'scormdocument') ? 'Scorm' : 'Document';
'Scorm' : 'Document';
while ($row = Database::fetch_array($result)) while ($row = Database::fetch_array($result)) {
{ $eid = $md_type . '.' . $row['id'];
$eid = $mdType . '.' . $row['id'];
$mdStore->mds_delete($eid); $mdStore->mds_delete($eid);
$mdStore->mds_delete_offspring($eid); $mdStore->mds_delete_offspring($eid);
} }
@ -57,23 +52,22 @@ function update_db_info($action, $oldPath, $newPath="")
/* UPDATE */ /* UPDATE */
if ($action == "update") if ($action == 'update') {
{ //Display::display_normal_message("new_path = $new_path");
//Display::display_normal_message("newPath = $newPath"); if ($new_path[0] == '.') $new_path = substr($new_path, 1);
if ($newPath[0] == ".") $newPath = substr($newPath,1); $new_path = str_replace('//', '/', $new_path);
$newPath = str_replace('//','/',$newPath); //Display::display_normal_message("character 0 = " . $new_path[0] . " 1=" . $new_path[1]);
//Display::display_normal_message("character 0 = " . $newPath[0] . " 1=" . $newPath[1]); //Display::display_normal_message("new_path = $new_path");
//Display::display_normal_message("newPath = $newPath");
//older broken version // Older broken version
//$query = "UPDATE `$dbTable` //$query = "UPDATE `$dbTable`
//SET path = CONCAT('".$newPath."', SUBSTRING(path, LENGTH('".$oldPath."')+1) ) //SET path = CONCAT('".$new_path."', SUBSTRING(path, LENGTH('".$old_path."')+1) )
//WHERE path = '".$oldPath."' OR path LIKE '".$oldPath."/%'"; //WHERE path = '".$old_path."' OR path LIKE '".$old_path."/%'";
//attempt to update - tested & working for root dir // Attempt to update - tested & working for root dir
$query = "UPDATE $dbTable $query = "UPDATE $dbTable
SET path = CONCAT('".$newPath."', SUBSTRING(path, LENGTH('".$oldPath."')+1) ) SET path = CONCAT('".$new_path."', SUBSTRING(path, LENGTH('".$old_path."')+1) )
WHERE path LIKE BINARY '".$oldPath."' OR path LIKE BINARY '".$oldPath."/%'"; WHERE path LIKE BINARY '".$old_path."' OR path LIKE BINARY '".$old_path."/%'";
} }
//echo $query; //echo $query;
//error_log($query,0); //error_log($query,0);
@ -81,43 +75,34 @@ function update_db_info($action, $oldPath, $newPath="")
//Display::display_normal_message("query = $query"); //Display::display_normal_message("query = $query");
} }
//------------------------------------------------------------------------------
/** /**
* Cheks a file or a directory actually exist at this location * Cheks a file or a directory actually exist at this location
* *
* @author - Hugues Peeters <peeters@ipm.ucl.ac.be> * @author - Hugues Peeters <peeters@ipm.ucl.ac.be>
* @param - filePath (string) - path of the presume existing file or dir * @param - file_path (string) - path of the presume existing file or dir
* @return - boolean TRUE if the file or the directory exists * @return - boolean TRUE if the file or the directory exists
* boolean FALSE otherwise. * boolean FALSE otherwise.
*/ */
function check_name_exist($file_path) {
function check_name_exist($filePath)
{
clearstatcache(); clearstatcache();
$save_dir = getcwd(); $save_dir = getcwd();
if(!is_dir(dirname($filePath))) if (!is_dir(dirname($file_path))) {
{
return false; return false;
} }
chdir ( dirname($filePath) ); chdir(dirname($file_path));
$fileName = basename ($filePath); $file_name = basename($file_path);
if (file_exists( $fileName )) if (file_exists($file_name)) {
{
chdir($save_dir); chdir($save_dir);
return true; return true;
} } else {
else
{
chdir($save_dir); chdir($save_dir);
return false; return false;
} }
} }
/** /**
* Delete a file or a directory * Deletes a file or a directory
* *
* @author - Hugues Peeters * @author - Hugues Peeters
* @param - $file (String) - the path of file or directory to delete * @param - $file (String) - the path of file or directory to delete
@ -125,34 +110,22 @@ function check_name_exist($filePath)
* bolean - false otherwise. * bolean - false otherwise.
* @see - delete() uses check_name_exist() and removeDir() functions * @see - delete() uses check_name_exist() and removeDir() functions
*/ */
function my_delete($file) {
function my_delete($file) if (check_name_exist($file)) {
{ if (is_file($file)) { // FILE CASE
if ( check_name_exist($file) )
{
if ( is_file($file) ) // FILE CASE
{
unlink($file); unlink($file);
return true; return true;
} } elseif (is_dir($file)) { // DIRECTORY CASE
elseif ( is_dir($file) ) // DIRECTORY CASE
{
removeDir($file); removeDir($file);
return true; return true;
} }
} } else {
else
{
return false; // no file or directory to delete return false; // no file or directory to delete
} }
} }
//------------------------------------------------------------------------------
/** /**
* removes a directory recursively * Removes a directory recursively
* *
* @returns true if OK, otherwise false * @returns true if OK, otherwise false
* *
@ -161,29 +134,19 @@ function my_delete($file)
* *
* @param string $dir directory to remove * @param string $dir directory to remove
*/ */
function removeDir($dir) {
function removeDir($dir) if (!@$opendir = opendir($dir)) {
{
if(!@$opendir = opendir($dir))
{
return false; return false;
} }
while($readdir = readdir($opendir)) while ($readdir = readdir($opendir)) {
{ if ($readdir != '..' && $readdir != '.') {
if($readdir != '..' && $readdir != '.') if (is_file($dir.'/'.$readdir)) {
{ if (!@unlink($dir.'/'.$readdir)) {
if(is_file($dir.'/'.$readdir))
{
if(!@unlink($dir.'/'.$readdir))
{
return false; return false;
} }
} } elseif (is_dir($dir.'/'.$readdir)) {
elseif(is_dir($dir.'/'.$readdir)) if (!removeDir($dir.'/'.$readdir)) {
{
if(!removeDir($dir.'/'.$readdir))
{
return false; return false;
} }
} }
@ -192,66 +155,61 @@ function removeDir($dir)
closedir($opendir); closedir($opendir);
if(!@rmdir($dir)) if (!@rmdir($dir)) {
{
return false; return false;
} }
return true; return true;
} }
//------------------------------------------------------------------------------
/** /**
* Rename a file or a directory * Renames a file or a directory
* *
* @author - Hugues Peeters <peeters@ipm.ucl.ac.be> * @author - Hugues Peeters <peeters@ipm.ucl.ac.be>
* @param - $filePath (string) - complete path of the file or the directory * @param - $file_path (string) - complete path of the file or the directory
* @param - $newFileName (string) - new name for the file or the directory * @param - $new_file_name (string) - new name for the file or the directory
* @return - boolean - true if succeed * @return - boolean - true if succeed
* - boolean - false otherwise * - boolean - false otherwise
* @see - rename() uses the check_name_exist() and php2phps() functions * @see - rename() uses the check_name_exist() and php2phps() functions
*/ */
function my_rename($file_path, $new_file_name) {
function my_rename($filePath, $newFileName)
{
$save_dir = getcwd(); $save_dir = getcwd();
$path = dirname($filePath); $path = dirname($file_path);
$oldFileName = basename($filePath); $old_file_name = basename($file_path);
$newFileName = replace_dangerous_char($newFileName); $new_file_name = replace_dangerous_char($new_file_name);
// If no extension, take the old one // If no extension, take the old one
if ((strpos($newFileName, '.') === FALSE) if ((strpos($new_file_name, '.') === false) && ($dotpos = strrpos($old_file_name, '.'))) {
&& ($dotpos = strrpos($oldFileName, '.'))) $new_file_name .= substr($old_file_name, $dotpos);
{
$newFileName .= substr($oldFileName, $dotpos);
} }
// Note: still possible: 'xx.yy' -rename-> '.yy' -rename-> 'zz' // Note: still possible: 'xx.yy' -rename-> '.yy' -rename-> 'zz'
// This is useful for folder names, where otherwise '.' would be sticky // This is useful for folder names, where otherwise '.' would be sticky
// Extension PHP is not allowed, change to PHPS // Extension PHP is not allowed, change to PHPS
$newFileName = php2phps($newFileName); $new_file_name = php2phps($new_file_name);
if ($newFileName == $oldFileName) return $oldFileName; if ($new_file_name == $old_file_name) {
return $old_file_name;
}
if (strtolower($newFileName) != strtolower($oldFileName) && check_name_exist($path."/".$newFileName)) return false; if (strtolower($new_file_name) != strtolower($old_file_name) && check_name_exist($path.'/'.$new_file_name)) {
return false;
}
// On a Windows server, it would be better not to do the above check // On a Windows server, it would be better not to do the above check
// because it succeeds for some new names resembling the old name. // because it succeeds for some new names resembling the old name.
// But on Unix/Linux the check must be done because rename overwrites. // But on Unix/Linux the check must be done because rename overwrites.
chdir($path); chdir($path);
$res = rename($oldFileName, $newFileName) ? $newFileName : false; $res = rename($old_file_name, $new_file_name) ? $new_file_name : false;
chdir($save_dir); chdir($save_dir);
return $res; return $res;
} }
//------------------------------------------------------------------------------
/** /**
* Move a file or a directory to an other area * Moves a file or a directory to an other area
* *
* @author - Hugues Peeters <peeters@ipm.ucl.ac.be> * @author - Hugues Peeters <peeters@ipm.ucl.ac.be>
* @param - $source (String) - the path of file or directory to move * @param - $source (String) - the path of file or directory to move
@ -260,116 +218,86 @@ function my_rename($filePath, $newFileName)
* bolean - false otherwise. * bolean - false otherwise.
* @see - move() uses check_name_exist() and copyDirTo() functions * @see - move() uses check_name_exist() and copyDirTo() functions
*/ */
function move($source, $target) {
if (check_name_exist($source)) {
$file_name = basename($source);
function move($source, $target) if (check_name_exist($target.'/'.$file_name)) {
{
if ( check_name_exist($source) )
{
$fileName = basename($source);
if ( check_name_exist($target."/".$fileName) )
{
return false; return false;
} } else {
else /* File case */
{ /* File case */ if (is_file($source)) {
if ( is_file($source) ) copy($source , $target.'/'.$file_name);
{
copy($source , $target."/".$fileName);
unlink($source); unlink($source);
return true; return true;
} }
/* Directory case */ /* Directory case */
elseif (is_dir($source)) elseif (is_dir($source)) {
{ // Check to not copy the directory inside itself
// check to not copy the directory inside itself if (ereg('^'.$source.'/', $target.'/')) { // TODO: ereg() function is deprecated in PHP 5.3
if (ereg("^".$source."/", $target."/"))
{
return false; return false;
} } else {
else
{
copyDirTo($source, $target); copyDirTo($source, $target);
return true; return true;
} }
} }
} }
} } else {
else
{
return false; return false;
} }
} }
//------------------------------------------------------------------------------
/** /**
* Move a directory and its content to an other area * Moves a directory and its content to an other area
* *
* @author - Hugues Peeters <peeters@ipm.ucl.ac.be> * @author - Hugues Peeters <peeters@ipm.ucl.ac.be>
* @param - $origDirPath (String) - the path of the directory to move * @param - $orig_dir_path (string) - the path of the directory to move
* @param - $destination (String) - the path of the new area * @param - $destination (string) - the path of the new area
* @return - no return !! * @return - no return
*/ */
function copyDirTo($orig_dir_path, $destination, $move = true) {
function copyDirTo($origDirPath, $destination, $move=true)
{
$save_dir = getcwd(); $save_dir = getcwd();
// extract directory name - create it at destination - update destination trail // Extract directory name - create it at destination - update destination trail
$dirName = basename($origDirPath); $dir_name = basename($orig_dir_path);
if(is_dir($dirName)){ if (is_dir($dir_name)) {
mkdir ($destination."/".$dirName, api_get_permissions_for_new_directories()); mkdir($destination.'/'.$dir_name, api_get_permissions_for_new_directories());
$destinationTrail = $destination."/".$dirName; $destination_trail = $destination.'/'.$dir_name;
if (is_dir($destination)) { if (is_dir($destination)) {
chdir ($origDirPath) ; chdir ($orig_dir_path) ;
$handle = opendir($origDirPath); $handle = opendir($orig_dir_path);
while ($element = readdir($handle) ) while ($element = readdir($handle)) {
{ if ( $element == '.' || $element == '..') {
if ( $element == "." || $element == "..") continue; // Skip the current and parent directories
{ } elseif (is_file($element)) {
continue; // skip the current and parent directories copy($element, $destination_trail.'/'.$element);
}
elseif ( is_file($element) )
{
copy($element, $destinationTrail."/".$element);
if($move) if ($move) {
{
unlink($element) ; unlink($element) ;
} }
} } elseif (is_dir($element)) {
elseif ( is_dir($element) ) $dir_to_copy[] = $orig_dir_path.'/'.$element;
{
$dirToCopy[] = $origDirPath."/".$element;
} }
} }
closedir($handle) ; closedir($handle) ;
if ( sizeof($dirToCopy) > 0) if (sizeof($dir_to_copy) > 0) {
{ foreach ($dir_to_copy as $this_dir) {
foreach($dirToCopy as $thisDir) copyDirTo($this_dir, $destination_trail, $move); // Recursivity
{
copyDirTo($thisDir, $destinationTrail, $move); // recursivity
} }
} }
if($move) if ($move) {
{ rmdir($orig_dir_path) ;
rmdir ($origDirPath) ;
} }
chdir($save_dir); chdir($save_dir);
} }
} }
} }
//------------------------------------------------------------------------------
/* NOTE: These functions batch is used to automatically build HTML forms /* NOTE: These functions batch is used to automatically build HTML forms
* with a list of the directories contained on the course Directory. * with a list of the directories contained on the course Directory.
* *
@ -384,35 +312,33 @@ function copyDirTo($origDirPath, $destination, $move=true)
* @param - path (string) - directory path of the one to index * @param - path (string) - directory path of the one to index
* @return - an array containing the path of all the subdirectories * @return - an array containing the path of all the subdirectories
*/ */
function index_dir($path) { function index_dir($path) {
$dirArray = array(); $dir_array = array();
$save_dir = getcwd(); $save_dir = getcwd();
if (is_dir($path)){ if (is_dir($path)){
chdir($path); chdir($path);
$handle = opendir($path); $handle = opendir($path);
// reads directory content end record subdirectoies names in $dir_array // Reads directory content end record subdirectoies names in $dir_array
if ($handle !== false) { if ($handle !== false) {
while ($element = readdir($handle)) { while ($element = readdir($handle)) {
if ( $element == "." || $element == "..") continue; // skip the current and parent directories if ($element == '.' || $element == '..') continue; // Skip the current and parent directories
if ( is_dir($element) ) $dirArray[] = $path."/".$element; if (is_dir($element)) $dir_array[] = $path.'/'.$element;
} }
closedir($handle) ; closedir($handle) ;
} }
// recursive operation if subdirectories exist // Recursive operation if subdirectories exist
$dirNumber = sizeof($dirArray); $dir_number = sizeof($dir_array);
if ( $dirNumber > 0 ) { if ($dir_number > 0) {
for ($i = 0 ; $i < $dirNumber ; $i++ ) { for ($i = 0 ; $i < $dir_number ; $i++) {
$subDirArray = index_dir( $dirArray[$i] ) ; // function recursivity $sub_dir_array = index_dir($dir_array[$i]); // Function recursivity
$dirArray = array_merge( (array)$dirArray , (array)$subDirArray ); // data merge $dir_array = array_merge((array)$dir_array, (array)$sub_dir_array); // Data merge
} }
} }
} }
chdir($save_dir) ; chdir($save_dir) ;
return $dirArray ; return $dir_array ;
} }
/** /**
* Indexes all the directories and subdirectories * Indexes all the directories and subdirectories
* contented in a given directory, and sort them alphabetically * contented in a given directory, and sort them alphabetically
@ -423,123 +349,91 @@ function index_dir($path) {
* false, if there is no directory * false, if there is no directory
* @see - index_and_sort_dir uses the index_dir() function * @see - index_and_sort_dir uses the index_dir() function
*/ */
function index_and_sort_dir($path) {
function index_and_sort_dir($path)
{
$dir_list = index_dir($path); $dir_list = index_dir($path);
if ($dir_list) {
if ($dir_list)
{
//sort($dir_list);
natsort($dir_list); natsort($dir_list);
return $dir_list; return $dir_list;
} }
else
{
return false; return false;
} }
}
/** /**
* build an html form listing all directories of a given directory * Builds a html form listing all directories of a given directory
* *
*/ */
function form_dir_list($source_type, $source_component, $command, $base_work_dir) {
function form_dir_list($sourceType, $sourceComponent, $command, $baseWorkDir) $dir_list = index_and_sort_dir($base_work_dir);
{ $dialog_box .= "<form action=\"".api_get_self()."\" method=\"post\">\n" ;
$dialog_box .= "<input type=\"hidden\" name=\"".$source_type."\" value=\"".$source_component."\">\n" ;
$dirList = index_and_sort_dir($baseWorkDir); $dialog_box .= get_lang('Move').' '.$source_component.' '.get_lang('To');
$dialogBox .= "<form action=\"".api_get_self()."\" method=\"post\">\n" ; $dialog_box .= "<select name=\"".$command."\">\n" ;
$dialogBox .= "<input type=\"hidden\" name=\"".$sourceType."\" value=\"".$sourceComponent."\">\n" ; $dialog_box .= "<option value=\"\" style=\"color:#999999\">".get_lang('Root')."\n";
$dialogBox .= get_lang('Move').' '.$sourceComponent.' '.get_lang('To');
$dialogBox .= "<select name=\"".$command."\">\n" ;
$dialogBox .= "<option value=\"\" style=\"color:#999999\">".get_lang('Root')."\n";
$bwdLen = strlen($baseWorkDir) ; // base directories lenght, used under $bwdLen = strlen($base_work_dir) ; // base directories lenght, used under
/* build html form inputs */ /* build html form inputs */
if ($dirList) if ($dir_list) {
{ while (list( , $path_value) = each($dir_list) ) {
while (list( , $pathValue) = each($dirList) ) $path_value = substr ( $path_value , $bwdLen ); // Truncates cunfidential informations confidentielles
{ $dirname = basename ($path_value); // Extracts $path_value directory name du nom
$pathValue = substr ( $pathValue , $bwdLen ); // truncate cunfidential informations confidentielles
$dirname = basename ($pathValue); // extract $pathValue directory name du nom
/* compute de the display tab */ /* compute de the display tab */
$tab = ""; // $tab reinitialisation $tab = ""; // $tab reinitialisation
$depth = substr_count($pathValue, "/"); // The number of nombre '/' indicates the directory deepness $depth = substr_count($path_value, '/'); // The number of nombre '/' indicates the directory deepness
for ($h=0; $h<$depth; $h++) for ($h = 0; $h < $depth; $h++) {
{
$tab .= "&nbsp;&nbsp;"; $tab .= "&nbsp;&nbsp;";
} }
$dialogBox .= "<option value=\"$pathValue\">$tab>$dirname\n"; $dialog_box .= "<option value=\"$path_value\">$tab>$dirname\n";
} }
} }
$dialogBox .= "</select>\n"; $dialog_box .= "</select>\n";
$dialogBox .= "<input type=\"submit\" value=\"".get_lang('Ok')."\">"; $dialog_box .= "<input type=\"submit\" value=\"".get_lang('Ok')."\">";
$dialogBox .= "</form>\n"; $dialog_box .= "</form>\n";
return $dialogBox; return $dialog_box;
} }
//------------------------------------------------------------------------------
/** /**
* to extract the extention of the filename * Extracting extention of a filename
* *
* @returns array * @returns array
* @param string $filename filename * @param string $filename filename
*/ */
function getextension($filename) function getextension($filename) {
{ $bouts = explode('.', $filename);
$bouts = explode(".", $filename); return array(array_pop($bouts), implode('.', $bouts));
return array(array_pop($bouts), implode(".", $bouts));
} }
/** /**
* to compute the size of the directory * Calculation size of a directory
* *
* @returns integer size * @returns integer size
* @param string $path path to size * @param string $path path to size
* @param boolean $recursive if true , include subdir in total * @param boolean $recursive if true , include subdir in total
*/ */
function dirsize($root,$recursive=true) function dirsize($root, $recursive = true) {
{
$dir = @opendir($root); $dir = @opendir($root);
$size = 0; $size = 0;
while ($file = @readdir($dir)) {
while($file=@readdir($dir)) if (!in_array($file, array('.', '..'))) {
{ if (is_dir($root.'/'.$file)) {
if(!in_array($file,array('.','..')))
{
if(is_dir($root.'/'.$file))
{
$size += $recursive ? dirsize($root.'/'.$file) : 0; $size += $recursive ? dirsize($root.'/'.$file) : 0;
} } else {
else
{
$size += @filesize($root.'/'.$file); $size += @filesize($root.'/'.$file);
} }
} }
} }
@closedir($dir); @closedir($dir);
return $size; return $size;
} }
/* /* CLASS FileManager */
===============================================================
CLASS FileManager
===============================================================
*/
/** /**
This class contains functions that you can access statically. This class contains functions that you can access statically.
@ -556,7 +450,6 @@ class FileManager
{ {
/** /**
---------------------------------------------------------------
Returns a list of all directories, except the base dir, Returns a list of all directories, except the base dir,
of the current course. This function uses recursion. of the current course. This function uses recursion.
@ -564,103 +457,82 @@ class FileManager
@author Roan Embrechts @author Roan Embrechts
@version 1.0.1 @version 1.0.1
---------------------------------------------------------------
*/ */
function list_all_directories($path) function list_all_directories($path) {
{
$resultArray = array(); $result_array = array();
if (is_dir($path)) { if (is_dir($path)) {
$save_dir = getcwd(); $save_dir = getcwd();
chdir($path); chdir($path);
$handle = opendir($path); $handle = opendir($path);
while ($element = readdir($handle) ) while ($element = readdir($handle)) {
{ if ($element == '.' || $element == '..') continue; // Skip the current and parent directories
if ( $element == "." || $element == "..") continue; // skip the current and parent directories if (is_dir($element)) {
if ( is_dir($element) ) $dir_array[] = $path.'/'.$element;
{
$dirArray[] = $path."/".$element;
} }
} }
closedir($handle); closedir($handle);
// recursive operation if subdirectories exist // Recursive operation if subdirectories exist
$dirNumber = sizeof($dirArray); $dir_number = sizeof($dir_array);
if ( $dirNumber > 0 ) if ($dir_number > 0) {
{ for ($i = 0 ; $i < $dir_number ; $i++) {
for ($i = 0 ; $i < $dirNumber ; $i++ ) $sub_dir_array = FileManager::list_all_directories($dir_array[$i]); // Function recursivity
{ if (is_array($dir_array) && is_array($sub_dir_array)) {
$subDirArray = FileManager::list_all_directories($dirArray[$i]) ; // function recursivity $dir_array = array_merge($dir_array, $sub_dir_array); // Data merge
if (is_array($dirArray) && is_array($subDirArray)) {
$dirArray = array_merge( $dirArray , $subDirArray ) ; // data merge
} }
} }
} }
$resultArray = $dirArray; $result_array = $dir_array;
chdir($save_dir) ; chdir($save_dir) ;
} }
return $resultArray ; return $result_array ;
} }
/** /**
===============================================================
This function receives a list of directories. This function receives a list of directories.
It returns a list of all files in these directories It returns a list of all files in these directories
@author Roan Embrechts @author Roan Embrechts
@version 1.0 @version 1.0
===============================================================
*/ */
function list_all_files($dirArray) function list_all_files($dir_array) {
{
$elementArray = array();
if(is_dir($dirArray))
{
$element_array = array();
if (is_dir($dir_array)) {
$save_dir = getcwd(); $save_dir = getcwd();
foreach ($dirArray as $directory) foreach ($dir_array as $directory) {
{
chdir($directory); chdir($directory);
$handle = opendir($directory); $handle = opendir($directory);
while ($element = readdir($handle) ) while ($element = readdir($handle)) {
{ if ($element == '.' || $element == '..' || $element == '.htaccess') continue; // Skip the current and parent directories
if ( $element == "." || $element == ".." || $element == '.htaccess') continue; // skip the current and parent directories if (!is_dir($element)) {
if ( ! is_dir($element) ) $element_array[] = $directory.'/'.$element;
{
$elementArray[] = $directory."/".$element;
} }
} }
closedir($handle); closedir($handle);
chdir("..") ; chdir('..');
chdir($save_dir); chdir($save_dir);
} }
} }
return $elementArray; return $element_array;
} }
/** /**
Load contents of file $filename into memory Loads contents of file $filename into memory and returns them as a string.
and return them as a string.
Function kept for compatibility with older PHP versions. Function kept for compatibility with older PHP versions.
Function is binary safe (is needed on Windows) Function is binary safe (is needed on Windows)
*/ */
function compat_load_file($file_name) function compat_load_file($file_name) {
{
$buffer = ''; $buffer = '';
if(file_exists($file_name)) if (file_exists($file_name)) {
{ $fp = fopen($file_name, 'rb');
$fp = fopen($file_name, "rb");
$buffer = fread ($fp, filesize($file_name)); $buffer = fread ($fp, filesize($file_name));
fclose ($fp); fclose ($fp);
//api_display_debug_info(htmlentities($buffer));
} }
return $buffer; return $buffer;
} }
/** /**
* Adds file/folder to document table in database * Adds file/folder to document table in database
* improvement from set_default_settings (see below): * improvement from set_default_settings (see below):
@ -678,41 +550,35 @@ class FileManager
* @author Roan Embrechts * @author Roan Embrechts
* @version 1.2 * @version 1.2
*/ */
function set_default_settings($upload_path, $filename, $filetype="file", $glued_table, $default_visibility='v') function set_default_settings($upload_path, $filename, $filetype = 'file', $glued_table, $default_visibility = 'v') {
{ if (!$default_visibility) $default_visibility = 'v';
if (!$default_visibility) $default_visibility="v";
//make sure path is not wrongly formed // Make sure path is not wrongly formed
if( strlen($upload_path) ) $upload_path = "/$upload_path"; $upload_path = !empty($upload_path) ? "/$upload_path" : '';
else $upload_path = "";
$endchar = substr($filename, strlen($filename) - 1, 1); $endchar = substr($filename, strlen($filename) - 1, 1);
if($endchar=="\\" || $endchar=="/") if ($endchar == "\\" || $endchar == '/') {
{
$filename = substr($filename, 0, strlen($filename) - 1); $filename = substr($filename, 0, strlen($filename) - 1);
} }
$full_file_name = $upload_path."/".$filename; $full_file_name = $upload_path.'/'.$filename;
//$upload_path = str_replace("//", "/", $upload_path); //$upload_path = str_replace("//", '/', $upload_path);
$full_file_name = str_replace("//", "/", $full_file_name); $full_file_name = str_replace("//", '/', $full_file_name);
$sql_query = "SELECT count(*) as number_existing FROM $glued_table WHERE path='$full_file_name'"; $sql_query = "SELECT count(*) as number_existing FROM $glued_table WHERE path='$full_file_name'";
//api_display_debug_info($sql_query);
$sql_result = Database::query($sql_query); $sql_result = Database::query($sql_query);
$result = Database::fetch_array($sql_result); $result = Database::fetch_array($sql_result);
//determine which query to execute // Determine which query to execute
if( $result["number_existing"] > 0 ) if ($result['number_existing'] > 0) {
{ // Entry exists, update
//entry exists, update
$query = "UPDATE $glued_table SET path='$full_file_name',visibility='$default_visibility', filetype='$filetype' WHERE path='$full_file_name'"; $query = "UPDATE $glued_table SET path='$full_file_name',visibility='$default_visibility', filetype='$filetype' WHERE path='$full_file_name'";
} } else {
else // No entry exists, create new one
{
//no entry exists, create new one
$query = "INSERT INTO $glued_table (path,visibility,filetype) VALUES('$full_file_name','$default_visibility','$filetype')"; $query = "INSERT INTO $glued_table (path,visibility,filetype) VALUES('$full_file_name','$default_visibility','$filetype')";
} }
Database::query($query); Database::query($query);
} }
/** /**
* Like in Java, creates the directory named by this abstract pathname, * Like in Java, creates the directory named by this abstract pathname,
* including any necessary but nonexistent parent directories. * including any necessary but nonexistent parent directories.
@ -725,14 +591,10 @@ class FileManager
* *
* @return boolean TRUE if succeeds FALSE otherwise * @return boolean TRUE if succeeds FALSE otherwise
*/ */
function mkdirs($path, $mode = '0770') function mkdirs($path, $mode = '0770') {
{ if (file_exists($path)) {
if (file_exists($path))
{
return false; return false;
} } else {
else
{
FileManager :: mkdirs(dirname($path), $mode); FileManager :: mkdirs(dirname($path), $mode);
//mkdir($path, $mode); //mkdir($path, $mode);
return true; return true;
@ -742,11 +604,7 @@ class FileManager
} //end class FileManager } //end class FileManager
/* /* DEPRECATED FUNCTIONS */
===============================================================
DEPRECATED FUNCTIONS
===============================================================
*/
/** /**
* @deprecated 06-FEB-2010. The function mkdir() is able to create directories recursively. * @deprecated 06-FEB-2010. The function mkdir() is able to create directories recursively.
@ -763,56 +621,43 @@ class FileManager
* @param string $mode fix if chmod is same of parent or default (Note: This misterious parameter is not used). * @param string $mode fix if chmod is same of parent or default (Note: This misterious parameter is not used).
* @global string $langCreatedIn string to say "create in" * @global string $langCreatedIn string to say "create in"
*/ */
function mkpath($path, $verbose = false, $mode = "herit") function mkpath($path, $verbose = false, $mode = 'herit') {
{
global $langCreatedIn, $_configuration; global $langCreatedIn, $_configuration;
$path = str_replace("/", "\\", $path); $path = str_replace('/', "\\", $path);
$dirs = explode("\\", $path); $dirs = explode("\\", $path);
$path = $dirs[0]; $path = $dirs[0];
if ($verbose) if ($verbose) {
{ echo '<ul>';
echo "<ul>";
} }
for ($i = 1; $i < sizeof($dirs); $i++) for ($i = 1; $i < sizeof($dirs); $i++) {
{
$path .= '/'.$dirs[$i]; $path .= '/'.$dirs[$i];
if (ereg('^'.$path,$_configuration['root_sys']) && strlen($path) < strlen($_configuration['root_sys'])) if (ereg('^'.$path, $_configuration['root_sys']) && strlen($path) < strlen($_configuration['root_sys'])) {
{
continue; continue;
} }
if (!is_dir($path)) if (!is_dir($path)) {
{
$ret = mkdir($path, api_get_permissions_for_new_directories()); $ret = mkdir($path, api_get_permissions_for_new_directories());
if ($ret) if ($ret) {
{ if ($verbose) {
if($verbose)
{
echo '<li><strong>'.basename($path).'</strong><br />'.$langCreatedIn.'<br /><strong>'.realpath($path.'/..').'</strong></li>'; echo '<li><strong>'.basename($path).'</strong><br />'.$langCreatedIn.'<br /><strong>'.realpath($path.'/..').'</strong></li>';
} }
} } else {
else if ($verbose) {
{
if ($verbose)
{
echo '</ul>error : '.$path.' not created'; echo '</ul>error : '.$path.' not created';
} }
$ret = false; $ret = false;
break; break;
} }
} }
} }
if ($verbose) if ($verbose) {
{
echo '</ul>'; echo '</ul>';
} }

@ -13,7 +13,7 @@
/** /**
* function make_clickable($string) * function make_clickable($string)
* *
* @desc completes url contained in the text with "<a href ...". * @desc Completes url contained in the text with "<a href ...".
* However the function simply returns the submitted text without any * However the function simply returns the submitted text without any
* transformation if it already contains some "<a href:" or "<img src=". * transformation if it already contains some "<a href:" or "<img src=".
* @param string $text text to be converted * @param string $text text to be converted
@ -142,7 +142,6 @@ function _text_parse_texexplorer($textext) {
$textext = str_replace(array("[texexplorer]", "[/texexplorer]"), array("<embed type=\"application/x-techexplorer\" texdata=\"", "\" autosize=\"true\" pluginspage=\"http://www.integretechpub.com/techexplorer/\">"), $textext); $textext = str_replace(array("[texexplorer]", "[/texexplorer]"), array("<embed type=\"application/x-techexplorer\" texdata=\"", "\" autosize=\"true\" pluginspage=\"http://www.integretechpub.com/techexplorer/\">"), $textext);
} }
return $textext; return $textext;
} }
/** /**
@ -159,11 +158,11 @@ function _text_parse_glossary($input) {
* @author Patrick Cool <patrick.cool@UGent.be> * @author Patrick Cool <patrick.cool@UGent.be>
*/ */
function _text_parse_tool($input) { function _text_parse_tool($input) {
// an array with all the valid tools // An array with all the valid tools
$tools[] = array(TOOL_ANNOUNCEMENT, 'announcements/announcements.php'); $tools[] = array(TOOL_ANNOUNCEMENT, 'announcements/announcements.php');
$tools[] = array(TOOL_CALENDAR_EVENT, 'calendar/agenda.php'); $tools[] = array(TOOL_CALENDAR_EVENT, 'calendar/agenda.php');
// check if the name between the [tool] [/tool] tags is a valid one // Check if the name between the [tool] [/tool] tags is a valid one
} }
/** /**
@ -173,7 +172,7 @@ function _text_parse_tool($input) {
function latex_gif_renderer($latex_code) { function latex_gif_renderer($latex_code) {
global $_course; global $_course;
// setting the paths and filenames // Setting the paths and filenames
$mimetex_path = api_get_path(LIBRARY_PATH).'mimetex/'; $mimetex_path = api_get_path(LIBRARY_PATH).'mimetex/';
$temp_path = api_get_path(SYS_COURSE_PATH).$_course['path'].'/temp/'; $temp_path = api_get_path(SYS_COURSE_PATH).$_course['path'].'/temp/';
$latex_filename = md5($latex_code).'.gif'; $latex_filename = md5($latex_code).'.gif';
@ -219,20 +218,21 @@ function cut($text, $maxchar, $embed = false) {
* @return mixed an integer or a float depends on the parameter * @return mixed an integer or a float depends on the parameter
*/ */
function float_format($number, $flag = 1) { function float_format($number, $flag = 1) {
if (is_numeric($number)) { // a number if (is_numeric($number)) {
if (!$number) { // zero if (!$number) {
$result = ($flag == 2 ? '0.00' : '0'); // output zero $result = ($flag == 2 ? '0.00' : '0');
} else { // value } else {
if (floor($number) == $number) { // whole number if (floor($number) == $number) {
$result = number_format($number, ($flag == 2 ? 2 : 0)); // format $result = number_format($number, ($flag == 2 ? 2 : 0));
} else { // cents } else {
$result = number_format(round($number, 2), ($flag == 0 ? 0 : 2)); // format $result = number_format(round($number, 2), ($flag == 0 ? 0 : 2));
} // integer or decimal }
} // value }
return $result; return $result;
} }
} }
// TODO: To be checked for timezones management and to be moved in the internationalization library.
/** /**
* Function to obtain last week timestamps * Function to obtain last week timestamps
* @return array times for every day inside week * @return array times for every day inside week

Loading…
Cancel
Save