fileUpload.lib.php 61 KB

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