Search moodle.org's
Developer Documentation

See Release Notes

  • Bug fixes for general core bugs in 4.2.x will end 22 April 2024 (12 months).
  • Bug fixes for security issues in 4.2.x will end 7 October 2024 (18 months).
  • PHP version: minimum PHP 8.0.0 Note: minimum PHP version has increased since Moodle 4.1. PHP 8.1.x is supported too.

Differences Between: [Versions 310 and 402] [Versions 311 and 402] [Versions 39 and 402]

   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  
  18  /**
  19   * Utility class for browsing of curse category files.
  20   *
  21   * @package    core_files
  22   * @copyright  2008 Petr Skoda (http://skodak.org)
  23   * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  24   */
  25  
  26  defined('MOODLE_INTERNAL') || die();
  27  
  28  /**
  29   * Represents a course category context in the tree navigated by {@link file_browser}.
  30   *
  31   * @package    core_files
  32   * @copyright  2008 Petr Skoda (http://skodak.org)
  33   * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  34   */
  35  class file_info_context_coursecat extends file_info {
  36      /** @var stdClass Category object */
  37      protected $category;
  38  
  39      /**
  40       * Constructor
  41       *
  42       * @param file_browser $browser file browser instance
  43       * @param stdClass $context context object
  44       * @param stdClass $category category object
  45       */
  46      public function __construct($browser, $context, $category) {
  47          parent::__construct($browser, $context);
  48          $this->category = $category;
  49      }
  50  
  51      /**
  52       * Return information about this specific context level
  53       *
  54       * @param string $component component
  55       * @param string $filearea file area
  56       * @param int $itemid item ID
  57       * @param string $filepath file path
  58       * @param string $filename file name
  59       * @return fileinfo|null
  60       */
  61      public function get_file_info($component, $filearea, $itemid, $filepath, $filename) {
  62          global $DB;
  63  
  64          if (!core_course_category::can_view_category($this->category)) {
  65              if (empty($component)) {
  66                  // we can not list the category contents, so try parent, or top system
  67                  if ($this->category->parent and $pc = $DB->get_record('course_categories', array('id'=>$this->category->parent))) {
  68                      $parent = context_coursecat::instance($pc->id, IGNORE_MISSING);
  69                      return $this->browser->get_file_info($parent);
  70                  } else {
  71                      return $this->browser->get_file_info();
  72                  }
  73              }
  74              return null;
  75          }
  76  
  77          if (empty($component)) {
  78              return $this;
  79          }
  80  
  81          $methodname = "get_area_{$component}_{$filearea}";
  82          if (method_exists($this, $methodname)) {
  83              return $this->$methodname($itemid, $filepath, $filename);
  84          }
  85  
  86          return null;
  87      }
  88  
  89      /**
  90       * Return a file from course category description area
  91       *
  92       * @param int $itemid item ID
  93       * @param string $filepath file path
  94       * @param string $filename file name
  95       * @return fileinfo|null
  96       */
  97      protected function get_area_coursecat_description($itemid, $filepath, $filename) {
  98          global $CFG;
  99  
 100          if (!$this->category->id) {
 101              // No coursecat description area for "system".
 102              return null;
 103          }
 104          if (!core_course_category::can_view_category($this->category)) {
 105              return null;
 106          }
 107          if (!has_capability('moodle/category:manage', $this->context)) {
 108              return null;
 109          }
 110  
 111          if (is_null($itemid)) {
 112              return $this;
 113          }
 114  
 115          $fs = get_file_storage();
 116  
 117          $filepath = is_null($filepath) ? '/' : $filepath;
 118          $filename = is_null($filename) ? '.' : $filename;
 119          $urlbase = $CFG->wwwroot.'/pluginfile.php';
 120          if (!$storedfile = $fs->get_file($this->context->id, 'coursecat', 'description', 0, $filepath, $filename)) {
 121              if ($filepath === '/' and $filename === '.') {
 122                  $storedfile = new virtual_root_file($this->context->id, 'coursecat', 'description', 0);
 123              } else {
 124                  // not found
 125                  return null;
 126              }
 127          }
 128  
 129          return new file_info_stored($this->browser, $this->context, $storedfile, $urlbase, get_string('areacategoryintro', 'repository'), false, true, true, false);
 130      }
 131  
 132      /**
 133       * Returns localised visible name.
 134       *
 135       * @return string
 136       */
 137      public function get_visible_name() {
 138          return format_string($this->category->name, true, array('context'=>$this->context));
 139      }
 140  
 141      /**
 142       * Whether or not new files or directories can be added
 143       *
 144       * @return bool
 145       */
 146      public function is_writable() {
 147          return false;
 148      }
 149  
 150      /**
 151       * Whether or not this is a directory
 152       *
 153       * @return bool
 154       */
 155      public function is_directory() {
 156          return true;
 157      }
 158  
 159      /**
 160       * Returns list of children.
 161       *
 162       * @return array of file_info instances
 163       */
 164      public function get_children() {
 165          $children = array();
 166  
 167          if ($child = $this->get_area_coursecat_description(0, '/', '.')) {
 168              $children[] = $child;
 169          }
 170  
 171          list($coursecats, $hiddencats) = $this->get_categories();
 172          foreach ($coursecats as $category) {
 173              $context = context_coursecat::instance($category->id);
 174              $children[] = new self($this->browser, $context, $category);
 175          }
 176  
 177          $courses = $this->get_courses($hiddencats);
 178          foreach ($courses as $course) {
 179              $children[] = $this->get_child_course($course);
 180          }
 181  
 182          return array_filter($children);
 183      }
 184  
 185      /**
 186       * List of courses in this category and in hidden subcategories
 187       *
 188       * @param array $hiddencats list of categories that are hidden from current user and returned by {@link get_categories()}
 189       * @return array list of courses
 190       */
 191      protected function get_courses($hiddencats) {
 192          global $DB, $CFG;
 193          require_once($CFG->libdir.'/modinfolib.php');
 194  
 195          // Let's retrieve only minimum number of fields from course table -
 196          // what is needed to check access or call get_fast_modinfo().
 197          $coursefields = array_merge(['id', 'visible', 'sortorder'], \course_modinfo::$cachedfields);
 198          $fields = 'c.' . join(',c.', $coursefields) . ', ' .
 199              \context_helper::get_preload_record_columns_sql('ctx');
 200  
 201          // First statement uses only category.
 202          $sql1 = "SELECT $fields
 203                     FROM {course} c
 204                     JOIN {context} ctx ON (ctx.instanceid = c.id) AND (ctx.contextlevel = :contextlevel1)
 205                    WHERE c.category = :categoryid";
 206  
 207          $params = ['categoryid' => $this->category->id, 'contextlevel1' => CONTEXT_COURSE];
 208  
 209          if (empty($hiddencats)) {
 210              return $DB->get_records_sql($sql1, $params);
 211          }
 212  
 213          // Second statement uses only context paths.
 214          $orcond = [];
 215          foreach ($hiddencats as $category) {
 216              $catcontext = context_coursecat::instance($category->id);
 217  
 218              // Case- and accent-sensitive search is not necessary for paths.
 219              // If we do without it, this will lead to an enormous performance boost on large scale tables.
 220              $orcond[] = $DB->sql_like('path', ':path' . $category->id, false, false);
 221  
 222              $params['path' . $category->id] = $catcontext->path . '/%';
 223          }
 224  
 225          $sql2 = "SELECT $fields
 226                     FROM {course} c
 227                     JOIN {context} ctx ON (ctx.instanceid = c.id) AND (ctx.contextlevel = :contextlevel2)
 228                    WHERE (" . implode(' OR ', $orcond) . ")";
 229  
 230          $params['contextlevel2'] = CONTEXT_COURSE;
 231  
 232          // Combine with UNION.
 233          $sql = "SELECT *
 234                    FROM (($sql1) UNION ($sql2)) d
 235                ORDER BY d.sortorder";
 236  
 237          return $DB->get_records_sql($sql, $params);
 238      }
 239  
 240      /**
 241       * Finds accessible and non-accessible direct subcategories
 242       *
 243       * @return array [$coursecats, $hiddencats] - child categories that are visible to the current user and not visible
 244       */
 245      protected function get_categories() {
 246          global $DB;
 247          $fields = 'c.*, ' . context_helper::get_preload_record_columns_sql('ctx');
 248          $coursecats = $DB->get_records_sql('SELECT ' . $fields . ' FROM {course_categories} c
 249                  LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)
 250                  WHERE c.parent = :parent ORDER BY c.sortorder',
 251              array('parent' => $this->category->id, 'contextlevel' => CONTEXT_COURSECAT));
 252  
 253          $hiddencats = [];
 254  
 255          foreach ($coursecats as $id => &$category) {
 256              context_helper::preload_from_record($category);
 257              if (!core_course_category::can_view_category($category)) {
 258                  $hiddencats[$id] = $coursecats[$id];
 259                  unset($coursecats[$id]);
 260              }
 261          }
 262          return [$coursecats, $hiddencats];
 263      }
 264  
 265      /**
 266       * Returns the file info element for a given course or null if course is not accessible
 267       *
 268       * @param stdClass $course may contain context fields for preloading
 269       * @return file_info_context_course|null
 270       */
 271      protected function get_child_course($course) {
 272          context_helper::preload_from_record($course);
 273          $context = context_course::instance($course->id);
 274          $child = new file_info_context_course($this->browser, $context, $course);
 275          return $child->get_file_info(null, null, null, null, null);
 276      }
 277  
 278      /**
 279       * Returns the number of children which are either files matching the specified extensions
 280       * or folders containing at least one such file.
 281       *
 282       * @param string|array $extensions, for example '*' or array('.gif','.jpg')
 283       * @param int $limit stop counting after at least $limit non-empty children are found
 284       * @return int
 285       */
 286      public function count_non_empty_children($extensions = '*', $limit = 1) {
 287          $cnt = 0;
 288          if ($child = $this->get_area_coursecat_description(0, '/', '.')) {
 289              $cnt += $child->count_non_empty_children($extensions) ? 1 : 0;
 290              if ($cnt >= $limit) {
 291                  return $cnt;
 292              }
 293          }
 294  
 295          list($coursecats, $hiddencats) = $this->get_categories();
 296          foreach ($coursecats as $category) {
 297              $context = context_coursecat::instance($category->id);
 298              $child = new file_info_context_coursecat($this->browser, $context, $category);
 299              $cnt += $child->count_non_empty_children($extensions) ? 1 : 0;
 300              if ($cnt >= $limit) {
 301                  return $cnt;
 302              }
 303          }
 304  
 305          $courses = $this->get_courses($hiddencats);
 306          foreach ($courses as $course) {
 307              if ($child = $this->get_child_course($course)) {
 308                  $cnt += $child->count_non_empty_children($extensions) ? 1 : 0;
 309                  if ($cnt >= $limit) {
 310                      return $cnt;
 311                  }
 312              }
 313          }
 314  
 315          return $cnt;
 316      }
 317  
 318      /**
 319       * Returns parent file_info instance
 320       *
 321       * @return file_info|null fileinfo instance or null for root directory
 322       */
 323      public function get_parent() {
 324          $parent = $this->context->get_parent_context();
 325          return $this->browser->get_file_info($parent);
 326      }
 327  }