fileUpload.lib.php 62 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910
  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. * Replaces all accentuated characters by non-accentuated characters for filenames, as
  68. * well as special HTML characters by their HTML entity's first letter.
  69. *
  70. * Although this method is not absolute, it gives good results in general. It first
  71. * transforms the string to HTML entities (&ocirc;, @oslash;, etc) then removes the
  72. * HTML character part to result in simple characters (o, o, etc).
  73. * In the case of special characters (out of alphabetical value) like &nbsp; and &lt;,
  74. * it will still replace them by the first letter of the HTML entity (n, l, ...) but it
  75. * is still an acceptable method, knowing we're filtering filenames here...
  76. * @param string The accentuated string
  77. * @return string The escaped string, not absolutely correct but satisfying
  78. */
  79. function replace_accents($string){
  80. global $charset;
  81. $string = api_htmlentities($string,ENT_QUOTES,$charset);
  82. $res = preg_replace("/&([a-z])[a-z]+;/i","$1",$string);
  83. return $res;
  84. }
  85. //------------------------------------------------------------------------------
  86. /**
  87. * change the file name extension from .php to .phps
  88. * Useful to secure a site !!
  89. *
  90. * @author - Hugues Peeters <peeters@ipm.ucl.ac.be>
  91. * @param - fileName (string) name of a file
  92. * @return - the filenam phps'ized
  93. */
  94. function php2phps ($fileName)
  95. {
  96. $fileName = preg_replace('/\.(php.?|phtml.?)(\.){0,1}.*$/i', '.phps', $fileName);
  97. return $fileName;
  98. }
  99. //------------------------------------------------------------------------------
  100. /**
  101. * Renames .htaccess & .HTACCESS tot htaccess.txt
  102. *
  103. * @param string $filename
  104. * @return string
  105. */
  106. function htaccess2txt($filename)
  107. {
  108. $filename = str_replace('.htaccess', 'htaccess.txt', $filename);
  109. $filename = str_replace('.HTACCESS', 'htaccess.txt', $filename);
  110. return $filename;
  111. }
  112. //------------------------------------------------------------------------------
  113. /**
  114. * this function executes our safety precautions
  115. * more functions can be added
  116. *
  117. * @param string $filename
  118. * @return string
  119. * @see php2phps()
  120. * @see htaccess2txt()
  121. */
  122. function disable_dangerous_file($filename)
  123. {
  124. $filename = php2phps($filename);
  125. $filename = htaccess2txt($filename);
  126. return $filename;
  127. }
  128. //------------------------------------------------------------------------------
  129. /**
  130. * this function generates a unique name for a file on a given location
  131. * filenames are changed to name_#.ext
  132. *
  133. * @param string $path
  134. * @param string $name
  135. * @return new unique name
  136. */
  137. function unique_name($path,$name)
  138. {
  139. $ext = substr(strrchr($name, "."), 0);
  140. $name_no_ext = substr($name, 0, strlen($name) - strlen(strstr($name,$ext)));
  141. $n = 0;
  142. $unique = '';
  143. while(file_exists($path . $name_no_ext . $unique . $ext))
  144. {
  145. $unique = '_' . ++$n;
  146. }
  147. return $name_no_ext . $unique . $ext;
  148. }
  149. //------------------------------------------------------------------------------
  150. /**
  151. * Returns the name without extension, used for the title
  152. *
  153. * @param string $name
  154. * @return name without the extension
  155. */
  156. function get_document_title($name)
  157. {
  158. //if they upload .htaccess...
  159. $name = disable_dangerous_file($name);
  160. $ext = substr(strrchr($name, "."), 0);
  161. $name_no_ext = substr($name, 0, strlen($name) - strlen(strstr($name,$ext)));
  162. $filename = addslashes($name_no_ext);
  163. return $filename;
  164. }
  165. //------------------------------------------------------------------------------
  166. /**
  167. * This function checks if the upload succeeded
  168. *
  169. * @param array $uploaded_file ($_FILES)
  170. * @return true if upload succeeded
  171. */
  172. function process_uploaded_file($uploaded_file) {
  173. // Checking the error code sent with the file upload.
  174. switch ($uploaded_file['error']) {
  175. case 1:
  176. // The uploaded file exceeds the upload_max_filesize directive in php.ini.
  177. Display::display_error_message(get_lang('UplExceedMaxServerUpload'). ini_get('upload_max_filesize'));
  178. return false;
  179. case 2:
  180. // The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.
  181. // 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).
  182. Display::display_error_message(get_lang('UplExceedMaxPostSize'). round($_POST['MAX_FILE_SIZE']/1024) ." KB");
  183. return false;
  184. case 3:
  185. // The uploaded file was only partially uploaded.
  186. Display::display_error_message(get_lang('$UplPartialUpload')." ".get_lang('PleaseTryAgain'));
  187. return false;
  188. case 4:
  189. // No file was uploaded.
  190. Display::display_error_message(get_lang('UplNoFileUploaded')." ". get_lang('UplSelectFileFirst'));
  191. return false;
  192. }
  193. // case 0: default: We assume there is no error, the file uploaded with success.
  194. return true;
  195. }
  196. //------------------------------------------------------------------------------
  197. /**
  198. * this function does the save-work for the documents.
  199. * it handles the uploaded file and adds the properties to the database
  200. * if unzip=1 and the file is a zipfile, it is extracted
  201. * if we decide to save ALL kinds of documents in one database,
  202. * we could extend this with a $type='document', 'scormdocument',...
  203. *
  204. * @param array $_course
  205. * @param array $uploaded_file ($_FILES)
  206. * @param string $base_work_dir
  207. * @param string $upload_path
  208. * @param int $user_id
  209. * @param int $to_group_id, 0 for everybody
  210. * @param int $to_user_id, NULL for everybody
  211. * @param int $maxFilledSpace
  212. * @param int $unzip 1/0
  213. * @param string $what_if_file_exists overwrite, rename or warn if exists (default)
  214. * @param boolean Optional output parameter. So far only use for unzip_uploaded_document function. If no output wanted on success, set to false.
  215. * @return path of the saved file
  216. */
  217. 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)
  218. {
  219. if(!$user_id) die("Not a valid user.");
  220. //strip slashes
  221. $uploaded_file['name']=stripslashes($uploaded_file['name']);
  222. //add extension to files without one (if possible)
  223. $uploaded_file['name']=add_ext_on_mime($uploaded_file['name'],$uploaded_file['type']);
  224. //check if there is enough space to save the file
  225. if (!enough_space($uploaded_file['size'], $maxFilledSpace))
  226. {
  227. Display::display_error_message(get_lang('UplNotEnoughSpace'));
  228. return false;
  229. }
  230. //if the want to unzip, check if the file has a .zip (or ZIP,Zip,ZiP,...) extension
  231. if ($unzip == 1 && preg_match("/.zip$/", strtolower($uploaded_file['name'])) )
  232. {
  233. return unzip_uploaded_document($uploaded_file, $upload_path, $base_work_dir, $maxFilledSpace, $output, $to_group_id);
  234. //display_message("Unzipping file");
  235. }
  236. //we can only unzip ZIP files (no gz, tar,...)
  237. elseif ($unzip == 1 && !preg_match("/.zip$/", strtolower($uploaded_file['name'])) )
  238. {
  239. Display::display_error_message(get_lang('UplNotAZip')." ".get_lang('PleaseTryAgain'));
  240. return false;
  241. }
  242. else
  243. {
  244. //clean up the name and prevent dangerous files
  245. //remove strange characters
  246. $clean_name = replace_dangerous_char($uploaded_file['name']);
  247. $clean_name = replace_accents($clean_name);
  248. //no "dangerous" files
  249. $clean_name = disable_dangerous_file($clean_name);
  250. if(!filter_extension($clean_name))
  251. {
  252. Display::display_error_message(get_lang('UplUnableToSaveFileFilteredExtension'));
  253. return false;
  254. }
  255. else
  256. {
  257. //extension is good
  258. //echo "<br/>clean name = ".$clean_name;
  259. //echo "<br/>upload_path = ".$upload_path;
  260. //if the upload path differs from / (= root) it will need a slash at the end
  261. if ($upload_path!='/')
  262. $upload_path = $upload_path.'/';
  263. //echo "<br/>upload_path = ".$upload_path;
  264. $file_path = $upload_path.$clean_name;
  265. //echo "<br/>file path = ".$file_path;
  266. //full path to where we want to store the file with trailing slash
  267. $where_to_save = $base_work_dir.$upload_path;
  268. //at least if the directory doesn't exist, tell so
  269. if(!is_dir($where_to_save)){
  270. Display::display_error_message(get_lang('DestDirectoryDoesntExist').' ('.$upload_path.')');
  271. return false;
  272. }
  273. //echo "<br/>where to save = ".$where_to_save;
  274. // full path of the destination
  275. $store_path = $where_to_save.$clean_name;
  276. //echo "<br/>store path = ".$store_path;
  277. //name of the document without the extension (for the title)
  278. $document_name = get_document_title($uploaded_file['name']);
  279. //size of the uploaded file (in bytes)
  280. $file_size = $uploaded_file['size'];
  281. $files_perm = api_get_setting('permissions_for_new_files');
  282. $files_perm = octdec(!empty($files_perm)?$files_perm:'0770');
  283. //what to do if the target file exists
  284. switch ($what_if_file_exists)
  285. {
  286. //overwrite the file if it exists
  287. case 'overwrite':
  288. //check if the target file exists, so we can give another message
  289. if (file_exists($store_path))
  290. {
  291. $file_exists = true;
  292. }
  293. else
  294. {
  295. $file_exists = false;
  296. }
  297. if (@move_uploaded_file($uploaded_file['tmp_name'], $store_path))
  298. {
  299. chmod($store_path,$files_perm);
  300. if($file_exists)
  301. {
  302. //UPDATE DATABASE!
  303. $document_id = DocumentManager::get_document_id($_course,$file_path);
  304. if ($document_id)
  305. {
  306. //update filesize
  307. update_existing_document($_course,$document_id,$uploaded_file['size']);
  308. //update document item_property
  309. api_item_property_update($_course,TOOL_DOCUMENT,$document_id,'DocumentUpdated',$user_id,$to_group_id,$to_user_id);
  310. }
  311. //if the file is in a folder, we need to update all parent folders
  312. item_property_update_on_folder($_course,$upload_path,$user_id);
  313. //display success message with extra info to user
  314. if($output){
  315. Display::display_confirmation_message(get_lang('UplUploadSucceeded')."<br/>".$file_path .' '. get_lang('UplFileOverwritten'),false);
  316. }
  317. return $file_path;
  318. }
  319. else
  320. {
  321. //put the document data in the database
  322. $document_id = add_document($_course,$file_path,'file',$file_size,$document_name);
  323. if ($document_id)
  324. {
  325. //put the document in item_property update
  326. api_item_property_update($_course,TOOL_DOCUMENT,$document_id,'DocumentAdded',$user_id,$to_group_id,$to_user_id);
  327. }
  328. //if the file is in a folder, we need to update all parent folders
  329. item_property_update_on_folder($_course,$upload_path,$user_id);
  330. //display success message to user
  331. Display::display_confirmation_message(get_lang('UplUploadSucceeded')."<br/>".$file_path,false);
  332. return $file_path;
  333. }
  334. }
  335. else
  336. {
  337. Display::display_error_message(get_lang('UplUnableToSaveFile'));
  338. return false;
  339. }
  340. break;
  341. //rename the file if it exists
  342. case 'rename':
  343. $new_name = unique_name($where_to_save, $clean_name);
  344. $store_path = $where_to_save.$new_name;
  345. $new_file_path = $upload_path.$new_name;
  346. if (@move_uploaded_file($uploaded_file['tmp_name'], $store_path))
  347. {
  348. chmod($store_path,$files_perm);
  349. //put the document data in the database
  350. $document_id = add_document($_course,$new_file_path,'file',$file_size,$document_name);
  351. if ($document_id)
  352. {
  353. //update document item_property
  354. api_item_property_update($_course,TOOL_DOCUMENT,$document_id,'DocumentAdded',$user_id,$to_group_id,$to_user_id);
  355. }
  356. //if the file is in a folder, we need to update all parent folders
  357. item_property_update_on_folder($_course,$upload_path,$user_id);
  358. //display success message to user
  359. if($output){
  360. Display::display_confirmation_message(get_lang('UplUploadSucceeded'). "<br>" .get_lang('UplFileSavedAs') . $new_file_path,false);
  361. }
  362. return $new_file_path;
  363. }
  364. else
  365. {
  366. Display::display_error_message(get_lang('UplUnableToSaveFile'));
  367. return false;
  368. }
  369. break;
  370. //only save the file if it doesn't exist or warn user if it does exist
  371. default:
  372. if (file_exists($store_path))
  373. {
  374. Display::display_error_message($clean_name.' '.get_lang('UplAlreadyExists'));
  375. }
  376. else
  377. {
  378. if (@move_uploaded_file($uploaded_file['tmp_name'], $store_path))
  379. {
  380. chmod($store_path,$files_perm);
  381. //put the document data in the database
  382. $document_id = add_document($_course,$file_path,'file',$file_size,$document_name);
  383. if ($document_id)
  384. {
  385. //update document item_property
  386. api_item_property_update($_course,TOOL_DOCUMENT,$document_id,'DocumentAdded',$user_id,$to_group_id,$to_user_id);
  387. }
  388. //if the file is in a folder, we need to update all parent folders
  389. item_property_update_on_folder($_course,$upload_path,$user_id);
  390. //display success message to user
  391. if($output){
  392. Display::display_confirmation_message(get_lang('UplUploadSucceeded')."<br/>".$file_path,false);
  393. }
  394. return $file_path;
  395. }
  396. else
  397. {
  398. Display::display_error_message(get_lang('UplUnableToSaveFile'));
  399. return false;
  400. }
  401. }
  402. break;
  403. }
  404. }
  405. }
  406. }
  407. //------------------------------------------------------------------------------
  408. /**
  409. * Check if there is enough place to add a file on a directory
  410. * on the base of a maximum directory size allowed
  411. * @deprecated use enough_space instead!
  412. * @author - Hugues Peeters <peeters@ipm.ucl.ac.be>
  413. * @param - fileSize (int) - size of the file in byte
  414. * @param - dir (string) - Path of the directory
  415. * whe the file should be added
  416. * @param - maxDirSpace (int) - maximum size of the diretory in byte
  417. * @return - boolean true if there is enough space,
  418. * boolean false otherwise
  419. *
  420. * @see - enough_size() uses dir_total_space() function
  421. */
  422. function enough_size($fileSize, $dir, $maxDirSpace)
  423. {
  424. if ($maxDirSpace)
  425. {
  426. $alreadyFilledSpace = dir_total_space($dir);
  427. if ( ($fileSize + $alreadyFilledSpace) > $maxDirSpace)
  428. {
  429. return false;
  430. }
  431. }
  432. return true;
  433. }
  434. //------------------------------------------------------------------------------
  435. /**
  436. * Check if there is enough place to add a file on a directory
  437. * on the base of a maximum directory size allowed
  438. *
  439. * @author Bert Vanderkimpen
  440. * @param int file_size size of the file in byte
  441. * @param array $_course
  442. * @param int max_dir_space maximum size
  443. * @return boolean true if there is enough space, false otherwise
  444. *
  445. * @see enough_space() uses documents_total_space() function
  446. */
  447. function enough_space($file_size, $max_dir_space)
  448. {
  449. if ($max_dir_space)
  450. {
  451. $already_filled_space = documents_total_space();
  452. if ( ($file_size + $already_filled_space) > $max_dir_space)
  453. {
  454. return false;
  455. }
  456. }
  457. return true;
  458. }
  459. //------------------------------------------------------------------------------
  460. /**
  461. * Compute the size already occupied by a directory and is subdirectories
  462. *
  463. * @author - Hugues Peeters <peeters@ipm.ucl.ac.be>
  464. * @param - dirPath (string) - size of the file in byte
  465. * @return - int - return the directory size in bytes
  466. */
  467. function dir_total_space($dirPath)
  468. {
  469. $save_dir = getcwd();
  470. chdir ($dirPath) ;
  471. $handle = opendir($dirPath);
  472. while ($element = readdir($handle) )
  473. {
  474. if ( $element == "." || $element == "..")
  475. {
  476. continue; // skip the current and parent directories
  477. }
  478. if ( is_file($element) )
  479. {
  480. $sumSize += filesize($element);
  481. }
  482. if ( is_dir($element) )
  483. {
  484. $dirList[] = $dirPath."/".$element;
  485. }
  486. }
  487. closedir($handle) ;
  488. if ( sizeof($dirList) > 0)
  489. {
  490. foreach($dirList as $j)
  491. {
  492. $sizeDir = dir_total_space($j); // recursivity
  493. $sumSize += $sizeDir;
  494. }
  495. }
  496. chdir($save_dir);//return to initial position
  497. return $sumSize;
  498. }
  499. //------------------------------------------------------------------------------
  500. /**
  501. * Calculate the total size of all documents in a course
  502. *
  503. * @author Bert vanderkimpen
  504. * @param int $to_group_id (to calculate group document space)
  505. * @return int total size
  506. */
  507. function documents_total_space($to_group_id='0')
  508. {
  509. $TABLE_ITEMPROPERTY = Database::get_course_table(TABLE_ITEM_PROPERTY);
  510. $TABLE_DOCUMENT = Database::get_course_table(TABLE_DOCUMENT);
  511. $sql = "SELECT SUM(size)
  512. FROM ".$TABLE_ITEMPROPERTY." AS props, ".$TABLE_DOCUMENT." AS docs
  513. WHERE docs.id = props.ref
  514. AND props.tool = '".TOOL_DOCUMENT."'
  515. AND props.to_group_id='".$to_group_id."'
  516. AND props.visibility <> 2";
  517. $result = api_sql_query($sql,__FILE__,__LINE__);
  518. if($result && mysql_num_rows($result)!=0)
  519. {
  520. $row = mysql_fetch_row($result);
  521. return $row[0];
  522. }
  523. else
  524. {
  525. return 0;
  526. }
  527. }
  528. //------------------------------------------------------------------------------
  529. /**
  530. * Try to add an extension to files without extension
  531. * Some applications on Macintosh computers don't add an extension to the files.
  532. * This subroutine try to fix this on the basis of the MIME type sent
  533. * by the browser.
  534. *
  535. * Note : some browsers don't send the MIME Type (e.g. Netscape 4).
  536. * We don't have solution for this kind of situation
  537. *
  538. * @author - Hugues Peeters <peeters@ipm.ucl.ac.be>
  539. * @author - Bert Vanderkimpen
  540. * @param - fileName (string) - Name of the file
  541. * @param - fileType (string) - Type of the file
  542. * @return - fileName (string)
  543. *
  544. */
  545. function add_ext_on_mime($fileName,$fileType)
  546. {
  547. /*
  548. * Check if the file has an extension AND if the browser has sent a MIME Type
  549. */
  550. //if(!ereg("([[:alnum:]]|[[[:punct:]])+\.[[:alnum:]]+$", $fileName) // TODO: This fails sometimes on non-ASCII encoded file names. To be removed.
  551. // && $fileType)
  552. if(!preg_match('/^.*\.[a-zA-Z_0-9]+$/', $fileName) && $fileType)
  553. {
  554. /*
  555. * Build a "MIME-types / extensions" connection table
  556. */
  557. static $mimeType = array();
  558. $mimeType[] = "application/msword"; $extension[] =".doc";
  559. $mimeType[] = "application/rtf"; $extension[] =".rtf";
  560. $mimeType[] = "application/vnd.ms-powerpoint"; $extension[] =".ppt";
  561. $mimeType[] = "application/vnd.ms-excel"; $extension[] =".xls";
  562. $mimeType[] = "application/pdf"; $extension[] =".pdf";
  563. $mimeType[] = "application/postscript"; $extension[] =".ps";
  564. $mimeType[] = "application/mac-binhex40"; $extension[] =".hqx";
  565. $mimeType[] = "application/x-gzip"; $extension[] ="tar.gz";
  566. $mimeType[] = "application/x-shockwave-flash"; $extension[] =".swf";
  567. $mimeType[] = "application/x-stuffit"; $extension[] =".sit";
  568. $mimeType[] = "application/x-tar"; $extension[] =".tar";
  569. $mimeType[] = "application/zip"; $extension[] =".zip";
  570. $mimeType[] = "application/x-tar"; $extension[] =".tar";
  571. $mimeType[] = "text/html"; $extension[] =".html";
  572. $mimeType[] = "text/plain"; $extension[] =".txt";
  573. $mimeType[] = "text/rtf"; $extension[] =".rtf";
  574. $mimeType[] = "img/gif"; $extension[] =".gif";
  575. $mimeType[] = "img/jpeg"; $extension[] =".jpg";
  576. $mimeType[] = "img/png"; $extension[] =".png";
  577. $mimeType[] = "audio/midi"; $extension[] =".mid";
  578. $mimeType[] = "audio/mpeg"; $extension[] =".mp3";
  579. $mimeType[] = "audio/x-aiff"; $extension[] =".aif";
  580. $mimeType[] = "audio/x-pn-realaudio"; $extension[] =".rm";
  581. $mimeType[] = "audio/x-pn-realaudio-plugin"; $extension[] =".rpm";
  582. $mimeType[] = "audio/x-wav"; $extension[] =".wav";
  583. $mimeType[] = "video/mpeg"; $extension[] =".mpg";
  584. $mimeType[] = "video/mpeg4-generic"; $extension[] =".mp4";
  585. $mimeType[] = "video/quicktime"; $extension[] =".mov";
  586. $mimeType[] = "video/x-msvideo"; $extension[] =".avi";
  587. $mimeType[] = "video/x-ms-wmv"; $extension[] =".wmv";
  588. $mimeType[] = "video/x-flv"; $extension[] =".flv";
  589. $mimeType[] = "application/vnd.ms-word.document.macroEnabled.12"; $extension[] =".docm";
  590. $mimeType[] = "application/vnd.openxmlformats-officedocument.wordprocessingml.document"; $extension[] =".docx";
  591. $mimeType[] = "application/vnd.ms-word.template.macroEnabled.12"; $extension[] =".dotm";
  592. $mimeType[] = "application/vnd.openxmlformats-officedocument.wordprocessingml.template"; $extension[] =".dotx";
  593. $mimeType[] = "application/vnd.ms-powerpoint.template.macroEnabled.12"; $extension[] =".potm";
  594. $mimeType[] = "application/vnd.openxmlformats-officedocument.presentationml.template"; $extension[] =".potx";
  595. $mimeType[] = "application/vnd.ms-powerpoint.addin.macroEnabled.12"; $extension[] =".ppam";
  596. $mimeType[] = "application/vnd.ms-powerpoint.slideshow.macroEnabled.12"; $extension[] =".ppsm";
  597. $mimeType[] = "application/vnd.openxmlformats-officedocument.presentationml.slideshow"; $extension[] =".ppsx";
  598. $mimeType[] = "application/vnd.ms-powerpoint.presentation.macroEnabled.12"; $extension[] =".pptm";
  599. $mimeType[] = "application/vnd.openxmlformats-officedocument.presentationml.presentation"; $extension[] =".pptx";
  600. $mimeType[] = "application/vnd.ms-excel.addin.macroEnabled.12"; $extension[] =".xlam";
  601. $mimeType[] = "application/vnd.ms-excel.sheet.binary.macroEnabled.12"; $extension[] =".xlsb";
  602. $mimeType[] = "application/vnd.ms-excel.sheet.macroEnabled.12"; $extension[] =".xlsm";
  603. $mimeType[] = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; $extension[] =".xlsx";
  604. $mimeType[] = "application/vnd.ms-excel.template.macroEnabled.12"; $extension[] =".xltm";
  605. $mimeType[] = "application/vnd.openxmlformats-officedocument.spreadsheetml.template"; $extension[] =".xltx";
  606. //test on PC (files with no extension get application/octet-stream)
  607. //$mimeType[] = "application/octet-stream"; $extension[] =".ext";
  608. /*
  609. * Check if the MIME type sent by the browser is in the table
  610. */
  611. foreach($mimeType as $key=>$type)
  612. {
  613. if ($type == $fileType)
  614. {
  615. $fileName .= $extension[$key];
  616. break;
  617. }
  618. }
  619. unset($mimeType, $extension, $type, $key); // Delete to eschew possible collisions
  620. }
  621. return $fileName;
  622. }
  623. //------------------------------------------------------------------------------
  624. /**
  625. *
  626. * @author Hugues Peeters <hugues.peeters@claroline.net>
  627. *
  628. * @param array $uploadedFile - follows the $_FILES Structure
  629. * @param string $baseWorkDir - base working directory of the module
  630. * @param string $uploadPath - destination of the upload.
  631. * This path is to append to $baseWorkDir
  632. * @param int $maxFilledSpace - amount of bytes to not exceed in the base
  633. * working directory
  634. *
  635. * @return boolean true if it succeds, false otherwise
  636. */
  637. function treat_uploaded_file($uploadedFile, $baseWorkDir, $uploadPath, $maxFilledSpace, $uncompress= '')
  638. {
  639. $uploadedFile['name']=stripslashes($uploadedFile['name']);
  640. if (!enough_size($uploadedFile['size'], $baseWorkDir, $maxFilledSpace))
  641. {
  642. return api_failure::set_failure('not_enough_space');
  643. }
  644. if ($uncompress == 'unzip' && preg_match("/.zip$/", strtolower($uploadedFile['name'])) )
  645. {
  646. return unzip_uploaded_file($uploadedFile, $uploadPath, $baseWorkDir, $maxFilledSpace);
  647. }
  648. else
  649. {
  650. $fileName = trim($uploadedFile['name']);
  651. // CHECK FOR NO DESIRED CHARACTERS
  652. $fileName = replace_dangerous_char($fileName);
  653. // TRY TO ADD AN EXTENSION TO FILES WITOUT EXTENSION
  654. $fileName = add_ext_on_mime($fileName,$uploadedFile['type']);
  655. // HANDLE PHP FILES
  656. $fileName = php2phps($fileName);
  657. // COPY THE FILE TO THE DESIRED DESTINATION
  658. if(move_uploaded_file($uploadedFile['tmp_name'], $baseWorkDir.$uploadPath."/".$fileName))
  659. set_default_settings($uploadPath,$fileName);
  660. return true;
  661. }
  662. }
  663. /**
  664. * Manages all the unzipping process of an uploaded file
  665. *
  666. * @author Hugues Peeters <hugues.peeters@claroline.net>
  667. *
  668. * @param array $uploadedFile - follows the $_FILES Structure
  669. * @param string $uploadPath - destination of the upload.
  670. * This path is to append to $baseWorkDir
  671. * @param string $baseWorkDir - base working directory of the module
  672. * @param int $maxFilledSpace - amount of bytes to not exceed in the base
  673. * working directory
  674. *
  675. * @return boolean true if it succeeds false otherwise
  676. */
  677. function unzip_uploaded_file($uploadedFile, $uploadPath, $baseWorkDir, $maxFilledSpace)
  678. {
  679. $zipFile = new pclZip($uploadedFile['tmp_name']);
  680. // Check the zip content (real size and file extension)
  681. $zipContentArray = $zipFile->listContent();
  682. $okScorm=false;
  683. foreach($zipContentArray as $thisContent)
  684. {
  685. if ( preg_match('~.(php.*|phtml)$~i', $thisContent['filename']) )
  686. {
  687. return api_failure::set_failure('php_file_in_zip_file');
  688. }
  689. elseif(stristr($thisContent['filename'],'imsmanifest.xml'))
  690. {
  691. $okScorm=true;
  692. }
  693. elseif(stristr($thisContent['filename'],'LMS'))
  694. {
  695. $okPlantynScorm1=true;
  696. }
  697. elseif(stristr($thisContent['filename'],'REF'))
  698. {
  699. $okPlantynScorm2=true;
  700. }
  701. elseif(stristr($thisContent['filename'],'SCO'))
  702. {
  703. $okPlantynScorm3=true;
  704. }
  705. elseif(stristr($thisContent['filename'],'AICC'))
  706. {
  707. $okAiccScorm=true;
  708. }
  709. $realFileSize += $thisContent['size'];
  710. }
  711. if ((($okPlantynScorm1==true) and ($okPlantynScorm2==true) and ($okPlantynScorm3==true)) or ($okAiccScorm==true))
  712. {
  713. $okScorm=true;
  714. }
  715. if(!$okScorm && defined('CHECK_FOR_SCORM') && CHECK_FOR_SCORM)
  716. {
  717. return api_failure::set_failure('not_scorm_content');
  718. }
  719. if (! enough_size($realFileSize, $baseWorkDir, $maxFilledSpace) )
  720. {
  721. return api_failure::set_failure('not_enough_space');
  722. }
  723. // it happens on Linux that $uploadPath sometimes doesn't start with '/'
  724. if($uploadPath[0] != '/')
  725. {
  726. $uploadPath='/'.$uploadPath;
  727. }
  728. if($uploadPath[strlen($uploadPath)-1] == '/')
  729. {
  730. $uploadPath=substr($uploadPath,0,-1);
  731. }
  732. /*
  733. --------------------------------------
  734. Uncompressing phase
  735. --------------------------------------
  736. */
  737. /*
  738. The first version, using OS unzip, is not used anymore
  739. because it does not return enough information.
  740. We need to process each individual file in the zip archive to
  741. - add it to the database
  742. - parse & change relative html links
  743. */
  744. if (PHP_OS == 'Linux' && ! get_cfg_var('safe_mode') && false) // *** UGent, changed by OC ***
  745. {
  746. // Shell Method - if this is possible, it gains some speed
  747. exec("unzip -d \"".$baseWorkDir.$uploadPath."/\"".$uploadedFile['name']." "
  748. .$uploadedFile['tmp_name']);
  749. }
  750. else
  751. {
  752. // PHP method - slower...
  753. $save_dir = getcwd();
  754. chdir($baseWorkDir.$uploadPath);
  755. $unzippingState = $zipFile->extract();
  756. for($j=0;$j<count($unzippingState);$j++)
  757. {
  758. $state=$unzippingState[$j];
  759. //fix relative links in html files
  760. $extension = strrchr($state["stored_filename"], ".");
  761. }
  762. if($dir=@opendir($baseWorkDir.$uploadPath))
  763. {
  764. while($file=readdir($dir))
  765. {
  766. if($file != '.' && $file != '..')
  767. {
  768. $filetype="file";
  769. if(is_dir($baseWorkDir.$uploadPath.'/'.$file)) $filetype="folder";
  770. $safe_file=replace_dangerous_char($file,'strict');
  771. @rename($baseWorkDir.$uploadPath.'/'.$file,$baseWorkDir.$uploadPath.'/'.$safe_file);
  772. set_default_settings($uploadPath,$safe_file,$filetype);
  773. }
  774. }
  775. closedir($dir);
  776. }
  777. chdir($save_dir); //back to previous dir position
  778. }
  779. return true;
  780. }
  781. //------------------------------------------------------------------------------
  782. /**
  783. * Manages all the unzipping process of an uploaded document
  784. * This uses the item_property table for properties of documents
  785. *
  786. * @author Hugues Peeters <hugues.peeters@claroline.net>
  787. * @author Bert Vanderkimpen
  788. *
  789. * @param array $uploadedFile - follows the $_FILES Structure
  790. * @param string $uploadPath - destination of the upload.
  791. * This path is to append to $baseWorkDir
  792. * @param string $baseWorkDir - base working directory of the module
  793. * @param int $maxFilledSpace - amount of bytes to not exceed in the base
  794. * working directory
  795. * @param boolean Output switch. Optional. If no output not wanted on success, set to false.
  796. *
  797. * @return boolean true if it succeeds false otherwise
  798. */
  799. function unzip_uploaded_document($uploaded_file, $upload_path, $base_work_dir, $max_filled_space, $output = true, $to_group_id=0)
  800. {
  801. global $_course;
  802. global $_user;
  803. global $to_user_id;
  804. global $to_group_id;
  805. $zip_file = new pclZip($uploaded_file['tmp_name']);
  806. // Check the zip content (real size and file extension)
  807. $zip_content_array = $zip_file->listContent();
  808. foreach((array) $zip_content_array as $this_content)
  809. {
  810. $real_filesize += $this_content['size'];
  811. }
  812. if (! enough_space($real_filesize, $max_filled_space) )
  813. {
  814. Display::display_error_message(get_lang('UplNotEnoughSpace'));
  815. return false;
  816. }
  817. // it happens on Linux that $uploadPath sometimes doesn't start with '/'
  818. if($upload_path[0] != '/')
  819. {
  820. $upload_path='/'.$upload_path;
  821. }
  822. /*
  823. --------------------------------------
  824. Uncompressing phase
  825. --------------------------------------
  826. */
  827. //get into the right directory
  828. $save_dir = getcwd();
  829. chdir($base_work_dir.$upload_path);
  830. //we extract using a callback function that "cleans" the path
  831. $unzipping_state = $zip_file->extract(PCLZIP_CB_PRE_EXTRACT, 'clean_up_files_in_zip');
  832. // Add all documents in the unzipped folder to the database
  833. add_all_documents_in_folder_to_database($_course,$_user['user_id'],$base_work_dir,$upload_path == '/' ? '' : $upload_path, $to_group_id);
  834. //Display::display_normal_message(get_lang('UplZipExtractSuccess'));
  835. return true;
  836. /*
  837. if ($upload_path != '/')
  838. $upload_path = $upload_path.'/';
  839. if($unzipping_state!=0)
  840. {
  841. for($j=0;$j<count($unzipping_state);$j++)
  842. {
  843. $state=$unzipping_state[$j];
  844. $filename = $state['stored_filename'];
  845. //echo("<br>filename = ".$filename."<br>");
  846. $filename2 = $state['filename'];
  847. //echo("<br>filename2 = ".$filename2."<br>");
  848. $filetype="file";
  849. //if(is_dir($filename))
  850. if($state['folder']==1)
  851. {
  852. $filetype="folder";
  853. $endchar=substr($filename,strlen($filename)-1,1);
  854. if($endchar=="\\" || $endchar=="/")
  855. $filename=substr($filename,0,strlen($filename)-1);
  856. }
  857. //store document in database
  858. if($state['status']=="ok" || $state['status']=="already_a_directory")
  859. {
  860. //echo $base_work_dir.$upload_path.clean_up_path($state["stored_filename"])." (".$filetype.")<br/>";
  861. $cleaned_up_filename = clean_up_path($filename);
  862. $file_path = $upload_path.$cleaned_up_filename;
  863. echo("file path = ".$file_path."<br>");
  864. //this is a quick fix for zipfiles that have files in folders but the folder is not stored in the zipfile
  865. //if the path has folders, check if they already are in the database
  866. if(dirname('/'.$cleaned_up_filename)!='/' AND dirname('/'.$cleaned_up_filename)!='\\')
  867. {
  868. $folder_id=DocumentManager::get_document_id($_course,$upload_path.dirname($cleaned_up_filename));
  869. if(!$folder_id)
  870. {
  871. echo($upload_path.dirname($cleaned_up_filename).' not found in database!<br>');
  872. $folder_id = add_document($_course,$upload_path.dirname($cleaned_up_filename),'folder',0,basename(dirname($cleaned_up_filename)));
  873. if($folder_id)
  874. {
  875. api_item_property_update($_course,TOOL_DOCUMENT,$folder_id,'FolderAdded',$_user['user_id'],$to_group_id,$to_user_id);
  876. //echo('folder '.$upload_path.dirname($cleaned_up_filename)." added<br>\n");
  877. }
  878. }
  879. }
  880. $store_path = $base_work_dir.$file_path;
  881. //echo("store path = ".$store_path."<br>");
  882. $document_name = get_document_title(basename($filename));
  883. //echo("document_name = ".$document_name."<br><br>");
  884. //put the document data in the database
  885. //if the file/dir does not exist, just add it
  886. //if(!file_exists($store_path)) <- not working, as the file is already extracted
  887. //so we check if the document is already in the database
  888. $document_id = DocumentManager::get_document_id($_course,$file_path);
  889. if(!$document_id)
  890. {
  891. $document_id = add_document($_course,$file_path,$filetype,$state['size'],$document_name);
  892. if ($document_id)
  893. {
  894. $lastedit_type = ($filetype=='folder')?'FolderAdded':'DocumentAdded';
  895. //update item property for document
  896. api_item_property_update($_course,TOOL_DOCUMENT,$document_id,$lastedit_type,$_user['user_id'],$to_group_id,$to_user_id);
  897. }
  898. }
  899. //file/dir exists -> update
  900. else
  901. {
  902. $lastedit_type = ($filetype=='folder')?'FolderUpdated':'DocumentUpdated';
  903. //update the document in item_property
  904. api_item_property_update($_course,TOOL_DOCUMENT,$document_id,$lastedit_type,$_user['user_id'],$to_group_id,$to_user_id);
  905. }
  906. }
  907. }
  908. //print_r_pre($zip_content_array);
  909. //if the file is in a folder, we need to update all parent folders
  910. item_property_update_on_folder($_course,$upload_path,$_user['user_id']);
  911. //display success message to user
  912. chdir($save_dir); //return to previous dir position
  913. if($output){
  914. Display::display_normal_message(get_lang('UplZipExtractSuccess'));
  915. }
  916. return true;
  917. }
  918. else {
  919. //zip file could not be extracted -> corrupt file
  920. Display::display_error_message(get_lang('UplZipCorrupt'));
  921. return false;
  922. }
  923. */
  924. }
  925. //------------------------------------------------------------------------------
  926. /**
  927. * this function is a callback function that is used while extracting a zipfile
  928. * http://www.phpconcept.net/pclzip/man/en/index.php?options-pclzip_cb_pre_extract
  929. *
  930. * @param $p_event
  931. * @param $p_header
  932. * @return 1 (If the function returns 1, then the extraction is resumed)
  933. */
  934. function clean_up_files_in_zip($p_event, &$p_header)
  935. {
  936. $res = clean_up_path($p_header['filename']);
  937. return $res;
  938. }
  939. //------------------------------------------------------------------------------
  940. /**
  941. * this function cleans up a given path
  942. * by eliminating dangerous file names and cleaning them
  943. *
  944. * @param string $path
  945. * @return $path
  946. * @see disable_dangerous_file()
  947. * @see replace_dangerous_char()
  948. */
  949. function clean_up_path(&$path)
  950. {
  951. //split the path in folders and files
  952. $path_array = explode('/',$path);
  953. //clean up every foler and filename in the path
  954. $val = '';
  955. foreach($path_array as $key => $val)
  956. {
  957. //we don't want to lose the dots in ././folder/file (cfr. zipfile)
  958. if($path_array[$key]!='.')
  959. $path_array[$key] = disable_dangerous_file( replace_dangerous_char($val) );
  960. }
  961. //join the "cleaned" path (modified in-place as passed by reference)
  962. $path = implode('/',$path_array);
  963. $res = filter_extension($path);
  964. return $res;
  965. }
  966. /**
  967. * Check if the file is dangerous, based on extension and/or mimetype.
  968. * The list of extensions accepted/rejected can be found from
  969. * api_get_setting('upload_extensions_exclude') and api_get_setting('upload_extensions_include')
  970. * @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')
  971. * @return int 0 to skip file, 1 to keep file
  972. */
  973. function filter_extension(&$filename)
  974. {
  975. if(substr($filename,-1)=='/'){return 1;} //authorize directories
  976. $blacklist = api_get_setting('upload_extensions_list_type');
  977. if($blacklist!='whitelist')//if = blacklist
  978. {
  979. $extensions = split(';',strtolower(api_get_setting('upload_extensions_blacklist')));
  980. $skip = api_get_setting('upload_extensions_skip');
  981. $ext = strrchr($filename, ".");
  982. $ext = substr($ext,1);
  983. if(empty($ext)){return 1;}//we're in blacklist mode, so accept empty extensions
  984. if(in_array(strtolower($ext),$extensions))
  985. {
  986. if($skip=='true')
  987. {
  988. return 0;
  989. }
  990. else
  991. {
  992. $new_ext = api_get_setting('upload_extensions_replace_by');
  993. $filename = str_replace(".".$ext,".".$new_ext,$filename);
  994. return 1;
  995. }
  996. }
  997. else
  998. {
  999. return 1;
  1000. }
  1001. }
  1002. else
  1003. {
  1004. $extensions = split(';',strtolower(api_get_setting('upload_extensions_whitelist')));
  1005. $skip = api_get_setting('upload_extensions_skip');
  1006. $ext = strrchr($filename, ".");
  1007. $ext = substr($ext,1);
  1008. if(empty($ext)){return 1;}//accept empty extensions
  1009. if(!in_array(strtolower($ext),$extensions))
  1010. {
  1011. if($skip=='true')
  1012. {
  1013. return 0;
  1014. }
  1015. else
  1016. {
  1017. $new_ext = api_get_setting('upload_extensions_replace_by');
  1018. $filename = str_replace(".".$ext,".".$new_ext,$filename);
  1019. return 1;
  1020. }
  1021. }
  1022. else
  1023. {
  1024. return 1;
  1025. }
  1026. }
  1027. }
  1028. //------------------------------------------------------------------------------
  1029. /**
  1030. * Adds a new document to the database
  1031. *
  1032. * @param array $_course
  1033. * @param string $path
  1034. * @param string $filetype
  1035. * @param int $filesize
  1036. * @param string $title
  1037. * @return id if inserted document
  1038. */
  1039. function add_document($_course,$path,$filetype,$filesize,$title,$comment=NULL, $readonly=0)
  1040. {
  1041. global $charset;
  1042. $table_document = Database::get_course_table(TABLE_DOCUMENT,$_course['dbName']);
  1043. $sql="INSERT INTO $table_document
  1044. (`path`,`filetype`,`size`,`title`, `comment`, readonly)
  1045. VALUES ('$path','$filetype','$filesize','".
  1046. Database::escape_string(htmlspecialchars($title, ENT_QUOTES, $charset))."', '$comment',$readonly)";
  1047. if(api_sql_query($sql,__FILE__,__LINE__))
  1048. {
  1049. //display_message("Added to database (id ".mysql_insert_id().")!");
  1050. return Database::insert_id();
  1051. }
  1052. else
  1053. {
  1054. //display_error("The uploaded file could not be added to the database (".mysql_error().")!");
  1055. return false;
  1056. }
  1057. }
  1058. //------------------------------------------------------------------------------
  1059. /*
  1060. function get_document_id() moved to document.lib.php
  1061. */
  1062. //------------------------------------------------------------------------------
  1063. /**
  1064. * Update an existing document in the database
  1065. * as the file exists, we only need to change the size
  1066. *
  1067. * @param array $_course
  1068. * @param int $document_id
  1069. * @param int $filesize
  1070. * @param int $readonly
  1071. * @return boolean true /false
  1072. */
  1073. function update_existing_document($_course,$document_id,$filesize,$readonly=0)
  1074. {
  1075. $document_table = Database::get_course_table(TABLE_DOCUMENT,$_course['dbName']);
  1076. $sql="UPDATE $document_table SET size = '$filesize' , readonly = '$readonly' WHERE id='$document_id'";
  1077. if(api_sql_query($sql,__FILE__,__LINE__))
  1078. {
  1079. return true;
  1080. }
  1081. else
  1082. {
  1083. return false;
  1084. }
  1085. }
  1086. /**
  1087. * this function updates the last_edit_date, last edit user id on all folders in a given path
  1088. *
  1089. * @param array $_course
  1090. * @param string $path
  1091. * @param int $user_id
  1092. */
  1093. function item_property_update_on_folder($_course,$path,$user_id)
  1094. {
  1095. //display_message("Start update_lastedit_on_folder");
  1096. //if we are in the root, just return... no need to update anything
  1097. if ($path=='/')
  1098. return;
  1099. //if the given path ends with a / we remove it
  1100. $endchar=substr($path,strlen($path)-1,1);
  1101. if($endchar=='/')
  1102. $path=substr($path,0,strlen($path)-1);
  1103. $TABLE_ITEMPROPERTY = Database::get_course_table(TABLE_ITEM_PROPERTY,$_course['dbName']);
  1104. //get the time
  1105. $time = date("Y-m-d H:i:s", time());
  1106. //get all paths in the given path
  1107. // /folder/subfolder/subsubfolder/file
  1108. // if file is updated, subsubfolder, subfolder and folder are updated
  1109. $exploded_path = explode('/',$path);
  1110. foreach ($exploded_path as $key => $value) {
  1111. //we don't want a slash before our first slash
  1112. if($key!=0){
  1113. $newpath .= "/".$value;
  1114. //echo "path= ".$newpath."<br>";
  1115. //select ID of given folder
  1116. $folder_id = DocumentManager::get_document_id($_course,$newpath);
  1117. if($folder_id)
  1118. {
  1119. $sql = "UPDATE $TABLE_ITEMPROPERTY SET `lastedit_date`='$time',`lastedit_type`='DocumentInFolderUpdated', `lastedit_user_id`='$user_id' WHERE tool='".TOOL_DOCUMENT."' AND ref='$folder_id'";
  1120. api_sql_query($sql,__FILE__,__LINE__);
  1121. }
  1122. }
  1123. }
  1124. }
  1125. //------------------------------------------------------------------------------
  1126. /**
  1127. * Returns the directory depth of the file.
  1128. *
  1129. * @author Olivier Cauberghe <olivier.cauberghe@ugent.be>
  1130. * @param path+filename eg: /main/document/document.php
  1131. * @return The directory depth
  1132. */
  1133. function get_levels($filename)
  1134. {
  1135. $levels=explode("/",$filename);
  1136. if(empty($levels[count($levels)-1])) unset($levels[count($levels)-1]);
  1137. return count($levels);
  1138. }
  1139. /*
  1140. function file_set_default_settings
  1141. moved to fileManage.lib.php,
  1142. class FileManager
  1143. */
  1144. //------------------------------------------------------------------------------
  1145. /**
  1146. * Adds file to document table in database
  1147. * @deprecated, use file_set_default_settings instead
  1148. *
  1149. * @author Olivier Cauberghe <olivier.cauberghe@ugent.be>
  1150. * @param path,filename
  1151. * @action Adds an entry to the document table with the default settings.
  1152. */
  1153. function set_default_settings($upload_path,$filename,$filetype="file")
  1154. {
  1155. global $dbTable,$_configuration;
  1156. global $default_visibility;
  1157. if (!$default_visibility)
  1158. $default_visibility="v";
  1159. $upload_path=str_replace('\\','/',$upload_path);
  1160. $upload_path=str_replace("//","/",$upload_path);
  1161. if($upload_path == '/')
  1162. {
  1163. $upload_path='';
  1164. }
  1165. elseif(!empty($upload_path) && $upload_path[0] != '/')
  1166. {
  1167. $upload_path="/$upload_path";
  1168. }
  1169. $endchar=substr($filename,strlen($filename)-1,1);
  1170. if($endchar == '/')
  1171. {
  1172. $filename=substr($filename,0,-1);
  1173. }
  1174. //$dbTable already has `backticks`!
  1175. //$query="select count(*) as bestaat from `$dbTable` where path='$upload_path/$filename'";
  1176. $query="select count(*) as bestaat from $dbTable where path='$upload_path/$filename'";
  1177. $result=api_sql_query($query,__FILE__,__LINE__);
  1178. $row=mysql_fetch_array($result);
  1179. if($row["bestaat"]>0)
  1180. //$query="update `$dbTable` set path='$upload_path/$filename',visibility='$default_visibility', filetype='$filetype' where path='$upload_path/$filename'";
  1181. $query="update $dbTable set path='$upload_path/$filename',visibility='$default_visibility', filetype='$filetype' where path='$upload_path/$filename'";
  1182. else //$query="INSERT INTO `$dbTable` (path,visibility,filetype) VALUES('$upload_path/$filename','$default_visibility','$filetype')";
  1183. $query="INSERT INTO $dbTable (path,visibility,filetype) VALUES('$upload_path/$filename','$default_visibility','$filetype')";
  1184. api_sql_query($query,__FILE__,__LINE__);
  1185. }
  1186. //------------------------------------------------------------------------------
  1187. /**
  1188. * retrieve the image path list in a html file
  1189. *
  1190. * @author Hugues Peeters <hugues.peeters@claroline.net>
  1191. * @param string $htmlFile
  1192. * @return array - images path list
  1193. */
  1194. function search_img_from_html($htmlFile)
  1195. {
  1196. $imgFilePath = array();
  1197. $fp = fopen($htmlFile, "r") or die('<center>can not open file</center>');
  1198. // search and store occurences of the <IMG> tag in an array
  1199. $size_file=(filesize($htmlFile)===0) ? 1 : filesize($htmlFile);
  1200. if (isset($fp) && !($fp===false)) {
  1201. $buffer = fread( $fp, $size_file );
  1202. if (strlen($buffer)>=0 && !($buffer===false)) {
  1203. //
  1204. } else {
  1205. die('<center>Can not read file.</center>');
  1206. }
  1207. } else {
  1208. die('<center>Can not read file.</center>');
  1209. }
  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="_self" 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="_self"
  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=\"_self\"";
  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 =\"_self\"";
  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="_self"
  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="_self"
  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=\"_self\" ";
  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=_self: ";
  1569. $replaceBy[$count] = " $param_name=\"" . $file_path_list[$count] . "\" target =\"_self\"";
  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. ."<button type='submit' name=\"cancel_submit_image\" value=\"".get_lang('Cancel')."\" class=\"cancel\">".get_lang('Cancel')."</button>"
  1635. ."<button type='submit' name=\"submit_image\" value=\"".get_lang('Ok')."\" class=\"save\">".get_lang('Ok')."</button>"
  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. ?>