fileUpload.lib.php 68 KB

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