fileManager.lib.php 78 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124
  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. This class contains functions that you can access statically.
  10. FileManager::list_all_directories($path)
  11. FileManager::list_all_files($dir_array)
  12. FileManager::compat_load_file($file_name)
  13. FileManager::set_default_settings($upload_path, $filename, $filetype="file", $glued_table, $default_visibility='v')
  14. @author Roan Embrechts
  15. @version 1.1, July 2004
  16. * @package chamilo.library
  17. */
  18. class FileManager
  19. {
  20. /**
  21. * Update the file or directory path in the document db document table
  22. *
  23. * @author - Hugues Peeters <peeters@ipm.ucl.ac.be>
  24. * @param - action (string) - action type require : 'delete' or 'update'
  25. * @param - old_path (string) - old path info stored to change
  26. * @param - new_path (string) - new path info to substitute
  27. * @desc Update the file or directory path in the document db document table
  28. *
  29. */
  30. static function update_db_info($action, $old_path, $new_path = '')
  31. {
  32. $dbTable = Database::get_course_table(TABLE_DOCUMENT);
  33. $course_id = api_get_course_int_id();
  34. /* DELETE */
  35. if ($action == 'delete') {
  36. $old_path = Database::escape_string($old_path);
  37. $to_delete = "WHERE c_id = $course_id AND path LIKE BINARY '".$old_path."' OR path LIKE BINARY '".$old_path."/%'";
  38. $query = "DELETE FROM $dbTable ".$to_delete;
  39. $result = Database::query("SELECT id FROM $dbTable ".$to_delete);
  40. if (Database::num_rows($result)) {
  41. require_once api_get_path(INCLUDE_PATH).'../metadata/md_funcs.php';
  42. $mdStore = new mdstore(true); // create if needed
  43. $md_type = (substr($dbTable, -13) == 'scormdocument') ? 'Scorm' : 'Document';
  44. while ($row = Database::fetch_array($result)) {
  45. $eid = $md_type.'.'.$row['id'];
  46. $mdStore->mds_delete($eid);
  47. $mdStore->mds_delete_offspring($eid);
  48. }
  49. }
  50. }
  51. /* UPDATE */
  52. if ($action == 'update') {
  53. if ($new_path[0] == '.') {
  54. $new_path = substr($new_path, 1);
  55. }
  56. $new_path = str_replace('//', '/', $new_path);
  57. // Attempt to update - tested & working for root dir
  58. $new_path = Database::escape_string($new_path);
  59. $query = "UPDATE $dbTable
  60. SET path = CONCAT('".$new_path."', SUBSTRING(path, LENGTH('".$old_path."')+1) )
  61. WHERE c_id = $course_id AND path LIKE BINARY '".$old_path."' OR path LIKE BINARY '".$old_path."/%'";
  62. }
  63. Database::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. static function check_name_exist($file_path)
  74. {
  75. clearstatcache();
  76. $save_dir = getcwd();
  77. if (!is_dir(dirname($file_path))) {
  78. return false;
  79. }
  80. chdir(dirname($file_path));
  81. $file_name = basename($file_path);
  82. if (file_exists($file_name)) {
  83. chdir($save_dir);
  84. return true;
  85. } else {
  86. chdir($save_dir);
  87. return false;
  88. }
  89. }
  90. /**
  91. * Deletes a file or a directory
  92. *
  93. * @author - Hugues Peeters
  94. * @param - $file (String) - the path of file or directory to delete
  95. * @return - bolean - true if the delete succeed
  96. * bolean - false otherwise.
  97. * @see - delete() uses check_name_exist() and removeDir() functions
  98. */
  99. static function my_delete($file)
  100. {
  101. if (self::check_name_exist($file)) {
  102. if (is_file($file)) { // FILE CASE
  103. unlink($file);
  104. return true;
  105. } elseif (is_dir($file)) { // DIRECTORY CASE
  106. self::removeDir($file);
  107. return true;
  108. }
  109. } else {
  110. return false; // no file or directory to delete
  111. }
  112. }
  113. /**
  114. * Removes a directory recursively
  115. *
  116. * @returns true if OK, otherwise false
  117. *
  118. * @author Amary <MasterNES@aol.com> (from Nexen.net)
  119. * @author Olivier Brouckaert <oli.brouckaert@skynet.be>
  120. *
  121. * @param string $dir directory to remove
  122. */
  123. static function removeDir($dir)
  124. {
  125. if (!@$opendir = opendir($dir)) {
  126. return false;
  127. }
  128. while ($readdir = readdir($opendir)) {
  129. if ($readdir != '..' && $readdir != '.') {
  130. if (is_file($dir.'/'.$readdir)) {
  131. if (!@unlink($dir.'/'.$readdir)) {
  132. return false;
  133. }
  134. } elseif (is_dir($dir.'/'.$readdir)) {
  135. if (!self::removeDir($dir.'/'.$readdir)) {
  136. return false;
  137. }
  138. }
  139. }
  140. }
  141. closedir($opendir);
  142. if (!@rmdir($dir)) {
  143. return false;
  144. }
  145. return true;
  146. }
  147. /**
  148. * Return true if folder is empty
  149. * @author : hubert.borderiou@grenet.fr
  150. * @param string $in_folder : folder path on disk
  151. * @return 1 if folder is empty, 0 otherwise
  152. */
  153. static function folder_is_empty($in_folder)
  154. {
  155. $tab_folder_content = scandir($in_folder);
  156. $folder_is_empty = 0;
  157. if ((count($tab_folder_content) == 2 && in_array(".", $tab_folder_content) && in_array(
  158. "..",
  159. $tab_folder_content
  160. )) || (count($tab_folder_content) < 2)
  161. ) {
  162. $folder_is_empty = 1;
  163. }
  164. return $folder_is_empty;
  165. }
  166. /**
  167. * Renames a file or a directory
  168. *
  169. * @author - Hugues Peeters <peeters@ipm.ucl.ac.be>
  170. * @param - $file_path (string) - complete path of the file or the directory
  171. * @param - $new_file_name (string) - new name for the file or the directory
  172. * @return - boolean - true if succeed
  173. * - boolean - false otherwise
  174. * @see - rename() uses the check_name_exist() and php2phps() functions
  175. */
  176. static function my_rename($file_path, $new_file_name)
  177. {
  178. $save_dir = getcwd();
  179. $path = dirname($file_path);
  180. $old_file_name = basename($file_path);
  181. $new_file_name = replace_dangerous_char($new_file_name);
  182. // If no extension, take the old one
  183. if ((strpos($new_file_name, '.') === false) && ($dotpos = strrpos($old_file_name, '.'))) {
  184. $new_file_name .= substr($old_file_name, $dotpos);
  185. }
  186. // Note: still possible: 'xx.yy' -rename-> '.yy' -rename-> 'zz'
  187. // This is useful for folder names, where otherwise '.' would be sticky
  188. // Extension PHP is not allowed, change to PHPS
  189. $new_file_name = self::php2phps($new_file_name);
  190. if ($new_file_name == $old_file_name) {
  191. return $old_file_name;
  192. }
  193. if (strtolower($new_file_name) != strtolower($old_file_name) && self::check_name_exist(
  194. $path.'/'.$new_file_name
  195. )
  196. ) {
  197. return false;
  198. }
  199. // On a Windows server, it would be better not to do the above check
  200. // because it succeeds for some new names resembling the old name.
  201. // But on Unix/Linux the check must be done because rename overwrites.
  202. chdir($path);
  203. $res = rename($old_file_name, $new_file_name) ? $new_file_name : false;
  204. chdir($save_dir);
  205. return $res;
  206. }
  207. /**
  208. * Moves a file or a directory to an other area
  209. *
  210. * @author - Hugues Peeters <peeters@ipm.ucl.ac.be>
  211. * @param - $source (String) - the path of file or directory to move
  212. * @param - $target (String) - the path of the new area
  213. * @return - bolean - true if the move succeed
  214. * bolean - false otherwise.
  215. * @see - move() uses check_name_exist() and copyDirTo() functions
  216. */
  217. static function move($source, $target)
  218. {
  219. if (self::check_name_exist($source)) {
  220. $file_name = basename($source);
  221. if (self::check_name_exist($target.'/'.$file_name)) {
  222. return false;
  223. } else {
  224. /* File case */
  225. if (is_file($source)) {
  226. copy($source, $target.'/'.$file_name);
  227. unlink($source);
  228. return true;
  229. } elseif (is_dir($source)) {
  230. /* Directory case */
  231. // Check to not copy the directory inside itself
  232. if (ereg('^'.$source.'/', $target.'/')) { // TODO: ereg() function is deprecated in PHP 5.3
  233. return false;
  234. } else {
  235. self::copyDirTo($source, $target);
  236. return true;
  237. }
  238. }
  239. }
  240. } else {
  241. return false;
  242. }
  243. }
  244. /**
  245. * Moves a directory and its content to an other area
  246. *
  247. * @author - Hugues Peeters <peeters@ipm.ucl.ac.be>
  248. * @param - $orig_dir_path (string) - the path of the directory to move
  249. * @param - $destination (string) - the path of the new area
  250. * @return - no return
  251. */
  252. static function copyDirTo($orig_dir_path, $destination, $move = true)
  253. {
  254. $save_dir = getcwd();
  255. // Extract directory name - create it at destination - update destination trail
  256. $dir_name = basename($orig_dir_path);
  257. if (is_dir($orig_dir_path)) {
  258. mkdir($destination.'/'.$dir_name, api_get_permissions_for_new_directories());
  259. $destination_trail = $destination.'/'.$dir_name;
  260. if (is_dir($destination)) {
  261. chdir($orig_dir_path);
  262. $handle = opendir($orig_dir_path);
  263. while ($element = readdir($handle)) {
  264. if ($element == '.' || $element == '..') {
  265. continue; // Skip the current and parent directories
  266. } elseif (is_file($element)) {
  267. copy($element, $destination_trail.'/'.$element);
  268. if ($move) {
  269. unlink($element);
  270. }
  271. } elseif (is_dir($element)) {
  272. $dir_to_copy[] = $orig_dir_path.'/'.$element;
  273. }
  274. }
  275. closedir($handle);
  276. if (sizeof($dir_to_copy) > 0) {
  277. foreach ($dir_to_copy as $this_dir) {
  278. self::copyDirTo($this_dir, $destination_trail, $move); // Recursivity
  279. }
  280. }
  281. if ($move) {
  282. rmdir($orig_dir_path);
  283. }
  284. chdir($save_dir);
  285. }
  286. }
  287. }
  288. /* NOTE: These functions batch is used to automatically build HTML forms
  289. * with a list of the directories contained on the course Directory.
  290. *
  291. * From a thechnical point of view, form_dir_lists calls sort_dir wich calls index_dir
  292. */
  293. /**
  294. * Gets all the directories and subdirectories
  295. * contented in a given directory
  296. *
  297. * @author - Hugues Peeters <peeters@ipm.ucl.ac.be>
  298. * @param - path (string) - directory path of the one to index
  299. * @return - an array containing the path of all the subdirectories
  300. */
  301. static function index_dir($path)
  302. {
  303. $dir_array = array();
  304. $save_dir = getcwd();
  305. if (is_dir($path)) {
  306. chdir($path);
  307. $handle = opendir($path);
  308. // Reads directory content end record subdirectoies names in $dir_array
  309. if ($handle !== false) {
  310. while ($element = readdir($handle)) {
  311. if ($element == '.' || $element == '..') {
  312. continue;
  313. } // Skip the current and parent directories
  314. if (is_dir($element)) {
  315. $dir_array[] = $path.'/'.$element;
  316. }
  317. }
  318. closedir($handle);
  319. }
  320. // Recursive operation if subdirectories exist
  321. $dir_number = sizeof($dir_array);
  322. if ($dir_number > 0) {
  323. for ($i = 0; $i < $dir_number; $i++) {
  324. $sub_dir_array = self::index_dir($dir_array[$i]); // Function recursivity
  325. $dir_array = array_merge((array)$dir_array, (array)$sub_dir_array); // Data merge
  326. }
  327. }
  328. }
  329. chdir($save_dir);
  330. return $dir_array;
  331. }
  332. /**
  333. * Indexes all the directories and subdirectories
  334. * contented in a given directory, and sort them alphabetically
  335. *
  336. * @author - Hugues Peeters <peeters@ipm.ucl.ac.be>
  337. * @param - path (string) - directory path of the one to index
  338. * @return - an array containing the path of all the subdirectories sorted
  339. * false, if there is no directory
  340. * @see - index_and_sort_dir uses the index_dir() function
  341. */
  342. static function index_and_sort_dir($path)
  343. {
  344. $dir_list = self::index_dir($path);
  345. if ($dir_list) {
  346. natsort($dir_list);
  347. return $dir_list;
  348. }
  349. return false;
  350. }
  351. /**
  352. * Extracting extention of a filename
  353. *
  354. * @returns array
  355. * @param string $filename filename
  356. */
  357. static function getextension($filename)
  358. {
  359. $bouts = explode('.', $filename);
  360. return array(array_pop($bouts), implode('.', $bouts));
  361. }
  362. /**
  363. * Calculation size of a directory
  364. *
  365. * @returns integer size
  366. * @param string $path path to size
  367. * @param boolean $recursive if true , include subdir in total
  368. */
  369. static function dirsize($root, $recursive = true)
  370. {
  371. $dir = @opendir($root);
  372. $size = 0;
  373. while ($file = @readdir($dir)) {
  374. if (!in_array($file, array('.', '..'))) {
  375. if (is_dir($root.'/'.$file)) {
  376. $size += $recursive ? dirsize($root.'/'.$file) : 0;
  377. } else {
  378. $size += @filesize($root.'/'.$file);
  379. }
  380. }
  381. }
  382. @closedir($dir);
  383. return $size;
  384. }
  385. /**
  386. Returns a list of all directories, except the base dir,
  387. of the current course. This function uses recursion.
  388. Convention: the parameter $path does not end with a slash.
  389. @author Roan Embrechts
  390. @version 1.0.1
  391. */
  392. static function list_all_directories($path)
  393. {
  394. $result_array = array();
  395. if (is_dir($path)) {
  396. $save_dir = getcwd();
  397. chdir($path);
  398. $handle = opendir($path);
  399. while ($element = readdir($handle)) {
  400. if ($element == '.' || $element == '..') {
  401. continue;
  402. } // Skip the current and parent directories
  403. if (is_dir($element)) {
  404. $dir_array[] = $path.'/'.$element;
  405. }
  406. }
  407. closedir($handle);
  408. // Recursive operation if subdirectories exist
  409. $dir_number = sizeof($dir_array);
  410. if ($dir_number > 0) {
  411. for ($i = 0; $i < $dir_number; $i++) {
  412. $sub_dir_array = self::list_all_directories($dir_array[$i]); // Function recursivity
  413. if (is_array($dir_array) && is_array($sub_dir_array)) {
  414. $dir_array = array_merge($dir_array, $sub_dir_array); // Data merge
  415. }
  416. }
  417. }
  418. $result_array = $dir_array;
  419. chdir($save_dir);
  420. }
  421. return $result_array;
  422. }
  423. /**
  424. This function receives a list of directories.
  425. It returns a list of all files in these directories
  426. @author Roan Embrechts
  427. @version 1.0
  428. */
  429. function list_all_files($dir_array)
  430. {
  431. $element_array = array();
  432. if (is_dir($dir_array)) {
  433. $save_dir = getcwd();
  434. foreach ($dir_array as $directory) {
  435. chdir($directory);
  436. $handle = opendir($directory);
  437. while ($element = readdir($handle)) {
  438. if ($element == '.' || $element == '..' || $element == '.htaccess') {
  439. continue;
  440. } // 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. static function compat_load_file($file_name)
  458. {
  459. $buffer = '';
  460. if (file_exists($file_name)) {
  461. $fp = fopen($file_name, 'rb');
  462. $buffer = fread($fp, filesize($file_name));
  463. fclose($fp);
  464. }
  465. return $buffer;
  466. }
  467. static function choose_image($file_name)
  468. {
  469. static $type, $image;
  470. /* TABLES INITIALISATION */
  471. if (!$type || !$image) {
  472. $type['word'] = array('doc', 'dot', 'rtf', 'mcw', 'wps', 'psw', 'docm', 'docx', 'dotm', 'dotx');
  473. $type['web'] = array('htm', 'html', 'htx', 'xml', 'xsl', 'php', 'xhtml');
  474. $type['image'] = array('gif', 'jpg', 'png', 'bmp', 'jpeg', 'tif', 'tiff');
  475. $type['image_vect'] = array('svg', 'svgz');
  476. $type['audio'] = array('wav', 'mid', 'mp2', 'mp3', 'midi', 'sib', 'amr', 'kar', 'oga', 'au', 'wma');
  477. $type['video'] = array(
  478. 'mp4',
  479. 'mov',
  480. 'rm',
  481. 'pls',
  482. 'mpg',
  483. 'mpeg',
  484. 'm2v',
  485. 'm4v',
  486. 'flv',
  487. 'f4v',
  488. 'avi',
  489. 'wmv',
  490. 'asf',
  491. '3gp',
  492. 'ogv',
  493. 'ogg',
  494. 'ogx',
  495. 'webm'
  496. );
  497. $type['excel'] = array('xls', 'xlt', 'xls', 'xlt', 'pxl', 'xlsx', 'xlsm', 'xlam', 'xlsb', 'xltm', 'xltx');
  498. $type['compressed'] = array('zip', 'tar', 'rar', 'gz');
  499. $type['code'] = array('js', 'cpp', 'c', 'java', 'phps', 'jsp', 'asp', 'aspx', 'cfm');
  500. $type['acrobat'] = array('pdf');
  501. $type['powerpoint'] = array('ppt', 'pps', 'pptm', 'pptx', 'potm', 'potx', 'ppam', 'ppsm', 'ppsx');
  502. $type['flash'] = array('fla', 'swf');
  503. $type['text'] = array('txt', 'log');
  504. $type['oo_writer'] = array('odt', 'ott', 'sxw', 'stw');
  505. $type['oo_calc'] = array('ods', 'ots', 'sxc', 'stc');
  506. $type['oo_impress'] = array('odp', 'otp', 'sxi', 'sti');
  507. $type['oo_draw'] = array('odg', 'otg', 'sxd', 'std');
  508. $type['epub'] = array('epub');
  509. $type['java'] = array('class', 'jar');
  510. $type['freemind'] = array('mm');
  511. $image['word'] = 'word.gif';
  512. $image['web'] = 'file_html.gif';
  513. $image['image'] = 'file_image.gif';
  514. $image['image_vect'] = 'file_svg.png';
  515. $image['audio'] = 'file_sound.gif';
  516. $image['video'] = 'film.gif';
  517. $image['excel'] = 'excel.gif';
  518. $image['compressed'] = 'file_zip.gif';
  519. $image['code'] = 'icons/22/mime_code.png';
  520. $image['acrobat'] = 'file_pdf.gif';
  521. $image['powerpoint'] = 'powerpoint.gif';
  522. $image['flash'] = 'file_flash.gif';
  523. $image['text'] = 'icons/22/mime_text.png';
  524. $image['oo_writer'] = 'file_oo_writer.gif';
  525. $image['oo_calc'] = 'file_oo_calc.gif';
  526. $image['oo_impress'] = 'file_oo_impress.gif';
  527. $image['oo_draw'] = 'file_oo_draw.gif';
  528. $image['epub'] = 'file_epub.gif';
  529. $image['java'] = 'file_java.png';
  530. $image['freemind'] = 'file_freemind.png';
  531. }
  532. /* FUNCTION CORE */
  533. $extension = array();
  534. if (!is_array($file_name)) {
  535. if (preg_match('/\.([[:alnum:]]+)(\?|$)/', $file_name, $extension)) {
  536. $extension[1] = strtolower($extension[1]);
  537. foreach ($type as $generic_type => $extension_list) {
  538. if (in_array($extension[1], $extension_list)) {
  539. return $image[$generic_type];
  540. }
  541. }
  542. }
  543. }
  544. return 'defaut.gif';
  545. }
  546. /**
  547. * Transform the file path to a URL.
  548. *
  549. * @param - $file_path (string) - Relative local path of the file on the hard disk
  550. * @return - Relative url
  551. */
  552. static function format_url($file_path)
  553. {
  554. $path_component = explode('/', $file_path);
  555. $path_component = array_map('rawurlencode', $path_component);
  556. return implode('/', $path_component);
  557. }
  558. /**
  559. * Calculates the total size of a directory by adding the sizes (that
  560. * are stored in the database) of all files & folders in this directory.
  561. *
  562. * @param string $path
  563. * @param boolean $can_see_invisible
  564. * @return Total size
  565. */
  566. static function get_total_folder_size($path, $can_see_invisible = false)
  567. {
  568. $table_itemproperty = Database::get_course_table(TABLE_ITEM_PROPERTY);
  569. $table_document = Database::get_course_table(TABLE_DOCUMENT);
  570. $tool_document = TOOL_DOCUMENT;
  571. $course_id = api_get_course_int_id();
  572. $session_id = api_get_session_id();
  573. $session_condition = api_get_session_condition($session_id, true, true, 'props.id_session');
  574. $visibility_rule = ' props.visibility '.($can_see_invisible ? '<> 2' : '= 1');
  575. $sql = "SELECT SUM(table1.size) FROM (
  576. SELECT size FROM $table_itemproperty AS props, $table_document AS docs
  577. WHERE docs.c_id = $course_id AND
  578. docs.id = props.ref AND
  579. docs.path LIKE '$path/%' AND
  580. props.c_id = $course_id AND
  581. props.tool = '$tool_document' AND
  582. $visibility_rule
  583. $session_condition
  584. GROUP BY ref
  585. ) as table1";
  586. $result = Database::query($sql);
  587. if ($result && Database::num_rows($result) != 0) {
  588. $row = Database::fetch_row($result);
  589. return $row[0] == null ? 0 : $row[0];
  590. } else {
  591. return 0;
  592. }
  593. }
  594. /**
  595. * Changes the file name extension from .php to .phps
  596. * Useful for securing a site.
  597. *
  598. * @author - Hugues Peeters <peeters@ipm.ucl.ac.be>
  599. * @param - file_name (string) name of a file
  600. *
  601. * @return string the filename phps'ized
  602. */
  603. static function php2phps($file_name)
  604. {
  605. return preg_replace('/\.(php.?|phtml.?)(\.){0,1}.*$/i', '.phps', $file_name);
  606. }
  607. /**
  608. * Renames .htaccess & .HTACCESS to htaccess.txt
  609. *
  610. * @param string $filename
  611. * @return string
  612. */
  613. static function htaccess2txt($filename)
  614. {
  615. return str_replace(array('.htaccess', '.HTACCESS'), array('htaccess.txt', 'htaccess.txt'), $filename);
  616. }
  617. /**
  618. * This function executes our safety precautions
  619. * more functions can be added
  620. *
  621. * @param string $filename
  622. * @return string
  623. * @see FileManager::php2phps()
  624. * @see htaccess2txt()
  625. */
  626. static function disable_dangerous_file($filename)
  627. {
  628. return self::htaccess2txt(self::php2phps($filename));
  629. }
  630. /**
  631. * This function generates a unique name for a file on a given location. Filenames are changed to name_#.ext
  632. *
  633. * @param string $path
  634. * @param string $name
  635. * @return new unique name
  636. */
  637. static function unique_name($path, $name)
  638. {
  639. $ext = substr(strrchr($name, '.'), 0);
  640. $name_no_ext = substr($name, 0, strlen($name) - strlen(strstr($name, $ext)));
  641. $n = 0;
  642. $unique = '';
  643. while (file_exists($path.$name_no_ext.$unique.$ext)) {
  644. $unique = '_'.++$n;
  645. }
  646. return $name_no_ext.$unique.$ext;
  647. }
  648. /**
  649. * Returns the name without extension, used for the title
  650. *
  651. * @param string $name
  652. * @return name without the extension
  653. */
  654. static function get_document_title($name)
  655. {
  656. // If they upload .htaccess...
  657. $name = self::disable_dangerous_file($name);
  658. $ext = substr(strrchr($name, '.'), 0);
  659. return addslashes(substr($name, 0, strlen($name) - strlen(strstr($name, $ext))));
  660. }
  661. /**
  662. * This function checks if the upload succeeded
  663. *
  664. * @param array $uploaded_file ($_FILES)
  665. * @param bool $show_output
  666. *
  667. * @return true if upload succeeded
  668. */
  669. static function process_uploaded_file($uploaded_file, $show_output = true)
  670. {
  671. // Checking the error code sent with the file upload.
  672. switch ($uploaded_file['error']) {
  673. case 1:
  674. // The uploaded file exceeds the upload_max_filesize directive in php.ini.
  675. if ($show_output) {
  676. Display::display_error_message(
  677. get_lang('UplExceedMaxServerUpload').ini_get('upload_max_filesize')
  678. );
  679. }
  680. return false;
  681. case 2:
  682. // The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.
  683. // Not used at the moment, but could be handy if we want to limit the size of an upload (e.g. image upload in html editor).
  684. $max_file_size = intval($_POST['MAX_FILE_SIZE']);
  685. if ($show_output) {
  686. Display::display_error_message(get_lang('UplExceedMaxPostSize').Text::format_file_size($max_file_size));
  687. }
  688. return false;
  689. case 3:
  690. // The uploaded file was only partially uploaded.
  691. if ($show_output) {
  692. Display::display_error_message(get_lang('UplPartialUpload').' '.get_lang('PleaseTryAgain'));
  693. }
  694. return false;
  695. case 4:
  696. // No file was uploaded.
  697. if ($show_output) {
  698. Display::display_error_message(get_lang('UplNoFileUploaded').' '.get_lang('UplSelectFileFirst'));
  699. }
  700. return false;
  701. }
  702. if (!file_exists($uploaded_file['tmp_name'])) {
  703. // No file was uploaded.
  704. if ($show_output) {
  705. Display::display_error_message(get_lang('UplUploadFailed'));
  706. }
  707. return false;
  708. }
  709. if (file_exists($uploaded_file['tmp_name'])) {
  710. $filesize = filesize($uploaded_file['tmp_name']);
  711. if (empty($filesize)) {
  712. // No file was uploaded.
  713. if ($show_output) {
  714. Display::display_error_message(get_lang('UplUploadFailedSizeIsZero'));
  715. }
  716. return false;
  717. }
  718. }
  719. $course_id = api_get_course_id();
  720. //Checking course quota if we are in a course
  721. if (!empty($course_id)) {
  722. $max_filled_space = DocumentManager::get_course_quota();
  723. // Check if there is enough space to save the file
  724. if (!DocumentManager::enough_space($uploaded_file['size'], $max_filled_space)) {
  725. if ($show_output) {
  726. Display::display_error_message(get_lang('UplNotEnoughSpace'));
  727. }
  728. return false;
  729. }
  730. }
  731. // case 0: default: We assume there is no error, the file uploaded with success.
  732. return true;
  733. }
  734. /**
  735. * This function does the save-work for the documents.
  736. * It handles the uploaded file and adds the properties to the database
  737. * If unzip=1 and the file is a zipfile, it is extracted
  738. * If we decide to save ALL kinds of documents in one database,
  739. * we could extend this with a $type='document', 'scormdocument',...
  740. *
  741. * @param array $_course
  742. * @param array $uploaded_file ($_FILES)
  743. * @param string $base_work_dir
  744. * @param string $upload_path
  745. * @param int $user_id
  746. * @param int $to_group_id, 0 for everybody
  747. * @param int $to_user_id, NULL for everybody
  748. * @param int $unzip 1/0
  749. * @param string $what_if_file_exists overwrite, rename or warn if exists (default)
  750. * @param boolean Optional output parameter. So far only use for unzip_uploaded_document function. If no output wanted on success, set to false.
  751. * @return path of the saved file
  752. */
  753. static function handle_uploaded_document(
  754. $_course,
  755. $uploaded_file,
  756. $base_work_dir,
  757. $upload_path,
  758. $user_id,
  759. $to_group_id = 0,
  760. $to_user_id = null,
  761. $unzip = 0,
  762. $what_if_file_exists = '',
  763. $output = true
  764. ) {
  765. if (!$user_id) {
  766. die('Not a valid user.');
  767. }
  768. // Strip slashes
  769. $uploaded_file['name'] = stripslashes($uploaded_file['name']);
  770. // Add extension to files without one (if possible)
  771. $uploaded_file['name'] = self::add_ext_on_mime($uploaded_file['name'], $uploaded_file['type']);
  772. $current_session_id = api_get_session_id();
  773. //Just in case process_uploaded_file is not called
  774. $max_filled_space = DocumentManager::get_course_quota();
  775. // Check if there is enough space to save the file
  776. if (!DocumentManager::enough_space($uploaded_file['size'], $max_filled_space)) {
  777. if ($output) {
  778. Display::display_error_message(get_lang('UplNotEnoughSpace'));
  779. }
  780. return false;
  781. }
  782. // If the want to unzip, check if the file has a .zip (or ZIP,Zip,ZiP,...) extension
  783. if ($unzip == 1 && preg_match('/.zip$/', strtolower($uploaded_file['name']))) {
  784. return self::unzip_uploaded_document(
  785. $uploaded_file,
  786. $upload_path,
  787. $base_work_dir,
  788. $max_filled_space,
  789. $output,
  790. $to_group_id
  791. );
  792. //display_message('Unzipping file');
  793. } elseif ($unzip == 1 && !preg_match(
  794. '/.zip$/',
  795. strtolower($uploaded_file['name'])
  796. )
  797. ) { // We can only unzip ZIP files (no gz, tar,...)
  798. if ($output) {
  799. Display::display_error_message(get_lang('UplNotAZip')." ".get_lang('PleaseTryAgain'));
  800. }
  801. return false;
  802. } else {
  803. // Clean up the name, only ASCII characters should stay. (and strict)
  804. $clean_name = replace_dangerous_char($uploaded_file['name'], 'strict');
  805. // No "dangerous" files
  806. $clean_name = self::disable_dangerous_file($clean_name);
  807. if (!self::filter_extension($clean_name)) {
  808. if ($output) {
  809. Display::display_error_message(get_lang('UplUnableToSaveFileFilteredExtension'));
  810. }
  811. return false;
  812. } else {
  813. // Extension is good
  814. //echo '<br />clean name = '.$clean_name;
  815. //echo '<br />upload_path = '.$upload_path;
  816. // If the upload path differs from / (= root) it will need a slash at the end
  817. if ($upload_path != '/') {
  818. $upload_path = $upload_path.'/';
  819. }
  820. //echo '<br />upload_path = '.$upload_path;
  821. $file_path = $upload_path.$clean_name;
  822. //echo '<br />file path = '.$file_path;
  823. // Full path to where we want to store the file with trailing slash
  824. $where_to_save = $base_work_dir.$upload_path;
  825. // At least if the directory doesn't exist, tell so
  826. if (!is_dir($where_to_save)) {
  827. if ($output) {
  828. Display::display_error_message(get_lang('DestDirectoryDoesntExist').' ('.$upload_path.')');
  829. }
  830. return false;
  831. }
  832. //echo '<br />where to save = '.$where_to_save;
  833. // Full path of the destination
  834. $store_path = $where_to_save.$clean_name;
  835. //echo '<br />store path = '.$store_path;
  836. // Name of the document without the extension (for the title)
  837. $document_name = self::get_document_title($uploaded_file['name']);
  838. // Size of the uploaded file (in bytes)
  839. $file_size = $uploaded_file['size'];
  840. $files_perm = api_get_permissions_for_new_files();
  841. // What to do if the target file exists
  842. switch ($what_if_file_exists) {
  843. // Overwrite the file if it exists
  844. case 'overwrite':
  845. // Check if the target file exists, so we can give another message
  846. $file_exists = file_exists($store_path);
  847. if (@move_uploaded_file($uploaded_file['tmp_name'], $store_path)) {
  848. chmod($store_path, $files_perm);
  849. if ($file_exists) {
  850. // UPDATE DATABASE
  851. $document_id = DocumentManager::get_document_id($_course, $file_path);
  852. if (is_numeric($document_id)) {
  853. // Update filesize
  854. self::update_existing_document($_course, $document_id, $uploaded_file['size']);
  855. // Update document item_property
  856. api_item_property_update(
  857. $_course,
  858. TOOL_DOCUMENT,
  859. $document_id,
  860. 'DocumentUpdated',
  861. $user_id,
  862. $to_group_id,
  863. $to_user_id,
  864. null,
  865. null,
  866. $current_session_id
  867. );
  868. //Redo visibility
  869. api_set_default_visibility(TOOL_DOCUMENT, $document_id);
  870. }
  871. // If the file is in a folder, we need to update all parent folders
  872. self::item_property_update_on_folder($_course, $upload_path, $user_id);
  873. // Display success message with extra info to user
  874. if ($output) {
  875. Display::display_confirmation_message(
  876. get_lang('UplUploadSucceeded').'<br />'.$file_path.' '.get_lang(
  877. 'UplFileOverwritten'
  878. ),
  879. false
  880. );
  881. }
  882. return $file_path;
  883. } else {
  884. // Put the document data in the database
  885. $document_id = self::add_document(
  886. $_course,
  887. $file_path,
  888. 'file',
  889. $file_size,
  890. $document_name,
  891. null,
  892. 0,
  893. true
  894. );
  895. if ($document_id) {
  896. // Put the document in item_property update
  897. api_item_property_update(
  898. $_course,
  899. TOOL_DOCUMENT,
  900. $document_id,
  901. 'DocumentAdded',
  902. $user_id,
  903. $to_group_id,
  904. $to_user_id,
  905. null,
  906. null,
  907. $current_session_id
  908. );
  909. }
  910. // If the file is in a folder, we need to update all parent folders
  911. self::item_property_update_on_folder($_course, $upload_path, $user_id);
  912. // Display success message to user
  913. if ($output) {
  914. Display::display_confirmation_message(
  915. get_lang('UplUploadSucceeded').'<br />'.$file_path,
  916. false
  917. );
  918. }
  919. return $file_path;
  920. }
  921. } else {
  922. if ($output) {
  923. Display::display_error_message(get_lang('UplUnableToSaveFile'));
  924. }
  925. return false;
  926. }
  927. break;
  928. // Rename the file if it exists
  929. case 'rename':
  930. $new_name = unique_name($where_to_save, $clean_name);
  931. $store_path = $where_to_save.$new_name;
  932. $new_file_path = $upload_path.$new_name;
  933. if (@move_uploaded_file($uploaded_file['tmp_name'], $store_path)) {
  934. chmod($store_path, $files_perm);
  935. // Put the document data in the database
  936. $document_id = self::add_document(
  937. $_course,
  938. $new_file_path,
  939. 'file',
  940. $file_size,
  941. $document_name,
  942. null,
  943. 0,
  944. true
  945. );
  946. if ($document_id) {
  947. // Update document item_property
  948. api_item_property_update(
  949. $_course,
  950. TOOL_DOCUMENT,
  951. $document_id,
  952. 'DocumentAdded',
  953. $user_id,
  954. $to_group_id,
  955. $to_user_id,
  956. null,
  957. null,
  958. $current_session_id
  959. );
  960. }
  961. // If the file is in a folder, we need to update all parent folders
  962. self::item_property_update_on_folder($_course, $upload_path, $user_id);
  963. // Display success message to user
  964. if ($output) {
  965. Display::display_confirmation_message(
  966. get_lang('UplUploadSucceeded').'<br />'.get_lang('UplFileSavedAs').$new_file_path,
  967. false
  968. );
  969. }
  970. return $new_file_path;
  971. } else {
  972. if ($output) {
  973. Display::display_error_message(get_lang('UplUnableToSaveFile'));
  974. }
  975. return false;
  976. }
  977. break;
  978. // Only save the file if it doesn't exist or warn user if it does exist
  979. default:
  980. if (file_exists($store_path)) {
  981. if ($output) {
  982. Display::display_error_message($clean_name.' '.get_lang('UplAlreadyExists'));
  983. }
  984. } else {
  985. if (@move_uploaded_file($uploaded_file['tmp_name'], $store_path)) {
  986. chmod($store_path, $files_perm);
  987. // Put the document data in the database
  988. $document_id = self::add_document(
  989. $_course,
  990. $file_path,
  991. 'file',
  992. $file_size,
  993. $document_name,
  994. null,
  995. 0,
  996. true
  997. );
  998. if ($document_id) {
  999. // Update document item_property
  1000. api_item_property_update(
  1001. $_course,
  1002. TOOL_DOCUMENT,
  1003. $document_id,
  1004. 'DocumentAdded',
  1005. $user_id,
  1006. $to_group_id,
  1007. $to_user_id,
  1008. null,
  1009. null,
  1010. $current_session_id
  1011. );
  1012. }
  1013. // If the file is in a folder, we need to update all parent folders
  1014. self::item_property_update_on_folder($_course, $upload_path, $user_id);
  1015. // Display success message to user
  1016. if ($output) {
  1017. Display::display_confirmation_message(
  1018. get_lang('UplUploadSucceeded').'<br />'.$file_path,
  1019. false
  1020. );
  1021. }
  1022. return $file_path;
  1023. } else {
  1024. if ($output) {
  1025. Display::display_error_message(get_lang('UplUnableToSaveFile'));
  1026. }
  1027. return false;
  1028. }
  1029. }
  1030. break;
  1031. }
  1032. }
  1033. }
  1034. }
  1035. /**
  1036. * Checks if there is enough place to add a file on a directory
  1037. * on the base of a maximum directory size allowed
  1038. * deprecated: use enough_space instead!
  1039. * @author - Hugues Peeters <peeters@ipm.ucl.ac.be>
  1040. * @param - file_size (int) - size of the file in byte
  1041. * @param - dir (string) - Path of the directory
  1042. * whe the file should be added
  1043. * @param - max_dir_space (int) - maximum size of the diretory in byte
  1044. * @return - boolean true if there is enough space,
  1045. * boolean false otherwise
  1046. *
  1047. * @see - enough_size() uses dir_total_space() function
  1048. */
  1049. static function enough_size($file_size, $dir, $max_dir_space)
  1050. {
  1051. if ($max_dir_space) {
  1052. $already_filled_space = self::dir_total_space($dir);
  1053. if (($file_size + $already_filled_space) > $max_dir_space) {
  1054. return false;
  1055. }
  1056. }
  1057. return true;
  1058. }
  1059. /**
  1060. * Computes the size already occupied by a directory and is subdirectories
  1061. *
  1062. * @author - Hugues Peeters <peeters@ipm.ucl.ac.be>
  1063. * @param - dir_path (string) - size of the file in byte
  1064. * @return - int - return the directory size in bytes
  1065. */
  1066. static function dir_total_space($dir_path)
  1067. {
  1068. $save_dir = getcwd();
  1069. chdir($dir_path);
  1070. $handle = opendir($dir_path);
  1071. while ($element = readdir($handle)) {
  1072. if ($element == '.' || $element == '..') {
  1073. continue; // Skip the current and parent directories
  1074. }
  1075. if (is_file($element)) {
  1076. $sumSize += filesize($element);
  1077. }
  1078. if (is_dir($element)) {
  1079. $dirList[] = $dir_path.'/'.$element;
  1080. }
  1081. }
  1082. closedir($handle);
  1083. if (sizeof($dirList) > 0) {
  1084. foreach ($dirList as $j) {
  1085. $sizeDir = self::dir_total_space($j); // Recursivity
  1086. $sumSize += $sizeDir;
  1087. }
  1088. }
  1089. chdir($save_dir); // Return to initial position
  1090. return $sumSize;
  1091. }
  1092. /**
  1093. * Tries to add an extension to files without extension
  1094. * Some applications on Macintosh computers don't add an extension to the files.
  1095. * This subroutine try to fix this on the basis of the MIME type sent
  1096. * by the browser.
  1097. *
  1098. * Note : some browsers don't send the MIME Type (e.g. Netscape 4).
  1099. * We don't have solution for this kind of situation
  1100. *
  1101. * @author - Hugues Peeters <peeters@ipm.ucl.ac.be>
  1102. * @author - Bert Vanderkimpen
  1103. * @param - file_name (string) - Name of the file
  1104. * @param - file_type (string) - Type of the file
  1105. * @return - file_name (string)
  1106. */
  1107. static function add_ext_on_mime($file_name, $file_type)
  1108. {
  1109. // Check whether the file has an extension AND whether the browser has sent a MIME Type
  1110. if (!preg_match('/^.*\.[a-zA-Z_0-9]+$/', $file_name) && $file_type) {
  1111. // Build a "MIME-types / extensions" connection table
  1112. static $mime_type = array();
  1113. $mime_type[] = 'application/msword';
  1114. $extension[] = '.doc';
  1115. $mime_type[] = 'application/rtf';
  1116. $extension[] = '.rtf';
  1117. $mime_type[] = 'application/vnd.ms-powerpoint';
  1118. $extension[] = '.ppt';
  1119. $mime_type[] = 'application/vnd.ms-excel';
  1120. $extension[] = '.xls';
  1121. $mime_type[] = 'application/pdf';
  1122. $extension[] = '.pdf';
  1123. $mime_type[] = 'application/postscript';
  1124. $extension[] = '.ps';
  1125. $mime_type[] = 'application/mac-binhex40';
  1126. $extension[] = '.hqx';
  1127. $mime_type[] = 'application/x-gzip';
  1128. $extension[] = 'tar.gz';
  1129. $mime_type[] = 'application/x-shockwave-flash';
  1130. $extension[] = '.swf';
  1131. $mime_type[] = 'application/x-stuffit';
  1132. $extension[] = '.sit';
  1133. $mime_type[] = 'application/x-tar';
  1134. $extension[] = '.tar';
  1135. $mime_type[] = 'application/zip';
  1136. $extension[] = '.zip';
  1137. $mime_type[] = 'application/x-tar';
  1138. $extension[] = '.tar';
  1139. $mime_type[] = 'text/html';
  1140. $extension[] = '.html';
  1141. $mime_type[] = 'text/plain';
  1142. $extension[] = '.txt';
  1143. $mime_type[] = 'text/rtf';
  1144. $extension[] = '.rtf';
  1145. $mime_type[] = 'img/gif';
  1146. $extension[] = '.gif';
  1147. $mime_type[] = 'img/jpeg';
  1148. $extension[] = '.jpg';
  1149. $mime_type[] = 'img/png';
  1150. $extension[] = '.png';
  1151. $mime_type[] = 'audio/midi';
  1152. $extension[] = '.mid';
  1153. $mime_type[] = 'audio/mpeg';
  1154. $extension[] = '.mp3';
  1155. $mime_type[] = 'audio/x-aiff';
  1156. $extension[] = '.aif';
  1157. $mime_type[] = 'audio/x-pn-realaudio';
  1158. $extension[] = '.rm';
  1159. $mime_type[] = 'audio/x-pn-realaudio-plugin';
  1160. $extension[] = '.rpm';
  1161. $mime_type[] = 'audio/x-wav';
  1162. $extension[] = '.wav';
  1163. $mime_type[] = 'video/mpeg';
  1164. $extension[] = '.mpg';
  1165. $mime_type[] = 'video/mpeg4-generic';
  1166. $extension[] = '.mp4';
  1167. $mime_type[] = 'video/quicktime';
  1168. $extension[] = '.mov';
  1169. $mime_type[] = 'video/x-msvideo';
  1170. $extension[] = '.avi';
  1171. $mime_type[] = 'video/x-ms-wmv';
  1172. $extension[] = '.wmv';
  1173. $mime_type[] = 'video/x-flv';
  1174. $extension[] = '.flv';
  1175. $mime_type[] = 'image/svg+xml';
  1176. $extension[] = '.svg';
  1177. $mime_type[] = 'image/svg+xml';
  1178. $extension[] = '.svgz';
  1179. $mime_type[] = 'video/ogg';
  1180. $extension[] = '.ogv';
  1181. $mime_type[] = 'audio/ogg';
  1182. $extension[] = '.oga';
  1183. $mime_type[] = 'application/ogg';
  1184. $extension[] = '.ogg';
  1185. $mime_type[] = 'application/ogg';
  1186. $extension[] = '.ogx';
  1187. $mime_type[] = 'application/x-freemind';
  1188. $extension[] = '.mm';
  1189. $mime_type[] = 'application/vnd.ms-word.document.macroEnabled.12';
  1190. $extension[] = '.docm';
  1191. $mime_type[] = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document';
  1192. $extension[] = '.docx';
  1193. $mime_type[] = 'application/vnd.ms-word.template.macroEnabled.12';
  1194. $extension[] = '.dotm';
  1195. $mime_type[] = 'application/vnd.openxmlformats-officedocument.wordprocessingml.template';
  1196. $extension[] = '.dotx';
  1197. $mime_type[] = 'application/vnd.ms-powerpoint.template.macroEnabled.12';
  1198. $extension[] = '.potm';
  1199. $mime_type[] = 'application/vnd.openxmlformats-officedocument.presentationml.template';
  1200. $extension[] = '.potx';
  1201. $mime_type[] = 'application/vnd.ms-powerpoint.addin.macroEnabled.12';
  1202. $extension[] = '.ppam';
  1203. $mime_type[] = 'application/vnd.ms-powerpoint.slideshow.macroEnabled.12';
  1204. $extension[] = '.ppsm';
  1205. $mime_type[] = 'application/vnd.openxmlformats-officedocument.presentationml.slideshow';
  1206. $extension[] = '.ppsx';
  1207. $mime_type[] = 'application/vnd.ms-powerpoint.presentation.macroEnabled.12';
  1208. $extension[] = '.pptm';
  1209. $mime_type[] = 'application/vnd.openxmlformats-officedocument.presentationml.presentation';
  1210. $extension[] = '.pptx';
  1211. $mime_type[] = 'application/vnd.ms-excel.addin.macroEnabled.12';
  1212. $extension[] = '.xlam';
  1213. $mime_type[] = 'application/vnd.ms-excel.sheet.binary.macroEnabled.12';
  1214. $extension[] = '.xlsb';
  1215. $mime_type[] = 'application/vnd.ms-excel.sheet.macroEnabled.12';
  1216. $extension[] = '.xlsm';
  1217. $mime_type[] = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
  1218. $extension[] = '.xlsx';
  1219. $mime_type[] = 'application/vnd.ms-excel.template.macroEnabled.12';
  1220. $extension[] = '.xltm';
  1221. $mime_type[] = 'application/vnd.openxmlformats-officedocument.spreadsheetml.template';
  1222. $extension[] = '.xltx';
  1223. // Test on PC (files with no extension get application/octet-stream)
  1224. //$mime_type[] = 'application/octet-stream'; $extension[] = '.ext';
  1225. // Check whether the MIME type sent by the browser is within the table
  1226. foreach ($mime_type as $key => & $type) {
  1227. if ($type == $file_type) {
  1228. $file_name .= $extension[$key];
  1229. break;
  1230. }
  1231. }
  1232. unset($mime_type, $extension, $type, $key); // Delete to eschew possible collisions
  1233. }
  1234. return $file_name;
  1235. }
  1236. /**
  1237. * Manages all the unzipping process of an uploaded document
  1238. * This uses the item_property table for properties of documents
  1239. *
  1240. * @author Hugues Peeters <hugues.peeters@claroline.net>
  1241. * @author Bert Vanderkimpen
  1242. *
  1243. * @param array $uploaded_file - follows the $_FILES Structure
  1244. * @param string $upload_path - destination of the upload.
  1245. * This path is to append to $base_work_dir
  1246. * @param string $base_work_dir - base working directory of the module
  1247. * @param int $max_filled_space - amount of bytes to not exceed in the base
  1248. * working directory
  1249. * @param boolean Output switch. Optional. If no output not wanted on success, set to false.
  1250. *
  1251. * @return boolean true if it succeeds false otherwise
  1252. */
  1253. static function unzip_uploaded_document(
  1254. $uploaded_file,
  1255. $upload_path,
  1256. $base_work_dir,
  1257. $max_filled_space,
  1258. $output = true,
  1259. $to_group_id = 0
  1260. ) {
  1261. $_course = api_get_course_info();
  1262. global $_user;
  1263. global $to_user_id;
  1264. global $to_group_id;
  1265. $zip_file = new PclZip($uploaded_file['tmp_name']);
  1266. // Check the zip content (real size and file extension)
  1267. $zip_content_array = (array)$zip_file->listContent();
  1268. $real_filesize = 0;
  1269. foreach ($zip_content_array as & $this_content) {
  1270. $real_filesize += $this_content['size'];
  1271. }
  1272. if (!DocumentManager::enough_space($real_filesize, $max_filled_space)) {
  1273. Display::display_error_message(get_lang('UplNotEnoughSpace'));
  1274. return false;
  1275. }
  1276. // It happens on Linux that $upload_path sometimes doesn't start with '/'
  1277. if ($upload_path[0] != '/') {
  1278. $upload_path = '/'.$upload_path;
  1279. }
  1280. /* Uncompressing phase */
  1281. // Get into the right directory
  1282. $save_dir = getcwd();
  1283. chdir($base_work_dir.$upload_path);
  1284. // We extract using a callback function that "cleans" the path
  1285. //@todo check if this works
  1286. $unzipping_state = $zip_file->extract(
  1287. PCLZIP_CB_PRE_EXTRACT,
  1288. 'FileManager::clean_up_files_in_zip',
  1289. PCLZIP_OPT_REPLACE_NEWER
  1290. );
  1291. // Add all documents in the unzipped folder to the database
  1292. self::add_all_documents_in_folder_to_database(
  1293. $_course,
  1294. $_user['user_id'],
  1295. $base_work_dir,
  1296. $upload_path == '/' ? '' : $upload_path,
  1297. $to_group_id
  1298. );
  1299. //Display::display_normal_message(get_lang('UplZipExtractSuccess'));
  1300. return true;
  1301. }
  1302. /**
  1303. * This function is a callback function that is used while extracting a zipfile
  1304. * http://www.phpconcept.net/pclzip/man/en/index.php?options-pclzip_cb_pre_extract
  1305. *
  1306. * @param $p_event
  1307. * @param $p_header
  1308. * @return 1 (If the function returns 1, then the extraction is resumed)
  1309. */
  1310. function clean_up_files_in_zip($p_event, &$p_header)
  1311. {
  1312. $res = self::clean_up_path($p_header['filename']);
  1313. return $res;
  1314. }
  1315. /**
  1316. * This function cleans up a given path
  1317. * by eliminating dangerous file names and cleaning them
  1318. *
  1319. * @param string $path
  1320. * @return $path
  1321. * @see FileManager::disable_dangerous_file()
  1322. * @see replace_dangerous_char()
  1323. */
  1324. static function clean_up_path(&$path)
  1325. {
  1326. // Split the path in folders and files
  1327. $path_array = explode('/', $path);
  1328. // Clean up every foler and filename in the path
  1329. foreach ($path_array as $key => & $val) {
  1330. // We don't want to lose the dots in ././folder/file (cfr. zipfile)
  1331. if ($val != '.') {
  1332. $val = self::disable_dangerous_file(replace_dangerous_char($val));
  1333. }
  1334. }
  1335. // Join the "cleaned" path (modified in-place as passed by reference)
  1336. $path = implode('/', $path_array);
  1337. $res = self::filter_extension($path);
  1338. return $res;
  1339. }
  1340. /**
  1341. * Checks if the file is dangerous, based on extension and/or mimetype.
  1342. * The list of extensions accepted/rejected can be found from
  1343. * api_get_setting('upload_extensions_exclude') and api_get_setting('upload_extensions_include')
  1344. * @param string filename passed by reference. The filename will be modified if filter rules say so! (you can include path but the filename should look like 'abc.html')
  1345. * @return int 0 to skip file, 1 to keep file
  1346. */
  1347. static function filter_extension(&$filename)
  1348. {
  1349. if (substr($filename, -1) == '/') {
  1350. return 1; // Authorize directories
  1351. }
  1352. $blacklist = api_get_setting('upload_extensions_list_type');
  1353. if ($blacklist != 'whitelist') { // if = blacklist
  1354. $extensions = explode(';', strtolower(api_get_setting('upload_extensions_blacklist')));
  1355. $skip = api_get_setting('upload_extensions_skip');
  1356. $ext = strrchr($filename, '.');
  1357. $ext = substr($ext, 1);
  1358. if (empty($ext)) {
  1359. return 1; // We're in blacklist mode, so accept empty extensions
  1360. }
  1361. if (in_array(strtolower($ext), $extensions)) {
  1362. if ($skip == 'true') {
  1363. return 0;
  1364. } else {
  1365. $new_ext = api_get_setting('upload_extensions_replace_by');
  1366. $filename = str_replace('.'.$ext, '.'.$new_ext, $filename);
  1367. return 1;
  1368. }
  1369. } else {
  1370. return 1;
  1371. }
  1372. } else {
  1373. $extensions = split(';', strtolower(api_get_setting('upload_extensions_whitelist')));
  1374. $skip = api_get_setting('upload_extensions_skip');
  1375. $ext = strrchr($filename, '.');
  1376. $ext = substr($ext, 1);
  1377. if (empty($ext)) {
  1378. return 1; // Accept empty extensions
  1379. }
  1380. if (!in_array(strtolower($ext), $extensions)) {
  1381. if ($skip == 'true') {
  1382. return 0;
  1383. } else {
  1384. $new_ext = api_get_setting('upload_extensions_replace_by');
  1385. $filename = str_replace('.'.$ext, '.'.$new_ext, $filename);
  1386. return 1;
  1387. }
  1388. } else {
  1389. return 1;
  1390. }
  1391. }
  1392. }
  1393. /**
  1394. * Adds a new document to the database
  1395. *
  1396. * @param array $_course
  1397. * @param string $path
  1398. * @param string $filetype
  1399. * @param int $filesize
  1400. * @param string $title
  1401. *
  1402. * @return id if inserted document
  1403. */
  1404. static function add_document(
  1405. $_course,
  1406. $path,
  1407. $filetype,
  1408. $filesize,
  1409. $title,
  1410. $comment = null,
  1411. $readonly = 0,
  1412. $save_visibility = true,
  1413. $group_id = null
  1414. ) {
  1415. $session_id = api_get_session_id();
  1416. $readonly = intval($readonly);
  1417. $comment = Database::escape_string($comment);
  1418. $path = Database::escape_string($path);
  1419. $filetype = Database::escape_string($filetype);
  1420. $filesize = intval($filesize);
  1421. $title = Database::escape_string(htmlspecialchars($title));
  1422. $c_id = $_course['real_id'];
  1423. $table_document = Database::get_course_table(TABLE_DOCUMENT);
  1424. $sql = "INSERT INTO $table_document (c_id, path, filetype, size, title, comment, readonly, session_id)
  1425. VALUES ($c_id, '$path','$filetype','$filesize','$title', '$comment', $readonly, $session_id)";
  1426. if (Database::query($sql)) {
  1427. $document_id = Database::insert_id();
  1428. if ($document_id) {
  1429. if ($save_visibility) {
  1430. api_set_default_visibility($document_id, TOOL_DOCUMENT, $group_id);
  1431. }
  1432. }
  1433. return $document_id;
  1434. } else {
  1435. return false;
  1436. }
  1437. }
  1438. /**
  1439. * Updates an existing document in the database
  1440. * as the file exists, we only need to change the size
  1441. *
  1442. * @param array $_course
  1443. * @param int $document_id
  1444. * @param int $filesize
  1445. * @param int $readonly
  1446. *
  1447. * @return boolean true /false
  1448. */
  1449. static function update_existing_document($_course, $document_id, $filesize, $readonly = 0)
  1450. {
  1451. $document_table = Database::get_course_table(TABLE_DOCUMENT);
  1452. $document_id = intval($document_id);
  1453. $filesize = intval($filesize);
  1454. $readonly = intval($readonly);
  1455. $course_id = $_course['real_id'];
  1456. $sql = "UPDATE $document_table SET size = '$filesize' , readonly = '$readonly'
  1457. WHERE c_id = $course_id AND id = $document_id";
  1458. if (Database::query($sql)) {
  1459. return true;
  1460. } else {
  1461. return false;
  1462. }
  1463. }
  1464. /**
  1465. * This function updates the last_edit_date, last edit user id on all folders in a given path
  1466. *
  1467. * @param array $_course
  1468. * @param string $path
  1469. * @param int $user_id
  1470. */
  1471. static function item_property_update_on_folder($_course, $path, $user_id)
  1472. {
  1473. //display_message("Start update_lastedit_on_folder");
  1474. // If we are in the root, just return... no need to update anything
  1475. if ($path == '/') {
  1476. return;
  1477. }
  1478. $user_id = intval($user_id);
  1479. // If the given path ends with a / we remove it
  1480. $endchar = substr($path, strlen($path) - 1, 1);
  1481. if ($endchar == '/') {
  1482. $path = substr($path, 0, strlen($path) - 1);
  1483. }
  1484. $TABLE_ITEMPROPERTY = Database::get_course_table(TABLE_ITEM_PROPERTY);
  1485. // Get the time
  1486. $time = date('Y-m-d H:i:s', time());
  1487. // Det all paths in the given path
  1488. // /folder/subfolder/subsubfolder/file
  1489. // if file is updated, subsubfolder, subfolder and folder are updated
  1490. $exploded_path = explode('/', $path);
  1491. $course_id = api_get_course_int_id();
  1492. foreach ($exploded_path as $key => & $value) {
  1493. // We don't want a slash before our first slash
  1494. if ($key != 0) {
  1495. $newpath .= '/'.$value;
  1496. //echo 'path= '.$newpath.'<br />';
  1497. // Select ID of given folder
  1498. $folder_id = DocumentManager::get_document_id($_course, $newpath);
  1499. if ($folder_id) {
  1500. $sql = "UPDATE $TABLE_ITEMPROPERTY SET lastedit_date='$time',lastedit_type='DocumentInFolderUpdated', lastedit_user_id='$user_id'
  1501. WHERE c_id = $course_id AND tool='".TOOL_DOCUMENT."' AND ref='$folder_id'";
  1502. Database::query($sql);
  1503. }
  1504. }
  1505. }
  1506. }
  1507. /**
  1508. * Returns the directory depth of the file.
  1509. *
  1510. * @author Olivier Cauberghe <olivier.cauberghe@ugent.be>
  1511. * @param path+filename eg: /main/document/document.php
  1512. * @return The directory depth
  1513. */
  1514. static function get_levels($filename)
  1515. {
  1516. $levels = explode('/', $filename);
  1517. if (empty($levels[count($levels) - 1])) {
  1518. unset($levels[count($levels) - 1]);
  1519. }
  1520. return count($levels);
  1521. }
  1522. /**
  1523. * Retrieves the image path list in a html file
  1524. *
  1525. * @author Hugues Peeters <hugues.peeters@claroline.net>
  1526. * @param string $html_file
  1527. * @return array - images path list
  1528. */
  1529. static function search_img_from_html($html_file)
  1530. {
  1531. $img_path_list = array();
  1532. if (!$fp = fopen($html_file, 'r')) {
  1533. return;
  1534. }
  1535. // Aearch and store occurences of the <img> tag in an array
  1536. $size_file = (filesize($html_file) === 0) ? 1 : filesize($html_file);
  1537. if (isset($fp) && $fp !== false) {
  1538. $buffer = fread($fp, $size_file);
  1539. if (strlen($buffer) >= 0 && $buffer !== false) {
  1540. //
  1541. } else {
  1542. die('<center>Can not read file.</center>');
  1543. }
  1544. } else {
  1545. die('<center>Can not read file.</center>');
  1546. }
  1547. $matches = array();
  1548. if (preg_match_all('~<[[:space:]]*img[^>]*>~i', $buffer, $matches)) {
  1549. $img_tag_list = $matches[0];
  1550. }
  1551. fclose($fp);
  1552. unset($buffer);
  1553. // Search the image file path from all the <IMG> tag detected
  1554. if (sizeof($img_tag_list) > 0) {
  1555. foreach ($img_tag_list as & $this_img_tag) {
  1556. if (preg_match('~src[[:space:]]*=[[:space:]]*[\"]{1}([^\"]+)[\"]{1}~i', $this_img_tag, $matches)) {
  1557. $img_path_list[] = $matches[1];
  1558. }
  1559. }
  1560. $img_path_list = array_unique($img_path_list); // Remove duplicate entries
  1561. }
  1562. return $img_path_list;
  1563. }
  1564. /**
  1565. * Creates a new directory trying to find a directory name
  1566. * that doesn't already exist
  1567. * (we could use unique_name() here...)
  1568. *
  1569. * @author Hugues Peeters <hugues.peeters@claroline.net>
  1570. * @author Bert Vanderkimpen
  1571. * @param array $_course current course information
  1572. * @param int $user_id current user id
  1573. * @param string $desiredDirName complete path of the desired name
  1574. * @param string The visible name of the directory
  1575. * @param int Visibility (0 for invisible, 1 for visible, 2 for deleted)
  1576. * @return string actual directory name if it succeeds,
  1577. * boolean false otherwise
  1578. */
  1579. static function create_unexisting_directory(
  1580. $_course,
  1581. $user_id,
  1582. $session_id,
  1583. $to_group_id,
  1584. $to_user_id,
  1585. $base_work_dir,
  1586. $desired_dir_name,
  1587. $title = null,
  1588. $visibility = ''
  1589. ) {
  1590. $nb = '';
  1591. // add numerical suffix to directory if another one of the same number already exists
  1592. while (file_exists($base_work_dir.$desired_dir_name.$nb)) {
  1593. $nb += 1;
  1594. }
  1595. if ($title == null) {
  1596. $title = basename($desired_dir_name);
  1597. }
  1598. $course_id = $_course['real_id'];
  1599. if (mkdir($base_work_dir.$desired_dir_name.$nb, api_get_permissions_for_new_directories(), true)) {
  1600. // Check if pathname already exists inside document table
  1601. $tbl_document = Database::get_course_table(TABLE_DOCUMENT);
  1602. $sql = "SELECT path FROM $tbl_document WHERE c_id = $course_id AND path='".$desired_dir_name.$nb."'";
  1603. $rs = Database::query($sql);
  1604. if (Database::num_rows($rs) == 0) {
  1605. $document_id = self::add_document(
  1606. $_course,
  1607. $desired_dir_name.$nb,
  1608. 'folder',
  1609. 0,
  1610. $title,
  1611. null,
  1612. 0,
  1613. true,
  1614. $to_group_id
  1615. );
  1616. if ($document_id) {
  1617. // Update document item_property
  1618. if ($visibility !== '') {
  1619. $visibilities = array(0 => 'invisible', 1 => 'visible', 2 => 'delete');
  1620. api_item_property_update(
  1621. $_course,
  1622. TOOL_DOCUMENT,
  1623. $document_id,
  1624. $visibilities[$visibility],
  1625. $user_id,
  1626. $to_group_id,
  1627. $to_user_id,
  1628. null,
  1629. null,
  1630. $session_id
  1631. );
  1632. } else {
  1633. api_item_property_update(
  1634. $_course,
  1635. TOOL_DOCUMENT,
  1636. $document_id,
  1637. 'FolderCreated',
  1638. $user_id,
  1639. $to_group_id,
  1640. $to_user_id,
  1641. null,
  1642. null,
  1643. $session_id
  1644. );
  1645. }
  1646. return $desired_dir_name.$nb;
  1647. }
  1648. } else {
  1649. //This means the folder NOT exist in the filesystem (now this was created) but there is a record in the Database
  1650. return $desired_dir_name.$nb;
  1651. }
  1652. } else {
  1653. return false;
  1654. }
  1655. }
  1656. /**
  1657. * Handles uploaded missing images
  1658. *
  1659. * @author Hugues Peeters <hugues.peeters@claroline.net>
  1660. * @author Bert Vanderkimpen
  1661. * @param array $_course
  1662. * @param array $uploaded_file_collection - follows the $_FILES Structure
  1663. * @param string $base_work_dir
  1664. * @param string $missing_files_dir
  1665. * @param int $user_id
  1666. * @param int $max_filled_space
  1667. */
  1668. static function move_uploaded_file_collection_into_directory(
  1669. $_course,
  1670. $uploaded_file_collection,
  1671. $base_work_dir,
  1672. $missing_files_dir,
  1673. $user_id,
  1674. $to_group_id,
  1675. $to_user_id,
  1676. $max_filled_space
  1677. ) {
  1678. $number_of_uploaded_images = count($uploaded_file_collection['name']);
  1679. for ($i = 0; $i < $number_of_uploaded_images; $i++) {
  1680. $missing_file['name'] = $uploaded_file_collection['name'][$i];
  1681. $missing_file['type'] = $uploaded_file_collection['type'][$i];
  1682. $missing_file['tmp_name'] = $uploaded_file_collection['tmp_name'][$i];
  1683. $missing_file['error'] = $uploaded_file_collection['error'][$i];
  1684. $missing_file['size'] = $uploaded_file_collection['size'][$i];
  1685. $upload_ok = self::process_uploaded_file($missing_file);
  1686. if ($upload_ok) {
  1687. $new_file_list[] = self::handle_uploaded_document(
  1688. $_course,
  1689. $missing_file,
  1690. $base_work_dir,
  1691. $missing_files_dir,
  1692. $user_id,
  1693. $to_group_id,
  1694. $to_user_id,
  1695. $max_filled_space,
  1696. 0,
  1697. 'overwrite'
  1698. );
  1699. }
  1700. unset($missing_file);
  1701. }
  1702. return $new_file_list;
  1703. }
  1704. /**
  1705. * Opens the old html file and replace the src path into the img tag
  1706. * This also works for files in subdirectories.
  1707. * @param $original_img_path is an array
  1708. * @param $new_img_path is an array
  1709. */
  1710. static function replace_img_path_in_html_file($original_img_path, $new_img_path, $html_file)
  1711. {
  1712. // Open the file
  1713. $fp = fopen($html_file, 'r');
  1714. $buffer = fread($fp, filesize($html_file));
  1715. $new_html_content = null;
  1716. // Fix the image tags
  1717. for ($i = 0, $fileNb = count($original_img_path); $i < $fileNb; $i++) {
  1718. $replace_what = $original_img_path[$i];
  1719. // We only need the directory and the filename /path/to/file_html_files/missing_file.gif -> file_html_files/missing_file.gif
  1720. $exploded_file_path = explode('/', $new_img_path[$i]);
  1721. $replace_by = $exploded_file_path[count($exploded_file_path) - 2].'/'.$exploded_file_path[count(
  1722. $exploded_file_path
  1723. ) - 1];
  1724. $buffer = str_replace($replace_what, $replace_by, $buffer);
  1725. }
  1726. $new_html_content .= $buffer;
  1727. @fclose($fp);
  1728. // Write the resulted new file
  1729. if (!$fp = fopen($html_file, 'w')) {
  1730. return;
  1731. }
  1732. if (!fwrite($fp, $new_html_content)) {
  1733. return;
  1734. }
  1735. }
  1736. /**
  1737. * Checks the extension of a file, if it's .htm or .html
  1738. * we use search_img_from_html to get all image paths in the file
  1739. *
  1740. * @param string $file
  1741. * @return array paths
  1742. * @see check_for_missing_files() uses search_img_from_html()
  1743. */
  1744. static function check_for_missing_files($file)
  1745. {
  1746. if (strrchr($file, '.') == '.htm' || strrchr($file, '.') == '.html') {
  1747. $img_file_path = self::search_img_from_html($file);
  1748. return $img_file_path;
  1749. }
  1750. return false;
  1751. }
  1752. /**
  1753. * This function builds a form that asks for the missing images in a html file
  1754. * maybe we should do this another way?
  1755. *
  1756. * @param array $missing_files
  1757. * @param string $upload_path
  1758. * @param string $file_name
  1759. * @return string the form
  1760. */
  1761. static function build_missing_files_form($missing_files, $upload_path, $file_name)
  1762. {
  1763. // Do we need a / or not?
  1764. $added_slash = ($upload_path == '/') ? '' : '/';
  1765. $folder_id = DocumentManager::get_document_id(api_get_course_info(), $upload_path);
  1766. // Build the form
  1767. $form = "<p><strong>".get_lang('MissingImagesDetected')."</strong></p>"
  1768. ."<form method=\"post\" action=\"".api_get_self()."\" enctype=\"multipart/form-data\">"
  1769. // Related_file is the path to the file that has missing images
  1770. ."<input type=\"hidden\" name=\"related_file\" value=\"".$upload_path.$added_slash.$file_name."\" />"
  1771. ."<input type=\"hidden\" name=\"upload_path\" value=\"".$upload_path."\" />"
  1772. ."<input type=\"hidden\" name=\"id\" value=\"".$folder_id."\" />"
  1773. ."<table border=\"0\">";
  1774. foreach ($missing_files as & $this_img_file_path) {
  1775. $form .= "<tr>"
  1776. ."<td>".basename($this_img_file_path)." : </td>"
  1777. ."<td>"
  1778. ."<input type=\"file\" name=\"img_file[]\"/>"
  1779. ."<input type=\"hidden\" name=\"img_file_path[]\" value=\"".$this_img_file_path."\" />"
  1780. ."</td>"
  1781. ."</tr>";
  1782. }
  1783. $form .= "</table>"
  1784. ."<button type='submit' name=\"cancel_submit_image\" value=\"".get_lang(
  1785. 'Cancel'
  1786. )."\" class=\"cancel\">".get_lang('Cancel')."</button>"
  1787. ."<button type='submit' name=\"submit_image\" value=\"".get_lang('Ok')."\" class=\"save\">".get_lang(
  1788. 'Ok'
  1789. )."</button>"
  1790. ."</form>";
  1791. return $form;
  1792. }
  1793. /**
  1794. * This recursive function can be used during the upgrade process form older versions of Chamilo
  1795. * It crawls the given directory, checks if the file is in the DB and adds it if it's not
  1796. *
  1797. * @param string $base_work_dir
  1798. * @param string $current_path, needed for recursivity
  1799. */
  1800. static function add_all_documents_in_folder_to_database(
  1801. $_course,
  1802. $user_id,
  1803. $base_work_dir,
  1804. $current_path = '',
  1805. $to_group_id = 0
  1806. ) {
  1807. $current_session_id = api_get_session_id();
  1808. $path = $base_work_dir.$current_path;
  1809. // Open dir
  1810. $handle = opendir($path);
  1811. if (is_dir($path)) {
  1812. // Run trough
  1813. while ($file = readdir($handle)) {
  1814. if ($file == '.' || $file == '..') {
  1815. continue;
  1816. }
  1817. $completepath = "$path/$file";
  1818. // Directory?
  1819. if (is_dir($completepath)) {
  1820. $title = self::get_document_title($file);
  1821. $safe_file = replace_dangerous_char($file);
  1822. @rename($path.'/'.$file, $path.'/'.$safe_file);
  1823. // If we can't find the file, add it
  1824. if (!DocumentManager::get_document_id($_course, $current_path.'/'.$safe_file)) {
  1825. $document_id = self::add_document($_course, $current_path.'/'.$safe_file, 'folder', 0, $title);
  1826. api_item_property_update(
  1827. $_course,
  1828. TOOL_DOCUMENT,
  1829. $document_id,
  1830. 'DocumentAdded',
  1831. $user_id,
  1832. $to_group_id,
  1833. null,
  1834. null,
  1835. null,
  1836. $current_session_id
  1837. );
  1838. //echo $current_path.'/'.$safe_file.' added!<br />';
  1839. }
  1840. // Recursive
  1841. self::add_all_documents_in_folder_to_database(
  1842. $_course,
  1843. $user_id,
  1844. $base_work_dir,
  1845. $current_path.'/'.$safe_file,
  1846. $to_group_id
  1847. );
  1848. } else {
  1849. //Rename
  1850. $safe_file = self::disable_dangerous_file(replace_dangerous_char($file, 'strict'));
  1851. @rename($base_work_dir.$current_path.'/'.$file, $base_work_dir.$current_path.'/'.$safe_file);
  1852. $document_id = DocumentManager::get_document_id($_course, $current_path.'/'.$safe_file);
  1853. if (!$document_id) {
  1854. $title = self::get_document_title($file);
  1855. $size = filesize($base_work_dir.$current_path.'/'.$safe_file);
  1856. $document_id = self::add_document(
  1857. $_course,
  1858. $current_path.'/'.$safe_file,
  1859. 'file',
  1860. $size,
  1861. $title
  1862. );
  1863. api_item_property_update(
  1864. $_course,
  1865. TOOL_DOCUMENT,
  1866. $document_id,
  1867. 'DocumentAdded',
  1868. $user_id,
  1869. $to_group_id,
  1870. null,
  1871. null,
  1872. null,
  1873. $current_session_id
  1874. );
  1875. //echo $current_path.'/'.$safe_file.' added!<br />';
  1876. } else {
  1877. api_item_property_update(
  1878. $_course,
  1879. TOOL_DOCUMENT,
  1880. $document_id,
  1881. 'DocumentUpdated',
  1882. $user_id,
  1883. $to_group_id,
  1884. null,
  1885. null,
  1886. null,
  1887. $current_session_id
  1888. );
  1889. }
  1890. }
  1891. }
  1892. }
  1893. }
  1894. }