fileUpload.lib.php 74 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113
  1. <?php
  2. /* For licensing terms, see /license.txt */
  3. /**
  4. * FILE UPLOAD LIBRARY
  5. *
  6. * This is the file upload library for Chamilo.
  7. * Include/require it in your code to use its functionality.
  8. *
  9. * @package chamilo.library
  10. * @todo test and reorganise
  11. */
  12. /**
  13. * Changes the file name extension from .php to .phps
  14. * Useful for securing a site.
  15. *
  16. * @author - Hugues Peeters <peeters@ipm.ucl.ac.be>
  17. * @param - file_name (string) name of a file
  18. * @return - the filenam phps'ized
  19. */
  20. function php2phps($file_name) {
  21. return preg_replace('/\.(php.?|phtml.?)(\.){0,1}.*$/i', '.phps', $file_name);
  22. }
  23. /**
  24. * Renames .htaccess & .HTACCESS to htaccess.txt
  25. *
  26. * @param string $filename
  27. * @return string
  28. */
  29. function htaccess2txt($filename) {
  30. return str_replace(array('.htaccess', '.HTACCESS'), array('htaccess.txt', 'htaccess.txt'), $filename);
  31. }
  32. /**
  33. * This function executes our safety precautions
  34. * more functions can be added
  35. *
  36. * @param string $filename
  37. * @return string
  38. * @see php2phps()
  39. * @see htaccess2txt()
  40. */
  41. function disable_dangerous_file($filename) {
  42. return htaccess2txt(php2phps($filename));
  43. }
  44. /**
  45. * This function generates a unique name for a file on a given location
  46. * file names are changed to name_#.ext
  47. *
  48. * @param string $path
  49. * @param string $name
  50. *
  51. * @deprecated
  52. *
  53. * @return string new unique name
  54. */
  55. function unique_name($path, $name)
  56. {
  57. $ext = substr(strrchr($name, '.'), 0);
  58. $name_no_ext = substr($name, 0, strlen($name) - strlen(strstr($name, $ext)));
  59. $n = 0;
  60. $unique = '';
  61. while (file_exists($path . $name_no_ext . $unique . $ext)) {
  62. $unique = '_' . ++$n;
  63. }
  64. return $name_no_ext . $unique . $ext;
  65. }
  66. /**
  67. * Returns the name without extension, used for the title
  68. *
  69. * @param string $name
  70. * @return name without the extension
  71. */
  72. function get_document_title($name) {
  73. // If they upload .htaccess...
  74. $name = disable_dangerous_file($name);
  75. $ext = substr(strrchr($name, '.'), 0);
  76. return substr($name, 0, strlen($name) - strlen(strstr($name, $ext)));
  77. }
  78. /**
  79. * This function checks if the upload succeeded
  80. *
  81. * @param array $uploaded_file ($_FILES)
  82. * @return true if upload succeeded
  83. */
  84. function process_uploaded_file($uploaded_file, $show_output = true)
  85. {
  86. // Checking the error code sent with the file upload.
  87. if (isset($uploaded_file['error'])) {
  88. switch ($uploaded_file['error']) {
  89. case 1:
  90. // The uploaded file exceeds the upload_max_filesize directive in php.ini.
  91. if ($show_output) {
  92. Display::display_error_message(get_lang('UplExceedMaxServerUpload').ini_get('upload_max_filesize'));
  93. }
  94. return false;
  95. case 2:
  96. // The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.
  97. // 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).
  98. $max_file_size = intval($_POST['MAX_FILE_SIZE']);
  99. if ($show_output) {
  100. Display::display_error_message(get_lang('UplExceedMaxPostSize'). format_file_size($max_file_size));
  101. }
  102. return false;
  103. case 3:
  104. // The uploaded file was only partially uploaded.
  105. if ($show_output) {
  106. Display::display_error_message(get_lang('UplPartialUpload').' '.get_lang('PleaseTryAgain'));
  107. }
  108. return false;
  109. case 4:
  110. // No file was uploaded.
  111. if ($show_output) {
  112. Display::display_error_message(get_lang('UplNoFileUploaded').' '. get_lang('UplSelectFileFirst'));
  113. }
  114. return false;
  115. }
  116. }
  117. if (!file_exists($uploaded_file['tmp_name'])) {
  118. // No file was uploaded.
  119. if ($show_output) {
  120. Display::display_error_message(get_lang('UplUploadFailed'));
  121. }
  122. return false;
  123. }
  124. if (file_exists($uploaded_file['tmp_name'])) {
  125. $filesize = filesize($uploaded_file['tmp_name']);
  126. if (empty($filesize)) {
  127. // No file was uploaded.
  128. if ($show_output) {
  129. Display::display_error_message(get_lang('UplUploadFailedSizeIsZero'));
  130. }
  131. return false;
  132. }
  133. }
  134. $course_id = api_get_course_id();
  135. //Checking course quota if we are in a course
  136. if (!empty($course_id)) {
  137. $max_filled_space = DocumentManager::get_course_quota();
  138. // Check if there is enough space to save the file
  139. if (!DocumentManager::enough_space($uploaded_file['size'], $max_filled_space)) {
  140. if ($show_output) {
  141. Display::display_error_message(get_lang('UplNotEnoughSpace'));
  142. }
  143. return false;
  144. }
  145. }
  146. // case 0: default: We assume there is no error, the file uploaded with success.
  147. return true;
  148. }
  149. /**
  150. * This function does the save-work for the documents.
  151. * It handles the uploaded file and adds the properties to the database
  152. * If unzip=1 and the file is a zipfile, it is extracted
  153. * If we decide to save ALL kinds of documents in one database,
  154. * we could extend this with a $type='document', 'scormdocument',...
  155. *
  156. * @param array $courseInfo
  157. * @param array $uploadedFile ($_FILES)
  158. * array(
  159. * 'name' => 'picture.jpg',
  160. * 'tmp_name' => '...', // absolute path
  161. * );
  162. * @param string $documentDir Example: /var/www/chamilo/courses/ABC/document
  163. * @param string $uploadPath Example: /folder1/folder2/
  164. * @param int $userId
  165. * @param int $groupId, 0 for everybody
  166. * @param int $toUserId, NULL for everybody
  167. * @param int $unzip 1/0
  168. * @param string $whatIfFileExists overwrite, rename or warn if exists (default)
  169. * @param boolean $output Optional output parameter.
  170. * @param bool $onlyUploadFile
  171. * @param string $comment
  172. * @param int $sessionId
  173. *
  174. * So far only use for unzip_uploaded_document function.
  175. * If no output wanted on success, set to false.
  176. * @param string $comment
  177. * @return string path of the saved file
  178. */
  179. function handle_uploaded_document(
  180. $courseInfo,
  181. $uploadedFile,
  182. $documentDir,
  183. $uploadPath,
  184. $userId,
  185. $groupId = 0,
  186. $toUserId = null,
  187. $unzip = 0,
  188. $whatIfFileExists = '',
  189. $output = true,
  190. $onlyUploadFile = false,
  191. $comment = null,
  192. $sessionId = null
  193. ) {
  194. if (!$userId) {
  195. return false;
  196. }
  197. $userInfo = api_get_user_info();
  198. $uploadedFile['name'] = stripslashes($uploadedFile['name']);
  199. // Add extension to files without one (if possible)
  200. $uploadedFile['name'] = add_ext_on_mime($uploadedFile['name'], $uploadedFile['type']);
  201. if (empty($sessionId)) {
  202. $sessionId = api_get_session_id();
  203. } else {
  204. $sessionId = intval($sessionId);
  205. }
  206. // Just in case process_uploaded_file is not called
  207. $maxSpace = DocumentManager::get_course_quota();
  208. // Check if there is enough space to save the file
  209. if (!DocumentManager::enough_space($uploadedFile['size'], $maxSpace)) {
  210. if ($output) {
  211. Display::display_error_message(get_lang('UplNotEnoughSpace'));
  212. }
  213. return false;
  214. }
  215. // If the want to unzip, check if the file has a .zip (or ZIP,Zip,ZiP,...) extension
  216. if ($unzip == 1 && preg_match('/.zip$/', strtolower($uploadedFile['name']))) {
  217. return unzip_uploaded_document(
  218. $courseInfo,
  219. $userInfo,
  220. $uploadedFile,
  221. $uploadPath,
  222. $documentDir,
  223. $maxSpace,
  224. $sessionId,
  225. $groupId,
  226. $output
  227. );
  228. } elseif ($unzip == 1 && !preg_match('/.zip$/', strtolower($uploadedFile['name']))) {
  229. // We can only unzip ZIP files (no gz, tar,...)
  230. if ($output) {
  231. Display::display_error_message(
  232. get_lang('UplNotAZip')." ".get_lang('PleaseTryAgain')
  233. );
  234. }
  235. return false;
  236. } else {
  237. // Clean up the name, only ASCII characters should stay. (and strict)
  238. $cleanName = api_replace_dangerous_char($uploadedFile['name'], 'strict');
  239. // No "dangerous" files
  240. $cleanName = disable_dangerous_file($cleanName);
  241. // Checking file extension
  242. if (!filter_extension($cleanName)) {
  243. if ($output) {
  244. Display::display_error_message(
  245. get_lang('UplUnableToSaveFileFilteredExtension')
  246. );
  247. }
  248. return false;
  249. } else {
  250. // If the upload path differs from / (= root) it will need a slash at the end
  251. if ($uploadPath != '/') {
  252. $uploadPath = $uploadPath.'/';
  253. }
  254. // Full path to where we want to store the file with trailing slash
  255. $whereToSave = $documentDir.$uploadPath;
  256. // At least if the directory doesn't exist, tell so
  257. if (!is_dir($whereToSave)) {
  258. if (!mkdir($whereToSave, api_get_permissions_for_new_directories())) {
  259. if ($output) {
  260. Display::display_error_message(
  261. get_lang('DestDirectoryDoesntExist').' ('.$uploadPath.')'
  262. );
  263. }
  264. return false;
  265. }
  266. }
  267. // Just upload the file "as is"
  268. if ($onlyUploadFile) {
  269. $errorResult = moveUploadedFile($uploadedFile, $whereToSave.$cleanName);
  270. if ($errorResult) {
  271. return $whereToSave.$cleanName;
  272. } else {
  273. return $errorResult;
  274. }
  275. }
  276. /*
  277. Based in the clean name we generate a new filesystem name
  278. Using the session_id and group_id if values are not empty
  279. */
  280. /*$fileExists = DocumentManager::documentExists(
  281. $uploadPath.$cleanName,
  282. $courseInfo,
  283. $sessionId,
  284. $groupId
  285. );*/
  286. $fileSystemName = DocumentManager::fixDocumentName(
  287. $cleanName,
  288. 'file',
  289. $courseInfo,
  290. $sessionId,
  291. $groupId
  292. );
  293. // Name of the document without the extension (for the title)
  294. $documentTitle = get_document_title($uploadedFile['name']);
  295. // Size of the uploaded file (in bytes)
  296. $fileSize = $uploadedFile['size'];
  297. // File permissions
  298. $filePermissions = api_get_permissions_for_new_files();
  299. // Example: /var/www/chamilo/courses/xxx/document/folder/picture.jpg
  300. $fullPath = $whereToSave.$fileSystemName;
  301. // Example: /folder/picture.jpg
  302. $filePath = $uploadPath.$fileSystemName;
  303. $docId = DocumentManager::get_document_id(
  304. $courseInfo,
  305. $filePath,
  306. $sessionId
  307. );
  308. $documentList = DocumentManager::getDocumentByPathInCourse(
  309. $courseInfo,
  310. $filePath //$filePath
  311. );
  312. // This means that the path already exists in this course.
  313. if (!empty($documentList) && $whatIfFileExists != 'overwrite') {
  314. //$found = false;
  315. // Checking if we are talking about the same course + session
  316. /*foreach ($documentList as $document) {
  317. if ($document['session_id'] == $sessionId) {
  318. $found = true;
  319. break;
  320. }
  321. }*/
  322. //if ($found == false) {
  323. $whatIfFileExists = 'rename';
  324. //}
  325. }
  326. // What to do if the target file exists
  327. switch ($whatIfFileExists) {
  328. // Overwrite the file if it exists
  329. case 'overwrite':
  330. // Check if the target file exists, so we can give another message
  331. $fileExists = file_exists($fullPath);
  332. if (moveUploadedFile($uploadedFile, $fullPath)) {
  333. chmod($fullPath, $filePermissions);
  334. if ($fileExists && $docId) {
  335. // UPDATE DATABASE
  336. $documentId = DocumentManager::get_document_id(
  337. $courseInfo,
  338. $filePath
  339. );
  340. if (is_numeric($documentId)) {
  341. // Update file size
  342. update_existing_document(
  343. $courseInfo,
  344. $documentId,
  345. $uploadedFile['size']
  346. );
  347. // Update document item_property
  348. api_item_property_update(
  349. $courseInfo,
  350. TOOL_DOCUMENT,
  351. $documentId,
  352. 'DocumentUpdated',
  353. $userId,
  354. $groupId,
  355. $toUserId,
  356. null,
  357. null,
  358. $sessionId
  359. );
  360. // Redo visibility
  361. api_set_default_visibility(TOOL_DOCUMENT, $documentId);
  362. } else {
  363. // There might be cases where the file exists on disk but there is no registration of that in the database
  364. // In this case, and if we are in overwrite mode, overwrite and create the db record
  365. $documentId = add_document(
  366. $courseInfo,
  367. $filePath,
  368. 'file',
  369. $fileSize,
  370. $documentTitle,
  371. $comment,
  372. 0,
  373. true,
  374. $groupId,
  375. $sessionId
  376. );
  377. if ($documentId) {
  378. // Put the document in item_property update
  379. api_item_property_update(
  380. $courseInfo,
  381. TOOL_DOCUMENT,
  382. $documentId,
  383. 'DocumentAdded',
  384. $userId,
  385. $groupId,
  386. $toUserId,
  387. null,
  388. null,
  389. $sessionId
  390. );
  391. // Redo visibility
  392. api_set_default_visibility(TOOL_DOCUMENT, $documentId);
  393. }
  394. }
  395. // If the file is in a folder, we need to update all parent folders
  396. item_property_update_on_folder($courseInfo, $uploadPath, $userId);
  397. // Display success message with extra info to user
  398. if ($output) {
  399. Display::display_confirmation_message(
  400. get_lang('UplUploadSucceeded') . '<br /> ' . $documentTitle . ' ' . get_lang('UplFileOverwritten'),
  401. false
  402. );
  403. }
  404. return $filePath;
  405. } else {
  406. // Put the document data in the database
  407. $documentId = add_document(
  408. $courseInfo,
  409. $filePath,
  410. 'file',
  411. $fileSize,
  412. $documentTitle,
  413. $comment,
  414. 0,
  415. true,
  416. $groupId,
  417. $sessionId
  418. );
  419. if ($documentId) {
  420. // Put the document in item_property update
  421. api_item_property_update(
  422. $courseInfo,
  423. TOOL_DOCUMENT,
  424. $documentId,
  425. 'DocumentAdded',
  426. $userId,
  427. $groupId,
  428. $toUserId,
  429. null,
  430. null,
  431. $sessionId
  432. );
  433. // Redo visibility
  434. api_set_default_visibility(TOOL_DOCUMENT, $documentId);
  435. }
  436. // If the file is in a folder, we need to update all parent folders
  437. item_property_update_on_folder($courseInfo, $uploadPath, $userId);
  438. // Display success message to user
  439. if ($output) {
  440. Display::display_confirmation_message(get_lang('UplUploadSucceeded').'<br /> '.$documentTitle, false);
  441. }
  442. return $filePath;
  443. }
  444. } else {
  445. if ($output) {
  446. Display::display_error_message(get_lang('UplUnableToSaveFile'));
  447. }
  448. return false;
  449. }
  450. break;
  451. // Rename the file if it exists
  452. case 'rename':
  453. // Always rename.
  454. $cleanName = DocumentManager::getUniqueFileName(
  455. $uploadPath,
  456. $cleanName,
  457. $courseInfo,
  458. $sessionId,
  459. $groupId
  460. );
  461. $fileSystemName = DocumentManager::fixDocumentName(
  462. $cleanName,
  463. 'file',
  464. $courseInfo,
  465. $sessionId,
  466. $groupId
  467. );
  468. $documentTitle = get_document_title($cleanName);
  469. $fullPath = $whereToSave.$fileSystemName;
  470. $filePath = $uploadPath.$fileSystemName;
  471. if (moveUploadedFile($uploadedFile, $fullPath)) {
  472. chmod($fullPath, $filePermissions);
  473. // Put the document data in the database
  474. $documentId = add_document(
  475. $courseInfo,
  476. $filePath,
  477. 'file',
  478. $fileSize,
  479. $documentTitle,
  480. $comment, // comment
  481. 0, // read only
  482. true, // save visibility
  483. $groupId,
  484. $sessionId
  485. );
  486. if ($documentId) {
  487. // Update document item_property
  488. api_item_property_update(
  489. $courseInfo,
  490. TOOL_DOCUMENT,
  491. $documentId,
  492. 'DocumentAdded',
  493. $userId,
  494. $groupId,
  495. $toUserId,
  496. null,
  497. null,
  498. $sessionId
  499. );
  500. // Redo visibility
  501. api_set_default_visibility(TOOL_DOCUMENT, $documentId);
  502. }
  503. // If the file is in a folder, we need to update all parent folders
  504. item_property_update_on_folder($courseInfo, $uploadPath, $userId);
  505. // Display success message to user
  506. if ($output) {
  507. Display::display_confirmation_message(
  508. get_lang('UplUploadSucceeded') . '<br />' . get_lang('UplFileSavedAs') .' '.$documentTitle,
  509. false
  510. );
  511. }
  512. return $filePath;
  513. } else {
  514. if ($output) {
  515. Display::display_error_message(get_lang('UplUnableToSaveFile'));
  516. }
  517. return false;
  518. }
  519. break;
  520. default:
  521. // Only save the file if it doesn't exist or warn user if it does exist
  522. if (file_exists($fullPath) && $docId) {
  523. if ($output) {
  524. Display::display_error_message($cleanName.' '.get_lang('UplAlreadyExists'));
  525. }
  526. } else {
  527. if (moveUploadedFile($uploadedFile, $fullPath)) {
  528. chmod($fullPath, $filePermissions);
  529. // Put the document data in the database
  530. $documentId = add_document(
  531. $courseInfo,
  532. $filePath,
  533. 'file',
  534. $fileSize,
  535. $documentTitle,
  536. $comment,
  537. 0,
  538. true,
  539. $groupId,
  540. $sessionId
  541. );
  542. if ($documentId) {
  543. // Update document item_property
  544. api_item_property_update(
  545. $courseInfo,
  546. TOOL_DOCUMENT,
  547. $documentId,
  548. 'DocumentAdded',
  549. $userId,
  550. $groupId,
  551. $toUserId,
  552. null,
  553. null,
  554. $sessionId
  555. );
  556. // Redo visibility
  557. api_set_default_visibility(TOOL_DOCUMENT, $documentId);
  558. }
  559. // If the file is in a folder, we need to update all parent folders
  560. item_property_update_on_folder(
  561. $courseInfo,
  562. $uploadPath,
  563. $userId
  564. );
  565. // Display success message to user
  566. if ($output) {
  567. Display::display_confirmation_message(
  568. get_lang('UplUploadSucceeded').'<br /> '.$documentTitle,
  569. false
  570. );
  571. }
  572. return $filePath;
  573. } else {
  574. if ($output) {
  575. Display::display_error_message(get_lang('UplUnableToSaveFile'));
  576. }
  577. return false;
  578. }
  579. }
  580. break;
  581. }
  582. }
  583. }
  584. }
  585. /**
  586. * @param string $file
  587. * @param string $storePath
  588. *
  589. * @return bool
  590. */
  591. function moveUploadedFile($file, $storePath)
  592. {
  593. $handleFromFile = isset($file['from_file']) && $file['from_file'] ? true : false;
  594. $moveFile = isset($file['move_file']) && $file['move_file'] ? true : false;
  595. if ($moveFile) {
  596. copy($file['tmp_name'], $storePath);
  597. }
  598. if ($handleFromFile) {
  599. return file_exists($file['tmp_name']);
  600. } else {
  601. return move_uploaded_file($file['tmp_name'], $storePath);
  602. }
  603. }
  604. /**
  605. * Checks if there is enough place to add a file on a directory
  606. * on the base of a maximum directory size allowed
  607. * deprecated: use enough_space instead!
  608. * @author - Hugues Peeters <peeters@ipm.ucl.ac.be>
  609. * @param - file_size (int) - size of the file in byte
  610. * @param - dir (string) - Path of the directory
  611. * whe the file should be added
  612. * @param - max_dir_space (int) - maximum size of the diretory in byte
  613. * @return - boolean true if there is enough space,
  614. * boolean false otherwise
  615. *
  616. * @see - enough_size() uses dir_total_space() function
  617. */
  618. function enough_size($file_size, $dir, $max_dir_space)
  619. {
  620. // If the directory is the archive directory, safely ignore the size limit
  621. if (api_get_path(SYS_ARCHIVE_PATH) == $dir) {
  622. return true;
  623. }
  624. if ($max_dir_space) {
  625. $already_filled_space = dir_total_space($dir);
  626. if (($file_size + $already_filled_space) > $max_dir_space) {
  627. return false;
  628. }
  629. }
  630. return true;
  631. }
  632. /**
  633. * Computes the size already occupied by a directory and is subdirectories
  634. *
  635. * @author - Hugues Peeters <peeters@ipm.ucl.ac.be>
  636. * @param - dir_path (string) - size of the file in byte
  637. * @return - int - return the directory size in bytes
  638. */
  639. function dir_total_space($dir_path)
  640. {
  641. $save_dir = getcwd();
  642. chdir($dir_path) ;
  643. $handle = opendir($dir_path);
  644. $sumSize = 0;
  645. $dirList = array();
  646. while ($element = readdir($handle)) {
  647. if ( $element == '.' || $element == '..') {
  648. continue; // Skip the current and parent directories
  649. }
  650. if (is_file($element)) {
  651. $sumSize += filesize($element);
  652. }
  653. if (is_dir($element)) {
  654. $dirList[] = $dir_path.'/'.$element;
  655. }
  656. }
  657. closedir($handle) ;
  658. if (sizeof($dirList) > 0) {
  659. foreach ($dirList as $j) {
  660. $sizeDir = dir_total_space($j); // Recursivity
  661. $sumSize += $sizeDir;
  662. }
  663. }
  664. chdir($save_dir); // Return to initial position
  665. return $sumSize;
  666. }
  667. /**
  668. * Tries to add an extension to files without extension
  669. * Some applications on Macintosh computers don't add an extension to the files.
  670. * This subroutine try to fix this on the basis of the MIME type sent
  671. * by the browser.
  672. *
  673. * Note : some browsers don't send the MIME Type (e.g. Netscape 4).
  674. * We don't have solution for this kind of situation
  675. *
  676. * @author - Hugues Peeters <peeters@ipm.ucl.ac.be>
  677. * @author - Bert Vanderkimpen
  678. * @param - file_name (string) - Name of the file
  679. * @param - file_type (string) - Type of the file
  680. * @return - file_name (string)
  681. */
  682. function add_ext_on_mime($file_name, $file_type)
  683. {
  684. // Check whether the file has an extension AND whether the browser has sent a MIME Type
  685. if (!preg_match('/^.*\.[a-zA-Z_0-9]+$/', $file_name) && $file_type) {
  686. // Build a "MIME-types / extensions" connection table
  687. static $mime_type = array();
  688. $mime_type[] = 'application/msword'; $extension[] = '.doc';
  689. $mime_type[] = 'application/rtf'; $extension[] = '.rtf';
  690. $mime_type[] = 'application/vnd.ms-powerpoint'; $extension[] = '.ppt';
  691. $mime_type[] = 'application/vnd.ms-excel'; $extension[] = '.xls';
  692. $mime_type[] = 'application/pdf'; $extension[] = '.pdf';
  693. $mime_type[] = 'application/postscript'; $extension[] = '.ps';
  694. $mime_type[] = 'application/mac-binhex40'; $extension[] = '.hqx';
  695. $mime_type[] = 'application/x-gzip'; $extension[] = 'tar.gz';
  696. $mime_type[] = 'application/x-shockwave-flash'; $extension[] = '.swf';
  697. $mime_type[] = 'application/x-stuffit'; $extension[] = '.sit';
  698. $mime_type[] = 'application/x-tar'; $extension[] = '.tar';
  699. $mime_type[] = 'application/zip'; $extension[] = '.zip';
  700. $mime_type[] = 'application/x-tar'; $extension[] = '.tar';
  701. $mime_type[] = 'text/html'; $extension[] = '.html';
  702. $mime_type[] = 'text/plain'; $extension[] = '.txt';
  703. $mime_type[] = 'text/rtf'; $extension[] = '.rtf';
  704. $mime_type[] = 'img/gif'; $extension[] = '.gif';
  705. $mime_type[] = 'img/jpeg'; $extension[] = '.jpg';
  706. $mime_type[] = 'img/png'; $extension[] = '.png';
  707. $mime_type[] = 'audio/midi'; $extension[] = '.mid';
  708. $mime_type[] = 'audio/mpeg'; $extension[] = '.mp3';
  709. $mime_type[] = 'audio/x-aiff'; $extension[] = '.aif';
  710. $mime_type[] = 'audio/x-pn-realaudio'; $extension[] = '.rm';
  711. $mime_type[] = 'audio/x-pn-realaudio-plugin'; $extension[] = '.rpm';
  712. $mime_type[] = 'audio/x-wav'; $extension[] = '.wav';
  713. $mime_type[] = 'video/mpeg'; $extension[] = '.mpg';
  714. $mime_type[] = 'video/mpeg4-generic'; $extension[] = '.mp4';
  715. $mime_type[] = 'video/quicktime'; $extension[] = '.mov';
  716. $mime_type[] = 'video/x-msvideo'; $extension[] = '.avi';
  717. $mime_type[] = 'video/x-ms-wmv'; $extension[] = '.wmv';
  718. $mime_type[] = 'video/x-flv'; $extension[] = '.flv';
  719. $mime_type[] = 'image/svg+xml'; $extension[] = '.svg';
  720. $mime_type[] = 'image/svg+xml'; $extension[] = '.svgz';
  721. $mime_type[] = 'video/ogg'; $extension[] = '.ogv';
  722. $mime_type[] = 'audio/ogg'; $extension[] = '.oga';
  723. $mime_type[] = 'application/ogg'; $extension[] = '.ogg';
  724. $mime_type[] = 'application/ogg'; $extension[] = '.ogx';
  725. $mime_type[] = 'application/x-freemind'; $extension[] = '.mm';
  726. $mime_type[] = 'application/vnd.ms-word.document.macroEnabled.12'; $extension[] = '.docm';
  727. $mime_type[] = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'; $extension[] = '.docx';
  728. $mime_type[] = 'application/vnd.ms-word.template.macroEnabled.12'; $extension[] = '.dotm';
  729. $mime_type[] = 'application/vnd.openxmlformats-officedocument.wordprocessingml.template'; $extension[] = '.dotx';
  730. $mime_type[] = 'application/vnd.ms-powerpoint.template.macroEnabled.12'; $extension[] = '.potm';
  731. $mime_type[] = 'application/vnd.openxmlformats-officedocument.presentationml.template'; $extension[] = '.potx';
  732. $mime_type[] = 'application/vnd.ms-powerpoint.addin.macroEnabled.12'; $extension[] = '.ppam';
  733. $mime_type[] = 'application/vnd.ms-powerpoint.slideshow.macroEnabled.12'; $extension[] = '.ppsm';
  734. $mime_type[] = 'application/vnd.openxmlformats-officedocument.presentationml.slideshow'; $extension[] = '.ppsx';
  735. $mime_type[] = 'application/vnd.ms-powerpoint.presentation.macroEnabled.12'; $extension[] = '.pptm';
  736. $mime_type[] = 'application/vnd.openxmlformats-officedocument.presentationml.presentation'; $extension[] = '.pptx';
  737. $mime_type[] = 'application/vnd.ms-excel.addin.macroEnabled.12'; $extension[] = '.xlam';
  738. $mime_type[] = 'application/vnd.ms-excel.sheet.binary.macroEnabled.12'; $extension[] = '.xlsb';
  739. $mime_type[] = 'application/vnd.ms-excel.sheet.macroEnabled.12'; $extension[] = '.xlsm';
  740. $mime_type[] = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'; $extension[] = '.xlsx';
  741. $mime_type[] = 'application/vnd.ms-excel.template.macroEnabled.12'; $extension[] = '.xltm';
  742. $mime_type[] = 'application/vnd.openxmlformats-officedocument.spreadsheetml.template'; $extension[] = '.xltx';
  743. // Test on PC (files with no extension get application/octet-stream)
  744. //$mime_type[] = 'application/octet-stream'; $extension[] = '.ext';
  745. // Check whether the MIME type sent by the browser is within the table
  746. foreach ($mime_type as $key => & $type) {
  747. if ($type == $file_type) {
  748. $file_name .= $extension[$key];
  749. break;
  750. }
  751. }
  752. unset($mime_type, $extension, $type, $key); // Delete to eschew possible collisions
  753. }
  754. return $file_name;
  755. }
  756. /**
  757. *
  758. * @author Hugues Peeters <hugues.peeters@claroline.net>
  759. *
  760. * @param array $uploaded_file - follows the $_FILES Structure
  761. * @param string $base_work_dir - base working directory of the module
  762. * @param string $upload_path - destination of the upload.
  763. * This path is to append to $base_work_dir
  764. * @param int $max_filled_space - amount of bytes to not exceed in the base
  765. * working directory
  766. *
  767. * @return boolean true if it succeds, false otherwise
  768. */
  769. function treat_uploaded_file($uploaded_file, $base_work_dir, $upload_path, $max_filled_space, $uncompress = '')
  770. {
  771. $uploaded_file['name'] = stripslashes($uploaded_file['name']);
  772. if (!enough_size($uploaded_file['size'], $base_work_dir, $max_filled_space)) {
  773. return api_failure::set_failure('not_enough_space');
  774. }
  775. if ($uncompress == 'unzip' && preg_match('/.zip$/', strtolower($uploaded_file['name']))) {
  776. return unzip_uploaded_file($uploaded_file, $upload_path, $base_work_dir, $max_filled_space);
  777. } else {
  778. $file_name = trim($uploaded_file['name']);
  779. // CHECK FOR NO DESIRED CHARACTERS
  780. $file_name = api_replace_dangerous_char($file_name, 'strict');
  781. // TRY TO ADD AN EXTENSION TO FILES WITOUT EXTENSION
  782. $file_name = add_ext_on_mime($file_name, $uploaded_file['type']);
  783. // HANDLE PHP FILES
  784. $file_name = ($file_name);
  785. // COPY THE FILE TO THE DESIRED DESTINATION
  786. if (move_uploaded_file($uploaded_file['tmp_name'], $base_work_dir.$upload_path.'/'.$file_name)) {
  787. set_default_settings($upload_path, $file_name);
  788. }
  789. return true;
  790. }
  791. }
  792. /**
  793. * Manages all the unzipping process of an uploaded file
  794. *
  795. * @author Hugues Peeters <hugues.peeters@claroline.net>
  796. *
  797. * @param array $uploaded_file - follows the $_FILES Structure
  798. * @param string $upload_path - destination of the upload.
  799. * This path is to append to $base_work_dir
  800. * @param string $base_work_dir - base working directory of the module
  801. * @param int $max_filled_space - amount of bytes to not exceed in the base
  802. * working directory
  803. *
  804. * @return boolean true if it succeeds false otherwise
  805. */
  806. function unzip_uploaded_file($uploaded_file, $upload_path, $base_work_dir, $max_filled_space)
  807. {
  808. $zip_file = new PclZip($uploaded_file['tmp_name']);
  809. // Check the zip content (real size and file extension)
  810. if (file_exists($uploaded_file['tmp_name'])) {
  811. $zip_content_array = $zip_file->listContent();
  812. $ok_scorm = false;
  813. $realFileSize = 0;
  814. foreach ($zip_content_array as & $this_content) {
  815. if (preg_match('~.(php.*|phtml)$~i', $this_content['filename'])) {
  816. return api_failure::set_failure('php_file_in_zip_file');
  817. } elseif (stristr($this_content['filename'], 'imsmanifest.xml')) {
  818. $ok_scorm = true;
  819. } elseif (stristr($this_content['filename'], 'LMS')) {
  820. $ok_plantyn_scorm1 = true;
  821. } elseif (stristr($this_content['filename'], 'REF')) {
  822. $ok_plantyn_scorm2 = true;
  823. } elseif (stristr($this_content['filename'], 'SCO')) {
  824. $ok_plantyn_scorm3 = true;
  825. } elseif (stristr($this_content['filename'], 'AICC')) {
  826. $ok_aicc_scorm = true;
  827. }
  828. $realFileSize += $this_content['size'];
  829. }
  830. if (($ok_plantyn_scorm1 && $ok_plantyn_scorm2 && $ok_plantyn_scorm3) || $ok_aicc_scorm) {
  831. $ok_scorm = true;
  832. }
  833. if (!$ok_scorm && defined('CHECK_FOR_SCORM') && CHECK_FOR_SCORM) {
  834. return api_failure::set_failure('not_scorm_content');
  835. }
  836. if (!enough_size($realFileSize, $base_work_dir, $max_filled_space)) {
  837. return api_failure::set_failure('not_enough_space');
  838. }
  839. // It happens on Linux that $upload_path sometimes doesn't start with '/'
  840. if ($upload_path[0] != '/' && substr($base_work_dir,-1,1) != '/') {
  841. $upload_path = '/'.$upload_path;
  842. }
  843. if ($upload_path[strlen($upload_path) - 1] == '/') {
  844. $upload_path=substr($upload_path, 0, -1);
  845. }
  846. /* Uncompressing phase */
  847. /*
  848. The first version, using OS unzip, is not used anymore
  849. because it does not return enough information.
  850. We need to process each individual file in the zip archive to
  851. - add it to the database
  852. - parse & change relative html links
  853. */
  854. if (PHP_OS == 'Linux' && ! get_cfg_var('safe_mode') && false) { // *** UGent, changed by OC ***
  855. // Shell Method - if this is possible, it gains some speed
  856. exec("unzip -d \"".$base_work_dir.$upload_path."/\"".$uploaded_file['name']." " .$uploaded_file['tmp_name']);
  857. } else {
  858. // PHP method - slower...
  859. $save_dir = getcwd();
  860. chdir($base_work_dir.$upload_path);
  861. $unzippingState = $zip_file->extract();
  862. for ($j=0; $j < count($unzippingState); $j++) {
  863. $state = $unzippingState[$j];
  864. // Fix relative links in html files
  865. $extension = strrchr($state['stored_filename'], '.');
  866. }
  867. if ($dir = @opendir($base_work_dir.$upload_path)) {
  868. while ($file = readdir($dir)) {
  869. if ($file != '.' && $file != '..') {
  870. $filetype = 'file';
  871. if (is_dir($base_work_dir.$upload_path.'/'.$file)) $filetype = 'folder';
  872. $safe_file = api_replace_dangerous_char($file, 'strict');
  873. @rename($base_work_dir.$upload_path.'/'.$file,$base_work_dir.$upload_path.'/'.$safe_file);
  874. set_default_settings($upload_path, $safe_file,$filetype);
  875. }
  876. }
  877. closedir($dir);
  878. } else {
  879. error_log('Could not create directory '.$base_work_dir.$upload_path.' to unzip files');
  880. }
  881. chdir($save_dir); // Back to previous dir position
  882. }
  883. }
  884. return true;
  885. }
  886. /**
  887. * Manages all the unzipping process of an uploaded document
  888. * This uses the item_property table for properties of documents
  889. *
  890. * @author Hugues Peeters <hugues.peeters@claroline.net>
  891. * @author Bert Vanderkimpen
  892. *
  893. * @param array $courseInfo
  894. * @param array $userInfo
  895. * @param array $uploaded_file - follows the $_FILES Structure
  896. * @param string $upload_path - destination of the upload.
  897. * This path is to append to $base_work_dir
  898. * @param string $base_work_dir - base working directory of the module
  899. * @param int $maxFilledSpace - amount of bytes to not exceed in the base
  900. * working directory
  901. * @param int $sessionId
  902. * @param int $groupId
  903. * @param boolean $output Optional. If no output not wanted on success, set to false.
  904. *
  905. * @return boolean true if it succeeds false otherwise
  906. */
  907. function unzip_uploaded_document(
  908. $courseInfo,
  909. $userInfo,
  910. $uploaded_file,
  911. $uploadPath,
  912. $base_work_dir,
  913. $maxFilledSpace,
  914. $sessionId = 0,
  915. $groupId = 0,
  916. $output = true
  917. ) {
  918. $zip = new PclZip($uploaded_file['tmp_name']);
  919. // Check the zip content (real size and file extension)
  920. $zip_content_array = (array)$zip->listContent();
  921. $realSize = 0;
  922. foreach ($zip_content_array as & $this_content) {
  923. $realSize += $this_content['size'];
  924. }
  925. if (!DocumentManager::enough_space($realSize, $maxFilledSpace)) {
  926. Display::display_error_message(get_lang('UplNotEnoughSpace'));
  927. return false;
  928. }
  929. $folder = api_get_unique_id();
  930. $destinationDir = api_get_path(SYS_ARCHIVE_PATH).$folder;
  931. mkdir($destinationDir, api_get_permissions_for_new_directories(), true);
  932. /* Uncompress zip file*/
  933. // We extract using a callback function that "cleans" the path
  934. $zip->extract(
  935. PCLZIP_OPT_PATH,
  936. $destinationDir,
  937. PCLZIP_CB_PRE_EXTRACT,
  938. 'clean_up_files_in_zip',
  939. PCLZIP_OPT_REPLACE_NEWER
  940. );
  941. // Add all documents in the unzipped folder to the database
  942. add_all_documents_in_folder_to_database(
  943. $courseInfo,
  944. $userInfo,
  945. $base_work_dir,
  946. $destinationDir,
  947. $sessionId,
  948. $groupId,
  949. $output,
  950. array('path' => $uploadPath)
  951. );
  952. if (is_dir($destinationDir)) {
  953. rmdirr($destinationDir);
  954. }
  955. return true;
  956. }
  957. /**
  958. * This function is a callback function that is used while extracting a zipfile
  959. * http://www.phpconcept.net/pclzip/man/en/index.php?options-pclzip_cb_pre_extract
  960. *
  961. * @param $p_event
  962. * @param $p_header
  963. * @return 1 (If the function returns 1, then the extraction is resumed)
  964. */
  965. function clean_up_files_in_zip($p_event, &$p_header)
  966. {
  967. $res = clean_up_path($p_header['filename']);
  968. return $res;
  969. }
  970. /**
  971. * This function cleans up a given path
  972. * by eliminating dangerous file names and cleaning them
  973. *
  974. * @param string $path
  975. * @return $path
  976. * @see disable_dangerous_file()
  977. * @see api_replace_dangerous_char()
  978. */
  979. function clean_up_path(&$path)
  980. {
  981. // Split the path in folders and files
  982. $path_array = explode('/', $path);
  983. // Clean up every foler and filename in the path
  984. foreach ($path_array as $key => & $val) {
  985. // We don't want to lose the dots in ././folder/file (cfr. zipfile)
  986. if ($val != '.') {
  987. $val = disable_dangerous_file(api_replace_dangerous_char($val));
  988. }
  989. }
  990. // Join the "cleaned" path (modified in-place as passed by reference)
  991. $path = implode('/', $path_array);
  992. $res = filter_extension($path);
  993. return $res;
  994. }
  995. /**
  996. * Checks if the file is dangerous, based on extension and/or mimetype.
  997. * The list of extensions accepted/rejected can be found from
  998. * api_get_setting('upload_extensions_exclude') and api_get_setting('upload_extensions_include')
  999. * @param string filename passed by reference. The filename will be modified
  1000. * if filter rules say so! (you can include path but the filename should look like 'abc.html')
  1001. * @return int 0 to skip file, 1 to keep file
  1002. */
  1003. function filter_extension(&$filename)
  1004. {
  1005. if (substr($filename, -1) == '/') {
  1006. return 1; // Authorize directories
  1007. }
  1008. $blacklist = api_get_setting('upload_extensions_list_type');
  1009. if ($blacklist != 'whitelist') { // if = blacklist
  1010. $extensions = explode(';', strtolower(api_get_setting('upload_extensions_blacklist')));
  1011. $skip = api_get_setting('upload_extensions_skip');
  1012. $ext = strrchr($filename, '.');
  1013. $ext = substr($ext, 1);
  1014. if (empty($ext)) {
  1015. return 1; // We're in blacklist mode, so accept empty extensions
  1016. }
  1017. if (in_array(strtolower($ext), $extensions)) {
  1018. if ($skip == 'true') {
  1019. return 0;
  1020. } else {
  1021. $new_ext = api_get_setting('upload_extensions_replace_by');
  1022. $filename = str_replace('.'.$ext, '.'.$new_ext, $filename);
  1023. return 1;
  1024. }
  1025. } else {
  1026. return 1;
  1027. }
  1028. } else {
  1029. $extensions = split(';', strtolower(api_get_setting('upload_extensions_whitelist')));
  1030. $skip = api_get_setting('upload_extensions_skip');
  1031. $ext = strrchr($filename, '.');
  1032. $ext = substr($ext, 1);
  1033. if (empty($ext)) {
  1034. return 1; // Accept empty extensions
  1035. }
  1036. if (!in_array(strtolower($ext), $extensions)) {
  1037. if ($skip == 'true') {
  1038. return 0;
  1039. } else {
  1040. $new_ext = api_get_setting('upload_extensions_replace_by');
  1041. $filename = str_replace('.'.$ext, '.'.$new_ext, $filename);
  1042. return 1;
  1043. }
  1044. } else {
  1045. return 1;
  1046. }
  1047. }
  1048. }
  1049. /**
  1050. * Adds a new document to the database
  1051. *
  1052. * @param array $_course
  1053. * @param string $path
  1054. * @param string $filetype
  1055. * @param int $filesize
  1056. * @param string $title
  1057. * @param string $comment
  1058. * @param int $readonly
  1059. * @param bool $save_visibility
  1060. * @param int $group_id
  1061. * @param int $session_id Session ID, if any
  1062. * @return int id if inserted document
  1063. */
  1064. function add_document(
  1065. $_course,
  1066. $path,
  1067. $filetype,
  1068. $filesize,
  1069. $title,
  1070. $comment = null,
  1071. $readonly = 0,
  1072. $save_visibility = true,
  1073. $group_id = null,
  1074. $session_id = 0
  1075. ) {
  1076. $session_id = intval($session_id);
  1077. if (empty($session_id)) {
  1078. $session_id = api_get_session_id();
  1079. }
  1080. $readonly = intval($readonly);
  1081. $c_id = $_course['real_id'];
  1082. $table_document = Database::get_course_table(TABLE_DOCUMENT);
  1083. $params = [
  1084. 'id' => '',
  1085. 'c_id' => $c_id,
  1086. 'path' => $path,
  1087. 'filetype' => $filetype,
  1088. 'size' => $filesize,
  1089. 'title' => $title,
  1090. 'comment' => $comment,
  1091. 'readonly' => $readonly,
  1092. 'session_id' => $session_id,
  1093. ];
  1094. $documentId = Database::insert($table_document, $params);
  1095. if ($documentId) {
  1096. $sql = "UPDATE $table_document SET id = iid WHERE iid = $documentId";
  1097. Database::query($sql);
  1098. if ($save_visibility) {
  1099. api_set_default_visibility($documentId, TOOL_DOCUMENT, $group_id);
  1100. }
  1101. return $documentId;
  1102. } else {
  1103. return false;
  1104. }
  1105. }
  1106. /**
  1107. * Updates an existing document in the database
  1108. * as the file exists, we only need to change the size
  1109. *
  1110. * @param array $_course
  1111. * @param int $documentId
  1112. * @param int $filesize
  1113. * @param int $readonly
  1114. * @return boolean true /false
  1115. */
  1116. function update_existing_document($_course, $documentId, $filesize, $readonly = 0)
  1117. {
  1118. $document_table = Database::get_course_table(TABLE_DOCUMENT);
  1119. $documentId = intval($documentId);
  1120. $filesize = intval($filesize);
  1121. $readonly = intval($readonly);
  1122. $course_id = $_course['real_id'];
  1123. $sql = "UPDATE $document_table SET
  1124. size = '$filesize',
  1125. readonly = '$readonly'
  1126. WHERE c_id = $course_id AND id = $documentId";
  1127. if (Database::query($sql)) {
  1128. return true;
  1129. } else {
  1130. return false;
  1131. }
  1132. }
  1133. /**
  1134. * This function updates the last_edit_date, last edit user id on all folders in a given path
  1135. *
  1136. * @param array $_course
  1137. * @param string $path
  1138. * @param int $user_id
  1139. */
  1140. function item_property_update_on_folder($_course, $path, $user_id)
  1141. {
  1142. // If we are in the root, just return... no need to update anything
  1143. if ($path == '/') {
  1144. return;
  1145. }
  1146. $user_id = intval($user_id);
  1147. // If the given path ends with a / we remove it
  1148. $endchar = substr($path, strlen($path) - 1, 1);
  1149. if ($endchar == '/') {
  1150. $path = substr($path, 0, strlen($path) - 1);
  1151. }
  1152. $table = Database::get_course_table(TABLE_ITEM_PROPERTY);
  1153. // Get the time
  1154. $time = date('Y-m-d H:i:s', time());
  1155. // Det all paths in the given path
  1156. // /folder/subfolder/subsubfolder/file
  1157. // if file is updated, subsubfolder, subfolder and folder are updated
  1158. $exploded_path = explode('/', $path);
  1159. $course_id = api_get_course_int_id();
  1160. $newpath = '';
  1161. foreach ($exploded_path as $key => & $value) {
  1162. // We don't want a slash before our first slash
  1163. if ($key != 0) {
  1164. $newpath .= '/'.$value;
  1165. //echo 'path= '.$newpath.'<br />';
  1166. // Select ID of given folder
  1167. $folder_id = DocumentManager::get_document_id($_course, $newpath);
  1168. if ($folder_id) {
  1169. $sql = "UPDATE $table SET
  1170. lastedit_date='$time',lastedit_type='DocumentInFolderUpdated', lastedit_user_id='$user_id'
  1171. WHERE c_id = $course_id AND tool='".TOOL_DOCUMENT."' AND ref='$folder_id'";
  1172. Database::query($sql);
  1173. }
  1174. }
  1175. }
  1176. }
  1177. /**
  1178. * Returns the directory depth of the file.
  1179. *
  1180. * @author Olivier Cauberghe <olivier.cauberghe@ugent.be>
  1181. * @param path+filename eg: /main/document/document.php
  1182. * @return The directory depth
  1183. */
  1184. function get_levels($filename) {
  1185. $levels=explode('/', $filename);
  1186. if (empty($levels[count($levels) - 1])) {
  1187. unset($levels[count($levels) - 1]);
  1188. }
  1189. return count($levels);
  1190. }
  1191. /**
  1192. * Adds file to document table in database
  1193. * deprecated: use file_set_default_settings instead
  1194. *
  1195. * @author Olivier Cauberghe <olivier.cauberghe@ugent.be>
  1196. * @param path,filename
  1197. * action: Adds an entry to the document table with the default settings.
  1198. */
  1199. function set_default_settings($upload_path, $filename, $filetype = 'file')
  1200. {
  1201. global $dbTable,$_configuration;
  1202. global $default_visibility;
  1203. if (!$default_visibility) {
  1204. $default_visibility = 'v';
  1205. }
  1206. $filetype = Database::escape_string($filetype);
  1207. $upload_path = str_replace('\\', '/', $upload_path);
  1208. $upload_path = str_replace('//', '/', $upload_path);
  1209. if ($upload_path == '/') {
  1210. $upload_path='';
  1211. } elseif (!empty($upload_path) && $upload_path[0] != '/') {
  1212. $upload_path="/$upload_path";
  1213. }
  1214. $endchar = substr($filename, strlen($filename) - 1, 1);
  1215. if ($endchar == '/') {
  1216. $filename = substr($filename, 0, -1);
  1217. }
  1218. $filename = Database::escape_string($filename);
  1219. $query = "SELECT count(*) as bestaat FROM $dbTable
  1220. WHERE path='$upload_path/$filename'";
  1221. $result = Database::query($query);
  1222. $row = Database::fetch_array($result);
  1223. if ($row['bestaat'] > 0) {
  1224. $query = "UPDATE $dbTable SET
  1225. path='$upload_path/$filename',
  1226. visibility='$default_visibility',
  1227. filetype='$filetype'
  1228. WHERE path='$upload_path/$filename'";
  1229. } else {
  1230. $query = "INSERT INTO $dbTable (path,visibility,filetype)
  1231. VALUES('$upload_path/$filename','$default_visibility','$filetype')";
  1232. }
  1233. Database::query($query);
  1234. }
  1235. /**
  1236. * Retrieves the image path list in a html file
  1237. *
  1238. * @author Hugues Peeters <hugues.peeters@claroline.net>
  1239. * @param string $html_file
  1240. * @return array - images path list
  1241. */
  1242. function search_img_from_html($html_file) {
  1243. $img_path_list = array();
  1244. if (!$fp = fopen($html_file, 'r')) {
  1245. return ;
  1246. }
  1247. // Aearch and store occurences of the <img> tag in an array
  1248. $size_file = (filesize($html_file) === 0) ? 1 : filesize($html_file);
  1249. if (isset($fp) && $fp !== false) {
  1250. $buffer = fread($fp, $size_file);
  1251. if (strlen($buffer) >= 0 && $buffer !== false) {
  1252. //
  1253. } else {
  1254. die('<center>Can not read file.</center>');
  1255. }
  1256. } else {
  1257. die('<center>Can not read file.</center>');
  1258. }
  1259. $matches = array();
  1260. if (preg_match_all('~<[[:space:]]*img[^>]*>~i', $buffer, $matches)) {
  1261. $img_tag_list = $matches[0];
  1262. }
  1263. fclose ($fp);
  1264. unset($buffer);
  1265. // Search the image file path from all the <IMG> tag detected
  1266. if (sizeof($img_tag_list) > 0) {
  1267. foreach ($img_tag_list as & $this_img_tag) {
  1268. if (preg_match('~src[[:space:]]*=[[:space:]]*[\"]{1}([^\"]+)[\"]{1}~i', $this_img_tag, $matches)) {
  1269. $img_path_list[] = $matches[1];
  1270. }
  1271. }
  1272. $img_path_list = array_unique($img_path_list); // Remove duplicate entries
  1273. }
  1274. return $img_path_list;
  1275. }
  1276. /**
  1277. * Creates a new directory trying to find a directory name
  1278. * that doesn't already exist
  1279. * (we could use unique_name() here...)
  1280. *
  1281. * @author Hugues Peeters <hugues.peeters@claroline.net>
  1282. * @author Bert Vanderkimpen
  1283. * @param array $_course current course information
  1284. * @param int $user_id current user id
  1285. * @param int $session_id
  1286. * @param int $to_group_id
  1287. * @param int $to_user_id
  1288. * @param string $base_work_dir /var/www/chamilo/courses/ABC/document
  1289. * @param string $desired_dir_name complete path of the desired name
  1290. * Example: /folder1/folder2
  1291. * @param string $title "folder2"
  1292. * @param int $visibility (0 for invisible, 1 for visible, 2 for deleted)
  1293. * @param bool $generateNewNameIfExists
  1294. * @return string actual directory name if it succeeds,
  1295. * boolean false otherwise
  1296. */
  1297. function create_unexisting_directory(
  1298. $_course,
  1299. $user_id,
  1300. $session_id,
  1301. $to_group_id,
  1302. $to_user_id,
  1303. $base_work_dir,
  1304. $desired_dir_name,
  1305. $title = null,
  1306. $visibility = null,
  1307. $generateNewNameIfExists = false
  1308. ) {
  1309. $course_id = $_course['real_id'];
  1310. $session_id = intval($session_id);
  1311. $folderExists = DocumentManager::folderExists(
  1312. $desired_dir_name,
  1313. $_course,
  1314. $session_id,
  1315. $to_group_id
  1316. );
  1317. if ($folderExists == true) {
  1318. if ($generateNewNameIfExists) {
  1319. $counter = 1;
  1320. while (1) {
  1321. $folderExists = DocumentManager::folderExists(
  1322. $desired_dir_name.'_'.$counter,
  1323. $_course,
  1324. $session_id,
  1325. $to_group_id
  1326. );
  1327. if ($folderExists == false) {
  1328. break;
  1329. }
  1330. $counter++;
  1331. }
  1332. $desired_dir_name = $desired_dir_name.'_'.$counter;
  1333. } else {
  1334. return false;
  1335. }
  1336. }
  1337. $systemFolderName = $desired_dir_name;
  1338. // Adding suffix
  1339. $suffix = DocumentManager::getDocumentSuffix(
  1340. $_course,
  1341. $session_id,
  1342. $to_group_id
  1343. );
  1344. $systemFolderName .= $suffix;
  1345. if ($title == null) {
  1346. $title = basename($desired_dir_name);
  1347. }
  1348. if (!is_dir($base_work_dir.$systemFolderName)) {
  1349. $result = mkdir(
  1350. $base_work_dir.$systemFolderName,
  1351. api_get_permissions_for_new_directories(),
  1352. true
  1353. );
  1354. if ($result) {
  1355. // Check if pathname already exists inside document table
  1356. $tbl_document = Database::get_course_table(TABLE_DOCUMENT);
  1357. $sql = "SELECT id, path FROM $tbl_document
  1358. WHERE
  1359. c_id = $course_id AND
  1360. (
  1361. path = '" . $systemFolderName . "'
  1362. )
  1363. ";
  1364. $rs = Database::query($sql);
  1365. if (Database::num_rows($rs) == 0) {
  1366. $document_id = add_document(
  1367. $_course,
  1368. $systemFolderName,
  1369. 'folder',
  1370. 0,
  1371. $title,
  1372. null,
  1373. 0,
  1374. true,
  1375. $to_group_id
  1376. );
  1377. if ($document_id) {
  1378. // Update document item_property
  1379. if (!empty($visibility)) {
  1380. $visibilities = array(
  1381. 0 => 'invisible',
  1382. 1 => 'visible',
  1383. 2 => 'delete'
  1384. );
  1385. api_item_property_update(
  1386. $_course,
  1387. TOOL_DOCUMENT,
  1388. $document_id,
  1389. $visibilities[$visibility],
  1390. $user_id,
  1391. $to_group_id,
  1392. $to_user_id,
  1393. null,
  1394. null,
  1395. $session_id
  1396. );
  1397. } else {
  1398. api_item_property_update(
  1399. $_course,
  1400. TOOL_DOCUMENT,
  1401. $document_id,
  1402. 'FolderCreated',
  1403. $user_id,
  1404. $to_group_id,
  1405. $to_user_id,
  1406. null,
  1407. null,
  1408. $session_id
  1409. );
  1410. }
  1411. $documentData = DocumentManager::get_document_data_by_id(
  1412. $document_id,
  1413. $_course['code'],
  1414. false,
  1415. $session_id
  1416. );
  1417. return $documentData;
  1418. }
  1419. } else {
  1420. $document = Database::fetch_array($rs);
  1421. $documentData = DocumentManager::get_document_data_by_id(
  1422. $document['id'],
  1423. $_course['code'],
  1424. false,
  1425. $session_id
  1426. );
  1427. /* This means the folder NOT exist in the filesystem
  1428. (now this was created) but there is a record in the Database*/
  1429. return $documentData;
  1430. }
  1431. }
  1432. }
  1433. return false;
  1434. }
  1435. /**
  1436. * Handles uploaded missing images
  1437. *
  1438. * @author Hugues Peeters <hugues.peeters@claroline.net>
  1439. * @author Bert Vanderkimpen
  1440. * @param array $_course
  1441. * @param array $uploaded_file_collection - follows the $_FILES Structure
  1442. * @param string $base_work_dir
  1443. * @param string $missing_files_dir
  1444. * @param int $user_id
  1445. * @param int $max_filled_space
  1446. */
  1447. function move_uploaded_file_collection_into_directory(
  1448. $_course,
  1449. $uploaded_file_collection,
  1450. $base_work_dir,
  1451. $missing_files_dir,
  1452. $user_id,
  1453. $to_group_id,
  1454. $to_user_id,
  1455. $max_filled_space
  1456. ) {
  1457. $number_of_uploaded_images = count($uploaded_file_collection['name']);
  1458. $new_file_list = array();
  1459. for ($i = 0; $i < $number_of_uploaded_images; $i++) {
  1460. $missing_file['name'] = $uploaded_file_collection['name'][$i];
  1461. $missing_file['type'] = $uploaded_file_collection['type'][$i];
  1462. $missing_file['tmp_name'] = $uploaded_file_collection['tmp_name'][$i];
  1463. $missing_file['error'] = $uploaded_file_collection['error'][$i];
  1464. $missing_file['size'] = $uploaded_file_collection['size'][$i];
  1465. $upload_ok = process_uploaded_file($missing_file);
  1466. if ($upload_ok) {
  1467. $new_file_list[] = handle_uploaded_document(
  1468. $_course,
  1469. $missing_file,
  1470. $base_work_dir,
  1471. $missing_files_dir,
  1472. $user_id,
  1473. $to_group_id,
  1474. $to_user_id,
  1475. $max_filled_space,
  1476. 0,
  1477. 'overwrite'
  1478. );
  1479. }
  1480. unset($missing_file);
  1481. }
  1482. return $new_file_list;
  1483. }
  1484. /**
  1485. * Opens the old html file and replace the src path into the img tag
  1486. * This also works for files in subdirectories.
  1487. * @param $original_img_path is an array
  1488. * @param $new_img_path is an array
  1489. */
  1490. function replace_img_path_in_html_file($original_img_path, $new_img_path, $html_file)
  1491. {
  1492. // Open the file
  1493. $fp = fopen($html_file, 'r');
  1494. $buffer = fread($fp, filesize($html_file));
  1495. $new_html_content = '';
  1496. // Fix the image tags
  1497. for ($i = 0, $fileNb = count($original_img_path); $i < $fileNb ; $i++) {
  1498. $replace_what = $original_img_path[$i];
  1499. // We only need the directory and the filename /path/to/file_html_files/missing_file.gif -> file_html_files/missing_file.gif
  1500. $exploded_file_path = explode('/', $new_img_path[$i]);
  1501. $replace_by = $exploded_file_path[count($exploded_file_path) - 2].'/'.$exploded_file_path[count($exploded_file_path) - 1];
  1502. $buffer = str_replace($replace_what, $replace_by, $buffer);
  1503. }
  1504. $new_html_content .= $buffer;
  1505. @fclose($fp);
  1506. // Write the resulted new file
  1507. if (!$fp = fopen($html_file, 'w')) {
  1508. return;
  1509. }
  1510. if (!fwrite($fp, $new_html_content)) {
  1511. return;
  1512. }
  1513. }
  1514. /**
  1515. * Creates a file containing an html redirection to a given url
  1516. *
  1517. * @author Hugues Peeters <hugues.peeters@claroline.net>
  1518. * @param string $file_path
  1519. * @param string $url
  1520. * @return void
  1521. */
  1522. function create_link_file($file_path, $url)
  1523. {
  1524. $file_content = '<html>'
  1525. .'<head>'
  1526. .'<meta http-equiv="refresh" content="1;url='.$url.'">'
  1527. .'</head>'
  1528. .'<body>'
  1529. .'</body>'
  1530. .'</html>';
  1531. if (file_exists($file_path)) {
  1532. if (!($fp = fopen ($file_path, 'w'))) {
  1533. return false;
  1534. }
  1535. return fwrite($fp, $file_content);
  1536. }
  1537. }
  1538. /**
  1539. * Opens html file $full_file_name;
  1540. * Parses the hyperlinks; and
  1541. * Writes the result back in the html file.
  1542. *
  1543. * @author Roan Embrechts
  1544. * @version 0.1
  1545. */
  1546. function api_replace_links_in_html($upload_path, $full_file_name)
  1547. {
  1548. // Open the file
  1549. if (file_exists($full_file_name)) {
  1550. $fp = fopen($full_file_name, 'r');
  1551. $buffer = fread ($fp, filesize ($full_file_name));
  1552. // Parse the contents
  1553. $new_html_content = api_replace_links_in_string($upload_path, $buffer);
  1554. // Write the result
  1555. $fp = fopen($full_file_name, 'w');
  1556. fwrite($fp, $new_html_content);
  1557. }
  1558. }
  1559. /**
  1560. deprecated: use api_replace_parameter instead
  1561. Parse the buffer string provided as parameter
  1562. Replace the a href tags so they are displayed correctly.
  1563. - works for files in root and subdirectories
  1564. - replace relative hyperlinks to use showinframes.php?file= ...
  1565. - add target="_self" to all absolute hyperlinks
  1566. - leave local anchors untouched (e.g. #CHAPTER1)
  1567. - leave links with download.php and showinframes.php untouched
  1568. @author Roan Embrechts
  1569. @version 0.6
  1570. */
  1571. function api_replace_links_in_string($upload_path, $buffer) {
  1572. // Search for hyperlinks
  1573. $matches = array();
  1574. if (preg_match_all('/<a[\s]*href[^<]*>/i', $buffer, $matches)) {
  1575. $tag_list = $matches[0];
  1576. }
  1577. // Search the filepath of all detected <a href> tags
  1578. if (sizeof($tag_list) > 0) {
  1579. $file_path_list = array();
  1580. $href_list = array();
  1581. foreach ($tag_list as & $this_tag) {
  1582. /* Match case insensitive, the stuff between the two ~ :
  1583. a href = <exactly one quote><one or more non-quotes><exactly one ">
  1584. e.g. a href="www.google.be", A HREF = "info.html"
  1585. to match ["] escape the " or else PHP interprets it
  1586. [\"]{1} --> matches exactly one "
  1587. + 1 or more (like * is 0 or more)
  1588. [\s]* matches whitespace
  1589. $matches contains captured subpatterns
  1590. the only one here is ([^\"]+) --> matches[1]
  1591. */
  1592. if (preg_match("~a href[\s]*=[\s]*[\"]{1}([^\"]+)[\"]{1}~i", $this_tag, $matches)) {
  1593. $file_path_list[] = $matches[1]; // older
  1594. $href_list[] = $matches[0]; // to also add target="_self"
  1595. }
  1596. }
  1597. }
  1598. // Replace the original hyperlinks by the correct ones
  1599. for ($count = 0; $count < sizeof($href_list); $count++) {
  1600. $replace_what[$count] = $href_list[$count];
  1601. $is_absolute_hyperlink = strpos($replace_what[$count], 'http');
  1602. $is_local_anchor = strpos($replace_what[$count], "#");
  1603. if (!$is_absolute_hyperlink && !$is_local_anchor) {
  1604. // This is a relative hyperlink
  1605. if ((strpos($replace_what[$count], 'showinframes.php') === false) &&
  1606. (strpos($replace_what[$count], 'download.php') === false)
  1607. ) {
  1608. // Fix the link to use showinframes.php
  1609. $replace_by[$count] = 'a href = "showinframes.php?file='.$upload_path.'/'.$file_path_list[$count].'" target="_self"';
  1610. } else {
  1611. // URL has been already fixed, leave it as is
  1612. $replace_by[$count] = $replace_what[$count];
  1613. }
  1614. } elseif ($is_absolute_hyperlink) {
  1615. $replace_by[$count] = 'a href="'.$file_path_list[$count].'" target ="_self"';
  1616. } else {
  1617. // Don't change anything
  1618. $replace_by[$count] = $replace_what[$count];
  1619. }
  1620. //Display::display_normal_message('Link replaced by ' . $replace_by[$count]); // debug
  1621. }
  1622. $buffer = str_replace($replace_what, $replace_by, $buffer);
  1623. return $buffer;
  1624. }
  1625. /**
  1626. EXPERIMENTAL - function seems to work, needs more testing
  1627. @param $upload_path is the path where the document is stored, like "/archive/"
  1628. if it is the root level, the function expects "/"
  1629. otherwise "/path/"
  1630. This function parses all tags with $param_name parameters.
  1631. so the tags are displayed correctly.
  1632. --------------
  1633. Algorithm v1.0
  1634. --------------
  1635. given a string and a parameter,
  1636. * OK find all tags in that string with the specified parameter (like href or src)
  1637. * OK for every one of these tags, find the src|href|... part to edit it
  1638. * OK change the src|href|... part to use download.php (or showinframes.php)
  1639. * OK do some special stuff for hyperlinks
  1640. Exceptions
  1641. * OK if download.php or showinframes.php is already in the tag, leave it alone
  1642. * OK if mailto is in the tag, leave it alone
  1643. * OK if the src|href param contains http://, it's absolute --> leave it alone
  1644. Special for hyperlinks (a href...)
  1645. * OK add target="_self"
  1646. * OK use showinframes.php instead of download.php
  1647. @author Roan Embrechts
  1648. @version 1.1
  1649. */
  1650. function api_replace_parameter($upload_path, $buffer, $param_name = 'src')
  1651. {
  1652. // Search for tags with $param_name as a parameter
  1653. /*
  1654. // [\s]* matches whitespace
  1655. // [\"=a-z] matches ", = and a-z
  1656. // ([\s]*[a-z]*)* matches all whitespace and normal alphabet
  1657. // characters a-z combinations but seems too slow
  1658. // perhaps ([\s]*[a-z]*) a maximum number of times ?
  1659. // [\s]*[a-z]*[\s]* matches many tags
  1660. // the ending "i" means to match case insensitive (a matches a and A)
  1661. */
  1662. $matches = array();
  1663. if (preg_match_all('/<[a-z]+[^<]*'.$param_name.'[^<]*>/i', $buffer, $matches)) {
  1664. $tag_list = $matches[0];
  1665. }
  1666. // Search the filepath of parameter $param_name in all detected tags
  1667. if (sizeof($tag_list) > 0) {
  1668. $file_path_list = array();
  1669. $href_list = array();
  1670. foreach ($tag_list as & $this_tag) {
  1671. //Display::display_normal_message(htmlentities($this_tag)); //debug
  1672. if ( preg_match("~".$param_name."[\s]*=[\s]*[\"]{1}([^\"]+)[\"]{1}~i", $this_tag, $matches)) {
  1673. $file_path_list[] = $matches[1]; // older
  1674. $href_list[] = $matches[0]; // to also add target="_self"
  1675. }
  1676. }
  1677. }
  1678. // Replace the original tags by the correct ones
  1679. for ($count = 0; $count < sizeof($href_list); $count++) {
  1680. $replace_what[$count] = $href_list[$count];
  1681. $is_absolute_hyperlink = strpos($replace_what[$count], 'http');
  1682. $is_local_anchor = strpos($replace_what[$count], '#');
  1683. if (!$is_absolute_hyperlink && !$is_local_anchor) {
  1684. if ((strpos($replace_what[$count], 'showinframes.php') === false)
  1685. && (strpos($replace_what[$count], 'download.php') === false)
  1686. && (strpos($replace_what[$count], 'mailto') === false)) {
  1687. // Fix the link to use download.php or showinframes.php
  1688. if (preg_match("/<a([\s]*[\"\/:'=a-z0-9]*){5}href[^<]*>/i", $tag_list[$count])) {
  1689. $replace_by[$count] = " $param_name =\"showinframes.php?file=" . $upload_path.$file_path_list[$count]."\" target=\"_self\" ";
  1690. } else {
  1691. $replace_by[$count] = " $param_name =\"download.php?doc_url=" . $upload_path.$file_path_list[$count]."\" ";
  1692. }
  1693. } else {
  1694. // "mailto" or url already fixed, leave as is
  1695. //$message .= "Already fixed or contains mailto: ";
  1696. $replace_by[$count] = $replace_what[$count];
  1697. }
  1698. } elseif ($is_absolute_hyperlink) {
  1699. //$message .= "Absolute hyperlink, don't change, add target=_self: ";
  1700. $replace_by[$count] = " $param_name=\"" . $file_path_list[$count] . "\" target =\"_self\"";
  1701. } else {
  1702. // Don't change anything
  1703. //$message .= "Local anchor, don't change: ";
  1704. $replace_by[$count] = $replace_what[$count];
  1705. }
  1706. //$message .= "In tag $count, <b>" . htmlentities($tag_list[$count])
  1707. // . "</b>, parameter <b>" . $replace_what[$count] . "</b> replaced by <b>" . $replace_by[$count] . "</b><br>"; //debug
  1708. }
  1709. //if ($message) api_display_debug_info($message); //debug
  1710. $buffer = str_replace($replace_what, $replace_by, $buffer);
  1711. return $buffer;
  1712. }
  1713. /**
  1714. * Checks the extension of a file, if it's .htm or .html
  1715. * we use search_img_from_html to get all image paths in the file
  1716. *
  1717. * @param string $file
  1718. * @return array paths
  1719. * @see check_for_missing_files() uses search_img_from_html()
  1720. */
  1721. function check_for_missing_files($file)
  1722. {
  1723. if (strrchr($file, '.') == '.htm' || strrchr($file, '.') == '.html') {
  1724. $img_file_path = search_img_from_html($file);
  1725. return $img_file_path;
  1726. }
  1727. return false;
  1728. }
  1729. /**
  1730. * This function builds a form that asks for the missing images in a html file
  1731. * maybe we should do this another way?
  1732. *
  1733. * @param array $missing_files
  1734. * @param string $upload_path
  1735. * @param string $file_name
  1736. * @return string the form
  1737. */
  1738. function build_missing_files_form($missing_files, $upload_path, $file_name)
  1739. {
  1740. // Do we need a / or not?
  1741. $added_slash = ($upload_path == '/') ? '' : '/';
  1742. $folder_id = DocumentManager::get_document_id(api_get_course_info(), $upload_path);
  1743. // Build the form
  1744. $form = "<p><strong>".get_lang('MissingImagesDetected')."</strong></p>"
  1745. ."<form method=\"post\" action=\"".api_get_self()."\" enctype=\"multipart/form-data\">"
  1746. // Related_file is the path to the file that has missing images
  1747. ."<input type=\"hidden\" name=\"related_file\" value=\"".$upload_path.$added_slash.$file_name."\" />"
  1748. ."<input type=\"hidden\" name=\"upload_path\" value=\"".$upload_path."\" />"
  1749. ."<input type=\"hidden\" name=\"id\" value=\"".$folder_id."\" />"
  1750. ."<table border=\"0\">";
  1751. foreach ($missing_files as & $this_img_file_path) {
  1752. $form .= "<tr>"
  1753. ."<td>".basename($this_img_file_path)." : </td>"
  1754. ."<td>"
  1755. ."<input type=\"file\" name=\"img_file[]\"/>"
  1756. ."<input type=\"hidden\" name=\"img_file_path[]\" value=\"".$this_img_file_path."\" />"
  1757. ."</td>"
  1758. ."</tr>";
  1759. }
  1760. $form .= "</table>"
  1761. ."<button type='submit' name=\"cancel_submit_image\" value=\"".get_lang('Cancel')."\" class=\"cancel\">".get_lang('Cancel')."</button>"
  1762. ."<button type='submit' name=\"submit_image\" value=\"".get_lang('Ok')."\" class=\"save\">".get_lang('Ok')."</button>"
  1763. ."</form>";
  1764. return $form;
  1765. }
  1766. /**
  1767. * This recursive function can be used during the upgrade process form older
  1768. * versions of Chamilo
  1769. * It crawls the given directory, checks if the file is in the DB and adds
  1770. * it if it's not
  1771. *
  1772. * @param array $courseInfo
  1773. * @param array $userInfo
  1774. * @param string $base_work_dir
  1775. * @param string $folderPath
  1776. * @param int $sessionId
  1777. * @param int $groupId
  1778. * @param bool $output
  1779. * @param array $parent
  1780. * @param string $uploadPath
  1781. *
  1782. */
  1783. function add_all_documents_in_folder_to_database(
  1784. $courseInfo,
  1785. $userInfo,
  1786. $base_work_dir,
  1787. $folderPath,
  1788. $sessionId = 0,
  1789. $groupId = 0,
  1790. $output = false,
  1791. $parent = array()
  1792. ) {
  1793. if (empty($userInfo) || empty($courseInfo)) {
  1794. return false;
  1795. }
  1796. $userId = $userInfo['user_id'];
  1797. // Open dir
  1798. $handle = opendir($folderPath);
  1799. $files = array();
  1800. if (is_dir($folderPath)) {
  1801. // Run trough
  1802. while ($file = readdir($handle)) {
  1803. if ($file == '.' || $file == '..') {
  1804. continue;
  1805. }
  1806. $parentPath = null;
  1807. if (!empty($parent) && isset($parent['path'])) {
  1808. $parentPath = $parent['path'];
  1809. if ($parentPath == '/') {
  1810. $parentPath = null;
  1811. }
  1812. }
  1813. $completePath = $parentPath.'/'.$file;
  1814. $sysFolderPath = $folderPath.'/'.$file;
  1815. // Is directory?
  1816. if (is_dir($sysFolderPath)) {
  1817. $newFolderData = create_unexisting_directory(
  1818. $courseInfo,
  1819. $userId,
  1820. $sessionId,
  1821. $groupId,
  1822. null,
  1823. $base_work_dir,
  1824. $completePath,
  1825. null,
  1826. null,
  1827. true
  1828. );
  1829. $files[$file] = $newFolderData;
  1830. // Recursive
  1831. add_all_documents_in_folder_to_database(
  1832. $courseInfo,
  1833. $userInfo,
  1834. $base_work_dir,
  1835. $sysFolderPath,
  1836. $sessionId,
  1837. $groupId,
  1838. $output,
  1839. $newFolderData
  1840. );
  1841. } else {
  1842. // Rename
  1843. $uploadedFile = array(
  1844. 'name' => $file,
  1845. 'tmp_name' => $sysFolderPath,
  1846. 'size' => filesize($sysFolderPath),
  1847. 'type' => null,
  1848. 'from_file' => true,
  1849. 'move_file' => true
  1850. );
  1851. handle_uploaded_document(
  1852. $courseInfo,
  1853. $uploadedFile,
  1854. $base_work_dir,
  1855. $parentPath,
  1856. $userId,
  1857. $groupId,
  1858. null,
  1859. 0,
  1860. 'overwrite',
  1861. $output,
  1862. false,
  1863. null,
  1864. $sessionId
  1865. );
  1866. }
  1867. }
  1868. }
  1869. }