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