fileUpload.lib.php 61 KB

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