fileUpload.lib.php 74 KB

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