fileUpload.lib.php 67 KB

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