fileManage.lib.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500
  1. <?php
  2. /* For licensing terms, see /license.txt */
  3. /**
  4. * This is the file manage library for Chamilo.
  5. * Include/require it in your code to use its functionality.
  6. * @package chamilo.library
  7. */
  8. /**
  9. * Update the file or directory path in the document db document table
  10. *
  11. * @author - Hugues Peeters <peeters@ipm.ucl.ac.be>
  12. * @param - action (string) - action type require : 'delete' or 'update'
  13. * @param - old_path (string) - old path info stored to change
  14. * @param - new_path (string) - new path info to substitute
  15. * @desc Update the file or directory path in the document db document table
  16. *
  17. */
  18. function update_db_info($action, $old_path, $new_path = '')
  19. {
  20. $dbTable = Database::get_course_table(TABLE_DOCUMENT);
  21. $course_id = api_get_course_int_id();
  22. switch ($action) {
  23. case 'delete':
  24. $old_path = Database::escape_string($old_path);
  25. $query = "DELETE FROM $dbTable
  26. WHERE
  27. c_id = $course_id AND
  28. (
  29. path LIKE BINARY '".$old_path."' OR
  30. path LIKE BINARY '".$old_path."/%'
  31. )";
  32. Database::query($query);
  33. break;
  34. case 'update':
  35. if ($new_path[0] == '.') $new_path = substr($new_path, 1);
  36. $new_path = str_replace('//', '/', $new_path);
  37. // Attempt to update - tested & working for root dir
  38. $new_path = Database::escape_string($new_path);
  39. $query = "UPDATE $dbTable SET
  40. path = CONCAT('".$new_path."', SUBSTRING(path, LENGTH('".$old_path."')+1) )
  41. WHERE c_id = $course_id AND (path LIKE BINARY '".$old_path."' OR path LIKE BINARY '".$old_path."/%')";
  42. Database::query($query);
  43. break;
  44. }
  45. }
  46. /**
  47. * Cheks a file or a directory actually exist at this location
  48. *
  49. * @author - Hugues Peeters <peeters@ipm.ucl.ac.be>
  50. * @param - file_path (string) - path of the presume existing file or dir
  51. * @return - boolean TRUE if the file or the directory exists
  52. * boolean FALSE otherwise.
  53. */
  54. function check_name_exist($file_path) {
  55. clearstatcache();
  56. $save_dir = getcwd();
  57. if (!is_dir(dirname($file_path))) {
  58. return false;
  59. }
  60. chdir(dirname($file_path));
  61. $file_name = basename($file_path);
  62. if (file_exists($file_name)) {
  63. chdir($save_dir);
  64. return true;
  65. } else {
  66. chdir($save_dir);
  67. return false;
  68. }
  69. }
  70. /**
  71. * Deletes a file or a directory
  72. *
  73. * @author - Hugues Peeters
  74. * @param $file (String) - the path of file or directory to delete
  75. * @return boolean - true if the delete succeed, false otherwise.
  76. * @see - delete() uses check_name_exist() and removeDir() functions
  77. */
  78. function my_delete($file)
  79. {
  80. if (check_name_exist($file)) {
  81. if (is_file($file)) { // FILE CASE
  82. unlink($file);
  83. return true;
  84. } elseif (is_dir($file)) { // DIRECTORY CASE
  85. removeDir($file);
  86. return true;
  87. }
  88. } else {
  89. return false; // no file or directory to delete
  90. }
  91. }
  92. /**
  93. * Removes a directory recursively
  94. *
  95. * @returns true if OK, otherwise false
  96. *
  97. * @author Amary <MasterNES@aol.com> (from Nexen.net)
  98. * @author Olivier Brouckaert <oli.brouckaert@skynet.be>
  99. *
  100. * @param string $dir directory to remove
  101. */
  102. function removeDir($dir)
  103. {
  104. if (!@$opendir = opendir($dir)) {
  105. return false;
  106. }
  107. while ($readdir = readdir($opendir)) {
  108. if ($readdir != '..' && $readdir != '.') {
  109. if (is_file($dir.'/'.$readdir)) {
  110. if (!@unlink($dir.'/'.$readdir)) {
  111. return false;
  112. }
  113. } elseif (is_dir($dir.'/'.$readdir)) {
  114. if (!removeDir($dir.'/'.$readdir)) {
  115. return false;
  116. }
  117. }
  118. }
  119. }
  120. closedir($opendir);
  121. if (!@rmdir($dir)) {
  122. return false;
  123. }
  124. return true;
  125. }
  126. /**
  127. * Return true if folder is empty
  128. * @author : hubert.borderiou@grenet.fr
  129. * @param string $in_folder : folder path on disk
  130. * @return 1 if folder is empty, 0 otherwise
  131. */
  132. function folder_is_empty($in_folder)
  133. {
  134. $folder_is_empty = 0;
  135. if (is_dir($in_folder)) {
  136. $tab_folder_content = scandir($in_folder);
  137. if ((count($tab_folder_content) == 2 &&
  138. in_array(".", $tab_folder_content) &&
  139. in_array("..", $tab_folder_content)
  140. ) ||
  141. (count($tab_folder_content) < 2)
  142. ) {
  143. $folder_is_empty = 1;
  144. }
  145. }
  146. return $folder_is_empty;
  147. }
  148. /**
  149. * Renames a file or a directory
  150. *
  151. * @author - Hugues Peeters <peeters@ipm.ucl.ac.be>
  152. * @param - $file_path (string) - complete path of the file or the directory
  153. * @param - $new_file_name (string) - new name for the file or the directory
  154. * @return - boolean - true if succeed
  155. * - boolean - false otherwise
  156. * @see - rename() uses the check_name_exist() and php2phps() functions
  157. */
  158. function my_rename($file_path, $new_file_name) {
  159. $save_dir = getcwd();
  160. $path = dirname($file_path);
  161. $old_file_name = basename($file_path);
  162. $new_file_name = api_replace_dangerous_char($new_file_name);
  163. // If no extension, take the old one
  164. if ((strpos($new_file_name, '.') === false) && ($dotpos = strrpos($old_file_name, '.'))) {
  165. $new_file_name .= substr($old_file_name, $dotpos);
  166. }
  167. // Note: still possible: 'xx.yy' -rename-> '.yy' -rename-> 'zz'
  168. // This is useful for folder names, where otherwise '.' would be sticky
  169. // Extension PHP is not allowed, change to PHPS
  170. $new_file_name = php2phps($new_file_name);
  171. if ($new_file_name == $old_file_name) {
  172. return $old_file_name;
  173. }
  174. if (strtolower($new_file_name) != strtolower($old_file_name) && check_name_exist($path.'/'.$new_file_name)) {
  175. return false;
  176. }
  177. // On a Windows server, it would be better not to do the above check
  178. // because it succeeds for some new names resembling the old name.
  179. // But on Unix/Linux the check must be done because rename overwrites.
  180. chdir($path);
  181. $res = rename($old_file_name, $new_file_name) ? $new_file_name : false;
  182. chdir($save_dir);
  183. return $res;
  184. }
  185. /**
  186. * Moves a file or a directory to an other area
  187. *
  188. * @author - Hugues Peeters <peeters@ipm.ucl.ac.be>
  189. * @param - $source (String) - the path of file or directory to move
  190. * @param - $target (String) - the path of the new area
  191. * @param bool $forceMove Whether to force a move or to make a copy (safer but slower) and then delete the original
  192. * @param bool $moveContent In some cases (including migrations), we need to move the *content* and not the folder itself
  193. * @return - bolean - true if the move succeed
  194. * bolean - false otherwise.
  195. * @see - move() uses check_name_exist() and copyDirTo() functions
  196. */
  197. function move($source, $target, $forceMove = false, $moveContent = false)
  198. {
  199. if (check_name_exist($source)) {
  200. $file_name = basename($source);
  201. $isWindowsOS = api_is_windows_os();
  202. $canExec = function_exists('exec');
  203. /* File case */
  204. if (is_file($source)) {
  205. if ($forceMove && !$isWindowsOS && $canExec) {
  206. exec('mv ' . $source . ' ' . $target . '/' . $file_name);
  207. } else {
  208. copy($source, $target . '/' . $file_name);
  209. unlink($source);
  210. }
  211. return true;
  212. } elseif (is_dir($source)) {
  213. /* Directory */
  214. if ($forceMove && !$isWindowsOS && $canExec) {
  215. if ($moveContent) {
  216. $base = basename($source);
  217. exec('mv '.$source.'/* '.$target.$base.'/');
  218. exec('rm -rf '.$source);
  219. } else {
  220. exec('mv $source $target');
  221. }
  222. } else {
  223. copyDirTo($source, $target);
  224. }
  225. return true;
  226. }
  227. } else {
  228. return false;
  229. }
  230. }
  231. /**
  232. * Moves a directory and its content to an other area
  233. *
  234. * @author - Hugues Peeters <peeters@ipm.ucl.ac.be>
  235. * @param - $orig_dir_path (string) - the path of the directory to move
  236. * @param - $destination (string) - the path of the new area
  237. * @return - no return
  238. */
  239. function copyDirTo($orig_dir_path, $destination, $move = true)
  240. {
  241. if ($orig_dir_path == $destination) {
  242. return false;
  243. }
  244. $save_dir = getcwd();
  245. // Extract directory name - create it at destination - update destination trail
  246. $dir_name = basename($orig_dir_path);
  247. $dir_to_copy = array();
  248. if (is_dir($orig_dir_path)) {
  249. if (!is_dir($destination.'/'.$dir_name)) {
  250. mkdir(
  251. $destination.'/'.$dir_name,
  252. api_get_permissions_for_new_directories()
  253. );
  254. }
  255. $destination_trail = $destination.'/'.$dir_name;
  256. if (is_dir($destination)) {
  257. chdir($orig_dir_path) ;
  258. $handle = opendir($orig_dir_path);
  259. while ($element = readdir($handle)) {
  260. if ($element == '.' || $element == '..') {
  261. continue; // Skip the current and parent directories
  262. } elseif (is_file($element)) {
  263. copy($element, $destination_trail.'/'.$element);
  264. if ($move) {
  265. unlink($element) ;
  266. }
  267. } elseif (is_dir($element)) {
  268. $dir_to_copy[] = $orig_dir_path.'/'.$element;
  269. }
  270. }
  271. closedir($handle) ;
  272. if (sizeof($dir_to_copy) > 0) {
  273. foreach ($dir_to_copy as $this_dir) {
  274. copyDirTo($this_dir, $destination_trail, $move); // Recursivity
  275. }
  276. }
  277. if ($move) {
  278. rmdir($orig_dir_path) ;
  279. }
  280. chdir($save_dir);
  281. }
  282. }
  283. }
  284. /**
  285. * Extracting extention of a filename
  286. *
  287. * @returns array
  288. * @param string $filename filename
  289. */
  290. function getextension($filename) {
  291. $bouts = explode('.', $filename);
  292. return array(array_pop($bouts), implode('.', $bouts));
  293. }
  294. /**
  295. * Calculation size of a directory
  296. *
  297. * @returns integer size
  298. * @param string $path path to size
  299. * @param boolean $recursive if true , include subdir in total
  300. */
  301. function dirsize($root, $recursive = true) {
  302. $dir = @opendir($root);
  303. $size = 0;
  304. while ($file = @readdir($dir)) {
  305. if (!in_array($file, array('.', '..'))) {
  306. if (is_dir($root.'/'.$file)) {
  307. $size += $recursive ? dirsize($root.'/'.$file) : 0;
  308. } else {
  309. $size += @filesize($root.'/'.$file);
  310. }
  311. }
  312. }
  313. @closedir($dir);
  314. return $size;
  315. }
  316. /* CLASS FileManager */
  317. /**
  318. This class contains functions that you can access statically.
  319. FileManager::list_all_directories($path)
  320. FileManager::list_all_files($dir_array)
  321. FileManager::compat_load_file($file_name)
  322. FileManager::set_default_settings($upload_path, $filename, $filetype="file", $glued_table, $default_visibility='v')
  323. @author Roan Embrechts
  324. @version 1.1, July 2004
  325. * @package chamilo.library
  326. */
  327. class FileManager
  328. {
  329. /**
  330. Returns a list of all directories, except the base dir,
  331. of the current course. This function uses recursion.
  332. Convention: the parameter $path does not end with a slash.
  333. @author Roan Embrechts
  334. @version 1.0.1
  335. */
  336. function list_all_directories($path)
  337. {
  338. $result_array = array();
  339. if (is_dir($path)) {
  340. $save_dir = getcwd();
  341. chdir($path);
  342. $handle = opendir($path);
  343. while ($element = readdir($handle)) {
  344. if ($element == '.' || $element == '..') continue;
  345. // Skip the current and parent directories
  346. if (is_dir($element)) {
  347. $dir_array[] = $path.'/'.$element;
  348. }
  349. }
  350. closedir($handle);
  351. // Recursive operation if subdirectories exist
  352. $dir_number = sizeof($dir_array);
  353. if ($dir_number > 0) {
  354. for ($i = 0 ; $i < $dir_number ; $i++) {
  355. $sub_dir_array = FileManager::list_all_directories($dir_array[$i]); // Function recursivity
  356. if (is_array($dir_array) && is_array($sub_dir_array)) {
  357. $dir_array = array_merge($dir_array, $sub_dir_array); // Data merge
  358. }
  359. }
  360. }
  361. $result_array = $dir_array;
  362. chdir($save_dir) ;
  363. }
  364. return $result_array ;
  365. }
  366. /**
  367. This function receives a list of directories.
  368. It returns a list of all files in these directories
  369. @author Roan Embrechts
  370. @version 1.0
  371. */
  372. function list_all_files($dir_array)
  373. {
  374. $element_array = array();
  375. if (is_dir($dir_array)) {
  376. $save_dir = getcwd();
  377. foreach ($dir_array as $directory) {
  378. chdir($directory);
  379. $handle = opendir($directory);
  380. while ($element = readdir($handle)) {
  381. if ($element == '.' || $element == '..' || $element == '.htaccess') continue;
  382. // Skip the current and parent directories
  383. if (!is_dir($element)) {
  384. $element_array[] = $directory.'/'.$element;
  385. }
  386. }
  387. closedir($handle);
  388. chdir('..');
  389. chdir($save_dir);
  390. }
  391. }
  392. return $element_array;
  393. }
  394. /**
  395. Loads contents of file $filename into memory and returns them as a string.
  396. Function kept for compatibility with older PHP versions.
  397. Function is binary safe (is needed on Windows)
  398. */
  399. function compat_load_file($file_name)
  400. {
  401. $buffer = '';
  402. if (file_exists($file_name)) {
  403. $fp = fopen($file_name, 'rb');
  404. $buffer = fread ($fp, filesize($file_name));
  405. fclose ($fp);
  406. }
  407. return $buffer;
  408. }
  409. /**
  410. * Adds file/folder to document table in database
  411. * improvement from set_default_settings (see below):
  412. * take all info from function parameters
  413. * no global variables needed
  414. *
  415. * NOTE $glued_table should already have backticks around it
  416. * (get it from the database library, and it is done automatically)
  417. *
  418. * @param path, filename, filetype,
  419. $glued_table, default_visibility
  420. * action: Adds an entry to the document table with the default settings.
  421. * @author Olivier Cauberghe <olivier.cauberghe@ugent.be>
  422. * @author Roan Embrechts
  423. * @version 1.2
  424. */
  425. function set_default_settings($upload_path, $filename, $filetype = 'file', $glued_table, $default_visibility = 'v')
  426. {
  427. if (!$default_visibility) $default_visibility = 'v';
  428. // Make sure path is not wrongly formed
  429. $upload_path = !empty($upload_path) ? "/$upload_path" : '';
  430. $endchar = substr($filename, strlen($filename) - 1, 1);
  431. if ($endchar == "\\" || $endchar == '/') {
  432. $filename = substr($filename, 0, strlen($filename) - 1);
  433. }
  434. $full_file_name = $upload_path.'/'.$filename;
  435. $full_file_name = str_replace("//", '/', $full_file_name);
  436. $sql_query = "SELECT count(*) as number_existing FROM $glued_table WHERE path='$full_file_name'";
  437. $sql_result = Database::query($sql_query);
  438. $result = Database::fetch_array($sql_result);
  439. // Determine which query to execute
  440. if ($result['number_existing'] > 0) {
  441. // Entry exists, update
  442. $query = "UPDATE $glued_table SET path='$full_file_name',visibility='$default_visibility', filetype='$filetype'
  443. WHERE path='$full_file_name'";
  444. } else {
  445. // No entry exists, create new one
  446. $query = "INSERT INTO $glued_table (path,visibility,filetype)
  447. VALUES ('$full_file_name','$default_visibility','$filetype')";
  448. }
  449. Database::query($query);
  450. }
  451. }