downloadfolder.inc.php 11 KB

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