downloadfolder.inc.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337
  1. <?php
  2. /* For licensing terms, see /license.txt */
  3. /**
  4. * Functions and main code for the download folder feature
  5. *
  6. * @package chamilo.document
  7. */
  8. use ChamiloSession as Session;
  9. set_time_limit(0);
  10. require_once '../inc/global.inc.php';
  11. api_protect_course_script();
  12. $sysCoursePath = api_get_path(SYS_COURSE_PATH);
  13. $courseInfo = api_get_course_info();
  14. $courseId = api_get_course_int_id();
  15. $sessionId = api_get_session_id();
  16. $groupId = api_get_group_id();
  17. $courseCode = api_get_course_id();
  18. // Check if folder exists in current course.
  19. $documentInfo = DocumentManager::get_document_data_by_id(
  20. $_GET['id'],
  21. $courseCode,
  22. false,
  23. 0
  24. );
  25. if (!empty($sessionId)) {
  26. /* If no data found and session id exists
  27. try to look the file inside the session */
  28. if (empty($documentInfo)) {
  29. $documentInfo = DocumentManager::get_document_data_by_id(
  30. $_GET['id'],
  31. $courseCode,
  32. false,
  33. $sessionId
  34. );
  35. }
  36. }
  37. $path = $documentInfo['path'];
  38. if (empty($path)) {
  39. $path = '/';
  40. }
  41. // A student should not be able to download a root shared directory
  42. if (($path == '/shared_folder' ||
  43. $path == '/shared_folder_session_' . api_get_session_id()) &&
  44. (!api_is_allowed_to_edit() || !api_is_platform_admin())
  45. ) {
  46. api_not_allowed(true);
  47. exit;
  48. }
  49. // Creating a ZIP file.
  50. $tempZipFile = api_get_path(SYS_ARCHIVE_PATH).api_get_unique_id().".zip";
  51. $zip = new PclZip($tempZipFile);
  52. $doc_table = Database::get_course_table(TABLE_DOCUMENT);
  53. $prop_table = Database::get_course_table(TABLE_ITEM_PROPERTY);
  54. // We need this path to clean it out of the zip file
  55. // I'm not using dir name as it gives too much problems (cfr.)
  56. $remove_dir = ($path != '/') ? substr($path, 0, strlen($path) - strlen(basename($path))) : '/';
  57. // Put the files in the zip
  58. // 2 possibilities: Admins get all files and folders in the selected folder (except for the deleted ones)
  59. // Normal users get only visible files that are in visible folders
  60. function fixDocumentNameCallback($p_event, &$p_header)
  61. {
  62. global $remove_dir;
  63. $files = Session::read('doc_files_to_download');
  64. $storedFile = $remove_dir.$p_header['stored_filename'];
  65. if (!isset($files[$storedFile])) {
  66. return 0;
  67. }
  68. $documentData = $files[$storedFile];
  69. $documentNameFixed = DocumentManager::undoFixDocumentName(
  70. $documentData['path'],
  71. $documentData['c_id'],
  72. $documentData['session_id'],
  73. $documentData['to_group_id']
  74. );
  75. // Changes file.phps to file.php
  76. $basename = basename($documentNameFixed);
  77. $basenamePHPFixed = str_replace('.phps', '.php', $basename);
  78. $documentNameFixed = str_replace(
  79. $basename,
  80. $basenamePHPFixed,
  81. $documentNameFixed
  82. );
  83. $documentNameFixed = str_replace($remove_dir, '/', $documentNameFixed);
  84. $p_header['stored_filename'] = $documentNameFixed;
  85. return 1;
  86. }
  87. $groupCondition = " props.to_group_id = ".$groupId;
  88. if (empty($groupId)) {
  89. $groupCondition = " (props.to_group_id = 0 OR props.to_group_id IS NULL ) ";
  90. }
  91. // Admins are allowed to download invisible files
  92. if (api_is_allowed_to_edit()) {
  93. // Set the path that will be used in the query
  94. if ($path == '/') {
  95. $querypath = ''; // To prevent ...path LIKE '//%'... in query
  96. } else {
  97. $querypath = $path;
  98. }
  99. $querypath = Database::escape_string($querypath);
  100. // Search for all files that are not deleted => visibility != 2
  101. $sql = "SELECT
  102. path,
  103. docs.session_id,
  104. docs.id,
  105. props.to_group_id,
  106. docs.c_id
  107. FROM $doc_table AS docs
  108. INNER JOIN $prop_table AS props
  109. ON
  110. docs.id = props.ref AND
  111. docs.c_id = props.c_id
  112. WHERE
  113. props.tool ='".TOOL_DOCUMENT."' AND
  114. docs.path LIKE '".$querypath."/%' AND
  115. docs.filetype = 'file' AND
  116. props.visibility <> '2' AND
  117. $groupCondition AND
  118. (props.session_id IN ('0', '$sessionId') OR props.session_id IS NULL) AND
  119. docs.c_id = ".$courseId." ";
  120. $sql.= DocumentManager::getSessionFolderFilters($querypath, $sessionId);
  121. $result = Database::query($sql);
  122. $files = array();
  123. while ($row = Database::fetch_array($result)) {
  124. $files[$row['path']] = $row;
  125. }
  126. Session::write('doc_files_to_download', $files);
  127. foreach ($files as $not_deleted_file) {
  128. // Filtering folders and
  129. if (strpos($not_deleted_file['path'], 'chat_files') > 0 ||
  130. strpos($not_deleted_file['path'], 'shared_folder') > 0
  131. ) {
  132. if (!empty($sessionId)) {
  133. if ($not_deleted_file['session_id'] != $sessionId) {
  134. continue;
  135. }
  136. }
  137. }
  138. //error_log($sysCoursePath.$courseInfo['path'].'/document'.$not_deleted_file['path']);
  139. //error_log($sysCoursePath.$courseInfo['path'].'/document'.$remove_dir);
  140. $zip->add(
  141. $sysCoursePath.$courseInfo['path'].'/document'.$not_deleted_file['path'],
  142. PCLZIP_OPT_REMOVE_PATH,
  143. $sysCoursePath.$courseInfo['path'].'/document'.$remove_dir,
  144. PCLZIP_CB_PRE_ADD,
  145. 'fixDocumentNameCallback'
  146. );
  147. }
  148. Session::erase('doc_files_to_download');
  149. } else {
  150. // For other users, we need to create a zip file with only visible files and folders
  151. if ($path == '/') {
  152. $querypath = ''; // To prevent ...path LIKE '//%'... in query
  153. } else {
  154. $querypath = $path;
  155. }
  156. /* A big problem: Visible files that are in a hidden folder are
  157. included when we do a query for visiblity='v'
  158. So... I do it in a couple of steps:
  159. 1st: Get all files that are visible in the given path
  160. */
  161. $querypath = Database::escape_string($querypath);
  162. $sql = "SELECT path, session_id, docs.id, props.to_group_id, docs.c_id
  163. FROM $doc_table AS docs
  164. INNER JOIN $prop_table AS props
  165. ON
  166. docs.id = props.ref AND
  167. docs.c_id = props.c_id
  168. WHERE
  169. docs.c_id = $courseId AND
  170. props.tool = '".TOOL_DOCUMENT."' AND
  171. docs.path LIKE '".$querypath."/%' AND
  172. props.visibility = '1' AND
  173. docs.filetype = 'file' AND
  174. (props.session_id IN ('0', '$sessionId') OR props.session_id IS NULL) AND
  175. $groupCondition
  176. ";
  177. $sql.= DocumentManager::getSessionFolderFilters($querypath, $sessionId);
  178. $result = Database::query($sql);
  179. $files = array();
  180. // Add them to an array
  181. while ($all_visible_files = Database::fetch_assoc($result)) {
  182. if (strpos($all_visible_files['path'], 'chat_files') > 0 ||
  183. strpos($all_visible_files['path'], 'shared_folder') > 0
  184. ) {
  185. if (!empty($sessionId)) {
  186. if ($all_visible_files['session_id'] != $sessionId) {
  187. continue;
  188. }
  189. }
  190. }
  191. $all_visible_files_path[] = $all_visible_files['path'];
  192. $files[$all_visible_files['path']] = $all_visible_files;
  193. }
  194. // 2nd: Get all folders that are invisible in the given path
  195. $sql = "SELECT path, session_id, docs.id, props.to_group_id, docs.c_id
  196. FROM $doc_table AS docs INNER JOIN $prop_table AS props
  197. ON
  198. docs.id = props.ref AND
  199. docs.c_id = props.c_id
  200. WHERE
  201. docs.c_id = $courseId AND
  202. props.tool = '".TOOL_DOCUMENT."' AND
  203. docs.path LIKE '".$querypath."/%' AND
  204. props.visibility <> '1' AND
  205. (props.session_id IN ('0', '$sessionId') OR props.session_id IS NULL) AND
  206. docs.filetype = 'folder'";
  207. $query2 = Database::query($sql);
  208. // If we get invisible folders, we have to filter out these results from all visible files we found
  209. if (Database::num_rows($query2) > 0) {
  210. $files = array();
  211. // Add item to an array
  212. while ($invisible_folders = Database::fetch_assoc($query2)) {
  213. //3rd: Get all files that are in the found invisible folder (these are "invisible" too)
  214. $sql = "SELECT path, docs.id, props.to_group_id, docs.c_id
  215. FROM $doc_table AS docs
  216. INNER JOIN $prop_table AS props
  217. ON
  218. docs.id = props.ref AND
  219. docs.c_id = props.c_id
  220. WHERE
  221. docs.c_id = $courseId AND
  222. props.tool ='".TOOL_DOCUMENT."' AND
  223. docs.path LIKE '".$invisible_folders['path']."/%' AND
  224. docs.filetype = 'file' AND
  225. (props.session_id IN ('0', '$sessionId') OR props.session_id IS NULL) AND
  226. props.visibility ='1'";
  227. $query3 = Database::query($sql);
  228. // Add tem to an array
  229. while ($files_in_invisible_folder = Database::fetch_assoc($query3)) {
  230. $files_in_invisible_folder_path[] = $files_in_invisible_folder['path'];
  231. $files[$files_in_invisible_folder['path']] = $files_in_invisible_folder;
  232. }
  233. }
  234. // Compare the array with visible files and the array with files in invisible folders
  235. // and keep the difference (= all visible files that are not in an invisible folder)
  236. $files_for_zipfile = diff(
  237. (array) $all_visible_files_path,
  238. (array) $files_in_invisible_folder_path
  239. );
  240. } else {
  241. // No invisible folders found, so all visible files can be added to the zipfile
  242. $files_for_zipfile = $all_visible_files_path;
  243. }
  244. Session::write('doc_files_to_download', $files);
  245. // Add all files in our final array to the zipfile
  246. for ($i = 0; $i < count($files_for_zipfile); $i++) {
  247. $zip->add(
  248. $sysCoursePath . $courseInfo['path'] . '/document' . $files_for_zipfile[$i],
  249. PCLZIP_OPT_REMOVE_PATH,
  250. $sysCoursePath . $courseInfo['path'] . '/document' . $remove_dir,
  251. PCLZIP_CB_PRE_ADD,
  252. 'fixDocumentNameCallback'
  253. );
  254. }
  255. Session::erase('doc_files_to_download');
  256. }
  257. // Launch event
  258. Event::event_download(
  259. ($path == '/') ? 'documents.zip (folder)' : basename($path).'.zip (folder)'
  260. );
  261. // Start download of created file
  262. $name = ($path == '/') ? 'documents.zip' : $documentInfo['title'].'.zip';
  263. if (Security::check_abs_path($tempZipFile, api_get_path(SYS_ARCHIVE_PATH))) {
  264. $result = DocumentManager::file_send_for_download($tempZipFile, true, $name);
  265. @unlink($tempZipFile);
  266. exit;
  267. } else {
  268. api_not_allowed(true);
  269. }
  270. /**
  271. * Returns the difference between two arrays, as an array of those key/values
  272. * Use this as array_diff doesn't give the
  273. *
  274. * @param array $arr1 first array
  275. * @param array $arr2 second array
  276. *
  277. * @return array difference between the two arrays
  278. */
  279. function diff($arr1, $arr2)
  280. {
  281. $res = array();
  282. $r = 0;
  283. foreach ($arr1 as & $av) {
  284. if (!in_array($av, $arr2)) {
  285. $res[$r] = $av;
  286. $r++;
  287. }
  288. }
  289. return $res;
  290. }