fileManage.lib.php 19 KB

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