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

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

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