fileUpload.lib.php 63 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939
  1. <?php
  2. /*
  3. ==============================================================================
  4. Dokeos - elearning and course management software
  5. Copyright (c) 2004 Dokeos S.A.
  6. Copyright (c) 2003 Ghent University (UGent)
  7. Copyright (c) 2001 Universite catholique de Louvain (UCL)
  8. Copyright (c) various contributors
  9. For a full list of contributors, see "credits.txt".
  10. The full license can be read in "license.txt".
  11. This program is free software; you can redistribute it and/or
  12. modify it under the terms of the GNU General Public License
  13. as published by the Free Software Foundation; either version 2
  14. of the License, or (at your option) any later version.
  15. See the GNU General Public License for more details.
  16. Contact: Dokeos, 181 rue Royale, B-1000 Brussels, Belgium, info@dokeos.com
  17. ==============================================================================
  18. */
  19. /**
  20. ==============================================================================
  21. FILE UPLOAD LIBRARY
  22. * This is the file upload library for Dokeos.
  23. * Include/require it in your code to use its functionality.
  24. *
  25. * @package dokeos.library
  26. * @todo test and reorganise
  27. ==============================================================================
  28. */
  29. /*
  30. ==============================================================================
  31. List of functions
  32. function php2phps ($fileName)
  33. function htaccess2txt($filename)
  34. function disable_dangerous_file($filename)
  35. function unique_name($path,$name)
  36. function get_document_title($name)
  37. function process_uploaded_file($uploaded_file)
  38. function handle_uploaded_document($_course,$uploaded_file,$base_work_dir,$upload_path,$user_id,$to_group_id,$to_user_id,$maxFilledSpace,$unzip=0,$what_if_file_exists='')
  39. function enough_size($fileSize, $dir, $maxDirSpace) //depreciated
  40. function enough_space($file_size, $max_dir_space)
  41. function dir_total_space($dirPath) //depreciated
  42. function documents_total_space()
  43. function add_ext_on_mime($fileName,$fileType)
  44. function treat_uploaded_file($uploadedFile, $baseWorkDir, $uploadPath, $maxFilledSpace, $uncompress= '') //depreciated
  45. function unzip_uploaded_file($uploaded_file, $upload_path, $base_work_dir, $max_filled_space)
  46. function clean_up_files_in_zip($p_event, &$p_header)
  47. function clean_up_path(&$path)
  48. function add_document($_course,$path,$filetype,$filesize,$title)
  49. function update_existing_document($_course,$document_id,$filesize)
  50. function item_property_update_on_folder($_course,$path,$user_id)
  51. function get_levels($filename)
  52. function set_default_settings($upload_path,$filename,$filetype="file")
  53. function search_img_from_html($htmlFile)
  54. function create_unexisting_directory($_course,$user_id,$base_work_dir,$desired_dir_name)
  55. function move_uploaded_file_collection_into_directory($_course, $uploaded_file_collection, $base_work_dir, $missing_files_dir,$user_id,$max_filled_space)
  56. function replace_img_path_in_html_file($originalImgPath, $newImgPath, $htmlFile)
  57. function create_link_file($filePath, $url)
  58. function api_replace_links_in_html($upload_path, $full_file_name)
  59. function api_replace_links_in_string($upload_path, $buffer)
  60. function check_for_missing_files($file)
  61. function build_missing_files_form($missing_files,$upload_path,$file_name)
  62. Still experimental:
  63. function api_replace_parameter($upload_path, $buffer, $param_name="src")
  64. ==============================================================================
  65. */
  66. //------------------------------------------------------------------------------
  67. /**
  68. * change the file name extension from .php to .phps
  69. * Useful to secure a site !!
  70. *
  71. * @author - Hugues Peeters <peeters@ipm.ucl.ac.be>
  72. * @param - fileName (string) name of a file
  73. * @return - the filenam phps'ized
  74. */
  75. function php2phps ($fileName)
  76. {
  77. $fileName = preg_replace('/\.(php.?|phtml.?)(\.){0,1}.*$/i', '.phps', $fileName);
  78. return $fileName;
  79. }
  80. //------------------------------------------------------------------------------
  81. /**
  82. * Renames .htaccess & .HTACCESS tot htaccess.txt
  83. *
  84. * @param string $filename
  85. * @return string
  86. */
  87. function htaccess2txt($filename)
  88. {
  89. $filename = str_replace('.htaccess', 'htaccess.txt', $filename);
  90. $filename = str_replace('.HTACCESS', 'htaccess.txt', $filename);
  91. return $filename;
  92. }
  93. //------------------------------------------------------------------------------
  94. /**
  95. * this function executes our safety precautions
  96. * more functions can be added
  97. *
  98. * @param string $filename
  99. * @return string
  100. * @see php2phps()
  101. * @see htaccess2txt()
  102. */
  103. function disable_dangerous_file($filename)
  104. {
  105. $filename = php2phps($filename);
  106. $filename = htaccess2txt($filename);
  107. return $filename;
  108. }
  109. //------------------------------------------------------------------------------
  110. /**
  111. * this function generates a unique name for a file on a given location
  112. * filenames are changed to name_#.ext
  113. *
  114. * @param string $path
  115. * @param string $name
  116. * @return new unique name
  117. */
  118. function unique_name($path,$name)
  119. {
  120. $ext = substr(strrchr($name, "."), 0);
  121. $name_no_ext = substr($name, 0, strlen($name) - strlen(strstr($name,$ext)));
  122. $n = 0;
  123. $unique = '';
  124. while(file_exists($path . $name_no_ext . $unique . $ext))
  125. {
  126. $unique = '_' . ++$n;
  127. }
  128. return $name_no_ext . $unique . $ext;
  129. }
  130. //------------------------------------------------------------------------------
  131. /**
  132. * Returns the name without extension, used for the title
  133. *
  134. * @param string $name
  135. * @return name without the extension
  136. */
  137. function get_document_title($name)
  138. {
  139. //if they upload .htaccess...
  140. $name = disable_dangerous_file($name);
  141. $ext = substr(strrchr($name, "."), 0);
  142. $name_no_ext = substr($name, 0, strlen($name) - strlen(strstr($name,$ext)));
  143. $filename = addslashes($name_no_ext);
  144. return $filename;
  145. }
  146. //------------------------------------------------------------------------------
  147. /**
  148. * This function checks if the upload succeeded
  149. *
  150. * @param array $uploaded_file ($_FILES)
  151. * @return true if upload succeeded
  152. */
  153. function process_uploaded_file($uploaded_file) {
  154. // Checking the error code sent with the file upload.
  155. switch ($uploaded_file['error']) {
  156. case 1:
  157. // The uploaded file exceeds the upload_max_filesize directive in php.ini.
  158. Display::display_error_message(get_lang('UplExceedMaxServerUpload'). ini_get('upload_max_filesize'));
  159. return false;
  160. case 2:
  161. // The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.
  162. // 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).
  163. Display::display_error_message(get_lang('UplExceedMaxPostSize'). round($_POST['MAX_FILE_SIZE']/1024) ." KB");
  164. return false;
  165. case 3:
  166. // The uploaded file was only partially uploaded.
  167. Display::display_error_message(get_lang('$UplPartialUpload')." ".get_lang('PleaseTryAgain'));
  168. return false;
  169. case 4:
  170. // No file was uploaded.
  171. Display::display_error_message(get_lang('UplNoFileUploaded')." ". get_lang('UplSelectFileFirst'));
  172. return false;
  173. }
  174. // case 0: default: We assume there is no error, the file uploaded with success.
  175. return true;
  176. }
  177. //------------------------------------------------------------------------------
  178. /**
  179. * this function does the save-work for the documents.
  180. * it handles the uploaded file and adds the properties to the database
  181. * if unzip=1 and the file is a zipfile, it is extracted
  182. * if we decide to save ALL kinds of documents in one database,
  183. * we could extend this with a $type='document', 'scormdocument',...
  184. *
  185. * @param array $_course
  186. * @param array $uploaded_file ($_FILES)
  187. * @param string $base_work_dir
  188. * @param string $upload_path
  189. * @param int $user_id
  190. * @param int $to_group_id, 0 for everybody
  191. * @param int $to_user_id, NULL for everybody
  192. * @param int $maxFilledSpace
  193. * @param int $unzip 1/0
  194. * @param string $what_if_file_exists overwrite, rename or warn if exists (default)
  195. * @param boolean Optional output parameter. So far only use for unzip_uploaded_document function. If no output wanted on success, set to false.
  196. * @return path of the saved file
  197. */
  198. 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)
  199. {
  200. if(!$user_id) die("Not a valid user.");
  201. //strip slashes
  202. $uploaded_file['name']=stripslashes($uploaded_file['name']);
  203. //add extension to files without one (if possible)
  204. $uploaded_file['name']=add_ext_on_mime($uploaded_file['name'],$uploaded_file['type']);
  205. $current_session_id = api_get_session_id();
  206. //check if there is enough space to save the file
  207. if (!enough_space($uploaded_file['size'], $maxFilledSpace))
  208. {
  209. Display::display_error_message(get_lang('UplNotEnoughSpace'));
  210. return false;
  211. }
  212. //if the want to unzip, check if the file has a .zip (or ZIP,Zip,ZiP,...) extension
  213. if ($unzip == 1 && preg_match("/.zip$/", strtolower($uploaded_file['name'])) )
  214. {
  215. return unzip_uploaded_document($uploaded_file, $upload_path, $base_work_dir, $maxFilledSpace, $output, $to_group_id);
  216. //display_message("Unzipping file");
  217. }
  218. //we can only unzip ZIP files (no gz, tar,...)
  219. elseif ($unzip == 1 && !preg_match("/.zip$/", strtolower($uploaded_file['name'])) )
  220. {
  221. Display::display_error_message(get_lang('UplNotAZip')." ".get_lang('PleaseTryAgain'));
  222. return false;
  223. }
  224. else
  225. {
  226. //clean up the name, only ASCII characters should stay. (and strict)
  227. $clean_name = replace_dangerous_char($uploaded_file['name'], 'strict');
  228. //no "dangerous" files
  229. $clean_name = disable_dangerous_file($clean_name);
  230. if(!filter_extension($clean_name))
  231. {
  232. Display::display_error_message(get_lang('UplUnableToSaveFileFilteredExtension'));
  233. return false;
  234. }
  235. else
  236. {
  237. //extension is good
  238. //echo "<br/>clean name = ".$clean_name;
  239. //echo "<br/>upload_path = ".$upload_path;
  240. //if the upload path differs from / (= root) it will need a slash at the end
  241. if ($upload_path!='/') {
  242. $upload_path = $upload_path.'/';
  243. }
  244. //echo "<br/>upload_path = ".$upload_path;
  245. $file_path = $upload_path.$clean_name;
  246. //echo "<br/>file path = ".$file_path;
  247. //full path to where we want to store the file with trailing slash
  248. $where_to_save = $base_work_dir.$upload_path;
  249. //at least if the directory doesn't exist, tell so
  250. if(!is_dir($where_to_save)){
  251. Display::display_error_message(get_lang('DestDirectoryDoesntExist').' ('.$upload_path.')');
  252. return false;
  253. }
  254. //echo "<br/>where to save = ".$where_to_save;
  255. // full path of the destination
  256. $store_path = $where_to_save.$clean_name;
  257. //echo "<br/>store path = ".$store_path;
  258. //name of the document without the extension (for the title)
  259. $document_name = get_document_title($uploaded_file['name']);
  260. //size of the uploaded file (in bytes)
  261. $file_size = $uploaded_file['size'];
  262. $files_perm = api_get_setting('permissions_for_new_files');
  263. $files_perm = octdec(!empty($files_perm)?$files_perm:'0770');
  264. //what to do if the target file exists
  265. switch ($what_if_file_exists)
  266. {
  267. //overwrite the file if it exists
  268. case 'overwrite':
  269. //check if the target file exists, so we can give another message
  270. if (file_exists($store_path))
  271. {
  272. $file_exists = true;
  273. }
  274. else
  275. {
  276. $file_exists = false;
  277. }
  278. if (@move_uploaded_file($uploaded_file['tmp_name'], $store_path))
  279. {
  280. chmod($store_path,$files_perm);
  281. if($file_exists)
  282. {
  283. //UPDATE DATABASE!
  284. $document_id = DocumentManager::get_document_id($_course,$file_path);
  285. if ($document_id)
  286. {
  287. //update filesize
  288. update_existing_document($_course,$document_id,$uploaded_file['size']);
  289. //update document item_property
  290. api_item_property_update($_course,TOOL_DOCUMENT,$document_id,'DocumentUpdated',$user_id,$to_group_id,$to_user_id,null,null,$current_session_id);
  291. }
  292. //if the file is in a folder, we need to update all parent folders
  293. item_property_update_on_folder($_course,$upload_path,$user_id);
  294. //display success message with extra info to user
  295. if($output){
  296. Display::display_confirmation_message(get_lang('UplUploadSucceeded')."<br/>".$file_path .' '. get_lang('UplFileOverwritten'),false);
  297. }
  298. return $file_path;
  299. }
  300. else
  301. {
  302. //put the document data in the database
  303. $document_id = add_document($_course,$file_path,'file',$file_size,$document_name);
  304. if ($document_id)
  305. {
  306. //put the document in item_property update
  307. api_item_property_update($_course,TOOL_DOCUMENT,$document_id,'DocumentAdded',$user_id,$to_group_id,$to_user_id,null,null,$current_session_id);
  308. }
  309. //if the file is in a folder, we need to update all parent folders
  310. item_property_update_on_folder($_course,$upload_path,$user_id);
  311. //display success message to user
  312. Display::display_confirmation_message(get_lang('UplUploadSucceeded')."<br/>".$file_path,false);
  313. return $file_path;
  314. }
  315. }
  316. else
  317. {
  318. Display::display_error_message(get_lang('UplUnableToSaveFile'));
  319. return false;
  320. }
  321. break;
  322. //rename the file if it exists
  323. case 'rename':
  324. $new_name = unique_name($where_to_save, $clean_name);
  325. $store_path = $where_to_save.$new_name;
  326. $new_file_path = $upload_path.$new_name;
  327. if (@move_uploaded_file($uploaded_file['tmp_name'], $store_path))
  328. {
  329. chmod($store_path,$files_perm);
  330. //put the document data in the database
  331. $document_id = add_document($_course,$new_file_path,'file',$file_size,$document_name);
  332. if ($document_id)
  333. {
  334. //update document item_property
  335. api_item_property_update($_course,TOOL_DOCUMENT,$document_id,'DocumentAdded',$user_id,$to_group_id,$to_user_id,null,null,$current_session_id);
  336. }
  337. //if the file is in a folder, we need to update all parent folders
  338. item_property_update_on_folder($_course,$upload_path,$user_id);
  339. //display success message to user
  340. if($output){
  341. Display::display_confirmation_message(get_lang('UplUploadSucceeded'). "<br>" .get_lang('UplFileSavedAs') . $new_file_path,false);
  342. }
  343. return $new_file_path;
  344. }
  345. else
  346. {
  347. Display::display_error_message(get_lang('UplUnableToSaveFile'));
  348. return false;
  349. }
  350. break;
  351. //only save the file if it doesn't exist or warn user if it does exist
  352. default:
  353. if (file_exists($store_path))
  354. {
  355. Display::display_error_message($clean_name.' '.get_lang('UplAlreadyExists'));
  356. }
  357. else
  358. {
  359. if (@move_uploaded_file($uploaded_file['tmp_name'], $store_path))
  360. {
  361. chmod($store_path,$files_perm);
  362. //put the document data in the database
  363. $document_id = add_document($_course,$file_path,'file',$file_size,$document_name);
  364. if ($document_id)
  365. {
  366. //update document item_property
  367. api_item_property_update($_course,TOOL_DOCUMENT,$document_id,'DocumentAdded',$user_id,$to_group_id,$to_user_id,null,null,$current_session_id);
  368. }
  369. //if the file is in a folder, we need to update all parent folders
  370. item_property_update_on_folder($_course,$upload_path,$user_id);
  371. //display success message to user
  372. if($output){
  373. Display::display_confirmation_message(get_lang('UplUploadSucceeded')."<br/>".$file_path,false);
  374. }
  375. return $file_path;
  376. }
  377. else
  378. {
  379. Display::display_error_message(get_lang('UplUnableToSaveFile'));
  380. return false;
  381. }
  382. }
  383. break;
  384. }
  385. }
  386. }
  387. }
  388. //------------------------------------------------------------------------------
  389. /**
  390. * Check if there is enough place to add a file on a directory
  391. * on the base of a maximum directory size allowed
  392. * @deprecated use enough_space instead!
  393. * @author - Hugues Peeters <peeters@ipm.ucl.ac.be>
  394. * @param - fileSize (int) - size of the file in byte
  395. * @param - dir (string) - Path of the directory
  396. * whe the file should be added
  397. * @param - maxDirSpace (int) - maximum size of the diretory in byte
  398. * @return - boolean true if there is enough space,
  399. * boolean false otherwise
  400. *
  401. * @see - enough_size() uses dir_total_space() function
  402. */
  403. function enough_size($fileSize, $dir, $maxDirSpace)
  404. {
  405. if ($maxDirSpace)
  406. {
  407. $alreadyFilledSpace = dir_total_space($dir);
  408. if ( ($fileSize + $alreadyFilledSpace) > $maxDirSpace)
  409. {
  410. return false;
  411. }
  412. }
  413. return true;
  414. }
  415. //------------------------------------------------------------------------------
  416. /**
  417. * Check if there is enough place to add a file on a directory
  418. * on the base of a maximum directory size allowed
  419. *
  420. * @author Bert Vanderkimpen
  421. * @param int file_size size of the file in byte
  422. * @param array $_course
  423. * @param int max_dir_space maximum size
  424. * @return boolean true if there is enough space, false otherwise
  425. *
  426. * @see enough_space() uses documents_total_space() function
  427. */
  428. function enough_space($file_size, $max_dir_space)
  429. {
  430. if ($max_dir_space)
  431. {
  432. $already_filled_space = documents_total_space();
  433. if ( ($file_size + $already_filled_space) > $max_dir_space)
  434. {
  435. return false;
  436. }
  437. }
  438. return true;
  439. }
  440. //------------------------------------------------------------------------------
  441. /**
  442. * Compute the size already occupied by a directory and is subdirectories
  443. *
  444. * @author - Hugues Peeters <peeters@ipm.ucl.ac.be>
  445. * @param - dirPath (string) - size of the file in byte
  446. * @return - int - return the directory size in bytes
  447. */
  448. function dir_total_space($dirPath)
  449. {
  450. $save_dir = getcwd();
  451. chdir ($dirPath) ;
  452. $handle = opendir($dirPath);
  453. while ($element = readdir($handle) )
  454. {
  455. if ( $element == "." || $element == "..")
  456. {
  457. continue; // skip the current and parent directories
  458. }
  459. if ( is_file($element) )
  460. {
  461. $sumSize += filesize($element);
  462. }
  463. if ( is_dir($element) )
  464. {
  465. $dirList[] = $dirPath."/".$element;
  466. }
  467. }
  468. closedir($handle) ;
  469. if ( sizeof($dirList) > 0)
  470. {
  471. foreach($dirList as $j)
  472. {
  473. $sizeDir = dir_total_space($j); // recursivity
  474. $sumSize += $sizeDir;
  475. }
  476. }
  477. chdir($save_dir);//return to initial position
  478. return $sumSize;
  479. }
  480. //------------------------------------------------------------------------------
  481. /**
  482. * Calculate the total size of all documents in a course
  483. *
  484. * @author Bert vanderkimpen
  485. * @param int $to_group_id (to calculate group document space)
  486. * @return int total size
  487. */
  488. function documents_total_space($to_group_id='0')
  489. {
  490. $TABLE_ITEMPROPERTY = Database::get_course_table(TABLE_ITEM_PROPERTY);
  491. $TABLE_DOCUMENT = Database::get_course_table(TABLE_DOCUMENT);
  492. $sql = "SELECT SUM(size)
  493. FROM ".$TABLE_ITEMPROPERTY." AS props, ".$TABLE_DOCUMENT." AS docs
  494. WHERE docs.id = props.ref
  495. AND props.tool = '".TOOL_DOCUMENT."'
  496. AND props.to_group_id='".$to_group_id."'
  497. AND props.visibility <> 2";
  498. $result = Database::query($sql,__FILE__,__LINE__);
  499. if($result && Database::num_rows($result)!=0)
  500. {
  501. $row = Database::fetch_row($result);
  502. return $row[0];
  503. }
  504. else
  505. {
  506. return 0;
  507. }
  508. }
  509. //------------------------------------------------------------------------------
  510. /**
  511. * Try to add an extension to files without extension
  512. * Some applications on Macintosh computers don't add an extension to the files.
  513. * This subroutine try to fix this on the basis of the MIME type sent
  514. * by the browser.
  515. *
  516. * Note : some browsers don't send the MIME Type (e.g. Netscape 4).
  517. * We don't have solution for this kind of situation
  518. *
  519. * @author - Hugues Peeters <peeters@ipm.ucl.ac.be>
  520. * @author - Bert Vanderkimpen
  521. * @param - fileName (string) - Name of the file
  522. * @param - fileType (string) - Type of the file
  523. * @return - fileName (string)
  524. *
  525. */
  526. function add_ext_on_mime($fileName,$fileType)
  527. {
  528. /*
  529. * Check if the file has an extension AND if the browser has sent a MIME Type
  530. */
  531. //if(!ereg("([[:alnum:]]|[[[:punct:]])+\.[[:alnum:]]+$", $fileName) // TODO: This fails sometimes on non-ASCII encoded file names. To be removed.
  532. // && $fileType)
  533. if(!preg_match('/^.*\.[a-zA-Z_0-9]+$/', $fileName) && $fileType)
  534. {
  535. /*
  536. * Build a "MIME-types / extensions" connection table
  537. */
  538. static $mimeType = array();
  539. $mimeType[] = "application/msword"; $extension[] =".doc";
  540. $mimeType[] = "application/rtf"; $extension[] =".rtf";
  541. $mimeType[] = "application/vnd.ms-powerpoint"; $extension[] =".ppt";
  542. $mimeType[] = "application/vnd.ms-excel"; $extension[] =".xls";
  543. $mimeType[] = "application/pdf"; $extension[] =".pdf";
  544. $mimeType[] = "application/postscript"; $extension[] =".ps";
  545. $mimeType[] = "application/mac-binhex40"; $extension[] =".hqx";
  546. $mimeType[] = "application/x-gzip"; $extension[] ="tar.gz";
  547. $mimeType[] = "application/x-shockwave-flash"; $extension[] =".swf";
  548. $mimeType[] = "application/x-stuffit"; $extension[] =".sit";
  549. $mimeType[] = "application/x-tar"; $extension[] =".tar";
  550. $mimeType[] = "application/zip"; $extension[] =".zip";
  551. $mimeType[] = "application/x-tar"; $extension[] =".tar";
  552. $mimeType[] = "text/html"; $extension[] =".html";
  553. $mimeType[] = "text/plain"; $extension[] =".txt";
  554. $mimeType[] = "text/rtf"; $extension[] =".rtf";
  555. $mimeType[] = "img/gif"; $extension[] =".gif";
  556. $mimeType[] = "img/jpeg"; $extension[] =".jpg";
  557. $mimeType[] = "img/png"; $extension[] =".png";
  558. $mimeType[] = "audio/midi"; $extension[] =".mid";
  559. $mimeType[] = "audio/mpeg"; $extension[] =".mp3";
  560. $mimeType[] = "audio/x-aiff"; $extension[] =".aif";
  561. $mimeType[] = "audio/x-pn-realaudio"; $extension[] =".rm";
  562. $mimeType[] = "audio/x-pn-realaudio-plugin"; $extension[] =".rpm";
  563. $mimeType[] = "audio/x-wav"; $extension[] =".wav";
  564. $mimeType[] = "video/mpeg"; $extension[] =".mpg";
  565. $mimeType[] = "video/mpeg4-generic"; $extension[] =".mp4";
  566. $mimeType[] = "video/quicktime"; $extension[] =".mov";
  567. $mimeType[] = "video/x-msvideo"; $extension[] =".avi";
  568. $mimeType[] = "video/x-ms-wmv"; $extension[] =".wmv";
  569. $mimeType[] = "video/x-flv"; $extension[] =".flv";
  570. $mimeType[] = "application/vnd.ms-word.document.macroEnabled.12"; $extension[] =".docm";
  571. $mimeType[] = "application/vnd.openxmlformats-officedocument.wordprocessingml.document"; $extension[] =".docx";
  572. $mimeType[] = "application/vnd.ms-word.template.macroEnabled.12"; $extension[] =".dotm";
  573. $mimeType[] = "application/vnd.openxmlformats-officedocument.wordprocessingml.template"; $extension[] =".dotx";
  574. $mimeType[] = "application/vnd.ms-powerpoint.template.macroEnabled.12"; $extension[] =".potm";
  575. $mimeType[] = "application/vnd.openxmlformats-officedocument.presentationml.template"; $extension[] =".potx";
  576. $mimeType[] = "application/vnd.ms-powerpoint.addin.macroEnabled.12"; $extension[] =".ppam";
  577. $mimeType[] = "application/vnd.ms-powerpoint.slideshow.macroEnabled.12"; $extension[] =".ppsm";
  578. $mimeType[] = "application/vnd.openxmlformats-officedocument.presentationml.slideshow"; $extension[] =".ppsx";
  579. $mimeType[] = "application/vnd.ms-powerpoint.presentation.macroEnabled.12"; $extension[] =".pptm";
  580. $mimeType[] = "application/vnd.openxmlformats-officedocument.presentationml.presentation"; $extension[] =".pptx";
  581. $mimeType[] = "application/vnd.ms-excel.addin.macroEnabled.12"; $extension[] =".xlam";
  582. $mimeType[] = "application/vnd.ms-excel.sheet.binary.macroEnabled.12"; $extension[] =".xlsb";
  583. $mimeType[] = "application/vnd.ms-excel.sheet.macroEnabled.12"; $extension[] =".xlsm";
  584. $mimeType[] = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; $extension[] =".xlsx";
  585. $mimeType[] = "application/vnd.ms-excel.template.macroEnabled.12"; $extension[] =".xltm";
  586. $mimeType[] = "application/vnd.openxmlformats-officedocument.spreadsheetml.template"; $extension[] =".xltx";
  587. //test on PC (files with no extension get application/octet-stream)
  588. //$mimeType[] = "application/octet-stream"; $extension[] =".ext";
  589. /*
  590. * Check if the MIME type sent by the browser is in the table
  591. */
  592. foreach($mimeType as $key=>$type)
  593. {
  594. if ($type == $fileType)
  595. {
  596. $fileName .= $extension[$key];
  597. break;
  598. }
  599. }
  600. unset($mimeType, $extension, $type, $key); // Delete to eschew possible collisions
  601. }
  602. return $fileName;
  603. }
  604. //------------------------------------------------------------------------------
  605. /**
  606. *
  607. * @author Hugues Peeters <hugues.peeters@claroline.net>
  608. *
  609. * @param array $uploadedFile - follows the $_FILES Structure
  610. * @param string $baseWorkDir - base working directory of the module
  611. * @param string $uploadPath - destination of the upload.
  612. * This path is to append to $baseWorkDir
  613. * @param int $maxFilledSpace - amount of bytes to not exceed in the base
  614. * working directory
  615. *
  616. * @return boolean true if it succeds, false otherwise
  617. */
  618. function treat_uploaded_file($uploadedFile, $baseWorkDir, $uploadPath, $maxFilledSpace, $uncompress= '')
  619. {
  620. $uploadedFile['name']=stripslashes($uploadedFile['name']);
  621. if (!enough_size($uploadedFile['size'], $baseWorkDir, $maxFilledSpace))
  622. {
  623. return api_failure::set_failure('not_enough_space');
  624. }
  625. if ($uncompress == 'unzip' && preg_match("/.zip$/", strtolower($uploadedFile['name'])) )
  626. {
  627. return unzip_uploaded_file($uploadedFile, $uploadPath, $baseWorkDir, $maxFilledSpace);
  628. }
  629. else
  630. {
  631. $fileName = trim($uploadedFile['name']);
  632. // CHECK FOR NO DESIRED CHARACTERS
  633. $fileName = replace_dangerous_char($fileName, 'strict');
  634. // TRY TO ADD AN EXTENSION TO FILES WITOUT EXTENSION
  635. $fileName = add_ext_on_mime($fileName,$uploadedFile['type']);
  636. // HANDLE PHP FILES
  637. $fileName = php2phps($fileName);
  638. // COPY THE FILE TO THE DESIRED DESTINATION
  639. if(move_uploaded_file($uploadedFile['tmp_name'], $baseWorkDir.$uploadPath."/".$fileName))
  640. set_default_settings($uploadPath,$fileName);
  641. return true;
  642. }
  643. }
  644. /**
  645. * Manages all the unzipping process of an uploaded file
  646. *
  647. * @author Hugues Peeters <hugues.peeters@claroline.net>
  648. *
  649. * @param array $uploadedFile - follows the $_FILES Structure
  650. * @param string $uploadPath - destination of the upload.
  651. * This path is to append to $baseWorkDir
  652. * @param string $baseWorkDir - base working directory of the module
  653. * @param int $maxFilledSpace - amount of bytes to not exceed in the base
  654. * working directory
  655. *
  656. * @return boolean true if it succeeds false otherwise
  657. */
  658. function unzip_uploaded_file($uploadedFile, $uploadPath, $baseWorkDir, $maxFilledSpace)
  659. {
  660. $zipFile = new pclZip($uploadedFile['tmp_name']);
  661. // Check the zip content (real size and file extension)
  662. $zipContentArray = $zipFile->listContent();
  663. $okScorm=false;
  664. foreach($zipContentArray as $thisContent)
  665. {
  666. if ( preg_match('~.(php.*|phtml)$~i', $thisContent['filename']) )
  667. {
  668. return api_failure::set_failure('php_file_in_zip_file');
  669. }
  670. elseif(stristr($thisContent['filename'],'imsmanifest.xml'))
  671. {
  672. $okScorm=true;
  673. }
  674. elseif(stristr($thisContent['filename'],'LMS'))
  675. {
  676. $okPlantynScorm1=true;
  677. }
  678. elseif(stristr($thisContent['filename'],'REF'))
  679. {
  680. $okPlantynScorm2=true;
  681. }
  682. elseif(stristr($thisContent['filename'],'SCO'))
  683. {
  684. $okPlantynScorm3=true;
  685. }
  686. elseif(stristr($thisContent['filename'],'AICC'))
  687. {
  688. $okAiccScorm=true;
  689. }
  690. $realFileSize += $thisContent['size'];
  691. }
  692. if ((($okPlantynScorm1==true) and ($okPlantynScorm2==true) and ($okPlantynScorm3==true)) or ($okAiccScorm==true))
  693. {
  694. $okScorm=true;
  695. }
  696. if(!$okScorm && defined('CHECK_FOR_SCORM') && CHECK_FOR_SCORM)
  697. {
  698. return api_failure::set_failure('not_scorm_content');
  699. }
  700. if (! enough_size($realFileSize, $baseWorkDir, $maxFilledSpace) )
  701. {
  702. return api_failure::set_failure('not_enough_space');
  703. }
  704. // it happens on Linux that $uploadPath sometimes doesn't start with '/'
  705. if($uploadPath[0] != '/')
  706. {
  707. $uploadPath='/'.$uploadPath;
  708. }
  709. if($uploadPath[strlen($uploadPath)-1] == '/')
  710. {
  711. $uploadPath=substr($uploadPath,0,-1);
  712. }
  713. /*
  714. --------------------------------------
  715. Uncompressing phase
  716. --------------------------------------
  717. */
  718. /*
  719. The first version, using OS unzip, is not used anymore
  720. because it does not return enough information.
  721. We need to process each individual file in the zip archive to
  722. - add it to the database
  723. - parse & change relative html links
  724. */
  725. if (PHP_OS == 'Linux' && ! get_cfg_var('safe_mode') && false) // *** UGent, changed by OC ***
  726. {
  727. // Shell Method - if this is possible, it gains some speed
  728. exec("unzip -d \"".$baseWorkDir.$uploadPath."/\"".$uploadedFile['name']." "
  729. .$uploadedFile['tmp_name']);
  730. }
  731. else
  732. {
  733. // PHP method - slower...
  734. $save_dir = getcwd();
  735. chdir($baseWorkDir.$uploadPath);
  736. $unzippingState = $zipFile->extract();
  737. for($j=0;$j<count($unzippingState);$j++)
  738. {
  739. $state=$unzippingState[$j];
  740. //fix relative links in html files
  741. $extension = strrchr($state["stored_filename"], ".");
  742. }
  743. if($dir=@opendir($baseWorkDir.$uploadPath))
  744. {
  745. while($file=readdir($dir))
  746. {
  747. if($file != '.' && $file != '..')
  748. {
  749. $filetype="file";
  750. if(is_dir($baseWorkDir.$uploadPath.'/'.$file)) $filetype="folder";
  751. $safe_file=replace_dangerous_char($file,'strict');
  752. @rename($baseWorkDir.$uploadPath.'/'.$file,$baseWorkDir.$uploadPath.'/'.$safe_file);
  753. set_default_settings($uploadPath,$safe_file,$filetype);
  754. }
  755. }
  756. closedir($dir);
  757. }
  758. chdir($save_dir); //back to previous dir position
  759. }
  760. return true;
  761. }
  762. //------------------------------------------------------------------------------
  763. /**
  764. * Manages all the unzipping process of an uploaded document
  765. * This uses the item_property table for properties of documents
  766. *
  767. * @author Hugues Peeters <hugues.peeters@claroline.net>
  768. * @author Bert Vanderkimpen
  769. *
  770. * @param array $uploadedFile - follows the $_FILES Structure
  771. * @param string $uploadPath - destination of the upload.
  772. * This path is to append to $baseWorkDir
  773. * @param string $baseWorkDir - base working directory of the module
  774. * @param int $maxFilledSpace - amount of bytes to not exceed in the base
  775. * working directory
  776. * @param boolean Output switch. Optional. If no output not wanted on success, set to false.
  777. *
  778. * @return boolean true if it succeeds false otherwise
  779. */
  780. function unzip_uploaded_document($uploaded_file, $upload_path, $base_work_dir, $max_filled_space, $output = true, $to_group_id=0)
  781. {
  782. global $_course;
  783. global $_user;
  784. global $to_user_id;
  785. global $to_group_id;
  786. $zip_file = new pclZip($uploaded_file['tmp_name']);
  787. // Check the zip content (real size and file extension)
  788. $zip_content_array = $zip_file->listContent();
  789. foreach((array) $zip_content_array as $this_content)
  790. {
  791. $real_filesize += $this_content['size'];
  792. }
  793. if (! enough_space($real_filesize, $max_filled_space) )
  794. {
  795. Display::display_error_message(get_lang('UplNotEnoughSpace'));
  796. return false;
  797. }
  798. // it happens on Linux that $uploadPath sometimes doesn't start with '/'
  799. if($upload_path[0] != '/')
  800. {
  801. $upload_path='/'.$upload_path;
  802. }
  803. /*
  804. --------------------------------------
  805. Uncompressing phase
  806. --------------------------------------
  807. */
  808. //get into the right directory
  809. $save_dir = getcwd();
  810. chdir($base_work_dir.$upload_path);
  811. //we extract using a callback function that "cleans" the path
  812. $unzipping_state = $zip_file->extract(PCLZIP_CB_PRE_EXTRACT, 'clean_up_files_in_zip');
  813. // Add all documents in the unzipped folder to the database
  814. add_all_documents_in_folder_to_database($_course,$_user['user_id'],$base_work_dir,$upload_path == '/' ? '' : $upload_path, $to_group_id);
  815. //Display::display_normal_message(get_lang('UplZipExtractSuccess'));
  816. return true;
  817. /*
  818. if ($upload_path != '/')
  819. $upload_path = $upload_path.'/';
  820. if($unzipping_state!=0)
  821. {
  822. for($j=0;$j<count($unzipping_state);$j++)
  823. {
  824. $state=$unzipping_state[$j];
  825. $filename = $state['stored_filename'];
  826. //echo("<br>filename = ".$filename."<br>");
  827. $filename2 = $state['filename'];
  828. //echo("<br>filename2 = ".$filename2."<br>");
  829. $filetype="file";
  830. //if(is_dir($filename))
  831. if($state['folder']==1)
  832. {
  833. $filetype="folder";
  834. $endchar=substr($filename,strlen($filename)-1,1);
  835. if($endchar=="\\" || $endchar=="/")
  836. $filename=substr($filename,0,strlen($filename)-1);
  837. }
  838. //store document in database
  839. if($state['status']=="ok" || $state['status']=="already_a_directory")
  840. {
  841. //echo $base_work_dir.$upload_path.clean_up_path($state["stored_filename"])." (".$filetype.")<br/>";
  842. $cleaned_up_filename = clean_up_path($filename);
  843. $file_path = $upload_path.$cleaned_up_filename;
  844. echo("file path = ".$file_path."<br>");
  845. //this is a quick fix for zipfiles that have files in folders but the folder is not stored in the zipfile
  846. //if the path has folders, check if they already are in the database
  847. if(dirname('/'.$cleaned_up_filename)!='/' AND dirname('/'.$cleaned_up_filename)!='\\')
  848. {
  849. $folder_id=DocumentManager::get_document_id($_course,$upload_path.dirname($cleaned_up_filename));
  850. if(!$folder_id)
  851. {
  852. echo($upload_path.dirname($cleaned_up_filename).' not found in database!<br>');
  853. $folder_id = add_document($_course,$upload_path.dirname($cleaned_up_filename),'folder',0,basename(dirname($cleaned_up_filename)));
  854. if($folder_id)
  855. {
  856. api_item_property_update($_course,TOOL_DOCUMENT,$folder_id,'FolderAdded',$_user['user_id'],$to_group_id,$to_user_id);
  857. //echo('folder '.$upload_path.dirname($cleaned_up_filename)." added<br>\n");
  858. }
  859. }
  860. }
  861. $store_path = $base_work_dir.$file_path;
  862. //echo("store path = ".$store_path."<br>");
  863. $document_name = get_document_title(basename($filename));
  864. //echo("document_name = ".$document_name."<br><br>");
  865. //put the document data in the database
  866. //if the file/dir does not exist, just add it
  867. //if(!file_exists($store_path)) <- not working, as the file is already extracted
  868. //so we check if the document is already in the database
  869. $document_id = DocumentManager::get_document_id($_course,$file_path);
  870. if(!$document_id)
  871. {
  872. $document_id = add_document($_course,$file_path,$filetype,$state['size'],$document_name);
  873. if ($document_id)
  874. {
  875. $lastedit_type = ($filetype=='folder')?'FolderAdded':'DocumentAdded';
  876. //update item property for document
  877. api_item_property_update($_course,TOOL_DOCUMENT,$document_id,$lastedit_type,$_user['user_id'],$to_group_id,$to_user_id);
  878. }
  879. }
  880. //file/dir exists -> update
  881. else
  882. {
  883. $lastedit_type = ($filetype=='folder')?'FolderUpdated':'DocumentUpdated';
  884. //update the document in item_property
  885. api_item_property_update($_course,TOOL_DOCUMENT,$document_id,$lastedit_type,$_user['user_id'],$to_group_id,$to_user_id);
  886. }
  887. }
  888. }
  889. //print_r_pre($zip_content_array);
  890. //if the file is in a folder, we need to update all parent folders
  891. item_property_update_on_folder($_course,$upload_path,$_user['user_id']);
  892. //display success message to user
  893. chdir($save_dir); //return to previous dir position
  894. if($output){
  895. Display::display_normal_message(get_lang('UplZipExtractSuccess'));
  896. }
  897. return true;
  898. }
  899. else {
  900. //zip file could not be extracted -> corrupt file
  901. Display::display_error_message(get_lang('UplZipCorrupt'));
  902. return false;
  903. }
  904. */
  905. }
  906. //------------------------------------------------------------------------------
  907. /**
  908. * this function is a callback function that is used while extracting a zipfile
  909. * http://www.phpconcept.net/pclzip/man/en/index.php?options-pclzip_cb_pre_extract
  910. *
  911. * @param $p_event
  912. * @param $p_header
  913. * @return 1 (If the function returns 1, then the extraction is resumed)
  914. */
  915. function clean_up_files_in_zip($p_event, &$p_header)
  916. {
  917. $res = clean_up_path($p_header['filename']);
  918. return $res;
  919. }
  920. //------------------------------------------------------------------------------
  921. /**
  922. * this function cleans up a given path
  923. * by eliminating dangerous file names and cleaning them
  924. *
  925. * @param string $path
  926. * @return $path
  927. * @see disable_dangerous_file()
  928. * @see replace_dangerous_char()
  929. */
  930. function clean_up_path(&$path)
  931. {
  932. //split the path in folders and files
  933. $path_array = explode('/',$path);
  934. //clean up every foler and filename in the path
  935. $val = '';
  936. foreach($path_array as $key => $val)
  937. {
  938. //we don't want to lose the dots in ././folder/file (cfr. zipfile)
  939. if($path_array[$key]!='.')
  940. $path_array[$key] = disable_dangerous_file( replace_dangerous_char($val) );
  941. }
  942. //join the "cleaned" path (modified in-place as passed by reference)
  943. $path = implode('/',$path_array);
  944. $res = filter_extension($path);
  945. return $res;
  946. }
  947. /**
  948. * Check if the file is dangerous, based on extension and/or mimetype.
  949. * The list of extensions accepted/rejected can be found from
  950. * api_get_setting('upload_extensions_exclude') and api_get_setting('upload_extensions_include')
  951. * @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')
  952. * @return int 0 to skip file, 1 to keep file
  953. */
  954. function filter_extension(&$filename)
  955. {
  956. if(substr($filename,-1)=='/'){return 1;} //authorize directories
  957. $blacklist = api_get_setting('upload_extensions_list_type');
  958. if($blacklist!='whitelist')//if = blacklist
  959. {
  960. $extensions = split(';',strtolower(api_get_setting('upload_extensions_blacklist')));
  961. $skip = api_get_setting('upload_extensions_skip');
  962. $ext = strrchr($filename, ".");
  963. $ext = substr($ext,1);
  964. if(empty($ext)){return 1;}//we're in blacklist mode, so accept empty extensions
  965. if(in_array(strtolower($ext),$extensions))
  966. {
  967. if($skip=='true')
  968. {
  969. return 0;
  970. }
  971. else
  972. {
  973. $new_ext = api_get_setting('upload_extensions_replace_by');
  974. $filename = str_replace(".".$ext,".".$new_ext,$filename);
  975. return 1;
  976. }
  977. }
  978. else
  979. {
  980. return 1;
  981. }
  982. }
  983. else
  984. {
  985. $extensions = split(';',strtolower(api_get_setting('upload_extensions_whitelist')));
  986. $skip = api_get_setting('upload_extensions_skip');
  987. $ext = strrchr($filename, ".");
  988. $ext = substr($ext,1);
  989. if(empty($ext)){return 1;}//accept empty extensions
  990. if(!in_array(strtolower($ext),$extensions))
  991. {
  992. if($skip=='true')
  993. {
  994. return 0;
  995. }
  996. else
  997. {
  998. $new_ext = api_get_setting('upload_extensions_replace_by');
  999. $filename = str_replace(".".$ext,".".$new_ext,$filename);
  1000. return 1;
  1001. }
  1002. }
  1003. else
  1004. {
  1005. return 1;
  1006. }
  1007. }
  1008. }
  1009. //------------------------------------------------------------------------------
  1010. /**
  1011. * Adds a new document to the database
  1012. *
  1013. * @param array $_course
  1014. * @param string $path
  1015. * @param string $filetype
  1016. * @param int $filesize
  1017. * @param string $title
  1018. * @return id if inserted document
  1019. */
  1020. function add_document($_course,$path,$filetype,$filesize,$title,$comment=NULL, $readonly=0)
  1021. {
  1022. global $charset;
  1023. $session_id = api_get_session_id();
  1024. $table_document = Database::get_course_table(TABLE_DOCUMENT,$_course['dbName']);
  1025. $sql="INSERT INTO $table_document
  1026. (`path`, `filetype`, `size`, `title`, `comment`, `readonly`, `session_id`)
  1027. VALUES ('$path','$filetype','$filesize','".
  1028. Database::escape_string(htmlspecialchars($title, ENT_QUOTES, $charset))."', '$comment', $readonly, $session_id)";
  1029. if(Database::query($sql,__FILE__,__LINE__))
  1030. {
  1031. //display_message("Added to database (id ".Database::insert_id().")!");
  1032. return Database::insert_id();
  1033. }
  1034. else
  1035. {
  1036. //display_error("The uploaded file could not be added to the database (".mysql_error().")!");
  1037. return false;
  1038. }
  1039. }
  1040. //------------------------------------------------------------------------------
  1041. /*
  1042. function get_document_id() moved to document.lib.php
  1043. */
  1044. //------------------------------------------------------------------------------
  1045. /**
  1046. * Update an existing document in the database
  1047. * as the file exists, we only need to change the size
  1048. *
  1049. * @param array $_course
  1050. * @param int $document_id
  1051. * @param int $filesize
  1052. * @param int $readonly
  1053. * @return boolean true /false
  1054. */
  1055. function update_existing_document($_course,$document_id,$filesize,$readonly=0)
  1056. {
  1057. $document_table = Database::get_course_table(TABLE_DOCUMENT,$_course['dbName']);
  1058. $sql="UPDATE $document_table SET size = '$filesize' , readonly = '$readonly' WHERE id='$document_id'";
  1059. if(Database::query($sql,__FILE__,__LINE__))
  1060. {
  1061. return true;
  1062. }
  1063. else
  1064. {
  1065. return false;
  1066. }
  1067. }
  1068. /**
  1069. * this function updates the last_edit_date, last edit user id on all folders in a given path
  1070. *
  1071. * @param array $_course
  1072. * @param string $path
  1073. * @param int $user_id
  1074. */
  1075. function item_property_update_on_folder($_course,$path,$user_id)
  1076. {
  1077. //display_message("Start update_lastedit_on_folder");
  1078. //if we are in the root, just return... no need to update anything
  1079. if ($path=='/')
  1080. return;
  1081. //if the given path ends with a / we remove it
  1082. $endchar=substr($path,strlen($path)-1,1);
  1083. if($endchar=='/')
  1084. $path=substr($path,0,strlen($path)-1);
  1085. $TABLE_ITEMPROPERTY = Database::get_course_table(TABLE_ITEM_PROPERTY,$_course['dbName']);
  1086. //get the time
  1087. $time = date("Y-m-d H:i:s", time());
  1088. //get all paths in the given path
  1089. // /folder/subfolder/subsubfolder/file
  1090. // if file is updated, subsubfolder, subfolder and folder are updated
  1091. $exploded_path = explode('/',$path);
  1092. foreach ($exploded_path as $key => $value) {
  1093. //we don't want a slash before our first slash
  1094. if($key!=0){
  1095. $newpath .= "/".$value;
  1096. //echo "path= ".$newpath."<br>";
  1097. //select ID of given folder
  1098. $folder_id = DocumentManager::get_document_id($_course,$newpath);
  1099. if($folder_id)
  1100. {
  1101. $sql = "UPDATE $TABLE_ITEMPROPERTY SET `lastedit_date`='$time',`lastedit_type`='DocumentInFolderUpdated', `lastedit_user_id`='$user_id' WHERE tool='".TOOL_DOCUMENT."' AND ref='$folder_id'";
  1102. Database::query($sql,__FILE__,__LINE__);
  1103. }
  1104. }
  1105. }
  1106. }
  1107. //------------------------------------------------------------------------------
  1108. /**
  1109. * Returns the directory depth of the file.
  1110. *
  1111. * @author Olivier Cauberghe <olivier.cauberghe@ugent.be>
  1112. * @param path+filename eg: /main/document/document.php
  1113. * @return The directory depth
  1114. */
  1115. function get_levels($filename)
  1116. {
  1117. $levels=explode("/",$filename);
  1118. if(empty($levels[count($levels)-1])) unset($levels[count($levels)-1]);
  1119. return count($levels);
  1120. }
  1121. /*
  1122. function file_set_default_settings
  1123. moved to fileManage.lib.php,
  1124. class FileManager
  1125. */
  1126. //------------------------------------------------------------------------------
  1127. /**
  1128. * Adds file to document table in database
  1129. * @deprecated, use file_set_default_settings instead
  1130. *
  1131. * @author Olivier Cauberghe <olivier.cauberghe@ugent.be>
  1132. * @param path,filename
  1133. * @action Adds an entry to the document table with the default settings.
  1134. */
  1135. function set_default_settings($upload_path,$filename,$filetype="file")
  1136. {
  1137. global $dbTable,$_configuration;
  1138. global $default_visibility;
  1139. if (!$default_visibility)
  1140. $default_visibility="v";
  1141. $upload_path=str_replace('\\','/',$upload_path);
  1142. $upload_path=str_replace("//","/",$upload_path);
  1143. if($upload_path == '/')
  1144. {
  1145. $upload_path='';
  1146. }
  1147. elseif(!empty($upload_path) && $upload_path[0] != '/')
  1148. {
  1149. $upload_path="/$upload_path";
  1150. }
  1151. $endchar=substr($filename,strlen($filename)-1,1);
  1152. if($endchar == '/')
  1153. {
  1154. $filename=substr($filename,0,-1);
  1155. }
  1156. //$dbTable already has `backticks`!
  1157. //$query="select count(*) as bestaat from `$dbTable` where path='$upload_path/$filename'";
  1158. $query="select count(*) as bestaat from $dbTable where path='$upload_path/$filename'";
  1159. $result=Database::query($query,__FILE__,__LINE__);
  1160. $row=Database::fetch_array($result);
  1161. if($row["bestaat"]>0)
  1162. //$query="update `$dbTable` set path='$upload_path/$filename',visibility='$default_visibility', filetype='$filetype' where path='$upload_path/$filename'";
  1163. $query="update $dbTable set path='$upload_path/$filename',visibility='$default_visibility', filetype='$filetype' where path='$upload_path/$filename'";
  1164. else //$query="INSERT INTO `$dbTable` (path,visibility,filetype) VALUES('$upload_path/$filename','$default_visibility','$filetype')";
  1165. $query="INSERT INTO $dbTable (path,visibility,filetype) VALUES('$upload_path/$filename','$default_visibility','$filetype')";
  1166. Database::query($query,__FILE__,__LINE__);
  1167. }
  1168. //------------------------------------------------------------------------------
  1169. /**
  1170. * retrieve the image path list in a html file
  1171. *
  1172. * @author Hugues Peeters <hugues.peeters@claroline.net>
  1173. * @param string $htmlFile
  1174. * @return array - images path list
  1175. */
  1176. function search_img_from_html($htmlFile)
  1177. {
  1178. $imgFilePath = array();
  1179. if(!$fp = fopen($htmlFile, "r")){ //or die('<center>can not open file</center>');
  1180. return ;
  1181. }
  1182. // search and store occurences of the <IMG> tag in an array
  1183. $size_file=(filesize($htmlFile)===0) ? 1 : filesize($htmlFile);
  1184. if (isset($fp) && !($fp===false)) {
  1185. $buffer = fread( $fp, $size_file );
  1186. if (strlen($buffer)>=0 && !($buffer===false)) {
  1187. //
  1188. } else {
  1189. die('<center>Can not read file.</center>');
  1190. }
  1191. } else {
  1192. die('<center>Can not read file.</center>');
  1193. }
  1194. $matches = array();
  1195. if ( preg_match_all('~<[[:space:]]*img[^>]*>~i', $buffer, $matches) )
  1196. {
  1197. $imgTagList = $matches[0];
  1198. }
  1199. fclose ($fp); unset($buffer);
  1200. // Search the image file path from all the <IMG> tag detected
  1201. if ( sizeof($imgTagList) > 0)
  1202. {
  1203. foreach($imgTagList as $thisImgTag)
  1204. {
  1205. if ( preg_match('~src[[:space:]]*=[[:space:]]*[\"]{1}([^\"]+)[\"]{1}~i',
  1206. $thisImgTag, $matches) )
  1207. {
  1208. $imgPathList[] = $matches[1];
  1209. }
  1210. }
  1211. $imgPathList = array_unique($imgPathList); // remove duplicate entries
  1212. }
  1213. return $imgPathList;
  1214. }
  1215. //------------------------------------------------------------------------------
  1216. /**
  1217. * creates a new directory trying to find a directory name
  1218. * that doesn't already exist
  1219. * (we could use unique_name() here...)
  1220. *
  1221. * @author Hugues Peeters <hugues.peeters@claroline.net>
  1222. * @author Bert Vanderkimpen
  1223. * @param array $_course current course information
  1224. * @param int $user_id current user id
  1225. * @param string $desiredDirName complete path of the desired name
  1226. * @return string actual directory name if it succeeds,
  1227. * boolean false otherwise
  1228. */
  1229. function create_unexisting_directory($_course,$user_id,$to_group_id,$to_user_id,$base_work_dir,$desired_dir_name, $title = null, $visibility = '')
  1230. {
  1231. $nb = '';
  1232. while ( file_exists($base_work_dir.$desired_dir_name.$nb) )
  1233. {
  1234. $nb += 1;
  1235. }
  1236. if( $title == null)
  1237. {
  1238. $title = basename($desired_dir_name);
  1239. }
  1240. $perm = api_get_setting('permissions_for_new_directories');
  1241. $perm = octdec(!empty($perm)?$perm:'0770');
  1242. if (mkdir($base_work_dir.$desired_dir_name.$nb,$perm,true))
  1243. {
  1244. $document_id = add_document($_course, $desired_dir_name.$nb,'folder',0,$title);
  1245. if ($document_id)
  1246. {
  1247. //update document item_property
  1248. $current_session_id = api_get_session_id();
  1249. if ($visibility !== '') {
  1250. $visibilities = array(0 => 'invisible', 1 => 'visible', 2 => 'delete');
  1251. api_item_property_update($_course,TOOL_DOCUMENT,$document_id,$visibilities[$visibility],$user_id,$to_group_id,$to_user_id,null,null,$current_session_id);
  1252. } else {
  1253. api_item_property_update($_course,TOOL_DOCUMENT,$document_id,'FolderCreated',$user_id,$to_group_id,$to_user_id,null,null,$current_session_id);
  1254. }
  1255. return $desired_dir_name.$nb;
  1256. }
  1257. }
  1258. else
  1259. {
  1260. return false;
  1261. }
  1262. }
  1263. //------------------------------------------------------------------------------
  1264. /**
  1265. * Handles uploaded missing images
  1266. *
  1267. * @author Hugues Peeters <hugues.peeters@claroline.net>
  1268. * @author Bert Vanderkimpen
  1269. * @param array $_course
  1270. * @param array $uploaded_file_collection - follows the $_FILES Structure
  1271. * @param string $base_work_dir
  1272. * @param string $missing_files_dir
  1273. * @param int $user_id
  1274. * @param int $max_filled_space
  1275. */
  1276. 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)
  1277. {
  1278. $number_of_uploaded_images = count($uploaded_file_collection['name']);
  1279. for ($i=0; $i < $number_of_uploaded_images; $i++)
  1280. {
  1281. $missing_file['name'] = $uploaded_file_collection['name'][$i];
  1282. $missing_file['type'] = $uploaded_file_collection['type'][$i];
  1283. $missing_file['tmp_name'] = $uploaded_file_collection['tmp_name'][$i];
  1284. $missing_file['error'] = $uploaded_file_collection['error'][$i];
  1285. $missing_file['size'] = $uploaded_file_collection['size'][$i];
  1286. $upload_ok = process_uploaded_file($missing_file);
  1287. if($upload_ok)
  1288. {
  1289. $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');
  1290. }
  1291. unset($missing_file);
  1292. }
  1293. return $new_file_list;
  1294. }
  1295. //------------------------------------------------------------------------------
  1296. //------------------------------------------------------------------------------
  1297. /*
  1298. * Open the old html file and replace the src path into the img tag
  1299. * This also works for files in subdirectories.
  1300. * @param $originalImgPath is an array
  1301. * @param $newImgPath is an array
  1302. */
  1303. function replace_img_path_in_html_file($originalImgPath, $newImgPath, $htmlFile)
  1304. {
  1305. global $_course;
  1306. /*
  1307. * Open the file
  1308. */
  1309. $fp = fopen($htmlFile, "r");
  1310. $buffer = fread ($fp, filesize ($htmlFile));
  1311. /*
  1312. * Fix the image tags
  1313. */
  1314. for ($i = 0, $fileNb = count($originalImgPath); $i < $fileNb ; $i++)
  1315. {
  1316. $replace_what = $originalImgPath[$i];
  1317. /*
  1318. we only need the directory and the filename
  1319. /path/to/file_html_files/missing_file.gif -> file_html_files/missing_file.gif
  1320. */
  1321. $exploded_file_path = explode('/',$newImgPath[$i]);
  1322. $replace_by = $exploded_file_path[count($exploded_file_path)-2].'/'.$exploded_file_path[count($exploded_file_path)-1];
  1323. //$message .= "Element [$i] <b>" . $replace_what . "</b> replaced by <b>" . $replace_by . "</b><br>"; //debug
  1324. //api_display_debug_info($message);
  1325. $buffer = str_replace( $replace_what, $replace_by, $buffer);
  1326. }
  1327. $new_html_content .= $buffer;
  1328. fclose ($fp) or die ('<center>cannot close file</center>');;
  1329. /*
  1330. * Write the resulted new file
  1331. */
  1332. if (!$fp = fopen($htmlFile, 'w')){ //or die('<center>cannot open file</center>');
  1333. return;
  1334. }
  1335. if (!fwrite($fp, $new_html_content)){ // or die('<center>cannot write in file</center>');
  1336. return;
  1337. }
  1338. }
  1339. //------------------------------------------------------------------------------
  1340. /**
  1341. * Creates a file containing an html redirection to a given url
  1342. *
  1343. * @author Hugues Peeters <hugues.peeters@claroline.net>
  1344. * @param string $filePath
  1345. * @param string $url
  1346. * @return void
  1347. */
  1348. function create_link_file($filePath, $url)
  1349. {
  1350. $fileContent = '<html>'
  1351. .'<head>'
  1352. .'<meta http-equiv="refresh" content="1;url='.$url.'">'
  1353. .'</head>'
  1354. .'<body>'
  1355. .'</body>'
  1356. .'</html>';
  1357. if (!($fp = fopen ($filePath, 'w'))) {
  1358. return false;
  1359. }
  1360. return fwrite($fp, $fileContent);
  1361. }
  1362. //------------------------------------------------------------------------------
  1363. /**
  1364. Open html file $full_file_name;
  1365. Parse the hyperlinks; and
  1366. Write the result back in the html file.
  1367. @author Roan Embrechts
  1368. @version 0.1
  1369. */
  1370. function api_replace_links_in_html($upload_path, $full_file_name)
  1371. {
  1372. //Open the file
  1373. $fp = fopen($full_file_name, "r");
  1374. $buffer = fread ($fp, filesize ($full_file_name));
  1375. //Parse the contents
  1376. $new_html_content = api_replace_links_in_string($upload_path, $buffer);
  1377. //Write the result
  1378. $fp = fopen($full_file_name, "w");
  1379. fwrite($fp, $new_html_content);
  1380. }
  1381. //------------------------------------------------------------------------------
  1382. /**
  1383. @deprecated, use api_replace_parameter instead
  1384. Parse the buffer string provided as parameter
  1385. Replace the a href tags so they are displayed correctly.
  1386. - works for files in root and subdirectories
  1387. - replace relative hyperlinks to use showinframes.php?file= ...
  1388. - add target="_self" to all absolute hyperlinks
  1389. - leave local anchors untouched (e.g. #CHAPTER1)
  1390. - leave links with download.php and showinframes.php untouched
  1391. @author Roan Embrechts
  1392. @version 0.6
  1393. */
  1394. function api_replace_links_in_string($upload_path, $buffer)
  1395. {
  1396. // Search for hyperlinks
  1397. $matches = array();
  1398. if ( preg_match_all("/<a[\s]*href[^<]*>/i", $buffer, $matches) )
  1399. {
  1400. $tag_list = $matches[0];
  1401. }
  1402. // Search the filepath of all detected <a href> tags
  1403. if (sizeof($tag_list) > 0)
  1404. {
  1405. $file_path_list=array();
  1406. $href_list=array();
  1407. foreach($tag_list as $this_tag)
  1408. {
  1409. /* Match case insensitive, the stuff between the two ~ :
  1410. a href = <exactly one quote><one or more non-quotes><exactly one ">
  1411. e.g. a href="www.google.be", A HREF = "info.html"
  1412. to match ["] escape the " or else PHP interprets it
  1413. [\"]{1} --> matches exactly one "
  1414. + 1 or more (like * is 0 or more)
  1415. [\s]* matches whitespace
  1416. $matches contains captured subpatterns
  1417. the only one here is ([^\"]+) --> matches[1]
  1418. */
  1419. if ( preg_match("~a href[\s]*=[\s]*[\"]{1}([^\"]+)[\"]{1}~i",
  1420. $this_tag, $matches) )
  1421. {
  1422. $file_path_list[] = $matches[1];//older
  1423. $href_list[] = $matches[0];//to also add target="_self"
  1424. }
  1425. }
  1426. }
  1427. // replace the original hyperlinks
  1428. // by the correct ones
  1429. for ($count = 0; $count < sizeof($href_list); $count++)
  1430. {
  1431. $replaceWhat[$count] = $href_list[$count];
  1432. $is_absolute_hyperlink = strpos($replaceWhat[$count], "http");
  1433. $is_local_anchor = strpos($replaceWhat[$count], "#");
  1434. if ($is_absolute_hyperlink == false && $is_local_anchor == false )
  1435. {
  1436. //this is a relative hyperlink
  1437. if (
  1438. (strpos($replaceWhat[$count], "showinframes.php") == false) &&
  1439. (strpos($replaceWhat[$count], "download.php") == false)
  1440. )
  1441. {
  1442. //fix the link to use showinframes.php
  1443. $replaceBy[$count] = "a href = \"showinframes.php?file=" . $upload_path."/".$file_path_list[$count]."\" target=\"_self\"";
  1444. }
  1445. else
  1446. {
  1447. //url already fixed, leave as is
  1448. $replaceBy[$count] = $replaceWhat[$count];
  1449. }
  1450. }
  1451. else if ($is_absolute_hyperlink)
  1452. {
  1453. $replaceBy[$count] = "a href=\"" . $file_path_list[$count] . "\" target =\"_self\"";
  1454. }
  1455. else
  1456. {
  1457. //don't change anything
  1458. $replaceBy[$count] = $replaceWhat[$count];
  1459. }
  1460. //Display::display_normal_message("link replaced by " . $replaceBy[$count]); //debug
  1461. }
  1462. $buffer = str_replace($replaceWhat, $replaceBy, $buffer);
  1463. return $buffer;
  1464. }
  1465. //------------------------------------------------------------------------------
  1466. /**
  1467. EXPERIMENTAL - function seems to work, needs more testing
  1468. @param $upload_path is the path where the document is stored, like "/archive/"
  1469. if it is the root level, the function expects "/"
  1470. otherwise "/path/"
  1471. This function parses all tags with $param_name parameters.
  1472. so the tags are displayed correctly.
  1473. --------------
  1474. Algorithm v1.0
  1475. --------------
  1476. given a string and a parameter,
  1477. * OK find all tags in that string with the specified parameter (like href or src)
  1478. * OK for every one of these tags, find the src|href|... part to edit it
  1479. * OK change the src|href|... part to use download.php (or showinframes.php)
  1480. * OK do some special stuff for hyperlinks
  1481. Exceptions
  1482. * OK if download.php or showinframes.php is already in the tag, leave it alone
  1483. * OK if mailto is in the tag, leave it alone
  1484. * OK if the src|href param contains http://, it's absolute --> leave it alone
  1485. Special for hyperlinks (a href...)
  1486. * OK add target="_self"
  1487. * OK use showinframes.php instead of download.php
  1488. @author Roan Embrechts
  1489. @version 1.1
  1490. */
  1491. function api_replace_parameter($upload_path, $buffer, $param_name="src")
  1492. {
  1493. /*
  1494. * Search for tags with $param_name as a parameter
  1495. */
  1496. /*
  1497. // [\s]* matches whitespace
  1498. // [\"=a-z] matches ", = and a-z
  1499. // ([\s]*[a-z]*)* matches all whitespace and normal alphabet
  1500. // characters a-z combinations but seems too slow
  1501. // perhaps ([\s]*[a-z]*) a maximum number of times ?
  1502. // [\s]*[a-z]*[\s]* matches many tags
  1503. // the ending "i" means to match case insensitive (a matches a and A)
  1504. */
  1505. $matches = array();
  1506. if ( preg_match_all("/<[a-z]+[^<]*".$param_name."[^<]*>/i", $buffer, $matches) )
  1507. {
  1508. $tag_list = $matches[0];
  1509. }
  1510. /*
  1511. * Search the filepath of parameter $param_name in all detected tags
  1512. */
  1513. if (sizeof($tag_list) > 0)
  1514. {
  1515. $file_path_list=array();
  1516. $href_list=array();
  1517. foreach($tag_list as $this_tag)
  1518. {
  1519. //Display::display_normal_message(htmlentities($this_tag)); //debug
  1520. if ( preg_match("~".$param_name."[\s]*=[\s]*[\"]{1}([^\"]+)[\"]{1}~i",
  1521. $this_tag, $matches) )
  1522. {
  1523. $file_path_list[] = $matches[1];//older
  1524. $href_list[] = $matches[0];//to also add target="_self"
  1525. }
  1526. }
  1527. }
  1528. /*
  1529. * Replace the original tags by the correct ones
  1530. */
  1531. for ($count = 0; $count < sizeof($href_list); $count++)
  1532. {
  1533. $replaceWhat[$count] = $href_list[$count];
  1534. $is_absolute_hyperlink = strpos($replaceWhat[$count], 'http');
  1535. $is_local_anchor = strpos($replaceWhat[$count], '#');
  1536. if ($is_absolute_hyperlink == false && $is_local_anchor == false )
  1537. {
  1538. if (
  1539. (strpos($replaceWhat[$count], 'showinframes.php') == false) &&
  1540. (strpos($replaceWhat[$count], 'download.php') == false) &&
  1541. (strpos($replaceWhat[$count], 'mailto') == false)
  1542. )
  1543. {
  1544. //fix the link to use download.php or showinframes.php
  1545. if ( preg_match("/<a([\s]*[\"\/:'=a-z0-9]*){5}href[^<]*>/i", $tag_list[$count]) )
  1546. {
  1547. $replaceBy[$count] = " $param_name =\"showinframes.php?file=" . $upload_path.$file_path_list[$count]."\" target=\"_self\" ";
  1548. }
  1549. else
  1550. {
  1551. $replaceBy[$count] = " $param_name =\"download.php?doc_url=" . $upload_path.$file_path_list[$count]."\" ";
  1552. }
  1553. }
  1554. else
  1555. {
  1556. //"mailto" or url already fixed, leave as is
  1557. //$message .= "Already fixed or contains mailto: ";
  1558. $replaceBy[$count] = $replaceWhat[$count];
  1559. }
  1560. }
  1561. else if ($is_absolute_hyperlink)
  1562. {
  1563. //$message .= "Absolute hyperlink, don't change, add target=_self: ";
  1564. $replaceBy[$count] = " $param_name=\"" . $file_path_list[$count] . "\" target =\"_self\"";
  1565. }
  1566. else
  1567. {
  1568. //don't change anything
  1569. //$message .= "Local anchor, don't change: ";
  1570. $replaceBy[$count] = $replaceWhat[$count];
  1571. }
  1572. //$message .= "In tag $count, <b>" . htmlentities($tag_list[$count])
  1573. // . "</b>, parameter <b>" . $replaceWhat[$count] . "</b> replaced by <b>" . $replaceBy[$count] . "</b><br>"; //debug
  1574. }
  1575. //if (isset($message) && $message == true) api_display_debug_info($message); //debug
  1576. $buffer = str_replace($replaceWhat, $replaceBy, $buffer);
  1577. return $buffer;
  1578. }
  1579. //------------------------------------------------------------------------------
  1580. /**
  1581. * Checks the extension of a file, if it's .htm or .html
  1582. * we use search_img_from_html to get all image paths in the file
  1583. *
  1584. * @param string $file
  1585. * @return array paths
  1586. * @see check_for_missing_files() uses search_img_from_html()
  1587. */
  1588. function check_for_missing_files($file)
  1589. {
  1590. if (strrchr($file, '.') == '.htm' || strrchr($file, '.') == '.html')
  1591. {
  1592. $img_file_path = search_img_from_html($file);
  1593. return $img_file_path;
  1594. }
  1595. return false;
  1596. }
  1597. //------------------------------------------------------------------------------
  1598. /**
  1599. * This builds a form that asks for the missing images in a html file
  1600. * maybe we should do this another way?
  1601. *
  1602. * @param array $missing_files
  1603. * @param string $upload_path
  1604. * @param string $file_name
  1605. * @return string the form
  1606. */
  1607. function build_missing_files_form($missing_files,$upload_path,$file_name)
  1608. {
  1609. //do we need a / or not?
  1610. $added_slash = ($upload_path=='/')?'':'/';
  1611. //build the form
  1612. $form .= "<p><strong>".get_lang('MissingImagesDetected')."</strong></p>\n"
  1613. ."<form method=\"post\" action=\"".api_get_self()."\" enctype=\"multipart/form-data\">\n"
  1614. //related_file is the path to the file that has missing images
  1615. ."<input type=\"hidden\" name=\"related_file\" value=\"".$upload_path.$added_slash.$file_name."\" />\n"
  1616. ."<input type=\"hidden\" name=\"upload_path\" value=\"".$upload_path."\" />\n"
  1617. ."<table border=\"0\">\n";
  1618. foreach($missing_files as $this_img_file_path )
  1619. {
  1620. $form .= "<tr>\n"
  1621. ."<td>".basename($this_img_file_path)." : </td>\n"
  1622. ."<td>"
  1623. ."<input type=\"file\" name=\"img_file[]\"/>"
  1624. ."<input type=\"hidden\" name=\"img_file_path[]\" value=\"".$this_img_file_path."\" />"
  1625. ."</td>\n"
  1626. ."</tr>\n";
  1627. }
  1628. $form .= "</table>\n"
  1629. ."<button type='submit' name=\"cancel_submit_image\" value=\"".get_lang('Cancel')."\" class=\"cancel\">".get_lang('Cancel')."</button>"
  1630. ."<button type='submit' name=\"submit_image\" value=\"".get_lang('Ok')."\" class=\"save\">".get_lang('Ok')."</button>"
  1631. ."</form>\n";
  1632. return $form;
  1633. }
  1634. //------------------------------------------------------------------------------
  1635. /**
  1636. * This recursive function can be used during the upgrade process form older versions of Dokeos
  1637. * It crawls the given directory, checks if the file is in the DB and adds it if it's not
  1638. *
  1639. * @param string $base_work_dir
  1640. * @param string $current_path, needed for recursivity
  1641. */
  1642. function add_all_documents_in_folder_to_database($_course,$user_id,$base_work_dir,$current_path='',$to_group_id=0)
  1643. {
  1644. $current_session_id = api_get_session_id();
  1645. $path = $base_work_dir.$current_path;
  1646. //open dir
  1647. $handle=opendir($path);
  1648. //run trough
  1649. while($file=readdir($handle))
  1650. {
  1651. if ($file=='.' || $file=='..') continue;
  1652. $completepath="$path/$file";
  1653. //directory?
  1654. if (is_dir($completepath))
  1655. {
  1656. $title=get_document_title($file);
  1657. $safe_file=replace_dangerous_char($file);
  1658. @rename($path.'/'.$file, $path.'/'.$safe_file);
  1659. //if we can't find the file, add it
  1660. if(!DocumentManager::get_document_id($_course, $current_path.'/'.$safe_file))
  1661. {
  1662. $document_id=add_document($_course,$current_path.'/'.$safe_file,'folder',0,$title);
  1663. api_item_property_update($_course,TOOL_DOCUMENT,$document_id,'DocumentAdded',$user_id, $to_group_id,null,null,null,$current_session_id);
  1664. //echo $current_path.'/'.$safe_file." added!<br/>";
  1665. }
  1666. //recursive
  1667. add_all_documents_in_folder_to_database($_course,$user_id,$base_work_dir,$current_path.'/'.$safe_file, $to_group_id);
  1668. }
  1669. //file!
  1670. else
  1671. {
  1672. //rename
  1673. $safe_file=disable_dangerous_file(replace_dangerous_char($file, 'strict'));
  1674. @rename($base_work_dir.$current_path.'/'.$file,$base_work_dir.$current_path.'/'.$safe_file);
  1675. if(!DocumentManager::get_document_id($_course, $current_path.'/'.$safe_file))
  1676. {
  1677. $title=get_document_title($file);
  1678. $size = filesize($base_work_dir.$current_path.'/'.$safe_file);
  1679. $document_id = add_document($_course,$current_path.'/'.$safe_file,'file',$size,$title);
  1680. api_item_property_update($_course,TOOL_DOCUMENT,$document_id,'DocumentAdded',$user_id,$to_group_id,null,null,null,$current_session_id);
  1681. //echo $current_path.'/'.$safe_file." added!<br/>";
  1682. }
  1683. }
  1684. }
  1685. }
  1686. /*
  1687. ==============================================================================
  1688. DEPRECATED FUNCTIONS
  1689. ==============================================================================
  1690. */
  1691. /**
  1692. * @deprecated Use transliteration instead, it is applicable for all languages.
  1693. *
  1694. * Replaces all accentuated characters by non-accentuated characters for filenames, as
  1695. * well as special HTML characters by their HTML entity's first letter.
  1696. *
  1697. * Although this method is not absolute, it gives good results in general. It first
  1698. * transforms the string to HTML entities (&ocirc;, @oslash;, etc) then removes the
  1699. * HTML character part to result in simple characters (o, o, etc).
  1700. * In the case of special characters (out of alphabetical value) like &nbsp; and &lt;,
  1701. * it will still replace them by the first letter of the HTML entity (n, l, ...) but it
  1702. * is still an acceptable method, knowing we're filtering filenames here...
  1703. * @param string The accentuated string
  1704. * @return string The escaped string, not absolutely correct but satisfying
  1705. */
  1706. function replace_accents($string, $encoding = null) {
  1707. /*
  1708. global $charset;
  1709. $string = api_htmlentities($string,ENT_QUOTES,$charset);
  1710. $res = preg_replace("/&([a-z])[a-z]+;/i","$1",$string);
  1711. return $res;
  1712. */
  1713. return api_transliterate($string, 'x', $encoding);
  1714. }
  1715. /**
  1716. * @deprecated Use transliteration instead, it is applicable for all languages.
  1717. */
  1718. function remove_accents($string, $encoding = null) {
  1719. /*
  1720. $string = strtr ( $string, "�����������������������������������������������������", "AAAAAAaaaaaaOOOOOOooooooEEEEeeeeCcIIIIiiiiUUUUuuuuyNn");
  1721. return $string;
  1722. */
  1723. return api_transliterate($string, 'x', $encoding);
  1724. }