fileManage.lib.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672
  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. *
  7. * @package chamilo.library
  8. */
  9. /**
  10. * Update the file or directory path in the document db document table
  11. *
  12. * @author - Hugues Peeters <peeters@ipm.ucl.ac.be>
  13. * @param - action (string) - action type require : 'delete' or 'update'
  14. * @param - old_path (string) - old path info stored to change
  15. * @param - new_path (string) - new path info to substitute
  16. * @desc Update the file or directory path in the document db document table
  17. *
  18. */
  19. function update_db_info($action, $old_path, $new_path = '') {
  20. global $dbTable; // Table 'document'
  21. /* DELETE */
  22. if ($action == 'delete') {
  23. /* // RH: metadata, update 2004/08/23
  24. these two lines replaced by new code below:
  25. $query = "DELETE FROM `$dbTable`
  26. WHERE path='".$old_path."' OR path LIKE '".$old_path."/%'";
  27. */
  28. $old_path = Database::escape_string($old_path);
  29. $to_delete = "WHERE path LIKE BINARY '".$old_path."' OR path LIKE BINARY '".$old_path."/%'";
  30. $query = "DELETE FROM $dbTable " . $to_delete;
  31. $result = Database::query("SELECT id FROM $dbTable " . $to_delete);
  32. if (Database::num_rows($result)) {
  33. require_once api_get_path(INCLUDE_PATH).'../metadata/md_funcs.php';
  34. $mdStore = new mdstore(TRUE); // create if needed
  35. $md_type = (substr($dbTable, -13) == 'scormdocument') ? 'Scorm' : 'Document';
  36. while ($row = Database::fetch_array($result)) {
  37. $eid = $md_type . '.' . $row['id'];
  38. $mdStore->mds_delete($eid);
  39. $mdStore->mds_delete_offspring($eid);
  40. }
  41. }
  42. }
  43. /* UPDATE */
  44. if ($action == 'update') {
  45. //Display::display_normal_message("new_path = $new_path");
  46. if ($new_path[0] == '.') $new_path = substr($new_path, 1);
  47. $new_path = str_replace('//', '/', $new_path);
  48. //Display::display_normal_message("character 0 = " . $new_path[0] . " 1=" . $new_path[1]);
  49. //Display::display_normal_message("new_path = $new_path");
  50. // Older broken version
  51. //$query = "UPDATE `$dbTable`
  52. //SET path = CONCAT('".$new_path."', SUBSTRING(path, LENGTH('".$old_path."')+1) )
  53. //WHERE path = '".$old_path."' OR path LIKE '".$old_path."/%'";
  54. // Attempt to update - tested & working for root dir
  55. $new_path = Database::escape_string($new_path);
  56. $query = "UPDATE $dbTable
  57. SET path = CONCAT('".$new_path."', SUBSTRING(path, LENGTH('".$old_path."')+1) )
  58. WHERE path LIKE BINARY '".$old_path."' OR path LIKE BINARY '".$old_path."/%'";
  59. }
  60. //echo $query;
  61. //error_log($query,0);
  62. Database::query($query);
  63. //Display::display_normal_message("query = $query");
  64. }
  65. /**
  66. * Cheks a file or a directory actually exist at this location
  67. *
  68. * @author - Hugues Peeters <peeters@ipm.ucl.ac.be>
  69. * @param - file_path (string) - path of the presume existing file or dir
  70. * @return - boolean TRUE if the file or the directory exists
  71. * boolean FALSE otherwise.
  72. */
  73. function check_name_exist($file_path) {
  74. clearstatcache();
  75. $save_dir = getcwd();
  76. if (!is_dir(dirname($file_path))) {
  77. return false;
  78. }
  79. chdir(dirname($file_path));
  80. $file_name = basename($file_path);
  81. if (file_exists($file_name)) {
  82. chdir($save_dir);
  83. return true;
  84. } else {
  85. chdir($save_dir);
  86. return false;
  87. }
  88. }
  89. /**
  90. * Deletes a file or a directory
  91. *
  92. * @author - Hugues Peeters
  93. * @param - $file (String) - the path of file or directory to delete
  94. * @return - bolean - true if the delete succeed
  95. * bolean - false otherwise.
  96. * @see - delete() uses check_name_exist() and removeDir() functions
  97. */
  98. function my_delete($file) {
  99. if (check_name_exist($file)) {
  100. if (is_file($file)) { // FILE CASE
  101. unlink($file);
  102. return true;
  103. } elseif (is_dir($file)) { // DIRECTORY CASE
  104. removeDir($file);
  105. return true;
  106. }
  107. } else {
  108. return false; // no file or directory to delete
  109. }
  110. }
  111. /**
  112. * Removes a directory recursively
  113. *
  114. * @returns true if OK, otherwise false
  115. *
  116. * @author Amary <MasterNES@aol.com> (from Nexen.net)
  117. * @author Olivier Brouckaert <oli.brouckaert@skynet.be>
  118. *
  119. * @param string $dir directory to remove
  120. */
  121. function removeDir($dir) {
  122. if (!@$opendir = opendir($dir)) {
  123. return false;
  124. }
  125. while ($readdir = readdir($opendir)) {
  126. if ($readdir != '..' && $readdir != '.') {
  127. if (is_file($dir.'/'.$readdir)) {
  128. if (!@unlink($dir.'/'.$readdir)) {
  129. return false;
  130. }
  131. } elseif (is_dir($dir.'/'.$readdir)) {
  132. if (!removeDir($dir.'/'.$readdir)) {
  133. return false;
  134. }
  135. }
  136. }
  137. }
  138. closedir($opendir);
  139. if (!@rmdir($dir)) {
  140. return false;
  141. }
  142. return true;
  143. }
  144. /**
  145. * Renames a file or a directory
  146. *
  147. * @author - Hugues Peeters <peeters@ipm.ucl.ac.be>
  148. * @param - $file_path (string) - complete path of the file or the directory
  149. * @param - $new_file_name (string) - new name for the file or the directory
  150. * @return - boolean - true if succeed
  151. * - boolean - false otherwise
  152. * @see - rename() uses the check_name_exist() and php2phps() functions
  153. */
  154. function my_rename($file_path, $new_file_name) {
  155. $save_dir = getcwd();
  156. $path = dirname($file_path);
  157. $old_file_name = basename($file_path);
  158. $new_file_name = replace_dangerous_char($new_file_name);
  159. // If no extension, take the old one
  160. if ((strpos($new_file_name, '.') === false) && ($dotpos = strrpos($old_file_name, '.'))) {
  161. $new_file_name .= substr($old_file_name, $dotpos);
  162. }
  163. // Note: still possible: 'xx.yy' -rename-> '.yy' -rename-> 'zz'
  164. // This is useful for folder names, where otherwise '.' would be sticky
  165. // Extension PHP is not allowed, change to PHPS
  166. $new_file_name = php2phps($new_file_name);
  167. if ($new_file_name == $old_file_name) {
  168. return $old_file_name;
  169. }
  170. if (strtolower($new_file_name) != strtolower($old_file_name) && check_name_exist($path.'/'.$new_file_name)) {
  171. return false;
  172. }
  173. // On a Windows server, it would be better not to do the above check
  174. // because it succeeds for some new names resembling the old name.
  175. // But on Unix/Linux the check must be done because rename overwrites.
  176. chdir($path);
  177. $res = rename($old_file_name, $new_file_name) ? $new_file_name : false;
  178. chdir($save_dir);
  179. return $res;
  180. }
  181. /**
  182. * Moves a file or a directory to an other area
  183. *
  184. * @author - Hugues Peeters <peeters@ipm.ucl.ac.be>
  185. * @param - $source (String) - the path of file or directory to move
  186. * @param - $target (String) - the path of the new area
  187. * @return - bolean - true if the move succeed
  188. * bolean - false otherwise.
  189. * @see - move() uses check_name_exist() and copyDirTo() functions
  190. */
  191. function move($source, $target) {
  192. if (check_name_exist($source)) {
  193. $file_name = basename($source);
  194. if (check_name_exist($target.'/'.$file_name)) {
  195. return false;
  196. } else {
  197. /* File case */
  198. if (is_file($source)) {
  199. copy($source , $target.'/'.$file_name);
  200. unlink($source);
  201. return true;
  202. }
  203. /* Directory case */
  204. elseif (is_dir($source)) {
  205. // Check to not copy the directory inside itself
  206. if (ereg('^'.$source.'/', $target.'/')) { // TODO: ereg() function is deprecated in PHP 5.3
  207. return false;
  208. } else {
  209. copyDirTo($source, $target);
  210. return true;
  211. }
  212. }
  213. }
  214. } else {
  215. return false;
  216. }
  217. }
  218. /**
  219. * Moves a directory and its content to an other area
  220. *
  221. * @author - Hugues Peeters <peeters@ipm.ucl.ac.be>
  222. * @param - $orig_dir_path (string) - the path of the directory to move
  223. * @param - $destination (string) - the path of the new area
  224. * @return - no return
  225. */
  226. function copyDirTo($orig_dir_path, $destination, $move = true) {
  227. $save_dir = getcwd();
  228. // Extract directory name - create it at destination - update destination trail
  229. $dir_name = basename($orig_dir_path);
  230. if (is_dir($orig_dir_path)) {
  231. mkdir($destination.'/'.$dir_name, api_get_permissions_for_new_directories());
  232. $destination_trail = $destination.'/'.$dir_name;
  233. if (is_dir($destination)) {
  234. chdir ($orig_dir_path) ;
  235. $handle = opendir($orig_dir_path);
  236. while ($element = readdir($handle)) {
  237. if ($element == '.' || $element == '..') {
  238. continue; // Skip the current and parent directories
  239. } elseif (is_file($element)) {
  240. copy($element, $destination_trail.'/'.$element);
  241. if ($move) {
  242. unlink($element) ;
  243. }
  244. } elseif (is_dir($element)) {
  245. $dir_to_copy[] = $orig_dir_path.'/'.$element;
  246. }
  247. }
  248. closedir($handle) ;
  249. if (sizeof($dir_to_copy) > 0) {
  250. foreach ($dir_to_copy as $this_dir) {
  251. copyDirTo($this_dir, $destination_trail, $move); // Recursivity
  252. }
  253. }
  254. if ($move) {
  255. rmdir($orig_dir_path) ;
  256. }
  257. chdir($save_dir);
  258. }
  259. }
  260. }
  261. /* NOTE: These functions batch is used to automatically build HTML forms
  262. * with a list of the directories contained on the course Directory.
  263. *
  264. * From a thechnical point of view, form_dir_lists calls sort_dir wich calls index_dir
  265. */
  266. /**
  267. * Gets all the directories and subdirectories
  268. * contented in a given directory
  269. *
  270. * @author - Hugues Peeters <peeters@ipm.ucl.ac.be>
  271. * @param - path (string) - directory path of the one to index
  272. * @return - an array containing the path of all the subdirectories
  273. */
  274. function index_dir($path) {
  275. $dir_array = array();
  276. $save_dir = getcwd();
  277. if (is_dir($path)){
  278. chdir($path);
  279. $handle = opendir($path);
  280. // Reads directory content end record subdirectoies names in $dir_array
  281. if ($handle !== false) {
  282. while ($element = readdir($handle)) {
  283. if ($element == '.' || $element == '..') continue; // Skip the current and parent directories
  284. if (is_dir($element)) $dir_array[] = $path.'/'.$element;
  285. }
  286. closedir($handle) ;
  287. }
  288. // Recursive operation if subdirectories exist
  289. $dir_number = sizeof($dir_array);
  290. if ($dir_number > 0) {
  291. for ($i = 0 ; $i < $dir_number ; $i++) {
  292. $sub_dir_array = index_dir($dir_array[$i]); // Function recursivity
  293. $dir_array = array_merge((array)$dir_array, (array)$sub_dir_array); // Data merge
  294. }
  295. }
  296. }
  297. chdir($save_dir) ;
  298. return $dir_array ;
  299. }
  300. /**
  301. * Indexes all the directories and subdirectories
  302. * contented in a given directory, and sort them alphabetically
  303. *
  304. * @author - Hugues Peeters <peeters@ipm.ucl.ac.be>
  305. * @param - path (string) - directory path of the one to index
  306. * @return - an array containing the path of all the subdirectories sorted
  307. * false, if there is no directory
  308. * @see - index_and_sort_dir uses the index_dir() function
  309. */
  310. function index_and_sort_dir($path) {
  311. $dir_list = index_dir($path);
  312. if ($dir_list) {
  313. natsort($dir_list);
  314. return $dir_list;
  315. }
  316. return false;
  317. }
  318. /**
  319. * Builds a html form listing all directories of a given directory
  320. *
  321. */
  322. function form_dir_list($source_type, $source_component, $command, $base_work_dir) {
  323. $dir_list = index_and_sort_dir($base_work_dir);
  324. $dialog_box .= "<form action=\"".api_get_self()."\" method=\"post\">\n" ;
  325. $dialog_box .= "<input type=\"hidden\" name=\"".$source_type."\" value=\"".$source_component."\">\n" ;
  326. $dialog_box .= get_lang('Move').' '.$source_component.' '.get_lang('To');
  327. $dialog_box .= "<select name=\"".$command."\">\n" ;
  328. $dialog_box .= "<option value=\"\" style=\"color:#999999\">".get_lang('Root')."\n";
  329. $bwdLen = strlen($base_work_dir) ; // base directories lenght, used under
  330. /* build html form inputs */
  331. if ($dir_list) {
  332. while (list( , $path_value) = each($dir_list) ) {
  333. $path_value = substr ( $path_value , $bwdLen ); // Truncates cunfidential informations confidentielles
  334. $dirname = basename ($path_value); // Extracts $path_value directory name du nom
  335. /* compute de the display tab */
  336. $tab = ""; // $tab reinitialisation
  337. $depth = substr_count($path_value, '/'); // The number of nombre '/' indicates the directory deepness
  338. for ($h = 0; $h < $depth; $h++) {
  339. $tab .= "&nbsp;&nbsp;";
  340. }
  341. $dialog_box .= "<option value=\"$path_value\">$tab>$dirname\n";
  342. }
  343. }
  344. $dialog_box .= "</select>\n";
  345. $dialog_box .= "<input type=\"submit\" value=\"".get_lang('Ok')."\">";
  346. $dialog_box .= "</form>\n";
  347. return $dialog_box;
  348. }
  349. /**
  350. * Extracting extention of a filename
  351. *
  352. * @returns array
  353. * @param string $filename filename
  354. */
  355. function getextension($filename) {
  356. $bouts = explode('.', $filename);
  357. return array(array_pop($bouts), implode('.', $bouts));
  358. }
  359. /**
  360. * Calculation size of a directory
  361. *
  362. * @returns integer size
  363. * @param string $path path to size
  364. * @param boolean $recursive if true , include subdir in total
  365. */
  366. function dirsize($root, $recursive = true) {
  367. $dir = @opendir($root);
  368. $size = 0;
  369. while ($file = @readdir($dir)) {
  370. if (!in_array($file, array('.', '..'))) {
  371. if (is_dir($root.'/'.$file)) {
  372. $size += $recursive ? dirsize($root.'/'.$file) : 0;
  373. } else {
  374. $size += @filesize($root.'/'.$file);
  375. }
  376. }
  377. }
  378. @closedir($dir);
  379. return $size;
  380. }
  381. /* CLASS FileManager */
  382. /**
  383. This class contains functions that you can access statically.
  384. FileManager::list_all_directories($path)
  385. FileManager::list_all_files($dir_array)
  386. FileManager::compat_load_file($file_name)
  387. FileManager::set_default_settings($upload_path, $filename, $filetype="file", $glued_table, $default_visibility='v')
  388. @author Roan Embrechts
  389. @version 1.1, July 2004
  390. */
  391. class FileManager
  392. {
  393. /**
  394. Returns a list of all directories, except the base dir,
  395. of the current course. This function uses recursion.
  396. Convention: the parameter $path does not end with a slash.
  397. @author Roan Embrechts
  398. @version 1.0.1
  399. */
  400. function list_all_directories($path) {
  401. $result_array = array();
  402. if (is_dir($path)) {
  403. $save_dir = getcwd();
  404. chdir($path);
  405. $handle = opendir($path);
  406. while ($element = readdir($handle)) {
  407. if ($element == '.' || $element == '..') continue; // Skip the current and parent directories
  408. if (is_dir($element)) {
  409. $dir_array[] = $path.'/'.$element;
  410. }
  411. }
  412. closedir($handle);
  413. // Recursive operation if subdirectories exist
  414. $dir_number = sizeof($dir_array);
  415. if ($dir_number > 0) {
  416. for ($i = 0 ; $i < $dir_number ; $i++) {
  417. $sub_dir_array = FileManager::list_all_directories($dir_array[$i]); // Function recursivity
  418. if (is_array($dir_array) && is_array($sub_dir_array)) {
  419. $dir_array = array_merge($dir_array, $sub_dir_array); // Data merge
  420. }
  421. }
  422. }
  423. $result_array = $dir_array;
  424. chdir($save_dir) ;
  425. }
  426. return $result_array ;
  427. }
  428. /**
  429. This function receives a list of directories.
  430. It returns a list of all files in these directories
  431. @author Roan Embrechts
  432. @version 1.0
  433. */
  434. function list_all_files($dir_array) {
  435. $element_array = array();
  436. if (is_dir($dir_array)) {
  437. $save_dir = getcwd();
  438. foreach ($dir_array as $directory) {
  439. chdir($directory);
  440. $handle = opendir($directory);
  441. while ($element = readdir($handle)) {
  442. if ($element == '.' || $element == '..' || $element == '.htaccess') continue; // Skip the current and parent directories
  443. if (!is_dir($element)) {
  444. $element_array[] = $directory.'/'.$element;
  445. }
  446. }
  447. closedir($handle);
  448. chdir('..');
  449. chdir($save_dir);
  450. }
  451. }
  452. return $element_array;
  453. }
  454. /**
  455. Loads contents of file $filename into memory and returns them as a string.
  456. Function kept for compatibility with older PHP versions.
  457. Function is binary safe (is needed on Windows)
  458. */
  459. function compat_load_file($file_name) {
  460. $buffer = '';
  461. if (file_exists($file_name)) {
  462. $fp = fopen($file_name, 'rb');
  463. $buffer = fread ($fp, filesize($file_name));
  464. fclose ($fp);
  465. }
  466. return $buffer;
  467. }
  468. /**
  469. * Adds file/folder to document table in database
  470. * improvement from set_default_settings (see below):
  471. * take all info from function parameters
  472. * no global variables needed
  473. *
  474. * NOTE $glued_table should already have backticks around it
  475. * (get it from the database library, and it is done automatically)
  476. *
  477. * @param path, filename, filetype,
  478. $glued_table, default_visibility
  479. * @action Adds an entry to the document table with the default settings.
  480. * @author Olivier Cauberghe <olivier.cauberghe@ugent.be>
  481. * @author Roan Embrechts
  482. * @version 1.2
  483. */
  484. function set_default_settings($upload_path, $filename, $filetype = 'file', $glued_table, $default_visibility = 'v') {
  485. if (!$default_visibility) $default_visibility = 'v';
  486. // Make sure path is not wrongly formed
  487. $upload_path = !empty($upload_path) ? "/$upload_path" : '';
  488. $endchar = substr($filename, strlen($filename) - 1, 1);
  489. if ($endchar == "\\" || $endchar == '/') {
  490. $filename = substr($filename, 0, strlen($filename) - 1);
  491. }
  492. $full_file_name = $upload_path.'/'.$filename;
  493. //$upload_path = str_replace("//", '/', $upload_path);
  494. $full_file_name = str_replace("//", '/', $full_file_name);
  495. $sql_query = "SELECT count(*) as number_existing FROM $glued_table WHERE path='$full_file_name'";
  496. $sql_result = Database::query($sql_query);
  497. $result = Database::fetch_array($sql_result);
  498. // Determine which query to execute
  499. if ($result['number_existing'] > 0) {
  500. // Entry exists, update
  501. $query = "UPDATE $glued_table SET path='$full_file_name',visibility='$default_visibility', filetype='$filetype' WHERE path='$full_file_name'";
  502. } else {
  503. // No entry exists, create new one
  504. $query = "INSERT INTO $glued_table (path,visibility,filetype) VALUES('$full_file_name','$default_visibility','$filetype')";
  505. }
  506. Database::query($query);
  507. }
  508. } //end class FileManager
  509. /* DEPRECATED FUNCTIONS */
  510. /**
  511. * Like in Java, creates the directory named by this abstract pathname,
  512. * including any necessary but nonexistent parent directories.
  513. *
  514. * @author Hugues Peeters <peeters@ipm.ucl.ac.be>
  515. * @author Christophe Gesche <gesche@ipm.ucl.ac.be>
  516. *
  517. * @param string $path - path to create
  518. * @param string $mode - directory permission (default is '770')
  519. *
  520. * @return boolean TRUE if succeeds FALSE otherwise
  521. */
  522. function mkdirs($path, $mode = '0770') {
  523. if (file_exists($path)) {
  524. return false;
  525. } else {
  526. FileManager :: mkdirs(dirname($path), $mode);
  527. //mkdir($path, $mode);
  528. return true;
  529. }
  530. }
  531. /**
  532. * @deprecated 06-FEB-2010. The function mkdir() is able to create directories recursively.
  533. * @link http://php.net/manual/en/function.mkdir.php
  534. *
  535. * to create missing directory in a gived path
  536. *
  537. * @returns a resource identifier or FALSE if the query was not executed correctly.
  538. * @author KilerCris@Mail.com original function from php manual
  539. * @author Christophe Gesch� gesche@ipm.ucl.ac.be Claroline Team
  540. * @since 28-Aug-2001 09:12
  541. * @param sting $path wanted path
  542. * @param boolean $verbose fix if comments must be printed
  543. * @param string $mode fix if chmod is same of parent or default (Note: This misterious parameter is not used).
  544. * @global string $langCreatedIn string to say "create in"
  545. */
  546. function mkpath($path, $verbose = false, $mode = 'herit') {
  547. global $langCreatedIn, $_configuration;
  548. $path = str_replace('/', "\\", $path);
  549. $dirs = explode("\\", $path);
  550. $path = $dirs[0];
  551. if ($verbose) {
  552. echo '<ul>';
  553. }
  554. for ($i = 1; $i < sizeof($dirs); $i++) {
  555. $path .= '/'.$dirs[$i];
  556. if (ereg('^'.$path, $_configuration['root_sys']) && strlen($path) < strlen($_configuration['root_sys'])) {
  557. continue;
  558. }
  559. if (!is_dir($path)) {
  560. $ret = mkdir($path, api_get_permissions_for_new_directories());
  561. if ($ret) {
  562. if ($verbose) {
  563. echo '<li><strong>'.basename($path).'</strong><br />'.$langCreatedIn.'<br /><strong>'.realpath($path.'/..').'</strong></li>';
  564. }
  565. } else {
  566. if ($verbose) {
  567. echo '</ul>error : '.$path.' not created';
  568. }
  569. $ret = false;
  570. break;
  571. }
  572. }
  573. }
  574. if ($verbose) {
  575. echo '</ul>';
  576. }
  577. return $ret;
  578. }