Search moodle.org's
Developer Documentation

See Release Notes

  • Bug fixes for general core bugs in 3.11.x will end 14 Nov 2022 (12 months plus 6 months extension).
  • Bug fixes for security issues in 3.11.x will end 13 Nov 2023 (18 months plus 12 months extension).
  • PHP version: minimum PHP 7.3.0 Note: minimum PHP version has increased since Moodle 3.10. PHP 7.4.x is supported too.

Differences Between: [Versions 310 and 311] [Versions 311 and 400] [Versions 311 and 401] [Versions 311 and 402] [Versions 311 and 403] [Versions 39 and 311]

   1  <?php
   2  
   3  // This file is part of Moodle - http://moodle.org/
   4  //
   5  // Moodle is free software: you can redistribute it and/or modify
   6  // it under the terms of the GNU General Public License as published by
   7  // the Free Software Foundation, either version 3 of the License, or
   8  // (at your option) any later version.
   9  //
  10  // Moodle is distributed in the hope that it will be useful,
  11  // but WITHOUT ANY WARRANTY; without even the implied warranty of
  12  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  13  // GNU General Public License for more details.
  14  //
  15  // You should have received a copy of the GNU General Public License
  16  // along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
  17  
  18  /**
  19   * @package    mod_resource
  20   * @copyright  2009 Petr Skoda  {@link http://skodak.org}
  21   * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  22   */
  23  
  24  defined('MOODLE_INTERNAL') || die;
  25  
  26  /**
  27   * List of features supported in Resource module
  28   * @param string $feature FEATURE_xx constant for requested feature
  29   * @return mixed True if module supports feature, false if not, null if doesn't know
  30   */
  31  function resource_supports($feature) {
  32      switch($feature) {
  33          case FEATURE_MOD_ARCHETYPE:           return MOD_ARCHETYPE_RESOURCE;
  34          case FEATURE_GROUPS:                  return false;
  35          case FEATURE_GROUPINGS:               return false;
  36          case FEATURE_MOD_INTRO:               return true;
  37          case FEATURE_COMPLETION_TRACKS_VIEWS: return true;
  38          case FEATURE_GRADE_HAS_GRADE:         return false;
  39          case FEATURE_GRADE_OUTCOMES:          return false;
  40          case FEATURE_BACKUP_MOODLE2:          return true;
  41          case FEATURE_SHOW_DESCRIPTION:        return true;
  42  
  43          default: return null;
  44      }
  45  }
  46  
  47  /**
  48   * This function is used by the reset_course_userdata function in moodlelib.
  49   * @param $data the data submitted from the reset course.
  50   * @return array status array
  51   */
  52  function resource_reset_userdata($data) {
  53  
  54      // Any changes to the list of dates that needs to be rolled should be same during course restore and course reset.
  55      // See MDL-9367.
  56  
  57      return array();
  58  }
  59  
  60  /**
  61   * List the actions that correspond to a view of this module.
  62   * This is used by the participation report.
  63   *
  64   * Note: This is not used by new logging system. Event with
  65   *       crud = 'r' and edulevel = LEVEL_PARTICIPATING will
  66   *       be considered as view action.
  67   *
  68   * @return array
  69   */
  70  function resource_get_view_actions() {
  71      return array('view','view all');
  72  }
  73  
  74  /**
  75   * List the actions that correspond to a post of this module.
  76   * This is used by the participation report.
  77   *
  78   * Note: This is not used by new logging system. Event with
  79   *       crud = ('c' || 'u' || 'd') and edulevel = LEVEL_PARTICIPATING
  80   *       will be considered as post action.
  81   *
  82   * @return array
  83   */
  84  function resource_get_post_actions() {
  85      return array('update', 'add');
  86  }
  87  
  88  /**
  89   * Add resource instance.
  90   * @param object $data
  91   * @param object $mform
  92   * @return int new resource instance id
  93   */
  94  function resource_add_instance($data, $mform) {
  95      global $CFG, $DB;
  96      require_once("$CFG->libdir/resourcelib.php");
  97      require_once("$CFG->dirroot/mod/resource/locallib.php");
  98      $cmid = $data->coursemodule;
  99      $data->timemodified = time();
 100  
 101      resource_set_display_options($data);
 102  
 103      $data->id = $DB->insert_record('resource', $data);
 104  
 105      // we need to use context now, so we need to make sure all needed info is already in db
 106      $DB->set_field('course_modules', 'instance', $data->id, array('id'=>$cmid));
 107      resource_set_mainfile($data);
 108  
 109      $completiontimeexpected = !empty($data->completionexpected) ? $data->completionexpected : null;
 110      \core_completion\api::update_completion_date_event($cmid, 'resource', $data->id, $completiontimeexpected);
 111  
 112      return $data->id;
 113  }
 114  
 115  /**
 116   * Update resource instance.
 117   * @param object $data
 118   * @param object $mform
 119   * @return bool true
 120   */
 121  function resource_update_instance($data, $mform) {
 122      global $CFG, $DB;
 123      require_once("$CFG->libdir/resourcelib.php");
 124      $data->timemodified = time();
 125      $data->id           = $data->instance;
 126      $data->revision++;
 127  
 128      resource_set_display_options($data);
 129  
 130      $DB->update_record('resource', $data);
 131      resource_set_mainfile($data);
 132  
 133      $completiontimeexpected = !empty($data->completionexpected) ? $data->completionexpected : null;
 134      \core_completion\api::update_completion_date_event($data->coursemodule, 'resource', $data->id, $completiontimeexpected);
 135  
 136      return true;
 137  }
 138  
 139  /**
 140   * Updates display options based on form input.
 141   *
 142   * Shared code used by resource_add_instance and resource_update_instance.
 143   *
 144   * @param object $data Data object
 145   */
 146  function resource_set_display_options($data) {
 147      $displayoptions = array();
 148      if ($data->display == RESOURCELIB_DISPLAY_POPUP) {
 149          $displayoptions['popupwidth']  = $data->popupwidth;
 150          $displayoptions['popupheight'] = $data->popupheight;
 151      }
 152      if (in_array($data->display, array(RESOURCELIB_DISPLAY_AUTO, RESOURCELIB_DISPLAY_EMBED, RESOURCELIB_DISPLAY_FRAME))) {
 153          $displayoptions['printintro']   = (int)!empty($data->printintro);
 154      }
 155      if (!empty($data->showsize)) {
 156          $displayoptions['showsize'] = 1;
 157      }
 158      if (!empty($data->showtype)) {
 159          $displayoptions['showtype'] = 1;
 160      }
 161      if (!empty($data->showdate)) {
 162          $displayoptions['showdate'] = 1;
 163      }
 164      $data->displayoptions = serialize($displayoptions);
 165  }
 166  
 167  /**
 168   * Delete resource instance.
 169   * @param int $id
 170   * @return bool true
 171   */
 172  function resource_delete_instance($id) {
 173      global $DB;
 174  
 175      if (!$resource = $DB->get_record('resource', array('id'=>$id))) {
 176          return false;
 177      }
 178  
 179      $cm = get_coursemodule_from_instance('resource', $id);
 180      \core_completion\api::update_completion_date_event($cm->id, 'resource', $id, null);
 181  
 182      // note: all context files are deleted automatically
 183  
 184      $DB->delete_records('resource', array('id'=>$resource->id));
 185  
 186      return true;
 187  }
 188  
 189  /**
 190   * Given a course_module object, this function returns any
 191   * "extra" information that may be needed when printing
 192   * this activity in a course listing.
 193   *
 194   * See {@link course_modinfo::get_array_of_activities()}
 195   *
 196   * @param stdClass $coursemodule
 197   * @return cached_cm_info info
 198   */
 199  function resource_get_coursemodule_info($coursemodule) {
 200      global $CFG, $DB;
 201      require_once("$CFG->libdir/filelib.php");
 202      require_once("$CFG->dirroot/mod/resource/locallib.php");
 203      require_once($CFG->libdir.'/completionlib.php');
 204  
 205      $context = context_module::instance($coursemodule->id);
 206  
 207      if (!$resource = $DB->get_record('resource', array('id'=>$coursemodule->instance),
 208              'id, name, display, displayoptions, tobemigrated, revision, intro, introformat')) {
 209          return NULL;
 210      }
 211  
 212      $info = new cached_cm_info();
 213      $info->name = $resource->name;
 214      if ($coursemodule->showdescription) {
 215          // Convert intro to html. Do not filter cached version, filters run at display time.
 216          $info->content = format_module_intro('resource', $resource, $coursemodule->id, false);
 217      }
 218  
 219      if ($resource->tobemigrated) {
 220          $info->icon ='i/invalid';
 221          return $info;
 222      }
 223  
 224      // See if there is at least one file.
 225      $fs = get_file_storage();
 226      $files = $fs->get_area_files($context->id, 'mod_resource', 'content', 0, 'sortorder DESC, id ASC', false, 0, 0, 1);
 227      if (count($files) >= 1) {
 228          $mainfile = reset($files);
 229          $info->icon = file_file_icon($mainfile, 24);
 230          $resource->mainfile = $mainfile->get_filename();
 231      }
 232  
 233      $display = resource_get_final_display_type($resource);
 234  
 235      if ($display == RESOURCELIB_DISPLAY_POPUP) {
 236          $fullurl = "$CFG->wwwroot/mod/resource/view.php?id=$coursemodule->id&amp;redirect=1";
 237          $options = empty($resource->displayoptions) ? [] : (array) unserialize_array($resource->displayoptions);
 238          $width  = empty($options['popupwidth'])  ? 620 : $options['popupwidth'];
 239          $height = empty($options['popupheight']) ? 450 : $options['popupheight'];
 240          $wh = "width=$width,height=$height,toolbar=no,location=no,menubar=no,copyhistory=no,status=no,directories=no,scrollbars=yes,resizable=yes";
 241          $info->onclick = "window.open('$fullurl', '', '$wh'); return false;";
 242  
 243      } else if ($display == RESOURCELIB_DISPLAY_NEW) {
 244          $fullurl = "$CFG->wwwroot/mod/resource/view.php?id=$coursemodule->id&amp;redirect=1";
 245          $info->onclick = "window.open('$fullurl'); return false;";
 246  
 247      }
 248  
 249      // If any optional extra details are turned on, store in custom data,
 250      // add some file details as well to be used later by resource_get_optional_details() without retriving.
 251      // Do not store filedetails if this is a reference - they will still need to be retrieved every time.
 252      if (($filedetails = resource_get_file_details($resource, $coursemodule)) && empty($filedetails['isref'])) {
 253          $displayoptions = (array) unserialize_array($resource->displayoptions);
 254          $displayoptions['filedetails'] = $filedetails;
 255          $info->customdata['displayoptions'] = serialize($displayoptions);
 256      } else {
 257          $info->customdata['displayoptions'] = $resource->displayoptions;
 258      }
 259      $info->customdata['display'] = $display;
 260  
 261      return $info;
 262  }
 263  
 264  /**
 265   * Called when viewing course page. Shows extra details after the link if
 266   * enabled.
 267   *
 268   * @param cm_info $cm Course module information
 269   */
 270  function resource_cm_info_view(cm_info $cm) {
 271      global $CFG;
 272      require_once($CFG->dirroot . '/mod/resource/locallib.php');
 273  
 274      $resource = (object) ['displayoptions' => $cm->customdata['displayoptions']];
 275      $details = resource_get_optional_details($resource, $cm);
 276      if ($details) {
 277          $cm->set_after_link(' ' . html_writer::tag('span', $details,
 278                  array('class' => 'resourcelinkdetails')));
 279      }
 280  }
 281  
 282  /**
 283   * Lists all browsable file areas
 284   *
 285   * @package  mod_resource
 286   * @category files
 287   * @param stdClass $course course object
 288   * @param stdClass $cm course module object
 289   * @param stdClass $context context object
 290   * @return array
 291   */
 292  function resource_get_file_areas($course, $cm, $context) {
 293      $areas = array();
 294      $areas['content'] = get_string('resourcecontent', 'resource');
 295      return $areas;
 296  }
 297  
 298  /**
 299   * File browsing support for resource module content area.
 300   *
 301   * @package  mod_resource
 302   * @category files
 303   * @param stdClass $browser file browser instance
 304   * @param stdClass $areas file areas
 305   * @param stdClass $course course object
 306   * @param stdClass $cm course module object
 307   * @param stdClass $context context object
 308   * @param string $filearea file area
 309   * @param int $itemid item ID
 310   * @param string $filepath file path
 311   * @param string $filename file name
 312   * @return file_info instance or null if not found
 313   */
 314  function resource_get_file_info($browser, $areas, $course, $cm, $context, $filearea, $itemid, $filepath, $filename) {
 315      global $CFG;
 316  
 317      if (!has_capability('moodle/course:managefiles', $context)) {
 318          // students can not peak here!
 319          return null;
 320      }
 321  
 322      $fs = get_file_storage();
 323  
 324      if ($filearea === 'content') {
 325          $filepath = is_null($filepath) ? '/' : $filepath;
 326          $filename = is_null($filename) ? '.' : $filename;
 327  
 328          $urlbase = $CFG->wwwroot.'/pluginfile.php';
 329          if (!$storedfile = $fs->get_file($context->id, 'mod_resource', 'content', 0, $filepath, $filename)) {
 330              if ($filepath === '/' and $filename === '.') {
 331                  $storedfile = new virtual_root_file($context->id, 'mod_resource', 'content', 0);
 332              } else {
 333                  // not found
 334                  return null;
 335              }
 336          }
 337          require_once("$CFG->dirroot/mod/resource/locallib.php");
 338          return new resource_content_file_info($browser, $context, $storedfile, $urlbase, $areas[$filearea], true, true, true, false);
 339      }
 340  
 341      // note: resource_intro handled in file_browser automatically
 342  
 343      return null;
 344  }
 345  
 346  /**
 347   * Serves the resource files.
 348   *
 349   * @package  mod_resource
 350   * @category files
 351   * @param stdClass $course course object
 352   * @param stdClass $cm course module object
 353   * @param stdClass $context context object
 354   * @param string $filearea file area
 355   * @param array $args extra arguments
 356   * @param bool $forcedownload whether or not force download
 357   * @param array $options additional options affecting the file serving
 358   * @return bool false if file not found, does not return if found - just send the file
 359   */
 360  function resource_pluginfile($course, $cm, $context, $filearea, $args, $forcedownload, array $options=array()) {
 361      global $CFG, $DB;
 362      require_once("$CFG->libdir/resourcelib.php");
 363  
 364      if ($context->contextlevel != CONTEXT_MODULE) {
 365          return false;
 366      }
 367  
 368      require_course_login($course, true, $cm);
 369      if (!has_capability('mod/resource:view', $context)) {
 370          return false;
 371      }
 372  
 373      if ($filearea !== 'content') {
 374          // intro is handled automatically in pluginfile.php
 375          return false;
 376      }
 377  
 378      array_shift($args); // ignore revision - designed to prevent caching problems only
 379  
 380      $fs = get_file_storage();
 381      $relativepath = implode('/', $args);
 382      $fullpath = rtrim("/$context->id/mod_resource/$filearea/0/$relativepath", '/');
 383      do {
 384          if (!$file = $fs->get_file_by_hash(sha1($fullpath))) {
 385              if ($fs->get_file_by_hash(sha1("$fullpath/."))) {
 386                  if ($file = $fs->get_file_by_hash(sha1("$fullpath/index.htm"))) {
 387                      break;
 388                  }
 389                  if ($file = $fs->get_file_by_hash(sha1("$fullpath/index.html"))) {
 390                      break;
 391                  }
 392                  if ($file = $fs->get_file_by_hash(sha1("$fullpath/Default.htm"))) {
 393                      break;
 394                  }
 395              }
 396              $resource = $DB->get_record('resource', array('id'=>$cm->instance), 'id, legacyfiles', MUST_EXIST);
 397              if ($resource->legacyfiles != RESOURCELIB_LEGACYFILES_ACTIVE) {
 398                  return false;
 399              }
 400              if (!$file = resourcelib_try_file_migration('/'.$relativepath, $cm->id, $cm->course, 'mod_resource', 'content', 0)) {
 401                  return false;
 402              }
 403              // file migrate - update flag
 404              $resource->legacyfileslast = time();
 405              $DB->update_record('resource', $resource);
 406          }
 407      } while (false);
 408  
 409      // should we apply filters?
 410      $mimetype = $file->get_mimetype();
 411      if ($mimetype === 'text/html' or $mimetype === 'text/plain' or $mimetype === 'application/xhtml+xml') {
 412          $filter = $DB->get_field('resource', 'filterfiles', array('id'=>$cm->instance));
 413          $CFG->embeddedsoforcelinktarget = true;
 414      } else {
 415          $filter = 0;
 416      }
 417  
 418      // finally send the file
 419      send_stored_file($file, null, $filter, $forcedownload, $options);
 420  }
 421  
 422  /**
 423   * Return a list of page types
 424   * @param string $pagetype current page type
 425   * @param stdClass $parentcontext Block's parent context
 426   * @param stdClass $currentcontext Current context of block
 427   */
 428  function resource_page_type_list($pagetype, $parentcontext, $currentcontext) {
 429      $module_pagetype = array('mod-resource-*'=>get_string('page-mod-resource-x', 'resource'));
 430      return $module_pagetype;
 431  }
 432  
 433  /**
 434   * Export file resource contents
 435   *
 436   * @return array of file content
 437   */
 438  function resource_export_contents($cm, $baseurl) {
 439      global $CFG, $DB;
 440      $contents = array();
 441      $context = context_module::instance($cm->id);
 442      $resource = $DB->get_record('resource', array('id'=>$cm->instance), '*', MUST_EXIST);
 443  
 444      $fs = get_file_storage();
 445      $files = $fs->get_area_files($context->id, 'mod_resource', 'content', 0, 'sortorder DESC, id ASC', false);
 446  
 447      foreach ($files as $fileinfo) {
 448          $file = array();
 449          $file['type'] = 'file';
 450          $file['filename']     = $fileinfo->get_filename();
 451          $file['filepath']     = $fileinfo->get_filepath();
 452          $file['filesize']     = $fileinfo->get_filesize();
 453          $file['fileurl']      = file_encode_url("$CFG->wwwroot/" . $baseurl, '/'.$context->id.'/mod_resource/content/'.$resource->revision.$fileinfo->get_filepath().$fileinfo->get_filename(), true);
 454          $file['timecreated']  = $fileinfo->get_timecreated();
 455          $file['timemodified'] = $fileinfo->get_timemodified();
 456          $file['sortorder']    = $fileinfo->get_sortorder();
 457          $file['userid']       = $fileinfo->get_userid();
 458          $file['author']       = $fileinfo->get_author();
 459          $file['license']      = $fileinfo->get_license();
 460          $file['mimetype']     = $fileinfo->get_mimetype();
 461          $file['isexternalfile'] = $fileinfo->is_external_file();
 462          if ($file['isexternalfile']) {
 463              $file['repositorytype'] = $fileinfo->get_repository_type();
 464          }
 465          $contents[] = $file;
 466      }
 467  
 468      return $contents;
 469  }
 470  
 471  /**
 472   * Register the ability to handle drag and drop file uploads
 473   * @return array containing details of the files / types the mod can handle
 474   */
 475  function resource_dndupload_register() {
 476      return array('files' => array(
 477                       array('extension' => '*', 'message' => get_string('dnduploadresource', 'mod_resource'))
 478                   ));
 479  }
 480  
 481  /**
 482   * Handle a file that has been uploaded
 483   * @param object $uploadinfo details of the file / content that has been uploaded
 484   * @return int instance id of the newly created mod
 485   */
 486  function resource_dndupload_handle($uploadinfo) {
 487      // Gather the required info.
 488      $data = new stdClass();
 489      $data->course = $uploadinfo->course->id;
 490      $data->name = $uploadinfo->displayname;
 491      $data->intro = '';
 492      $data->introformat = FORMAT_HTML;
 493      $data->coursemodule = $uploadinfo->coursemodule;
 494      $data->files = $uploadinfo->draftitemid;
 495  
 496      // Set the display options to the site defaults.
 497      $config = get_config('resource');
 498      $data->display = $config->display;
 499      $data->popupheight = $config->popupheight;
 500      $data->popupwidth = $config->popupwidth;
 501      $data->printintro = $config->printintro;
 502      $data->showsize = (isset($config->showsize)) ? $config->showsize : 0;
 503      $data->showtype = (isset($config->showtype)) ? $config->showtype : 0;
 504      $data->showdate = (isset($config->showdate)) ? $config->showdate : 0;
 505      $data->filterfiles = $config->filterfiles;
 506  
 507      return resource_add_instance($data, null);
 508  }
 509  
 510  /**
 511   * Mark the activity completed (if required) and trigger the course_module_viewed event.
 512   *
 513   * @param  stdClass $resource   resource object
 514   * @param  stdClass $course     course object
 515   * @param  stdClass $cm         course module object
 516   * @param  stdClass $context    context object
 517   * @since Moodle 3.0
 518   */
 519  function resource_view($resource, $course, $cm, $context) {
 520  
 521      // Trigger course_module_viewed event.
 522      $params = array(
 523          'context' => $context,
 524          'objectid' => $resource->id
 525      );
 526  
 527      $event = \mod_resource\event\course_module_viewed::create($params);
 528      $event->add_record_snapshot('course_modules', $cm);
 529      $event->add_record_snapshot('course', $course);
 530      $event->add_record_snapshot('resource', $resource);
 531      $event->trigger();
 532  
 533      // Completion.
 534      $completion = new completion_info($course);
 535      $completion->set_module_viewed($cm);
 536  }
 537  
 538  /**
 539   * Check if the module has any update that affects the current user since a given time.
 540   *
 541   * @param  cm_info $cm course module data
 542   * @param  int $from the time to check updates from
 543   * @param  array $filter  if we need to check only specific updates
 544   * @return stdClass an object with the different type of areas indicating if they were updated or not
 545   * @since Moodle 3.2
 546   */
 547  function resource_check_updates_since(cm_info $cm, $from, $filter = array()) {
 548      $updates = course_check_module_updates_since($cm, $from, array('content'), $filter);
 549      return $updates;
 550  }
 551  
 552  /**
 553   * This function receives a calendar event and returns the action associated with it, or null if there is none.
 554   *
 555   * This is used by block_myoverview in order to display the event appropriately. If null is returned then the event
 556   * is not displayed on the block.
 557   *
 558   * @param calendar_event $event
 559   * @param \core_calendar\action_factory $factory
 560   * @return \core_calendar\local\event\entities\action_interface|null
 561   */
 562  function mod_resource_core_calendar_provide_event_action(calendar_event $event,
 563                                                        \core_calendar\action_factory $factory, $userid = 0) {
 564  
 565      global $USER;
 566  
 567      if (empty($userid)) {
 568          $userid = $USER->id;
 569      }
 570  
 571      $cm = get_fast_modinfo($event->courseid, $userid)->instances['resource'][$event->instance];
 572  
 573      $completion = new \completion_info($cm->get_course());
 574  
 575      $completiondata = $completion->get_data($cm, false, $userid);
 576  
 577      if ($completiondata->completionstate != COMPLETION_INCOMPLETE) {
 578          return null;
 579      }
 580  
 581      return $factory->create_instance(
 582          get_string('view'),
 583          new \moodle_url('/mod/resource/view.php', ['id' => $cm->id]),
 584          1,
 585          true
 586      );
 587  }
 588  
 589  
 590  /**
 591   * Given an array with a file path, it returns the itemid and the filepath for the defined filearea.
 592   *
 593   * @param  string $filearea The filearea.
 594   * @param  array  $args The path (the part after the filearea and before the filename).
 595   * @return array The itemid and the filepath inside the $args path, for the defined filearea.
 596   */
 597  function mod_resource_get_path_from_pluginfile(string $filearea, array $args) : array {
 598      // Resource never has an itemid (the number represents the revision but it's not stored in database).
 599      array_shift($args);
 600  
 601      // Get the filepath.
 602      if (empty($args)) {
 603          $filepath = '/';
 604      } else {
 605          $filepath = '/' . implode('/', $args) . '/';
 606      }
 607  
 608      return [
 609          'itemid' => 0,
 610          'filepath' => $filepath,
 611      ];
 612  }