fileUpload.lib.php 54 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477
  1. <?php
  2. /* For licensing terms, see /license.txt */
  3. /**
  4. * FILE UPLOAD LIBRARY
  5. *
  6. * This is the file upload library for Chamilo.
  7. * Include/require it in your code to use its functionality.
  8. *
  9. * @package chamilo.library
  10. * @todo test and reorganise
  11. */
  12. /**
  13. * Code
  14. */
  15. require_once api_get_path(LIBRARY_PATH).'document.lib.php';
  16. /**
  17. * Changes the file name extension from .php to .phps
  18. * Useful for securing a site.
  19. *
  20. * @author - Hugues Peeters <peeters@ipm.ucl.ac.be>
  21. * @param - file_name (string) name of a file
  22. * @return - the filenam phps'ized
  23. */
  24. function php2phps($file_name) {
  25. return preg_replace('/\.(php.?|phtml.?)(\.){0,1}.*$/i', '.phps', $file_name);
  26. }
  27. /**
  28. * Renames .htaccess & .HTACCESS to htaccess.txt
  29. *
  30. * @param string $filename
  31. * @return string
  32. */
  33. function htaccess2txt($filename) {
  34. return str_replace(array('.htaccess', '.HTACCESS'), array('htaccess.txt', 'htaccess.txt'), $filename);
  35. }
  36. /**
  37. * This function executes our safety precautions
  38. * more functions can be added
  39. *
  40. * @param string $filename
  41. * @return string
  42. * @see php2phps()
  43. * @see htaccess2txt()
  44. */
  45. function disable_dangerous_file($filename) {
  46. return htaccess2txt(php2phps($filename));
  47. }
  48. /**
  49. * This function generates a unique name for a file on a given location
  50. * filenames are changed to name_#.ext
  51. *
  52. * @param string $path
  53. * @param string $name
  54. * @return new unique name
  55. */
  56. function unique_name($path, $name) {
  57. $ext = substr(strrchr($name, '.'), 0);
  58. $name_no_ext = substr($name, 0, strlen($name) - strlen(strstr($name, $ext)));
  59. $n = 0;
  60. $unique = '';
  61. while (file_exists($path . $name_no_ext . $unique . $ext)) {
  62. $unique = '_' . ++$n;
  63. }
  64. return $name_no_ext . $unique . $ext;
  65. }
  66. /**
  67. * Returns the name without extension, used for the title
  68. *
  69. * @param string $name
  70. * @return name without the extension
  71. */
  72. function get_document_title($name) {
  73. // If they upload .htaccess...
  74. $name = disable_dangerous_file($name);
  75. $ext = substr(strrchr($name, '.'), 0);
  76. return addslashes(substr($name, 0, strlen($name) - strlen(strstr($name, $ext))));
  77. }
  78. /**
  79. * This function checks if the upload succeeded
  80. *
  81. * @param array $uploaded_file ($_FILES)
  82. * @return true if upload succeeded
  83. */
  84. function process_uploaded_file($uploaded_file, $show_output = true) {
  85. // Checking the error code sent with the file upload.
  86. switch ($uploaded_file['error']) {
  87. case 1:
  88. // The uploaded file exceeds the upload_max_filesize directive in php.ini.
  89. if ($show_output)
  90. Display::display_error_message(get_lang('UplExceedMaxServerUpload').ini_get('upload_max_filesize'));
  91. return false;
  92. case 2:
  93. // The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.
  94. // 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).
  95. $max_file_size = intval($_POST['MAX_FILE_SIZE']);
  96. if ($show_output) {
  97. Display::display_error_message(get_lang('UplExceedMaxPostSize'). round($max_file_size/1024) .' KB');
  98. }
  99. return false;
  100. case 3:
  101. // The uploaded file was only partially uploaded.
  102. if ($show_output) {
  103. Display::display_error_message(get_lang('UplPartialUpload').' '.get_lang('PleaseTryAgain'));
  104. }
  105. return false;
  106. case 4:
  107. // No file was uploaded.
  108. if ($show_output) {
  109. Display::display_error_message(get_lang('UplNoFileUploaded').' '. get_lang('UplSelectFileFirst'));
  110. }
  111. return false;
  112. }
  113. if (!file_exists($uploaded_file['tmp_name'])) {
  114. // No file was uploaded.
  115. if ($show_output) {
  116. Display::display_error_message(get_lang('UplUploadFailed'));
  117. }
  118. return false;
  119. }
  120. if (file_exists($uploaded_file['tmp_name'])) {
  121. $filesize = filesize($uploaded_file['tmp_name']);
  122. if (empty($filesize)) {
  123. // No file was uploaded.
  124. if ($show_output) {
  125. Display::display_error_message(get_lang('UplUploadFailedSizeIsZero'));
  126. }
  127. return false;
  128. }
  129. }
  130. // case 0: default: We assume there is no error, the file uploaded with success.
  131. return true;
  132. }
  133. /**
  134. * This function does the save-work for the documents.
  135. * It handles the uploaded file and adds the properties to the database
  136. * If unzip=1 and the file is a zipfile, it is extracted
  137. * If we decide to save ALL kinds of documents in one database,
  138. * we could extend this with a $type='document', 'scormdocument',...
  139. *
  140. * @param array $_course
  141. * @param array $uploaded_file ($_FILES)
  142. * @param string $base_work_dir
  143. * @param string $upload_path
  144. * @param int $user_id
  145. * @param int $to_group_id, 0 for everybody
  146. * @param int $to_user_id, NULL for everybody
  147. * @param int $maxFilledSpace
  148. * @param int $unzip 1/0
  149. * @param string $what_if_file_exists overwrite, rename or warn if exists (default)
  150. * @param boolean Optional output parameter. So far only use for unzip_uploaded_document function. If no output wanted on success, set to false.
  151. * @return path of the saved file
  152. */
  153. function handle_uploaded_document($_course, $uploaded_file, $base_work_dir, $upload_path, $user_id, $to_group_id = 0, $to_user_id = null, $maxFilledSpace = '', $unzip = 0, $what_if_file_exists = '', $output = true) {
  154. if (!$user_id) die('Not a valid user.');
  155. // Strip slashes
  156. $uploaded_file['name'] = stripslashes($uploaded_file['name']);
  157. // Add extension to files without one (if possible)
  158. $uploaded_file['name'] = add_ext_on_mime($uploaded_file['name'], $uploaded_file['type']);
  159. $current_session_id = api_get_session_id();
  160. // Check if there is enough space to save the file
  161. if (!DocumentManager::enough_space($uploaded_file['size'], $maxFilledSpace)) {
  162. if ($output) {
  163. Display::display_error_message(get_lang('UplNotEnoughSpace'));
  164. }
  165. return false;
  166. }
  167. // If the want to unzip, check if the file has a .zip (or ZIP,Zip,ZiP,...) extension
  168. if ($unzip == 1 && preg_match('/.zip$/', strtolower($uploaded_file['name']))) {
  169. return unzip_uploaded_document($uploaded_file, $upload_path, $base_work_dir, $maxFilledSpace, $output, $to_group_id);
  170. //display_message('Unzipping file');
  171. } elseif ($unzip == 1 && !preg_match('/.zip$/', strtolower($uploaded_file['name']))) { // We can only unzip ZIP files (no gz, tar,...)
  172. if ($output) {
  173. Display::display_error_message(get_lang('UplNotAZip')." ".get_lang('PleaseTryAgain'));
  174. }
  175. return false;
  176. } else {
  177. // Clean up the name, only ASCII characters should stay. (and strict)
  178. $clean_name = replace_dangerous_char($uploaded_file['name'], 'strict');
  179. // No "dangerous" files
  180. $clean_name = disable_dangerous_file($clean_name);
  181. if (!filter_extension($clean_name)) {
  182. if ($output){
  183. Display::display_error_message(get_lang('UplUnableToSaveFileFilteredExtension'));
  184. }
  185. return false;
  186. } else {
  187. // Extension is good
  188. //echo '<br />clean name = '.$clean_name;
  189. //echo '<br />upload_path = '.$upload_path;
  190. // If the upload path differs from / (= root) it will need a slash at the end
  191. if ($upload_path != '/') {
  192. $upload_path = $upload_path.'/';
  193. }
  194. //echo '<br />upload_path = '.$upload_path;
  195. $file_path = $upload_path.$clean_name;
  196. //echo '<br />file path = '.$file_path;
  197. // Full path to where we want to store the file with trailing slash
  198. $where_to_save = $base_work_dir.$upload_path;
  199. // At least if the directory doesn't exist, tell so
  200. if (!is_dir($where_to_save)) {
  201. if ($output){
  202. Display::display_error_message(get_lang('DestDirectoryDoesntExist').' ('.$upload_path.')');
  203. }
  204. return false;
  205. }
  206. //echo '<br />where to save = '.$where_to_save;
  207. // Full path of the destination
  208. $store_path = $where_to_save.$clean_name;
  209. //echo '<br />store path = '.$store_path;
  210. // Name of the document without the extension (for the title)
  211. $document_name = get_document_title($uploaded_file['name']);
  212. // Size of the uploaded file (in bytes)
  213. $file_size = $uploaded_file['size'];
  214. $files_perm = api_get_permissions_for_new_files();
  215. // What to do if the target file exists
  216. switch ($what_if_file_exists) {
  217. // Overwrite the file if it exists
  218. case 'overwrite':
  219. // Check if the target file exists, so we can give another message
  220. $file_exists = file_exists($store_path);
  221. if (@move_uploaded_file($uploaded_file['tmp_name'], $store_path)) {
  222. chmod($store_path, $files_perm);
  223. if ($file_exists) {
  224. // UPDATE DATABASE
  225. $document_id = DocumentManager::get_document_id($_course, $file_path);
  226. if (is_numeric($document_id)) {
  227. // Update filesize
  228. update_existing_document($_course, $document_id, $uploaded_file['size']);
  229. // Update document item_property
  230. api_item_property_update($_course, TOOL_DOCUMENT, $document_id, 'DocumentUpdated', $user_id, $to_group_id, $to_user_id, null, null, $current_session_id);
  231. }
  232. // If the file is in a folder, we need to update all parent folders
  233. item_property_update_on_folder($_course, $upload_path, $user_id);
  234. // Display success message with extra info to user
  235. if ($output) {
  236. Display::display_confirmation_message(get_lang('UplUploadSucceeded').'<br />'.$file_path .' '. get_lang('UplFileOverwritten'), false);
  237. }
  238. return $file_path;
  239. } else {
  240. // Put the document data in the database
  241. $document_id = add_document($_course, $file_path, 'file', $file_size, $document_name);
  242. if ($document_id) {
  243. // Put the document in item_property update
  244. api_item_property_update($_course, TOOL_DOCUMENT, $document_id, 'DocumentAdded', $user_id, $to_group_id, $to_user_id, null, null, $current_session_id);
  245. }
  246. // If the file is in a folder, we need to update all parent folders
  247. item_property_update_on_folder($_course, $upload_path, $user_id);
  248. // Display success message to user
  249. if ($output){
  250. Display::display_confirmation_message(get_lang('UplUploadSucceeded').'<br />'.$file_path, false);
  251. }
  252. return $file_path;
  253. }
  254. } else {
  255. if ($output){
  256. Display::display_error_message(get_lang('UplUnableToSaveFile'));
  257. }
  258. return false;
  259. }
  260. break;
  261. // Rename the file if it exists
  262. case 'rename':
  263. $new_name = unique_name($where_to_save, $clean_name);
  264. $store_path = $where_to_save.$new_name;
  265. $new_file_path = $upload_path.$new_name;
  266. if (@move_uploaded_file($uploaded_file['tmp_name'], $store_path)) {
  267. chmod($store_path, $files_perm);
  268. // Put the document data in the database
  269. $document_id = add_document($_course, $new_file_path, 'file', $file_size, $document_name);
  270. if ($document_id) {
  271. // Update document item_property
  272. api_item_property_update($_course, TOOL_DOCUMENT, $document_id, 'DocumentAdded', $user_id, $to_group_id, $to_user_id, null, null, $current_session_id);
  273. }
  274. // If the file is in a folder, we need to update all parent folders
  275. item_property_update_on_folder($_course, $upload_path, $user_id);
  276. // Display success message to user
  277. if ($output){
  278. Display::display_confirmation_message(get_lang('UplUploadSucceeded').'<br />'.get_lang('UplFileSavedAs').$new_file_path, false);
  279. }
  280. return $new_file_path;
  281. } else {
  282. Display::display_error_message(get_lang('UplUnableToSaveFile'));
  283. return false;
  284. }
  285. break;
  286. // Only save the file if it doesn't exist or warn user if it does exist
  287. default:
  288. if (file_exists($store_path)) {
  289. if ($output) {
  290. Display::display_error_message($clean_name.' '.get_lang('UplAlreadyExists'));
  291. }
  292. } else {
  293. if (@move_uploaded_file($uploaded_file['tmp_name'], $store_path)) {
  294. chmod($store_path, $files_perm);
  295. // Put the document data in the database
  296. $document_id = add_document($_course, $file_path, 'file', $file_size, $document_name);
  297. if ($document_id) {
  298. // Update document item_property
  299. api_item_property_update($_course, TOOL_DOCUMENT, $document_id, 'DocumentAdded', $user_id, $to_group_id, $to_user_id, null, null, $current_session_id);
  300. }
  301. // If the file is in a folder, we need to update all parent folders
  302. item_property_update_on_folder($_course,$upload_path,$user_id);
  303. // Display success message to user
  304. if ($output){
  305. Display::display_confirmation_message(get_lang('UplUploadSucceeded').'<br />'.$file_path, false);
  306. }
  307. return $file_path;
  308. } else {
  309. if ($output){
  310. Display::display_error_message(get_lang('UplUnableToSaveFile'));
  311. }
  312. return false;
  313. }
  314. }
  315. break;
  316. }
  317. }
  318. }
  319. }
  320. /**
  321. * Checks if there is enough place to add a file on a directory
  322. * on the base of a maximum directory size allowed
  323. * deprecated: use enough_space instead!
  324. * @author - Hugues Peeters <peeters@ipm.ucl.ac.be>
  325. * @param - file_size (int) - size of the file in byte
  326. * @param - dir (string) - Path of the directory
  327. * whe the file should be added
  328. * @param - max_dir_space (int) - maximum size of the diretory in byte
  329. * @return - boolean true if there is enough space,
  330. * boolean false otherwise
  331. *
  332. * @see - enough_size() uses dir_total_space() function
  333. */
  334. function enough_size($file_size, $dir, $max_dir_space) {
  335. if ($max_dir_space) {
  336. $already_filled_space = dir_total_space($dir);
  337. if (($file_size + $already_filled_space) > $max_dir_space) {
  338. return false;
  339. }
  340. }
  341. return true;
  342. }
  343. /**
  344. * Computes the size already occupied by a directory and is subdirectories
  345. *
  346. * @author - Hugues Peeters <peeters@ipm.ucl.ac.be>
  347. * @param - dir_path (string) - size of the file in byte
  348. * @return - int - return the directory size in bytes
  349. */
  350. function dir_total_space($dir_path) {
  351. $save_dir = getcwd();
  352. chdir($dir_path) ;
  353. $handle = opendir($dir_path);
  354. while ($element = readdir($handle)) {
  355. if ( $element == '.' || $element == '..') {
  356. continue; // Skip the current and parent directories
  357. }
  358. if (is_file($element)) {
  359. $sumSize += filesize($element);
  360. }
  361. if (is_dir($element)) {
  362. $dirList[] = $dir_path.'/'.$element;
  363. }
  364. }
  365. closedir($handle) ;
  366. if (sizeof($dirList) > 0) {
  367. foreach ($dirList as $j) {
  368. $sizeDir = dir_total_space($j); // Recursivity
  369. $sumSize += $sizeDir;
  370. }
  371. }
  372. chdir($save_dir); // Return to initial position
  373. return $sumSize;
  374. }
  375. /**
  376. * Tries to add an extension to files without extension
  377. * Some applications on Macintosh computers don't add an extension to the files.
  378. * This subroutine try to fix this on the basis of the MIME type sent
  379. * by the browser.
  380. *
  381. * Note : some browsers don't send the MIME Type (e.g. Netscape 4).
  382. * We don't have solution for this kind of situation
  383. *
  384. * @author - Hugues Peeters <peeters@ipm.ucl.ac.be>
  385. * @author - Bert Vanderkimpen
  386. * @param - file_name (string) - Name of the file
  387. * @param - file_type (string) - Type of the file
  388. * @return - file_name (string)
  389. */
  390. function add_ext_on_mime($file_name, $file_type) {
  391. // Check whether the file has an extension AND whether the browser has sent a MIME Type
  392. if (!preg_match('/^.*\.[a-zA-Z_0-9]+$/', $file_name) && $file_type) {
  393. // Build a "MIME-types / extensions" connection table
  394. static $mime_type = array();
  395. $mime_type[] = 'application/msword'; $extension[] = '.doc';
  396. $mime_type[] = 'application/rtf'; $extension[] = '.rtf';
  397. $mime_type[] = 'application/vnd.ms-powerpoint'; $extension[] = '.ppt';
  398. $mime_type[] = 'application/vnd.ms-excel'; $extension[] = '.xls';
  399. $mime_type[] = 'application/pdf'; $extension[] = '.pdf';
  400. $mime_type[] = 'application/postscript'; $extension[] = '.ps';
  401. $mime_type[] = 'application/mac-binhex40'; $extension[] = '.hqx';
  402. $mime_type[] = 'application/x-gzip'; $extension[] = 'tar.gz';
  403. $mime_type[] = 'application/x-shockwave-flash'; $extension[] = '.swf';
  404. $mime_type[] = 'application/x-stuffit'; $extension[] = '.sit';
  405. $mime_type[] = 'application/x-tar'; $extension[] = '.tar';
  406. $mime_type[] = 'application/zip'; $extension[] = '.zip';
  407. $mime_type[] = 'application/x-tar'; $extension[] = '.tar';
  408. $mime_type[] = 'text/html'; $extension[] = '.html';
  409. $mime_type[] = 'text/plain'; $extension[] = '.txt';
  410. $mime_type[] = 'text/rtf'; $extension[] = '.rtf';
  411. $mime_type[] = 'img/gif'; $extension[] = '.gif';
  412. $mime_type[] = 'img/jpeg'; $extension[] = '.jpg';
  413. $mime_type[] = 'img/png'; $extension[] = '.png';
  414. $mime_type[] = 'audio/midi'; $extension[] = '.mid';
  415. $mime_type[] = 'audio/mpeg'; $extension[] = '.mp3';
  416. $mime_type[] = 'audio/x-aiff'; $extension[] = '.aif';
  417. $mime_type[] = 'audio/x-pn-realaudio'; $extension[] = '.rm';
  418. $mime_type[] = 'audio/x-pn-realaudio-plugin'; $extension[] = '.rpm';
  419. $mime_type[] = 'audio/x-wav'; $extension[] = '.wav';
  420. $mime_type[] = 'video/mpeg'; $extension[] = '.mpg';
  421. $mime_type[] = 'video/mpeg4-generic'; $extension[] = '.mp4';
  422. $mime_type[] = 'video/quicktime'; $extension[] = '.mov';
  423. $mime_type[] = 'video/x-msvideo'; $extension[] = '.avi';
  424. $mime_type[] = 'video/x-ms-wmv'; $extension[] = '.wmv';
  425. $mime_type[] = 'video/x-flv'; $extension[] = '.flv';
  426. $mime_type[] = 'image/svg+xml'; $extension[] = '.svg';
  427. $mime_type[] = 'image/svg+xml'; $extension[] = '.svgz';
  428. $mime_type[] = 'video/ogg'; $extension[] = '.ogv';
  429. $mime_type[] = 'audio/ogg'; $extension[] = '.oga';
  430. $mime_type[] = 'application/ogg'; $extension[] = '.ogg';
  431. $mime_type[] = 'application/ogg'; $extension[] = '.ogx';
  432. $mime_type[] = 'application/vnd.ms-word.document.macroEnabled.12'; $extension[] = '.docm';
  433. $mime_type[] = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'; $extension[] = '.docx';
  434. $mime_type[] = 'application/vnd.ms-word.template.macroEnabled.12'; $extension[] = '.dotm';
  435. $mime_type[] = 'application/vnd.openxmlformats-officedocument.wordprocessingml.template'; $extension[] = '.dotx';
  436. $mime_type[] = 'application/vnd.ms-powerpoint.template.macroEnabled.12'; $extension[] = '.potm';
  437. $mime_type[] = 'application/vnd.openxmlformats-officedocument.presentationml.template'; $extension[] = '.potx';
  438. $mime_type[] = 'application/vnd.ms-powerpoint.addin.macroEnabled.12'; $extension[] = '.ppam';
  439. $mime_type[] = 'application/vnd.ms-powerpoint.slideshow.macroEnabled.12'; $extension[] = '.ppsm';
  440. $mime_type[] = 'application/vnd.openxmlformats-officedocument.presentationml.slideshow'; $extension[] = '.ppsx';
  441. $mime_type[] = 'application/vnd.ms-powerpoint.presentation.macroEnabled.12'; $extension[] = '.pptm';
  442. $mime_type[] = 'application/vnd.openxmlformats-officedocument.presentationml.presentation'; $extension[] = '.pptx';
  443. $mime_type[] = 'application/vnd.ms-excel.addin.macroEnabled.12'; $extension[] = '.xlam';
  444. $mime_type[] = 'application/vnd.ms-excel.sheet.binary.macroEnabled.12'; $extension[] = '.xlsb';
  445. $mime_type[] = 'application/vnd.ms-excel.sheet.macroEnabled.12'; $extension[] = '.xlsm';
  446. $mime_type[] = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'; $extension[] = '.xlsx';
  447. $mime_type[] = 'application/vnd.ms-excel.template.macroEnabled.12'; $extension[] = '.xltm';
  448. $mime_type[] = 'application/vnd.openxmlformats-officedocument.spreadsheetml.template'; $extension[] = '.xltx';
  449. // Test on PC (files with no extension get application/octet-stream)
  450. //$mime_type[] = 'application/octet-stream'; $extension[] = '.ext';
  451. // Check whether the MIME type sent by the browser is within the table
  452. foreach ($mime_type as $key => & $type) {
  453. if ($type == $file_type) {
  454. $file_name .= $extension[$key];
  455. break;
  456. }
  457. }
  458. unset($mime_type, $extension, $type, $key); // Delete to eschew possible collisions
  459. }
  460. return $file_name;
  461. }
  462. /**
  463. *
  464. * @author Hugues Peeters <hugues.peeters@claroline.net>
  465. *
  466. * @param array $uploaded_file - follows the $_FILES Structure
  467. * @param string $base_work_dir - base working directory of the module
  468. * @param string $upload_path - destination of the upload.
  469. * This path is to append to $base_work_dir
  470. * @param int $max_filled_space - amount of bytes to not exceed in the base
  471. * working directory
  472. *
  473. * @return boolean true if it succeds, false otherwise
  474. */
  475. function treat_uploaded_file($uploaded_file, $base_work_dir, $upload_path, $max_filled_space, $uncompress = '') {
  476. $uploaded_file['name'] = stripslashes($uploaded_file['name']);
  477. if (!enough_size($uploaded_file['size'], $base_work_dir, $max_filled_space)) {
  478. return api_failure::set_failure('not_enough_space');
  479. }
  480. if ($uncompress == 'unzip' && preg_match('/.zip$/', strtolower($uploaded_file['name']))) {
  481. return unzip_uploaded_file($uploaded_file, $upload_path, $base_work_dir, $max_filled_space);
  482. } else {
  483. $file_name = trim($uploaded_file['name']);
  484. // CHECK FOR NO DESIRED CHARACTERS
  485. $file_name = replace_dangerous_char($file_name, 'strict');
  486. // TRY TO ADD AN EXTENSION TO FILES WITOUT EXTENSION
  487. $file_name = add_ext_on_mime($file_name, $uploaded_file['type']);
  488. // HANDLE PHP FILES
  489. $file_name = ($file_name);
  490. // COPY THE FILE TO THE DESIRED DESTINATION
  491. if (move_uploaded_file($uploaded_file['tmp_name'], $base_work_dir.$upload_path.'/'.$file_name)) {
  492. set_default_settings($upload_path, $file_name);
  493. }
  494. return true;
  495. }
  496. }
  497. /**
  498. * Manages all the unzipping process of an uploaded file
  499. *
  500. * @author Hugues Peeters <hugues.peeters@claroline.net>
  501. *
  502. * @param array $uploaded_file - follows the $_FILES Structure
  503. * @param string $upload_path - destination of the upload.
  504. * This path is to append to $base_work_dir
  505. * @param string $base_work_dir - base working directory of the module
  506. * @param int $max_filled_space - amount of bytes to not exceed in the base
  507. * working directory
  508. *
  509. * @return boolean true if it succeeds false otherwise
  510. */
  511. function unzip_uploaded_file($uploaded_file, $upload_path, $base_work_dir, $max_filled_space) {
  512. require_once api_get_path(LIBRARY_PATH).'pclzip/pclzip.lib.php';
  513. $zip_file = new pclZip($uploaded_file['tmp_name']);
  514. // Check the zip content (real size and file extension)
  515. if (file_exists($uploaded_file)) {
  516. $zip_content_array = $zip_file->listContent();
  517. $ok_scorm = false;
  518. foreach ($zip_content_array as & $this_content) {
  519. if (preg_match('~.(php.*|phtml)$~i', $this_content['filename'])) {
  520. return api_failure::set_failure('php_file_in_zip_file');
  521. } elseif (stristr($this_content['filename'], 'imsmanifest.xml')) {
  522. $ok_scorm = true;
  523. } elseif (stristr($this_content['filename'], 'LMS')) {
  524. $ok_plantyn_scorm1 = true;
  525. } elseif (stristr($this_content['filename'], 'REF')) {
  526. $ok_plantyn_scorm2 = true;
  527. } elseif (stristr($this_content['filename'], 'SCO')) {
  528. $ok_plantyn_scorm3 = true;
  529. } elseif (stristr($this_content['filename'], 'AICC')) {
  530. $ok_aicc_scorm = true;
  531. }
  532. $realFileSize += $this_content['size'];
  533. }
  534. if (($ok_plantyn_scorm1 && $ok_plantyn_scorm2 && $ok_plantyn_scorm3) || $ok_aicc_scorm) {
  535. $ok_scorm = true;
  536. }
  537. if (!$ok_scorm && defined('CHECK_FOR_SCORM') && CHECK_FOR_SCORM) {
  538. return api_failure::set_failure('not_scorm_content');
  539. }
  540. if (!enough_size($realFileSize, $base_work_dir, $max_filled_space)) {
  541. return api_failure::set_failure('not_enough_space');
  542. }
  543. // It happens on Linux that $upload_path sometimes doesn't start with '/'
  544. if ($upload_path[0] != '/') {
  545. $upload_path = '/'.$upload_path;
  546. }
  547. if ($upload_path[strlen($upload_path) - 1] == '/') {
  548. $upload_path=substr($upload_path, 0, -1);
  549. }
  550. /* Uncompressing phase */
  551. /*
  552. The first version, using OS unzip, is not used anymore
  553. because it does not return enough information.
  554. We need to process each individual file in the zip archive to
  555. - add it to the database
  556. - parse & change relative html links
  557. */
  558. if (PHP_OS == 'Linux' && ! get_cfg_var('safe_mode') && false) { // *** UGent, changed by OC ***
  559. // Shell Method - if this is possible, it gains some speed
  560. exec("unzip -d \"".$base_work_dir.$upload_path."/\"".$uploaded_file['name']." " .$uploaded_file['tmp_name']);
  561. } else {
  562. // PHP method - slower...
  563. $save_dir = getcwd();
  564. chdir($base_work_dir.$upload_path);
  565. $unzippingState = $zip_file->extract();
  566. for ($j=0; $j < count($unzippingState); $j++) {
  567. $state = $unzippingState[$j];
  568. // Fix relative links in html files
  569. $extension = strrchr($state['stored_filename'], '.');
  570. }
  571. if ($dir = @opendir($base_work_dir.$upload_path)) {
  572. while ($file = readdir($dir)) {
  573. if ($file != '.' && $file != '..') {
  574. $filetype = 'file';
  575. if (is_dir($base_work_dir.$upload_path.'/'.$file)) $filetype = 'folder';
  576. $safe_file = replace_dangerous_char($file, 'strict');
  577. @rename($base_work_dir.$upload_path.'/'.$file,$base_work_dir.$upload_path.'/'.$safe_file);
  578. set_default_settings($upload_path, $safe_file,$filetype);
  579. }
  580. }
  581. closedir($dir);
  582. }
  583. chdir($save_dir); // Back to previous dir position
  584. }
  585. }
  586. return true;
  587. }
  588. /**
  589. * Manages all the unzipping process of an uploaded document
  590. * This uses the item_property table for properties of documents
  591. *
  592. * @author Hugues Peeters <hugues.peeters@claroline.net>
  593. * @author Bert Vanderkimpen
  594. *
  595. * @param array $uploaded_file - follows the $_FILES Structure
  596. * @param string $upload_path - destination of the upload.
  597. * This path is to append to $base_work_dir
  598. * @param string $base_work_dir - base working directory of the module
  599. * @param int $max_filled_space - amount of bytes to not exceed in the base
  600. * working directory
  601. * @param boolean Output switch. Optional. If no output not wanted on success, set to false.
  602. *
  603. * @return boolean true if it succeeds false otherwise
  604. */
  605. function unzip_uploaded_document($uploaded_file, $upload_path, $base_work_dir, $max_filled_space, $output = true, $to_group_id = 0) {
  606. global $_course;
  607. global $_user;
  608. global $to_user_id;
  609. global $to_group_id;
  610. require_once api_get_path(LIBRARY_PATH).'pclzip/pclzip.lib.php';
  611. $zip_file = new pclZip($uploaded_file['tmp_name']);
  612. // Check the zip content (real size and file extension)
  613. $zip_content_array = (array)$zip_file->listContent();
  614. foreach($zip_content_array as & $this_content) {
  615. $real_filesize += $this_content['size'];
  616. }
  617. if (!DocumentManager::enough_space($real_filesize, $max_filled_space)) {
  618. Display::display_error_message(get_lang('UplNotEnoughSpace'));
  619. return false;
  620. }
  621. // It happens on Linux that $upload_path sometimes doesn't start with '/'
  622. if ($upload_path[0] != '/') {
  623. $upload_path='/'.$upload_path;
  624. }
  625. /* Uncompressing phase */
  626. // Get into the right directory
  627. $save_dir = getcwd();
  628. chdir($base_work_dir.$upload_path);
  629. // We extract using a callback function that "cleans" the path
  630. $unzipping_state = $zip_file->extract(PCLZIP_CB_PRE_EXTRACT, 'clean_up_files_in_zip', PCLZIP_OPT_REPLACE_NEWER);
  631. // Add all documents in the unzipped folder to the database
  632. add_all_documents_in_folder_to_database($_course, $_user['user_id'], $base_work_dir ,$upload_path == '/' ? '' : $upload_path, $to_group_id);
  633. //Display::display_normal_message(get_lang('UplZipExtractSuccess'));
  634. return true;
  635. }
  636. /**
  637. * This function is a callback function that is used while extracting a zipfile
  638. * http://www.phpconcept.net/pclzip/man/en/index.php?options-pclzip_cb_pre_extract
  639. *
  640. * @param $p_event
  641. * @param $p_header
  642. * @return 1 (If the function returns 1, then the extraction is resumed)
  643. */
  644. function clean_up_files_in_zip($p_event, &$p_header) {
  645. $res = clean_up_path($p_header['filename']);
  646. return $res;
  647. }
  648. /**
  649. * This function cleans up a given path
  650. * by eliminating dangerous file names and cleaning them
  651. *
  652. * @param string $path
  653. * @return $path
  654. * @see disable_dangerous_file()
  655. * @see replace_dangerous_char()
  656. */
  657. function clean_up_path(&$path) {
  658. // Split the path in folders and files
  659. $path_array = explode('/', $path);
  660. // Clean up every foler and filename in the path
  661. foreach ($path_array as $key => & $val) {
  662. // We don't want to lose the dots in ././folder/file (cfr. zipfile)
  663. if ($val != '.') {
  664. $val = disable_dangerous_file(replace_dangerous_char($val));
  665. }
  666. }
  667. // Join the "cleaned" path (modified in-place as passed by reference)
  668. $path = implode('/', $path_array);
  669. $res = filter_extension($path);
  670. return $res;
  671. }
  672. /**
  673. * Checks if the file is dangerous, based on extension and/or mimetype.
  674. * The list of extensions accepted/rejected can be found from
  675. * api_get_setting('upload_extensions_exclude') and api_get_setting('upload_extensions_include')
  676. * @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')
  677. * @return int 0 to skip file, 1 to keep file
  678. */
  679. function filter_extension(&$filename) {
  680. if (substr($filename, -1) == '/') {
  681. return 1; // Authorize directories
  682. }
  683. $blacklist = api_get_setting('upload_extensions_list_type');
  684. if ($blacklist != 'whitelist') { // if = blacklist
  685. $extensions = split(';', strtolower(api_get_setting('upload_extensions_blacklist')));
  686. $skip = api_get_setting('upload_extensions_skip');
  687. $ext = strrchr($filename, '.');
  688. $ext = substr($ext, 1);
  689. if (empty($ext)) {
  690. return 1; // We're in blacklist mode, so accept empty extensions
  691. }
  692. if (in_array(strtolower($ext), $extensions)) {
  693. if ($skip == 'true') {
  694. return 0;
  695. } else {
  696. $new_ext = api_get_setting('upload_extensions_replace_by');
  697. $filename = str_replace('.'.$ext, '.'.$new_ext, $filename);
  698. return 1;
  699. }
  700. } else {
  701. return 1;
  702. }
  703. } else {
  704. $extensions = split(';', strtolower(api_get_setting('upload_extensions_whitelist')));
  705. $skip = api_get_setting('upload_extensions_skip');
  706. $ext = strrchr($filename, '.');
  707. $ext = substr($ext, 1);
  708. if (empty($ext)) {
  709. return 1; // Accept empty extensions
  710. }
  711. if (!in_array(strtolower($ext), $extensions)) {
  712. if ($skip == 'true') {
  713. return 0;
  714. } else {
  715. $new_ext = api_get_setting('upload_extensions_replace_by');
  716. $filename = str_replace('.'.$ext, '.'.$new_ext, $filename);
  717. return 1;
  718. }
  719. } else {
  720. return 1;
  721. }
  722. }
  723. }
  724. /**
  725. * Adds a new document to the database
  726. *
  727. * @param array $_course
  728. * @param string $path
  729. * @param string $filetype
  730. * @param int $filesize
  731. * @param string $title
  732. * @return id if inserted document
  733. */
  734. function add_document($_course, $path, $filetype, $filesize, $title, $comment = null, $readonly = 0) {
  735. $session_id = api_get_session_id();
  736. $readonly = intval($readonly);
  737. $comment = Database::escape_string($comment);
  738. $path = Database::escape_string($path);
  739. $filetype = Database::escape_string($filetype);
  740. $filesize = intval($filesize);
  741. $table_document = Database::get_course_table(TABLE_DOCUMENT);
  742. $sql = "INSERT INTO $table_document (c_id, path, filetype, size, title, comment, readonly, session_id)
  743. VALUES ({$_course['real_id']}, '$path','$filetype','$filesize','".Database::escape_string($title)."', '$comment', $readonly, $session_id)";
  744. if (Database::query($sql)) {
  745. //display_message("Added to database (id ".Database::insert_id().")!");
  746. return Database::insert_id();
  747. } else {
  748. //display_error("The uploaded file could not be added to the database (".Database::error().")!");
  749. return false;
  750. }
  751. }
  752. /**
  753. * Updates an existing document in the database
  754. * as the file exists, we only need to change the size
  755. *
  756. * @param array $_course
  757. * @param int $document_id
  758. * @param int $filesize
  759. * @param int $readonly
  760. * @return boolean true /false
  761. */
  762. function update_existing_document($_course, $document_id, $filesize, $readonly = 0) {
  763. $document_table = Database::get_course_table(TABLE_DOCUMENT);
  764. $document_id = intval($document_id);
  765. $filesize = intval($filesize);
  766. $readonly = intval($readonly);
  767. $course_id = $_course['real_id'];
  768. $sql = "UPDATE $document_table SET size = '$filesize' , readonly = '$readonly'
  769. WHERE c_id = $course_id AND id = $document_id";
  770. if (Database::query($sql)) {
  771. return true;
  772. } else {
  773. return false;
  774. }
  775. }
  776. /**
  777. * This function updates the last_edit_date, last edit user id on all folders in a given path
  778. *
  779. * @param array $_course
  780. * @param string $path
  781. * @param int $user_id
  782. */
  783. function item_property_update_on_folder($_course, $path, $user_id) {
  784. //display_message("Start update_lastedit_on_folder");
  785. // If we are in the root, just return... no need to update anything
  786. if ($path == '/') {
  787. return;
  788. }
  789. $user_id = intval($user_id);
  790. // If the given path ends with a / we remove it
  791. $endchar = substr($path, strlen($path) - 1, 1);
  792. if ($endchar == '/') {
  793. $path = substr($path, 0, strlen($path) - 1);
  794. }
  795. $TABLE_ITEMPROPERTY = Database::get_course_table(TABLE_ITEM_PROPERTY);
  796. // Get the time
  797. $time = date('Y-m-d H:i:s', time());
  798. // Det all paths in the given path
  799. // /folder/subfolder/subsubfolder/file
  800. // if file is updated, subsubfolder, subfolder and folder are updated
  801. $exploded_path = explode('/', $path);
  802. $course_id = api_get_course_int_id();
  803. foreach ($exploded_path as $key => & $value) {
  804. // We don't want a slash before our first slash
  805. if ($key != 0) {
  806. $newpath .= '/'.$value;
  807. //echo 'path= '.$newpath.'<br />';
  808. // Select ID of given folder
  809. $folder_id = DocumentManager::get_document_id($_course, $newpath);
  810. if ($folder_id) {
  811. $sql = "UPDATE $TABLE_ITEMPROPERTY SET lastedit_date='$time',lastedit_type='DocumentInFolderUpdated', lastedit_user_id='$user_id'
  812. WHERE c_id = $course_id AND tool='".TOOL_DOCUMENT."' AND ref='$folder_id'";
  813. Database::query($sql);
  814. }
  815. }
  816. }
  817. }
  818. /**
  819. * Returns the directory depth of the file.
  820. *
  821. * @author Olivier Cauberghe <olivier.cauberghe@ugent.be>
  822. * @param path+filename eg: /main/document/document.php
  823. * @return The directory depth
  824. */
  825. function get_levels($filename) {
  826. $levels=explode('/', $filename);
  827. if (empty($levels[count($levels) - 1])) {
  828. unset($levels[count($levels) - 1]);
  829. }
  830. return count($levels);
  831. }
  832. /**
  833. * Adds file to document table in database
  834. * deprecated: use file_set_default_settings instead
  835. *
  836. * @author Olivier Cauberghe <olivier.cauberghe@ugent.be>
  837. * @param path,filename
  838. * action: Adds an entry to the document table with the default settings.
  839. */
  840. function set_default_settings($upload_path, $filename, $filetype = 'file') {
  841. global $dbTable,$_configuration;
  842. global $default_visibility;
  843. if (!$default_visibility) {
  844. $default_visibility = 'v';
  845. }
  846. $filetype = Database::escape_string($filetype);
  847. $upload_path = str_replace('\\', '/', $upload_path);
  848. $upload_path = str_replace('//', '/', $upload_path);
  849. if ($upload_path == '/') {
  850. $upload_path='';
  851. } elseif (!empty($upload_path) && $upload_path[0] != '/') {
  852. $upload_path="/$upload_path";
  853. }
  854. $endchar = substr($filename, strlen($filename) - 1, 1);
  855. if ($endchar == '/') {
  856. $filename = substr($filename, 0, -1);
  857. }
  858. // $dbTable already has backticks!
  859. //$query = "select count(*) as bestaat from $dbTable where path='$upload_path/$filename'";
  860. $query = "select count(*) as bestaat from $dbTable where path='$upload_path/$filename'";
  861. $result = Database::query($query);
  862. $row = Database::fetch_array($result);
  863. if ($row['bestaat'] > 0) {
  864. //$query = "update $dbTable set path='$upload_path/$filename',visibility='$default_visibility', filetype='$filetype' where path='$upload_path/$filename'";
  865. $query = "UPDATE $dbTable SET path='$upload_path/$filename',visibility='$default_visibility', filetype='$filetype' where path='$upload_path/$filename'";
  866. } else {
  867. //$query = "INSERT INTO $dbTable (path,visibility,filetype) VALUES('$upload_path/$filename','$default_visibility','$filetype')";
  868. $query = "INSERT INTO $dbTable (path,visibility,filetype) VALUES('$upload_path/$filename','$default_visibility','$filetype')";
  869. }
  870. Database::query($query);
  871. }
  872. /**
  873. * Retrieves the image path list in a html file
  874. *
  875. * @author Hugues Peeters <hugues.peeters@claroline.net>
  876. * @param string $html_file
  877. * @return array - images path list
  878. */
  879. function search_img_from_html($html_file) {
  880. $img_path_list = array();
  881. if (!$fp = fopen($html_file, 'r')) {
  882. return ;
  883. }
  884. // Aearch and store occurences of the <img> tag in an array
  885. $size_file = (filesize($html_file) === 0) ? 1 : filesize($html_file);
  886. if (isset($fp) && $fp !== false) {
  887. $buffer = fread($fp, $size_file);
  888. if (strlen($buffer) >= 0 && $buffer !== false) {
  889. //
  890. } else {
  891. die('<center>Can not read file.</center>');
  892. }
  893. } else {
  894. die('<center>Can not read file.</center>');
  895. }
  896. $matches = array();
  897. if (preg_match_all('~<[[:space:]]*img[^>]*>~i', $buffer, $matches)) {
  898. $img_tag_list = $matches[0];
  899. }
  900. fclose ($fp);
  901. unset($buffer);
  902. // Search the image file path from all the <IMG> tag detected
  903. if (sizeof($img_tag_list) > 0) {
  904. foreach ($img_tag_list as & $this_img_tag) {
  905. if (preg_match('~src[[:space:]]*=[[:space:]]*[\"]{1}([^\"]+)[\"]{1}~i', $this_img_tag, $matches)) {
  906. $img_path_list[] = $matches[1];
  907. }
  908. }
  909. $img_path_list = array_unique($img_path_list); // Remove duplicate entries
  910. }
  911. return $img_path_list;
  912. }
  913. /**
  914. * Creates a new directory trying to find a directory name
  915. * that doesn't already exist
  916. * (we could use unique_name() here...)
  917. *
  918. * @author Hugues Peeters <hugues.peeters@claroline.net>
  919. * @author Bert Vanderkimpen
  920. * @param array $_course current course information
  921. * @param int $user_id current user id
  922. * @param string $desiredDirName complete path of the desired name
  923. * @param string The visible name of the directory
  924. * @param int Visibility (0 for invisible, 1 for visible, 2 for deleted)
  925. * @return string actual directory name if it succeeds,
  926. * boolean false otherwise
  927. */
  928. function create_unexisting_directory($_course, $user_id, $session_id, $to_group_id, $to_user_id, $base_work_dir, $desired_dir_name, $title = null, $visibility = '') {
  929. $nb = '';
  930. // add numerical suffix to directory if another one of the same number already exists
  931. while (file_exists($base_work_dir.$desired_dir_name.$nb)) {
  932. $nb += 1;
  933. }
  934. if ($title == null) {
  935. $title = basename($desired_dir_name);
  936. }
  937. $course_id = $_course['real_id'];
  938. if (mkdir($base_work_dir.$desired_dir_name.$nb, api_get_permissions_for_new_directories(), true)) {
  939. // Check if pathname already exists inside document table
  940. $tbl_document = Database::get_course_table(TABLE_DOCUMENT);
  941. $sql = "SELECT path FROM $tbl_document WHERE c_id = $course_id AND path='".$desired_dir_name.$nb."'";
  942. $rs = Database::query($sql);
  943. if (Database::num_rows($rs) == 0) {
  944. $document_id = add_document($_course, $desired_dir_name.$nb, 'folder', 0, $title);
  945. if ($document_id) {
  946. // Update document item_property
  947. if ($visibility !== '') {
  948. $visibilities = array(0 => 'invisible', 1 => 'visible', 2 => 'delete');
  949. api_item_property_update($_course, TOOL_DOCUMENT, $document_id, $visibilities[$visibility], $user_id, $to_group_id, $to_user_id, null, null, $session_id);
  950. } else {
  951. api_item_property_update($_course, TOOL_DOCUMENT, $document_id, 'FolderCreated', $user_id, $to_group_id, $to_user_id, null, null, $session_id);
  952. }
  953. return $desired_dir_name.$nb;
  954. }
  955. } else {
  956. //This means the folder NOT exist in the filesystem (now this was created) but there is a record in the Database
  957. return $desired_dir_name.$nb;
  958. }
  959. } else {
  960. return false;
  961. }
  962. }
  963. /**
  964. * Handles uploaded missing images
  965. *
  966. * @author Hugues Peeters <hugues.peeters@claroline.net>
  967. * @author Bert Vanderkimpen
  968. * @param array $_course
  969. * @param array $uploaded_file_collection - follows the $_FILES Structure
  970. * @param string $base_work_dir
  971. * @param string $missing_files_dir
  972. * @param int $user_id
  973. * @param int $max_filled_space
  974. */
  975. function move_uploaded_file_collection_into_directory($_course, $uploaded_file_collection, $base_work_dir, $missing_files_dir, $user_id, $to_group_id, $to_user_id, $max_filled_space) {
  976. $number_of_uploaded_images = count($uploaded_file_collection['name']);
  977. for ($i = 0; $i < $number_of_uploaded_images; $i++) {
  978. $missing_file['name'] = $uploaded_file_collection['name'][$i];
  979. $missing_file['type'] = $uploaded_file_collection['type'][$i];
  980. $missing_file['tmp_name'] = $uploaded_file_collection['tmp_name'][$i];
  981. $missing_file['error'] = $uploaded_file_collection['error'][$i];
  982. $missing_file['size'] = $uploaded_file_collection['size'][$i];
  983. $upload_ok = process_uploaded_file($missing_file);
  984. if ($upload_ok) {
  985. $new_file_list[] = handle_uploaded_document($_course, $missing_file, $base_work_dir, $missing_files_dir, $user_id, $to_group_id, $to_user_id, $max_filled_space, 0, 'overwrite');
  986. }
  987. unset($missing_file);
  988. }
  989. return $new_file_list;
  990. }
  991. /**
  992. * Opens the old html file and replace the src path into the img tag
  993. * This also works for files in subdirectories.
  994. * @param $original_img_path is an array
  995. * @param $new_img_path is an array
  996. */
  997. function replace_img_path_in_html_file($original_img_path, $new_img_path, $html_file) {
  998. global $_course;
  999. // Open the file
  1000. $fp = fopen($html_file, 'r');
  1001. $buffer = fread($fp, filesize($html_file));
  1002. // Fix the image tags
  1003. for ($i = 0, $fileNb = count($original_img_path); $i < $fileNb ; $i++) {
  1004. $replace_what = $original_img_path[$i];
  1005. // We only need the directory and the filename /path/to/file_html_files/missing_file.gif -> file_html_files/missing_file.gif
  1006. $exploded_file_path = explode('/', $new_img_path[$i]);
  1007. $replace_by = $exploded_file_path[count($exploded_file_path) - 2].'/'.$exploded_file_path[count($exploded_file_path) - 1];
  1008. //$message .= "Element [$i] <b>" . $replace_what . "</b> replaced by <b>" . $replace_by . "</b><br />"; //debug
  1009. //api_display_debug_info($message);
  1010. $buffer = str_replace($replace_what, $replace_by, $buffer);
  1011. }
  1012. $new_html_content .= $buffer;
  1013. @fclose($fp);
  1014. // Write the resulted new file
  1015. if (!$fp = fopen($html_file, 'w')) {
  1016. return;
  1017. }
  1018. if (!fwrite($fp, $new_html_content)) {
  1019. return;
  1020. }
  1021. }
  1022. /**
  1023. * Creates a file containing an html redirection to a given url
  1024. *
  1025. * @author Hugues Peeters <hugues.peeters@claroline.net>
  1026. * @param string $file_path
  1027. * @param string $url
  1028. * @return void
  1029. */
  1030. function create_link_file($file_path, $url) {
  1031. $file_content = '<html>'
  1032. .'<head>'
  1033. .'<meta http-equiv="refresh" content="1;url='.$url.'">'
  1034. .'</head>'
  1035. .'<body>'
  1036. .'</body>'
  1037. .'</html>';
  1038. if (file_exists($file_path)) {
  1039. if (!($fp = fopen ($file_path, 'w'))) {
  1040. return false;
  1041. }
  1042. return fwrite($fp, $file_content);
  1043. }
  1044. }
  1045. /**
  1046. * Opens html file $full_file_name;
  1047. * Parses the hyperlinks; and
  1048. * Writes the result back in the html file.
  1049. *
  1050. * @author Roan Embrechts
  1051. * @version 0.1
  1052. */
  1053. function api_replace_links_in_html($upload_path, $full_file_name) {
  1054. // Open the file
  1055. if (file_exists($full_file_name)) {
  1056. $fp = fopen($full_file_name, 'r');
  1057. $buffer = fread ($fp, filesize ($full_file_name));
  1058. // Parse the contents
  1059. $new_html_content = api_replace_links_in_string($upload_path, $buffer);
  1060. // Write the result
  1061. $fp = fopen($full_file_name, 'w');
  1062. fwrite($fp, $new_html_content);
  1063. }
  1064. }
  1065. /**
  1066. deprecated: use api_replace_parameter instead
  1067. Parse the buffer string provided as parameter
  1068. Replace the a href tags so they are displayed correctly.
  1069. - works for files in root and subdirectories
  1070. - replace relative hyperlinks to use showinframes.php?file= ...
  1071. - add target="_self" to all absolute hyperlinks
  1072. - leave local anchors untouched (e.g. #CHAPTER1)
  1073. - leave links with download.php and showinframes.php untouched
  1074. @author Roan Embrechts
  1075. @version 0.6
  1076. */
  1077. function api_replace_links_in_string($upload_path, $buffer) {
  1078. // Search for hyperlinks
  1079. $matches = array();
  1080. if (preg_match_all('/<a[\s]*href[^<]*>/i', $buffer, $matches)) {
  1081. $tag_list = $matches[0];
  1082. }
  1083. // Search the filepath of all detected <a href> tags
  1084. if (sizeof($tag_list) > 0) {
  1085. $file_path_list = array();
  1086. $href_list = array();
  1087. foreach ($tag_list as & $this_tag) {
  1088. /* Match case insensitive, the stuff between the two ~ :
  1089. a href = <exactly one quote><one or more non-quotes><exactly one ">
  1090. e.g. a href="www.google.be", A HREF = "info.html"
  1091. to match ["] escape the " or else PHP interprets it
  1092. [\"]{1} --> matches exactly one "
  1093. + 1 or more (like * is 0 or more)
  1094. [\s]* matches whitespace
  1095. $matches contains captured subpatterns
  1096. the only one here is ([^\"]+) --> matches[1]
  1097. */
  1098. if (preg_match("~a href[\s]*=[\s]*[\"]{1}([^\"]+)[\"]{1}~i", $this_tag, $matches)) {
  1099. $file_path_list[] = $matches[1]; // older
  1100. $href_list[] = $matches[0]; // to also add target="_self"
  1101. }
  1102. }
  1103. }
  1104. // Replace the original hyperlinks by the correct ones
  1105. for ($count = 0; $count < sizeof($href_list); $count++) {
  1106. $replace_what[$count] = $href_list[$count];
  1107. $is_absolute_hyperlink = strpos($replace_what[$count], 'http');
  1108. $is_local_anchor = strpos($replace_what[$count], "#");
  1109. if (!$is_absolute_hyperlink && !$is_local_anchor) {
  1110. // This is a relative hyperlink
  1111. if ((strpos($replace_what[$count], 'showinframes.php') === false) && (strpos($replace_what[$count], 'download.php') === false)) {
  1112. // Fix the link to use showinframes.php
  1113. $replace_by[$count] = 'a href = "showinframes.php?file='.$upload_path.'/'.$file_path_list[$count].'" target="_self"';
  1114. } else {
  1115. // URL has been already fixed, leave it as is
  1116. $replace_by[$count] = $replace_what[$count];
  1117. }
  1118. } elseif ($is_absolute_hyperlink) {
  1119. $replace_by[$count] = 'a href="'.$file_path_list[$count].'" target ="_self"';
  1120. } else {
  1121. // Don't change anything
  1122. $replace_by[$count] = $replace_what[$count];
  1123. }
  1124. //Display::display_normal_message('Link replaced by ' . $replace_by[$count]); // debug
  1125. }
  1126. $buffer = str_replace($replace_what, $replace_by, $buffer);
  1127. return $buffer;
  1128. }
  1129. /**
  1130. EXPERIMENTAL - function seems to work, needs more testing
  1131. @param $upload_path is the path where the document is stored, like "/archive/"
  1132. if it is the root level, the function expects "/"
  1133. otherwise "/path/"
  1134. This function parses all tags with $param_name parameters.
  1135. so the tags are displayed correctly.
  1136. --------------
  1137. Algorithm v1.0
  1138. --------------
  1139. given a string and a parameter,
  1140. * OK find all tags in that string with the specified parameter (like href or src)
  1141. * OK for every one of these tags, find the src|href|... part to edit it
  1142. * OK change the src|href|... part to use download.php (or showinframes.php)
  1143. * OK do some special stuff for hyperlinks
  1144. Exceptions
  1145. * OK if download.php or showinframes.php is already in the tag, leave it alone
  1146. * OK if mailto is in the tag, leave it alone
  1147. * OK if the src|href param contains http://, it's absolute --> leave it alone
  1148. Special for hyperlinks (a href...)
  1149. * OK add target="_self"
  1150. * OK use showinframes.php instead of download.php
  1151. @author Roan Embrechts
  1152. @version 1.1
  1153. */
  1154. function api_replace_parameter($upload_path, $buffer, $param_name = 'src') {
  1155. // Search for tags with $param_name as a parameter
  1156. /*
  1157. // [\s]* matches whitespace
  1158. // [\"=a-z] matches ", = and a-z
  1159. // ([\s]*[a-z]*)* matches all whitespace and normal alphabet
  1160. // characters a-z combinations but seems too slow
  1161. // perhaps ([\s]*[a-z]*) a maximum number of times ?
  1162. // [\s]*[a-z]*[\s]* matches many tags
  1163. // the ending "i" means to match case insensitive (a matches a and A)
  1164. */
  1165. $matches = array();
  1166. if (preg_match_all('/<[a-z]+[^<]*'.$param_name.'[^<]*>/i', $buffer, $matches)) {
  1167. $tag_list = $matches[0];
  1168. }
  1169. // Search the filepath of parameter $param_name in all detected tags
  1170. if (sizeof($tag_list) > 0) {
  1171. $file_path_list = array();
  1172. $href_list = array();
  1173. foreach ($tag_list as & $this_tag) {
  1174. //Display::display_normal_message(htmlentities($this_tag)); //debug
  1175. if ( preg_match("~".$param_name."[\s]*=[\s]*[\"]{1}([^\"]+)[\"]{1}~i", $this_tag, $matches)) {
  1176. $file_path_list[] = $matches[1]; // older
  1177. $href_list[] = $matches[0]; // to also add target="_self"
  1178. }
  1179. }
  1180. }
  1181. // Replace the original tags by the correct ones
  1182. for ($count = 0; $count < sizeof($href_list); $count++) {
  1183. $replace_what[$count] = $href_list[$count];
  1184. $is_absolute_hyperlink = strpos($replace_what[$count], 'http');
  1185. $is_local_anchor = strpos($replace_what[$count], '#');
  1186. if (!$is_absolute_hyperlink && !$is_local_anchor) {
  1187. if ((strpos($replace_what[$count], 'showinframes.php') === false)
  1188. && (strpos($replace_what[$count], 'download.php') === false)
  1189. && (strpos($replace_what[$count], 'mailto') === false)) {
  1190. // Fix the link to use download.php or showinframes.php
  1191. if (preg_match("/<a([\s]*[\"\/:'=a-z0-9]*){5}href[^<]*>/i", $tag_list[$count])) {
  1192. $replace_by[$count] = " $param_name =\"showinframes.php?file=" . $upload_path.$file_path_list[$count]."\" target=\"_self\" ";
  1193. } else {
  1194. $replace_by[$count] = " $param_name =\"download.php?doc_url=" . $upload_path.$file_path_list[$count]."\" ";
  1195. }
  1196. } else {
  1197. // "mailto" or url already fixed, leave as is
  1198. //$message .= "Already fixed or contains mailto: ";
  1199. $replace_by[$count] = $replace_what[$count];
  1200. }
  1201. } elseif ($is_absolute_hyperlink) {
  1202. //$message .= "Absolute hyperlink, don't change, add target=_self: ";
  1203. $replace_by[$count] = " $param_name=\"" . $file_path_list[$count] . "\" target =\"_self\"";
  1204. } else {
  1205. // Don't change anything
  1206. //$message .= "Local anchor, don't change: ";
  1207. $replace_by[$count] = $replace_what[$count];
  1208. }
  1209. //$message .= "In tag $count, <b>" . htmlentities($tag_list[$count])
  1210. // . "</b>, parameter <b>" . $replace_what[$count] . "</b> replaced by <b>" . $replace_by[$count] . "</b><br>"; //debug
  1211. }
  1212. //if ($message) api_display_debug_info($message); //debug
  1213. $buffer = str_replace($replace_what, $replace_by, $buffer);
  1214. return $buffer;
  1215. }
  1216. /**
  1217. * Checks the extension of a file, if it's .htm or .html
  1218. * we use search_img_from_html to get all image paths in the file
  1219. *
  1220. * @param string $file
  1221. * @return array paths
  1222. * @see check_for_missing_files() uses search_img_from_html()
  1223. */
  1224. function check_for_missing_files($file) {
  1225. if (strrchr($file, '.') == '.htm' || strrchr($file, '.') == '.html') {
  1226. $img_file_path = search_img_from_html($file);
  1227. return $img_file_path;
  1228. }
  1229. return false;
  1230. }
  1231. /**
  1232. * This function builds a form that asks for the missing images in a html file
  1233. * maybe we should do this another way?
  1234. *
  1235. * @param array $missing_files
  1236. * @param string $upload_path
  1237. * @param string $file_name
  1238. * @return string the form
  1239. */
  1240. function build_missing_files_form($missing_files, $upload_path, $file_name) {
  1241. // Do we need a / or not?
  1242. $added_slash = ($upload_path == '/') ? '' : '/';
  1243. $folder_id = DocumentManager::get_document_id(api_get_course_info(), $upload_path);
  1244. // Build the form
  1245. $form .= "<p><strong>".get_lang('MissingImagesDetected')."</strong></p>"
  1246. ."<form method=\"post\" action=\"".api_get_self()."\" enctype=\"multipart/form-data\">"
  1247. // Related_file is the path to the file that has missing images
  1248. ."<input type=\"hidden\" name=\"related_file\" value=\"".$upload_path.$added_slash.$file_name."\" />"
  1249. ."<input type=\"hidden\" name=\"upload_path\" value=\"".$upload_path."\" />"
  1250. ."<input type=\"hidden\" name=\"id\" value=\"".$folder_id."\" />"
  1251. ."<table border=\"0\">";
  1252. foreach ($missing_files as & $this_img_file_path) {
  1253. $form .= "<tr>"
  1254. ."<td>".basename($this_img_file_path)." : </td>"
  1255. ."<td>"
  1256. ."<input type=\"file\" name=\"img_file[]\"/>"
  1257. ."<input type=\"hidden\" name=\"img_file_path[]\" value=\"".$this_img_file_path."\" />"
  1258. ."</td>"
  1259. ."</tr>";
  1260. }
  1261. $form .= "</table>"
  1262. ."<button type='submit' name=\"cancel_submit_image\" value=\"".get_lang('Cancel')."\" class=\"cancel\">".get_lang('Cancel')."</button>"
  1263. ."<button type='submit' name=\"submit_image\" value=\"".get_lang('Ok')."\" class=\"save\">".get_lang('Ok')."</button>"
  1264. ."</form>";
  1265. return $form;
  1266. }
  1267. /**
  1268. * This recursive function can be used during the upgrade process form older versions of Chamilo
  1269. * It crawls the given directory, checks if the file is in the DB and adds it if it's not
  1270. *
  1271. * @param string $base_work_dir
  1272. * @param string $current_path, needed for recursivity
  1273. */
  1274. function add_all_documents_in_folder_to_database($_course, $user_id, $base_work_dir, $current_path = '', $to_group_id = 0) {
  1275. $current_session_id = api_get_session_id();
  1276. $path = $base_work_dir.$current_path;
  1277. // Open dir
  1278. $handle = opendir($path);
  1279. if (is_dir($path)) {
  1280. // Run trough
  1281. while ($file = readdir($handle)) {
  1282. if ($file == '.' || $file == '..') continue;
  1283. $completepath = "$path/$file";
  1284. // Directory?
  1285. if (is_dir($completepath)) {
  1286. $title = get_document_title($file);
  1287. $safe_file = replace_dangerous_char($file);
  1288. @rename($path.'/'.$file, $path.'/'.$safe_file);
  1289. // If we can't find the file, add it
  1290. if (!DocumentManager::get_document_id($_course, $current_path.'/'.$safe_file)) {
  1291. $document_id = add_document($_course, $current_path.'/'.$safe_file, 'folder', 0, $title);
  1292. api_item_property_update($_course, TOOL_DOCUMENT, $document_id, 'DocumentAdded', $user_id, $to_group_id, null, null, null, $current_session_id);
  1293. //echo $current_path.'/'.$safe_file.' added!<br />';
  1294. }
  1295. // Recursive
  1296. add_all_documents_in_folder_to_database($_course,$user_id,$base_work_dir,$current_path.'/'.$safe_file, $to_group_id);
  1297. } else {
  1298. //Rename
  1299. $safe_file = disable_dangerous_file(replace_dangerous_char($file, 'strict'));
  1300. @rename($base_work_dir.$current_path.'/'.$file, $base_work_dir.$current_path.'/'.$safe_file);
  1301. $document_id = DocumentManager::get_document_id($_course, $current_path.'/'.$safe_file);
  1302. if (!$document_id) {
  1303. $title = get_document_title($file);
  1304. $size = filesize($base_work_dir.$current_path.'/'.$safe_file);
  1305. $document_id = add_document($_course, $current_path.'/'.$safe_file, 'file', $size, $title);
  1306. api_item_property_update($_course, TOOL_DOCUMENT, $document_id, 'DocumentAdded', $user_id, $to_group_id, null, null, null, $current_session_id);
  1307. //echo $current_path.'/'.$safe_file.' added!<br />';
  1308. } else {
  1309. api_item_property_update($_course, TOOL_DOCUMENT, $document_id, 'DocumentUpdated', $user_id, $to_group_id, null, null, null, $current_session_id);
  1310. }
  1311. }
  1312. }
  1313. }
  1314. }