fileUpload.lib.php 55 KB

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