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