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.
/mod/page/ -> lib.php (source)

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_page
  20   * @copyright  2009 Petr Skoda (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 Page 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 page_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 page_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 page_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 page_get_post_actions() {
  85      return array('update', 'add');
  86  }
  87  
  88  /**
  89   * Add page instance.
  90   * @param stdClass $data
  91   * @param mod_page_mod_form $mform
  92   * @return int new page instance id
  93   */
  94  function page_add_instance($data, $mform = null) {
  95      global $CFG, $DB;
  96      require_once("$CFG->libdir/resourcelib.php");
  97  
  98      $cmid = $data->coursemodule;
  99  
 100      $data->timemodified = time();
 101      $displayoptions = array();
 102      if ($data->display == RESOURCELIB_DISPLAY_POPUP) {
 103          $displayoptions['popupwidth']  = $data->popupwidth;
 104          $displayoptions['popupheight'] = $data->popupheight;
 105      }
 106      $displayoptions['printheading'] = $data->printheading;
 107      $displayoptions['printintro']   = $data->printintro;
 108      $displayoptions['printlastmodified'] = $data->printlastmodified;
 109      $data->displayoptions = serialize($displayoptions);
 110  
 111      if ($mform) {
 112          $data->content       = $data->page['text'];
 113          $data->contentformat = $data->page['format'];
 114      }
 115  
 116      $data->id = $DB->insert_record('page', $data);
 117  
 118      // we need to use context now, so we need to make sure all needed info is already in db
 119      $DB->set_field('course_modules', 'instance', $data->id, array('id'=>$cmid));
 120      $context = context_module::instance($cmid);
 121  
 122      if ($mform and !empty($data->page['itemid'])) {
 123          $draftitemid = $data->page['itemid'];
 124          $data->content = file_save_draft_area_files($draftitemid, $context->id, 'mod_page', 'content', 0, page_get_editor_options($context), $data->content);
 125          $DB->update_record('page', $data);
 126      }
 127  
 128      $completiontimeexpected = !empty($data->completionexpected) ? $data->completionexpected : null;
 129      \core_completion\api::update_completion_date_event($cmid, 'page', $data->id, $completiontimeexpected);
 130  
 131      return $data->id;
 132  }
 133  
 134  /**
 135   * Update page instance.
 136   * @param object $data
 137   * @param object $mform
 138   * @return bool true
 139   */
 140  function page_update_instance($data, $mform) {
 141      global $CFG, $DB;
 142      require_once("$CFG->libdir/resourcelib.php");
 143  
 144      $cmid        = $data->coursemodule;
 145      $draftitemid = $data->page['itemid'];
 146  
 147      $data->timemodified = time();
 148      $data->id           = $data->instance;
 149      $data->revision++;
 150  
 151      $displayoptions = array();
 152      if ($data->display == RESOURCELIB_DISPLAY_POPUP) {
 153          $displayoptions['popupwidth']  = $data->popupwidth;
 154          $displayoptions['popupheight'] = $data->popupheight;
 155      }
 156      $displayoptions['printheading'] = $data->printheading;
 157      $displayoptions['printintro']   = $data->printintro;
 158      $displayoptions['printlastmodified'] = $data->printlastmodified;
 159      $data->displayoptions = serialize($displayoptions);
 160  
 161      $data->content       = $data->page['text'];
 162      $data->contentformat = $data->page['format'];
 163  
 164      $DB->update_record('page', $data);
 165  
 166      $context = context_module::instance($cmid);
 167      if ($draftitemid) {
 168          $data->content = file_save_draft_area_files($draftitemid, $context->id, 'mod_page', 'content', 0, page_get_editor_options($context), $data->content);
 169          $DB->update_record('page', $data);
 170      }
 171  
 172      $completiontimeexpected = !empty($data->completionexpected) ? $data->completionexpected : null;
 173      \core_completion\api::update_completion_date_event($cmid, 'page', $data->id, $completiontimeexpected);
 174  
 175      return true;
 176  }
 177  
 178  /**
 179   * Delete page instance.
 180   * @param int $id
 181   * @return bool true
 182   */
 183  function page_delete_instance($id) {
 184      global $DB;
 185  
 186      if (!$page = $DB->get_record('page', array('id'=>$id))) {
 187          return false;
 188      }
 189  
 190      $cm = get_coursemodule_from_instance('page', $id);
 191      \core_completion\api::update_completion_date_event($cm->id, 'page', $id, null);
 192  
 193      // note: all context files are deleted automatically
 194  
 195      $DB->delete_records('page', array('id'=>$page->id));
 196  
 197      return true;
 198  }
 199  
 200  /**
 201   * Given a course_module object, this function returns any
 202   * "extra" information that may be needed when printing
 203   * this activity in a course listing.
 204   *
 205   * See {@link course_modinfo::get_array_of_activities()}
 206   *
 207   * @param stdClass $coursemodule
 208   * @return cached_cm_info Info to customise main page display
 209   */
 210  function page_get_coursemodule_info($coursemodule) {
 211      global $CFG, $DB;
 212      require_once("$CFG->libdir/resourcelib.php");
 213  
 214      if (!$page = $DB->get_record('page', array('id'=>$coursemodule->instance),
 215              'id, name, display, displayoptions, intro, introformat')) {
 216          return NULL;
 217      }
 218  
 219      $info = new cached_cm_info();
 220      $info->name = $page->name;
 221  
 222      if ($coursemodule->showdescription) {
 223          // Convert intro to html. Do not filter cached version, filters run at display time.
 224          $info->content = format_module_intro('page', $page, $coursemodule->id, false);
 225      }
 226  
 227      if ($page->display != RESOURCELIB_DISPLAY_POPUP) {
 228          return $info;
 229      }
 230  
 231      $fullurl = "$CFG->wwwroot/mod/page/view.php?id=$coursemodule->id&amp;inpopup=1";
 232      $options = empty($page->displayoptions) ? [] : (array) unserialize_array($page->displayoptions);
 233      $width  = empty($options['popupwidth'])  ? 620 : $options['popupwidth'];
 234      $height = empty($options['popupheight']) ? 450 : $options['popupheight'];
 235      $wh = "width=$width,height=$height,toolbar=no,location=no,menubar=no,copyhistory=no,status=no,directories=no,scrollbars=yes,resizable=yes";
 236      $info->onclick = "window.open('$fullurl', '', '$wh'); return false;";
 237  
 238      return $info;
 239  }
 240  
 241  
 242  /**
 243   * Lists all browsable file areas
 244   *
 245   * @package  mod_page
 246   * @category files
 247   * @param stdClass $course course object
 248   * @param stdClass $cm course module object
 249   * @param stdClass $context context object
 250   * @return array
 251   */
 252  function page_get_file_areas($course, $cm, $context) {
 253      $areas = array();
 254      $areas['content'] = get_string('content', 'page');
 255      return $areas;
 256  }
 257  
 258  /**
 259   * File browsing support for page module content area.
 260   *
 261   * @package  mod_page
 262   * @category files
 263   * @param stdClass $browser file browser instance
 264   * @param stdClass $areas file areas
 265   * @param stdClass $course course object
 266   * @param stdClass $cm course module object
 267   * @param stdClass $context context object
 268   * @param string $filearea file area
 269   * @param int $itemid item ID
 270   * @param string $filepath file path
 271   * @param string $filename file name
 272   * @return file_info instance or null if not found
 273   */
 274  function page_get_file_info($browser, $areas, $course, $cm, $context, $filearea, $itemid, $filepath, $filename) {
 275      global $CFG;
 276  
 277      if (!has_capability('moodle/course:managefiles', $context)) {
 278          // students can not peak here!
 279          return null;
 280      }
 281  
 282      $fs = get_file_storage();
 283  
 284      if ($filearea === 'content') {
 285          $filepath = is_null($filepath) ? '/' : $filepath;
 286          $filename = is_null($filename) ? '.' : $filename;
 287  
 288          $urlbase = $CFG->wwwroot.'/pluginfile.php';
 289          if (!$storedfile = $fs->get_file($context->id, 'mod_page', 'content', 0, $filepath, $filename)) {
 290              if ($filepath === '/' and $filename === '.') {
 291                  $storedfile = new virtual_root_file($context->id, 'mod_page', 'content', 0);
 292              } else {
 293                  // not found
 294                  return null;
 295              }
 296          }
 297          require_once("$CFG->dirroot/mod/page/locallib.php");
 298          return new page_content_file_info($browser, $context, $storedfile, $urlbase, $areas[$filearea], true, true, true, false);
 299      }
 300  
 301      // note: page_intro handled in file_browser automatically
 302  
 303      return null;
 304  }
 305  
 306  /**
 307   * Serves the page files.
 308   *
 309   * @package  mod_page
 310   * @category files
 311   * @param stdClass $course course object
 312   * @param stdClass $cm course module object
 313   * @param stdClass $context context object
 314   * @param string $filearea file area
 315   * @param array $args extra arguments
 316   * @param bool $forcedownload whether or not force download
 317   * @param array $options additional options affecting the file serving
 318   * @return bool false if file not found, does not return if found - just send the file
 319   */
 320  function page_pluginfile($course, $cm, $context, $filearea, $args, $forcedownload, array $options=array()) {
 321      global $CFG, $DB;
 322      require_once("$CFG->libdir/resourcelib.php");
 323  
 324      if ($context->contextlevel != CONTEXT_MODULE) {
 325          return false;
 326      }
 327  
 328      require_course_login($course, true, $cm);
 329      if (!has_capability('mod/page:view', $context)) {
 330          return false;
 331      }
 332  
 333      if ($filearea !== 'content') {
 334          // intro is handled automatically in pluginfile.php
 335          return false;
 336      }
 337  
 338      // $arg could be revision number or index.html
 339      $arg = array_shift($args);
 340      if ($arg == 'index.html' || $arg == 'index.htm') {
 341          // serve page content
 342          $filename = $arg;
 343  
 344          if (!$page = $DB->get_record('page', array('id'=>$cm->instance), '*', MUST_EXIST)) {
 345              return false;
 346          }
 347  
 348          // We need to rewrite the pluginfile URLs so the media filters can work.
 349          $content = file_rewrite_pluginfile_urls($page->content, 'webservice/pluginfile.php', $context->id, 'mod_page', 'content',
 350                                                  $page->revision);
 351          $formatoptions = new stdClass;
 352          $formatoptions->noclean = true;
 353          $formatoptions->overflowdiv = true;
 354          $formatoptions->context = $context;
 355          $content = format_text($content, $page->contentformat, $formatoptions);
 356  
 357          // Remove @@PLUGINFILE@@/.
 358          $options = array('reverse' => true);
 359          $content = file_rewrite_pluginfile_urls($content, 'webservice/pluginfile.php', $context->id, 'mod_page', 'content',
 360                                                  $page->revision, $options);
 361          $content = str_replace('@@PLUGINFILE@@/', '', $content);
 362  
 363          send_file($content, $filename, 0, 0, true, true);
 364      } else {
 365          $fs = get_file_storage();
 366          $relativepath = implode('/', $args);
 367          $fullpath = "/$context->id/mod_page/$filearea/0/$relativepath";
 368          if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
 369              $page = $DB->get_record('page', array('id'=>$cm->instance), 'id, legacyfiles', MUST_EXIST);
 370              if ($page->legacyfiles != RESOURCELIB_LEGACYFILES_ACTIVE) {
 371                  return false;
 372              }
 373              if (!$file = resourcelib_try_file_migration('/'.$relativepath, $cm->id, $cm->course, 'mod_page', 'content', 0)) {
 374                  return false;
 375              }
 376              //file migrate - update flag
 377              $page->legacyfileslast = time();
 378              $DB->update_record('page', $page);
 379          }
 380  
 381          // finally send the file
 382          send_stored_file($file, null, 0, $forcedownload, $options);
 383      }
 384  }
 385  
 386  /**
 387   * Return a list of page types
 388   * @param string $pagetype current page type
 389   * @param stdClass $parentcontext Block's parent context
 390   * @param stdClass $currentcontext Current context of block
 391   */
 392  function page_page_type_list($pagetype, $parentcontext, $currentcontext) {
 393      $module_pagetype = array('mod-page-*'=>get_string('page-mod-page-x', 'page'));
 394      return $module_pagetype;
 395  }
 396  
 397  /**
 398   * Export page resource contents
 399   *
 400   * @return array of file content
 401   */
 402  function page_export_contents($cm, $baseurl) {
 403      global $CFG, $DB;
 404      $contents = array();
 405      $context = context_module::instance($cm->id);
 406  
 407      $page = $DB->get_record('page', array('id'=>$cm->instance), '*', MUST_EXIST);
 408  
 409      // page contents
 410      $fs = get_file_storage();
 411      $files = $fs->get_area_files($context->id, 'mod_page', 'content', 0, 'sortorder DESC, id ASC', false);
 412      foreach ($files as $fileinfo) {
 413          $file = array();
 414          $file['type']         = 'file';
 415          $file['filename']     = $fileinfo->get_filename();
 416          $file['filepath']     = $fileinfo->get_filepath();
 417          $file['filesize']     = $fileinfo->get_filesize();
 418          $file['fileurl']      = file_encode_url("$CFG->wwwroot/" . $baseurl, '/'.$context->id.'/mod_page/content/'.$page->revision.$fileinfo->get_filepath().$fileinfo->get_filename(), true);
 419          $file['timecreated']  = $fileinfo->get_timecreated();
 420          $file['timemodified'] = $fileinfo->get_timemodified();
 421          $file['sortorder']    = $fileinfo->get_sortorder();
 422          $file['userid']       = $fileinfo->get_userid();
 423          $file['author']       = $fileinfo->get_author();
 424          $file['license']      = $fileinfo->get_license();
 425          $file['mimetype']     = $fileinfo->get_mimetype();
 426          $file['isexternalfile'] = $fileinfo->is_external_file();
 427          if ($file['isexternalfile']) {
 428              $file['repositorytype'] = $fileinfo->get_repository_type();
 429          }
 430          $contents[] = $file;
 431      }
 432  
 433      // page html conent
 434      $filename = 'index.html';
 435      $pagefile = array();
 436      $pagefile['type']         = 'file';
 437      $pagefile['filename']     = $filename;
 438      $pagefile['filepath']     = '/';
 439      $pagefile['filesize']     = 0;
 440      $pagefile['fileurl']      = file_encode_url("$CFG->wwwroot/" . $baseurl, '/'.$context->id.'/mod_page/content/' . $filename, true);
 441      $pagefile['timecreated']  = null;
 442      $pagefile['timemodified'] = $page->timemodified;
 443      // make this file as main file
 444      $pagefile['sortorder']    = 1;
 445      $pagefile['userid']       = null;
 446      $pagefile['author']       = null;
 447      $pagefile['license']      = null;
 448      $contents[] = $pagefile;
 449  
 450      return $contents;
 451  }
 452  
 453  /**
 454   * Register the ability to handle drag and drop file uploads
 455   * @return array containing details of the files / types the mod can handle
 456   */
 457  function page_dndupload_register() {
 458      return array('types' => array(
 459                       array('identifier' => 'text/html', 'message' => get_string('createpage', 'page')),
 460                       array('identifier' => 'text', 'message' => get_string('createpage', 'page'))
 461                   ));
 462  }
 463  
 464  /**
 465   * Handle a file that has been uploaded
 466   * @param object $uploadinfo details of the file / content that has been uploaded
 467   * @return int instance id of the newly created mod
 468   */
 469  function page_dndupload_handle($uploadinfo) {
 470      // Gather the required info.
 471      $data = new stdClass();
 472      $data->course = $uploadinfo->course->id;
 473      $data->name = $uploadinfo->displayname;
 474      $data->intro = '<p>'.$uploadinfo->displayname.'</p>';
 475      $data->introformat = FORMAT_HTML;
 476      if ($uploadinfo->type == 'text/html') {
 477          $data->contentformat = FORMAT_HTML;
 478          $data->content = clean_param($uploadinfo->content, PARAM_CLEANHTML);
 479      } else {
 480          $data->contentformat = FORMAT_PLAIN;
 481          $data->content = clean_param($uploadinfo->content, PARAM_TEXT);
 482      }
 483      $data->coursemodule = $uploadinfo->coursemodule;
 484  
 485      // Set the display options to the site defaults.
 486      $config = get_config('page');
 487      $data->display = $config->display;
 488      $data->popupheight = $config->popupheight;
 489      $data->popupwidth = $config->popupwidth;
 490      $data->printheading = $config->printheading;
 491      $data->printintro = $config->printintro;
 492      $data->printlastmodified = $config->printlastmodified;
 493  
 494      return page_add_instance($data, null);
 495  }
 496  
 497  /**
 498   * Mark the activity completed (if required) and trigger the course_module_viewed event.
 499   *
 500   * @param  stdClass $page       page object
 501   * @param  stdClass $course     course object
 502   * @param  stdClass $cm         course module object
 503   * @param  stdClass $context    context object
 504   * @since Moodle 3.0
 505   */
 506  function page_view($page, $course, $cm, $context) {
 507  
 508      // Trigger course_module_viewed event.
 509      $params = array(
 510          'context' => $context,
 511          'objectid' => $page->id
 512      );
 513  
 514      $event = \mod_page\event\course_module_viewed::create($params);
 515      $event->add_record_snapshot('course_modules', $cm);
 516      $event->add_record_snapshot('course', $course);
 517      $event->add_record_snapshot('page', $page);
 518      $event->trigger();
 519  
 520      // Completion.
 521      $completion = new completion_info($course);
 522      $completion->set_module_viewed($cm);
 523  }
 524  
 525  /**
 526   * Check if the module has any update that affects the current user since a given time.
 527   *
 528   * @param  cm_info $cm course module data
 529   * @param  int $from the time to check updates from
 530   * @param  array $filter  if we need to check only specific updates
 531   * @return stdClass an object with the different type of areas indicating if they were updated or not
 532   * @since Moodle 3.2
 533   */
 534  function page_check_updates_since(cm_info $cm, $from, $filter = array()) {
 535      $updates = course_check_module_updates_since($cm, $from, array('content'), $filter);
 536      return $updates;
 537  }
 538  
 539  /**
 540   * This function receives a calendar event and returns the action associated with it, or null if there is none.
 541   *
 542   * This is used by block_myoverview in order to display the event appropriately. If null is returned then the event
 543   * is not displayed on the block.
 544   *
 545   * @param calendar_event $event
 546   * @param \core_calendar\action_factory $factory
 547   * @return \core_calendar\local\event\entities\action_interface|null
 548   */
 549  function mod_page_core_calendar_provide_event_action(calendar_event $event,
 550                                                        \core_calendar\action_factory $factory, $userid = 0) {
 551      global $USER;
 552  
 553      if (empty($userid)) {
 554          $userid = $USER->id;
 555      }
 556  
 557      $cm = get_fast_modinfo($event->courseid, $userid)->instances['page'][$event->instance];
 558  
 559      $completion = new \completion_info($cm->get_course());
 560  
 561      $completiondata = $completion->get_data($cm, false, $userid);
 562  
 563      if ($completiondata->completionstate != COMPLETION_INCOMPLETE) {
 564          return null;
 565      }
 566  
 567      return $factory->create_instance(
 568          get_string('view'),
 569          new \moodle_url('/mod/page/view.php', ['id' => $cm->id]),
 570          1,
 571          true
 572      );
 573  }
 574  
 575  /**
 576   * Given an array with a file path, it returns the itemid and the filepath for the defined filearea.
 577   *
 578   * @param  string $filearea The filearea.
 579   * @param  array  $args The path (the part after the filearea and before the filename).
 580   * @return array The itemid and the filepath inside the $args path, for the defined filearea.
 581   */
 582  function mod_page_get_path_from_pluginfile(string $filearea, array $args) : array {
 583      // Page never has an itemid (the number represents the revision but it's not stored in database).
 584      array_shift($args);
 585  
 586      // Get the filepath.
 587      if (empty($args)) {
 588          $filepath = '/';
 589      } else {
 590          $filepath = '/' . implode('/', $args) . '/';
 591      }
 592  
 593      return [
 594          'itemid' => 0,
 595          'filepath' => $filepath,
 596      ];
 597  }