fileUpload.lib.php 61 KB

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