fileUpload.lib.php 76 KB

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