downloadfolder.inc.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348
  1. <?php
  2. /* For licensing terms, see /license.txt */
  3. use ChamiloSession as Session;
  4. /**
  5. * Functions and main code for the download folder feature.
  6. *
  7. * @package chamilo.document
  8. */
  9. set_time_limit(0);
  10. require_once __DIR__.'/../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. if ($remove_dir != '/') {
  84. $documentNameFixed = str_replace($remove_dir, '/', $documentNameFixed);
  85. if (substr($documentNameFixed, 0, 1) == '/') {
  86. $documentNameFixed = substr($documentNameFixed, 1, api_strlen($documentNameFixed));
  87. }
  88. } else {
  89. $documentNameFixed = ltrim($documentNameFixed, '/');
  90. }
  91. $p_header['stored_filename'] = $documentNameFixed;
  92. return 1;
  93. }
  94. $groupJoin = '';
  95. if (!empty($groupId)) {
  96. $table = Database::get_course_table(TABLE_GROUP);
  97. $groupJoin = " INNER JOIN $table g ON (g.iid = props.to_group_id AND g.c_id = docs.c_id)";
  98. $groupCondition = " g.id = ".$groupId;
  99. } else {
  100. $groupCondition = " (props.to_group_id = 0 OR props.to_group_id IS NULL ) ";
  101. }
  102. // Admins are allowed to download invisible files
  103. if (api_is_allowed_to_edit()) {
  104. // Set the path that will be used in the query
  105. if ($path == '/') {
  106. $querypath = ''; // To prevent ...path LIKE '//%'... in query
  107. } else {
  108. $querypath = $path;
  109. }
  110. $querypath = Database::escape_string($querypath);
  111. // Search for all files that are not deleted => visibility != 2
  112. $sql = "SELECT
  113. path,
  114. docs.session_id,
  115. docs.id,
  116. props.to_group_id,
  117. docs.c_id
  118. FROM $doc_table AS docs
  119. INNER JOIN $prop_table AS props
  120. ON
  121. docs.id = props.ref AND
  122. docs.c_id = props.c_id
  123. $groupJoin
  124. WHERE
  125. props.tool ='".TOOL_DOCUMENT."' AND
  126. docs.path LIKE '".$querypath."/%' AND
  127. docs.filetype = 'file' AND
  128. props.visibility <> '2' AND
  129. $groupCondition AND
  130. (props.session_id IN ('0', '$sessionId') OR props.session_id IS NULL) AND
  131. docs.c_id = ".$courseId." ";
  132. $sql .= DocumentManager::getSessionFolderFilters($querypath, $sessionId);
  133. $result = Database::query($sql);
  134. $files = [];
  135. while ($row = Database::fetch_array($result)) {
  136. $files[$row['path']] = $row;
  137. }
  138. Session::write('doc_files_to_download', $files);
  139. foreach ($files as $not_deleted_file) {
  140. // Filtering folders and
  141. if (strpos($not_deleted_file['path'], 'chat_files') > 0 ||
  142. strpos($not_deleted_file['path'], 'shared_folder') > 0
  143. ) {
  144. if (!empty($sessionId)) {
  145. if ($not_deleted_file['session_id'] != $sessionId) {
  146. continue;
  147. }
  148. }
  149. }
  150. $zip->add(
  151. $sysCoursePath.$courseInfo['path'].'/document'.$not_deleted_file['path'],
  152. PCLZIP_OPT_REMOVE_PATH,
  153. $sysCoursePath.$courseInfo['path'].'/document'.$remove_dir,
  154. PCLZIP_CB_PRE_ADD,
  155. 'fixDocumentNameCallback'
  156. );
  157. }
  158. Session::erase('doc_files_to_download');
  159. } else {
  160. // For other users, we need to create a zip file with only visible files and folders
  161. if ($path == '/') {
  162. $querypath = ''; // To prevent ...path LIKE '//%'... in query
  163. } else {
  164. $querypath = $path;
  165. }
  166. /* A big problem: Visible files that are in a hidden folder are
  167. included when we do a query for visibility='v'
  168. So... I do it in a couple of steps:
  169. 1st: Get all files that are visible in the given path
  170. */
  171. $querypath = Database::escape_string($querypath);
  172. $sql = "SELECT path, docs.session_id, docs.id, props.to_group_id, docs.c_id
  173. FROM $doc_table AS docs
  174. INNER JOIN $prop_table AS props
  175. ON
  176. docs.id = props.ref AND
  177. docs.c_id = props.c_id
  178. $groupJoin
  179. WHERE
  180. docs.c_id = $courseId AND
  181. props.tool = '".TOOL_DOCUMENT."' AND
  182. docs.path LIKE '".$querypath."/%' AND
  183. props.visibility = '1' AND
  184. docs.filetype = 'file' AND
  185. (props.session_id IN ('0', '$sessionId') OR props.session_id IS NULL) AND
  186. $groupCondition
  187. ";
  188. $sql .= DocumentManager::getSessionFolderFilters($querypath, $sessionId);
  189. $result = Database::query($sql);
  190. $files = [];
  191. $all_visible_files_path = [];
  192. // Add them to an array
  193. while ($all_visible_files = Database::fetch_assoc($result)) {
  194. if (strpos($all_visible_files['path'], 'chat_files') > 0 ||
  195. strpos($all_visible_files['path'], 'shared_folder') > 0
  196. ) {
  197. if (!empty($sessionId)) {
  198. if ($all_visible_files['session_id'] != $sessionId) {
  199. continue;
  200. }
  201. }
  202. }
  203. $all_visible_files_path[] = $all_visible_files['path'];
  204. $files[$all_visible_files['path']] = $all_visible_files;
  205. }
  206. // 2nd: Get all folders that are invisible in the given path
  207. $sql = "SELECT path, docs.session_id, docs.id, props.to_group_id, docs.c_id
  208. FROM $doc_table AS docs
  209. INNER JOIN $prop_table AS props
  210. ON
  211. docs.id = props.ref AND
  212. docs.c_id = props.c_id
  213. WHERE
  214. docs.c_id = $courseId AND
  215. props.tool = '".TOOL_DOCUMENT."' AND
  216. docs.path LIKE '".$querypath."/%' AND
  217. props.visibility <> '1' AND
  218. (props.session_id IN ('0', '$sessionId') OR props.session_id IS NULL) AND
  219. docs.filetype = 'folder'";
  220. $query2 = Database::query($sql);
  221. // If we get invisible folders, we have to filter out these results from all visible files we found
  222. if (Database::num_rows($query2) > 0) {
  223. $files = [];
  224. // Add item to an array
  225. while ($invisible_folders = Database::fetch_assoc($query2)) {
  226. //3rd: Get all files that are in the found invisible folder (these are "invisible" too)
  227. $sql = "SELECT path, docs.id, props.to_group_id, docs.c_id
  228. FROM $doc_table AS docs
  229. INNER JOIN $prop_table AS props
  230. ON
  231. docs.id = props.ref AND
  232. docs.c_id = props.c_id
  233. WHERE
  234. docs.c_id = $courseId AND
  235. props.tool ='".TOOL_DOCUMENT."' AND
  236. docs.path LIKE '".$invisible_folders['path']."/%' AND
  237. docs.filetype = 'file' AND
  238. (props.session_id IN ('0', '$sessionId') OR props.session_id IS NULL) AND
  239. props.visibility ='1'";
  240. $query3 = Database::query($sql);
  241. // Add tem to an array
  242. while ($files_in_invisible_folder = Database::fetch_assoc($query3)) {
  243. $files_in_invisible_folder_path[] = $files_in_invisible_folder['path'];
  244. $files[$files_in_invisible_folder['path']] = $files_in_invisible_folder;
  245. }
  246. }
  247. // Compare the array with visible files and the array with files in invisible folders
  248. // and keep the difference (= all visible files that are not in an invisible folder)
  249. $files_for_zipfile = diff(
  250. (array) $all_visible_files_path,
  251. (array) $files_in_invisible_folder_path
  252. );
  253. } else {
  254. // No invisible folders found, so all visible files can be added to the zipfile
  255. $files_for_zipfile = $all_visible_files_path;
  256. }
  257. Session::write('doc_files_to_download', $files);
  258. // Add all files in our final array to the zipfile
  259. for ($i = 0; $i < count($files_for_zipfile); $i++) {
  260. $zip->add(
  261. $sysCoursePath.$courseInfo['path'].'/document'.$files_for_zipfile[$i],
  262. PCLZIP_OPT_REMOVE_PATH,
  263. $sysCoursePath.$courseInfo['path'].'/document'.$remove_dir,
  264. PCLZIP_CB_PRE_ADD,
  265. 'fixDocumentNameCallback'
  266. );
  267. }
  268. Session::erase('doc_files_to_download');
  269. }
  270. // Launch event
  271. Event::event_download(
  272. ($path == '/') ? 'documents.zip (folder)' : basename($path).'.zip (folder)'
  273. );
  274. // Start download of created file
  275. $name = ($path == '/') ? 'documents.zip' : $documentInfo['title'].'.zip';
  276. if (Security::check_abs_path($tempZipFile, api_get_path(SYS_ARCHIVE_PATH))) {
  277. $result = DocumentManager::file_send_for_download($tempZipFile, true, $name);
  278. if ($result === false) {
  279. api_not_allowed(true);
  280. }
  281. @unlink($tempZipFile);
  282. exit;
  283. } else {
  284. api_not_allowed(true);
  285. }
  286. /**
  287. * Returns the difference between two arrays, as an array of those key/values
  288. * Use this as array_diff doesn't give the.
  289. *
  290. * @param array $arr1 first array
  291. * @param array $arr2 second array
  292. *
  293. * @return array difference between the two arrays
  294. */
  295. function diff($arr1, $arr2)
  296. {
  297. $res = [];
  298. $r = 0;
  299. foreach ($arr1 as &$av) {
  300. if (!in_array($av, $arr2)) {
  301. $res[$r] = $av;
  302. $r++;
  303. }
  304. }
  305. return $res;
  306. }