fileUpload.lib.php 54 KB

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