fileUpload.lib.php 72 KB

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