lib.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362
  1. <?php
  2. // This file is part of Moodle - http://moodle.org/
  3. //
  4. // Moodle is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // Moodle is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU General Public License
  15. // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
  16. /**
  17. * This plugin is used to access local files
  18. *
  19. * @since Moodle 2.0
  20. * @package repository_local
  21. * @copyright 2010 Dongsheng Cai {@link http://dongsheng.org}
  22. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  23. */
  24. require_once($CFG->dirroot . '/repository/lib.php');
  25. /**
  26. * repository_local class is used to browse moodle files
  27. *
  28. * @since Moodle 2.0
  29. * @package repository_local
  30. * @copyright 2012 Marina Glancy
  31. * @copyright 2009 Dongsheng Cai {@link http://dongsheng.org}
  32. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  33. */
  34. class repository_local extends repository {
  35. /**
  36. * Get file listing
  37. *
  38. * @param string $encodedpath
  39. * @param string $page no paging is used in repository_local
  40. * @return mixed
  41. */
  42. public function get_listing($encodedpath = '', $page = '') {
  43. global $CFG, $USER, $OUTPUT;
  44. $ret = array();
  45. $ret['dynload'] = true;
  46. $ret['nosearch'] = false;
  47. $ret['nologin'] = true;
  48. $ret['list'] = array();
  49. $itemid = null;
  50. $filename = null;
  51. $filearea = null;
  52. $filepath = null;
  53. $component = null;
  54. if (!empty($encodedpath)) {
  55. $params = json_decode(base64_decode($encodedpath), true);
  56. if (is_array($params) && isset($params['contextid'])) {
  57. $component = is_null($params['component']) ? NULL : clean_param($params['component'], PARAM_COMPONENT);
  58. $filearea = is_null($params['filearea']) ? NULL : clean_param($params['filearea'], PARAM_AREA);
  59. $itemid = is_null($params['itemid']) ? NULL : clean_param($params['itemid'], PARAM_INT);
  60. $filepath = is_null($params['filepath']) ? NULL : clean_param($params['filepath'], PARAM_PATH);
  61. $filename = is_null($params['filename']) ? NULL : clean_param($params['filename'], PARAM_FILE);
  62. $context = context::instance_by_id(clean_param($params['contextid'], PARAM_INT));
  63. }
  64. }
  65. if (empty($context) && !empty($this->context)) {
  66. $context = $this->context->get_course_context(false);
  67. }
  68. if (empty($context)) {
  69. $context = context_system::instance();
  70. }
  71. // prepare list of allowed extensions: $extensions is either string '*'
  72. // or array of lowercase extensions, i.e. array('.gif','.jpg')
  73. $extensions = optional_param_array('accepted_types', '', PARAM_RAW);
  74. if (empty($extensions) || $extensions === '*' || (is_array($extensions) && in_array('*', $extensions))) {
  75. $extensions = '*';
  76. } else {
  77. if (!is_array($extensions)) {
  78. $extensions = array($extensions);
  79. }
  80. $extensions = array_map('core_text::strtolower', $extensions);
  81. }
  82. // build file tree
  83. $browser = get_file_browser();
  84. if (!($fileinfo = $browser->get_file_info($context, $component, $filearea, $itemid, $filepath, $filename))) {
  85. // if file doesn't exist, build path nodes root of current context
  86. $fileinfo = $browser->get_file_info($context, null, null, null, null, null);
  87. }
  88. $ret['list'] = $this->get_non_empty_children($fileinfo, $extensions);
  89. // build path navigation
  90. $path = array();
  91. for ($level = $fileinfo; $level; $level = $level->get_parent()) {
  92. array_unshift($path, $level);
  93. }
  94. array_unshift($path, null);
  95. $ret['path'] = array();
  96. for ($i=1; $i<count($path); $i++) {
  97. if ($path[$i] == $fileinfo || !$this->can_skip($path[$i], $extensions, $path[$i-1])) {
  98. $ret['path'][] = $this->get_node_path($path[$i]);
  99. }
  100. }
  101. return $ret;
  102. }
  103. /**
  104. * Tells how the file can be picked from this repository
  105. *
  106. * @return int
  107. */
  108. public function supported_returntypes() {
  109. return FILE_INTERNAL | FILE_REFERENCE;
  110. }
  111. /**
  112. * Does this repository used to browse moodle files?
  113. *
  114. * @return boolean
  115. */
  116. public function has_moodle_files() {
  117. return true;
  118. }
  119. /**
  120. * Returns all children elements that have one of the specified extensions
  121. *
  122. * This function may skip subfolders and recursively add their children
  123. * {@link repository_local::can_skip()}
  124. *
  125. * @param file_info $fileinfo
  126. * @param string|array $extensions, for example '*' or array('.gif','.jpg')
  127. * @return array array of file_info elements
  128. */
  129. private function get_non_empty_children(file_info $fileinfo, $extensions) {
  130. $nonemptychildren = $fileinfo->get_non_empty_children($extensions);
  131. $list = array();
  132. foreach ($nonemptychildren as $child) {
  133. if ($this->can_skip($child, $extensions, $fileinfo)) {
  134. $list = array_merge($list, $this->get_non_empty_children($child, $extensions));
  135. } else {
  136. $list[] = $this->get_node($child);
  137. }
  138. }
  139. return $list;
  140. }
  141. /**
  142. * Whether this folder may be skipped in folder hierarchy
  143. *
  144. * 1. Skip the name of a single filearea in a module
  145. * 2. Skip course categories for non-admins who do not have navshowmycoursecategories setting
  146. *
  147. * @param file_info $fileinfo
  148. * @param string|array $extensions, for example '*' or array('.gif','.jpg')
  149. * @param file_info|int $parent specify parent here if we know it to avoid creating extra objects
  150. * @return bool
  151. */
  152. private function can_skip(file_info $fileinfo, $extensions, $parent = -1) {
  153. global $CFG;
  154. if (!$fileinfo->is_directory()) {
  155. // do not skip files
  156. return false;
  157. }
  158. if ($fileinfo instanceof file_info_context_coursecat) {
  159. // This is a course category. For non-admins we do not display categories
  160. return empty($CFG->navshowmycoursecategories) &&
  161. !has_capability('moodle/course:update', context_system::instance());
  162. } else if ($fileinfo instanceof file_info_context_course ||
  163. $fileinfo instanceof file_info_context_user ||
  164. $fileinfo instanceof file_info_area_course_legacy ||
  165. $fileinfo instanceof file_info_context_module ||
  166. $fileinfo instanceof file_info_context_system) {
  167. // these instances can never be filearea inside an activity, they will never be skipped
  168. return false;
  169. } else {
  170. $params = $fileinfo->get_params();
  171. if (strlen($params['filearea']) &&
  172. ($params['filepath'] === '/' || empty($params['filepath'])) &&
  173. ($params['filename'] === '.' || empty($params['filename'])) &&
  174. context::instance_by_id($params['contextid'])->contextlevel == CONTEXT_MODULE) {
  175. if ($parent === -1) {
  176. $parent = $fileinfo->get_parent();
  177. }
  178. // This is a filearea inside an activity, it can be skipped if it has no non-empty siblings
  179. if ($parent && ($parent instanceof file_info_context_module)) {
  180. if ($parent->count_non_empty_children($extensions, 2) <= 1) {
  181. return true;
  182. }
  183. }
  184. }
  185. }
  186. return false;
  187. }
  188. /**
  189. * Converts file_info object to element of repository return list
  190. *
  191. * @param file_info $fileinfo
  192. * @return array
  193. */
  194. private function get_node(file_info $fileinfo) {
  195. global $OUTPUT;
  196. $encodedpath = base64_encode(json_encode($fileinfo->get_params()));
  197. $node = array(
  198. 'title' => $fileinfo->get_visible_name(),
  199. 'datemodified' => $fileinfo->get_timemodified(),
  200. 'datecreated' => $fileinfo->get_timecreated()
  201. );
  202. if ($fileinfo->is_directory()) {
  203. $node['path'] = $encodedpath;
  204. $node['thumbnail'] = $OUTPUT->pix_url(file_folder_icon(90))->out(false);
  205. $node['children'] = array();
  206. } else {
  207. $node['size'] = $fileinfo->get_filesize();
  208. $node['author'] = $fileinfo->get_author();
  209. $node['license'] = $fileinfo->get_license();
  210. $node['isref'] = $fileinfo->is_external_file();
  211. if ($fileinfo->get_status() == 666) {
  212. $node['originalmissing'] = true;
  213. }
  214. $node['source'] = $encodedpath;
  215. $node['thumbnail'] = $OUTPUT->pix_url(file_file_icon($fileinfo, 90))->out(false);
  216. $node['icon'] = $OUTPUT->pix_url(file_file_icon($fileinfo, 24))->out(false);
  217. if ($imageinfo = $fileinfo->get_imageinfo()) {
  218. // what a beautiful picture, isn't it
  219. $fileurl = new moodle_url($fileinfo->get_url());
  220. $node['realthumbnail'] = $fileurl->out(false, array('preview' => 'thumb', 'oid' => $fileinfo->get_timemodified()));
  221. $node['realicon'] = $fileurl->out(false, array('preview' => 'tinyicon', 'oid' => $fileinfo->get_timemodified()));
  222. $node['image_width'] = $imageinfo['width'];
  223. $node['image_height'] = $imageinfo['height'];
  224. }
  225. }
  226. return $node;
  227. }
  228. /**
  229. * Converts file_info object to element of repository return path
  230. *
  231. * @param file_info $fileinfo
  232. * @return array
  233. */
  234. private function get_node_path(file_info $fileinfo) {
  235. $encodedpath = base64_encode(json_encode($fileinfo->get_params()));
  236. return array(
  237. 'path' => $encodedpath,
  238. 'name' => $fileinfo->get_visible_name()
  239. );
  240. }
  241. /**
  242. * Search through all the files.
  243. *
  244. * This method will do a raw search through the database, then will try
  245. * to match with files that a user can access. A maximum of 50 files will be
  246. * returned at a time, excluding possible duplicates found along the way.
  247. *
  248. * Queries are done in chunk of 100 files to prevent too many records to be fetched
  249. * at once. When too many files are not included, or a maximum of 10 queries are
  250. * performed we consider that this was the last page.
  251. *
  252. * @param String $q The query string.
  253. * @param integer $page The page number.
  254. * @return array of results.
  255. */
  256. public function search($q, $page = 1) {
  257. global $DB, $SESSION;
  258. // Because the repository API is weird, the first page is 0, but it should be 1.
  259. if (!$page) {
  260. $page = 1;
  261. }
  262. if (!isset($SESSION->repository_local_search)) {
  263. $SESSION->repository_local_search = array();
  264. }
  265. $fs = get_file_storage();
  266. $fb = get_file_browser();
  267. $max = 50;
  268. $limit = 100;
  269. if ($page <= 1) {
  270. $SESSION->repository_local_search['query'] = $q;
  271. $SESSION->repository_local_search['from'] = 0;
  272. $from = 0;
  273. } else {
  274. // Yes, the repository does not send the query again...
  275. $q = $SESSION->repository_local_search['query'];
  276. $from = (int) $SESSION->repository_local_search['from'];
  277. }
  278. $count = $fs->search_server_files('%' . $DB->sql_like_escape($q) . '%', null, null, true);
  279. $remaining = $count - $from;
  280. $maxloops = 3000;
  281. $loops = 0;
  282. $results = array();
  283. while (count($results) < $max && $maxloops > 0 && $remaining > 0) {
  284. if (empty($files)) {
  285. $files = $fs->search_server_files('%' . $DB->sql_like_escape($q) . '%', $from, $limit);
  286. $from += $limit;
  287. };
  288. $remaining--;
  289. $maxloops--;
  290. $loops++;
  291. $file = array_shift($files);
  292. if (!$file) {
  293. // This should not happen.
  294. throw new coding_exception('Unexpected end of files list.');
  295. }
  296. $key = $file->get_contenthash() . ':' . $file->get_filename();
  297. if (isset($results[$key])) {
  298. // We found the file with same content and same name, let's skip it.
  299. continue;
  300. }
  301. $ctx = context::instance_by_id($file->get_contextid());
  302. $fileinfo = $fb->get_file_info($ctx, $file->get_component(), $file->get_filearea(), $file->get_itemid(),
  303. $file->get_filepath(), $file->get_filename());
  304. if ($fileinfo) {
  305. $results[$key] = $this->get_node($fileinfo);
  306. }
  307. }
  308. // Save the position for the paging to work.
  309. if ($maxloops > 0 && $remaining > 0) {
  310. $SESSION->repository_local_search['from'] += $loops;
  311. $pages = -1;
  312. } else {
  313. $SESSION->repository_local_search['from'] = 0;
  314. $pages = 0;
  315. }
  316. $return = array(
  317. 'list' => array_values($results),
  318. 'dynload' => true,
  319. 'pages' => $pages,
  320. 'page' => $page
  321. );
  322. return $return;
  323. }
  324. /**
  325. * Is this repository accessing private data?
  326. *
  327. * @return bool
  328. */
  329. public function contains_private_data() {
  330. return false;
  331. }
  332. }