Search moodle.org's
Developer Documentation

See Release Notes
Long Term Support Release

  • Bug fixes for general core bugs in 4.1.x will end 13 November 2023 (12 months).
  • Bug fixes for security issues in 4.1.x will end 10 November 2025 (36 months).
  • PHP version: minimum PHP 7.4.0 Note: minimum PHP version has increased since Moodle 4.0. PHP 8.0.x is supported too.

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

   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   * Contains helper class for the H5P area.
  19   *
  20   * @package    core_h5p
  21   * @copyright  2019 Sara Arjona <sara@moodle.com>
  22   * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  23   */
  24  
  25  namespace core_h5p;
  26  
  27  use context_system;
  28  use core_h5p\local\library\autoloader;
  29  
  30  defined('MOODLE_INTERNAL') || die();
  31  
  32  /**
  33   * Helper class for the H5P area.
  34   *
  35   * @copyright  2019 Sara Arjona <sara@moodle.com>
  36   * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  37   */
  38  class helper {
  39  
  40      /**
  41       * Store an H5P file.
  42       *
  43       * @param factory $factory The \core_h5p\factory object
  44       * @param stored_file $file Moodle file instance
  45       * @param stdClass $config Button options config
  46       * @param bool $onlyupdatelibs Whether new libraries can be installed or only the existing ones can be updated
  47       * @param bool $skipcontent Should the content be skipped (so only the libraries will be saved)?
  48       *
  49       * @return int|false|null The H5P identifier or null if there is an error when saving or false if it's not a valid H5P package
  50       */
  51      public static function save_h5p(factory $factory, \stored_file $file, \stdClass $config, bool $onlyupdatelibs = false,
  52              bool $skipcontent = false) {
  53  
  54          if (api::is_valid_package($file, $onlyupdatelibs, $skipcontent, $factory, false)) {
  55              $core = $factory->get_core();
  56              $h5pvalidator = $factory->get_validator();
  57              $h5pstorage = $factory->get_storage();
  58  
  59              $content = [
  60                  'pathnamehash' => $file->get_pathnamehash(),
  61                  'contenthash' => $file->get_contenthash(),
  62              ];
  63              $options = ['disable' => self::get_display_options($core, $config)];
  64  
  65              // Add the 'title' if exists from 'h5p.json' data to keep it for the editor.
  66              if (!empty($h5pvalidator->h5pC->mainJsonData['title'])) {
  67                  $content['title'] = $h5pvalidator->h5pC->mainJsonData['title'];
  68              }
  69  
  70              // If exists, add the metadata from 'h5p.json' to avoid loosing this information.
  71              $data = $h5pvalidator->h5pC->mainJsonData;
  72              if (!empty($data)) {
  73                  // The metadata fields are defined in 'joubel/core/h5p-metadata.class.php'.
  74                  $metadatafields = [
  75                      'title',
  76                      'a11yTitle',
  77                      'changes',
  78                      'authors',
  79                      'source',
  80                      'license',
  81                      'licenseVersion',
  82                      'licenseExtras',
  83                      'authorComments',
  84                      'yearFrom',
  85                      'yearTo',
  86                      'defaultLanguage',
  87                  ];
  88                  $content['metadata'] = array_reduce($metadatafields, function ($array, $field) use ($data) {
  89                      if (array_key_exists($field, $data)) {
  90                          $array[$field] = $data[$field];
  91                      }
  92                      return $array;
  93                  }, []);
  94              }
  95              $h5pstorage->savePackage($content, null, $skipcontent, $options);
  96  
  97              return $h5pstorage->contentId;
  98          }
  99  
 100          return false;
 101      }
 102  
 103      /**
 104       * Get the error messages stored in our H5P framework.
 105       *
 106       * @param stdClass $messages The error, exception and info messages, raised while preparing and running an H5P content.
 107       * @param factory $factory The \core_h5p\factory object
 108       *
 109       * @return stdClass with framework error messages.
 110       */
 111      public static function get_messages(\stdClass $messages, factory $factory): \stdClass {
 112          $core = $factory->get_core();
 113  
 114          // Check if there are some errors and store them in $messages.
 115          if (empty($messages->error)) {
 116              $messages->error = $core->h5pF->getMessages('error') ?: false;
 117          } else {
 118              $messages->error = array_merge($messages->error, $core->h5pF->getMessages('error'));
 119          }
 120  
 121          if (empty($messages->info)) {
 122              $messages->info = $core->h5pF->getMessages('info') ?: false;
 123          } else {
 124              $messages->info = array_merge($messages->info, $core->h5pF->getMessages('info'));
 125          }
 126  
 127          return $messages;
 128      }
 129  
 130      /**
 131       * Get the representation of display options as int.
 132       *
 133       * @param core $core The \core_h5p\core object
 134       * @param stdClass $config Button options config
 135       *
 136       * @return int The representation of display options as int
 137       */
 138      public static function get_display_options(core $core, \stdClass $config): int {
 139          $export = isset($config->export) ? $config->export : 0;
 140          $embed = isset($config->embed) ? $config->embed : 0;
 141          $copyright = isset($config->copyright) ? $config->copyright : 0;
 142          $frame = ($export || $embed || $copyright);
 143          if (!$frame) {
 144              $frame = isset($config->frame) ? $config->frame : 0;
 145          }
 146  
 147          $disableoptions = [
 148              core::DISPLAY_OPTION_FRAME     => $frame,
 149              core::DISPLAY_OPTION_DOWNLOAD  => $export,
 150              core::DISPLAY_OPTION_EMBED     => $embed,
 151              core::DISPLAY_OPTION_COPYRIGHT => $copyright,
 152          ];
 153  
 154          return $core->getStorableDisplayOptions($disableoptions, 0);
 155      }
 156  
 157      /**
 158       * Convert the int representation of display options into stdClass
 159       *
 160       * @param core $core The \core_h5p\core object
 161       * @param int $displayint integer value representing display options
 162       *
 163       * @return int The representation of display options as int
 164       */
 165      public static function decode_display_options(core $core, int $displayint = null): \stdClass {
 166          $config = new \stdClass();
 167          if ($displayint === null) {
 168              $displayint = self::get_display_options($core, $config);
 169          }
 170          $displayarray = $core->getDisplayOptionsForEdit($displayint);
 171          $config->export = $displayarray[core::DISPLAY_OPTION_DOWNLOAD] ?? 0;
 172          $config->embed = $displayarray[core::DISPLAY_OPTION_EMBED] ?? 0;
 173          $config->copyright = $displayarray[core::DISPLAY_OPTION_COPYRIGHT] ?? 0;
 174          return $config;
 175      }
 176  
 177      /**
 178       * Checks if the author of the .h5p file is "trustable". If the file hasn't been uploaded by a user with the
 179       * required capability, the content won't be deployed.
 180       *
 181       * @param  stored_file $file The .h5p file to be deployed
 182       * @return bool Returns true if the file can be deployed, false otherwise.
 183       */
 184      public static function can_deploy_package(\stored_file $file): bool {
 185          if (null === $file->get_userid()) {
 186              // If there is no userid, it is owned by the system.
 187              return true;
 188          }
 189  
 190          $context = \context::instance_by_id($file->get_contextid());
 191          if (has_capability('moodle/h5p:deploy', $context, $file->get_userid())) {
 192              return true;
 193          }
 194  
 195          return false;
 196      }
 197  
 198      /**
 199       * Checks if the content-type libraries can be upgraded.
 200       * The H5P content-type libraries can only be upgraded if the author of the .h5p file can manage content-types or if all the
 201       * content-types exist, to avoid users without the required capability to upload malicious content.
 202       *
 203       * @param  stored_file $file The .h5p file to be deployed
 204       * @return bool Returns true if the content-type libraries can be created/updated, false otherwise.
 205       */
 206      public static function can_update_library(\stored_file $file): bool {
 207          if (null === $file->get_userid()) {
 208              // If there is no userid, it is owned by the system.
 209              return true;
 210          }
 211  
 212          // Check if the owner of the .h5p file has the capability to manage content-types.
 213          $context = \context::instance_by_id($file->get_contextid());
 214          if (has_capability('moodle/h5p:updatelibraries', $context, $file->get_userid())) {
 215              return true;
 216          }
 217  
 218          return false;
 219      }
 220  
 221      /**
 222       * Convenience to take a fixture test file and create a stored_file.
 223       *
 224       * @param string $filepath The filepath of the file
 225       * @param  int   $userid  The author of the file
 226       * @param  \context $context The context where the file will be created
 227       * @return stored_file The file created
 228       */
 229      public static function create_fake_stored_file_from_path(string $filepath, int $userid = 0,
 230              \context $context = null): \stored_file {
 231          if (is_null($context)) {
 232              $context = context_system::instance();
 233          }
 234          $filerecord = [
 235              'contextid' => $context->id,
 236              'component' => 'core_h5p',
 237              'filearea'  => 'unittest',
 238              'itemid'    => rand(),
 239              'filepath'  => '/',
 240              'filename'  => basename($filepath),
 241          ];
 242          if (!is_null($userid)) {
 243              $filerecord['userid'] = $userid;
 244          }
 245  
 246          $fs = get_file_storage();
 247          return $fs->create_file_from_pathname($filerecord, $filepath);
 248      }
 249  
 250      /**
 251       * Get information about different H5P tools and their status.
 252       *
 253       * @return array Data to render by the template
 254       */
 255      public static function get_h5p_tools_info(): array {
 256          $tools = array();
 257  
 258          // Getting information from available H5P tools one by one because their enabled/disabled options are totally different.
 259          // Check the atto button status.
 260          $link = \editor_atto\plugininfo\atto::get_manage_url();
 261          $status = strpos(get_config('editor_atto', 'toolbar'), 'h5p') > -1;
 262          $tools[] = self::convert_info_into_array('atto_h5p', $link, $status);
 263  
 264          // Check the Display H5P filter status.
 265          $link = \core\plugininfo\filter::get_manage_url();
 266          $status = filter_get_active_state('displayh5p', context_system::instance()->id);
 267          $tools[] = self::convert_info_into_array('filter_displayh5p', $link, $status);
 268  
 269          // Check H5P scheduled task.
 270          $link = '';
 271          $status = 0;
 272          $statusaction = '';
 273          if ($task = \core\task\manager::get_scheduled_task('\core\task\h5p_get_content_types_task')) {
 274              $status = !$task->get_disabled();
 275              $link = new \moodle_url(
 276                  '/admin/tool/task/scheduledtasks.php',
 277                  array('action' => 'edit', 'task' => get_class($task))
 278              );
 279              if ($status && \core\task\manager::is_runnable() && get_config('tool_task', 'enablerunnow')) {
 280                  $statusaction = \html_writer::link(
 281                      new \moodle_url('/admin/tool/task/schedule_task.php',
 282                          array('task' => get_class($task))),
 283                      get_string('runnow', 'tool_task'));
 284              }
 285          }
 286          $tools[] = self::convert_info_into_array('task_h5p', $link, $status, $statusaction);
 287  
 288          return $tools;
 289      }
 290  
 291      /**
 292       * Convert information into needed mustache template data array
 293       * @param string $tool The name of the tool
 294       * @param \moodle_url $link The URL to management page
 295       * @param int $status The current status of the tool
 296       * @param string $statusaction A link to 'Run now' option for the task
 297       * @return array
 298       */
 299      static private function convert_info_into_array(string $tool,
 300          \moodle_url $link,
 301          int $status,
 302          string $statusaction = ''): array {
 303  
 304          $statusclasses = array(
 305              TEXTFILTER_DISABLED => 'badge badge-danger',
 306              TEXTFILTER_OFF => 'badge badge-warning',
 307              0 => 'badge badge-danger',
 308              TEXTFILTER_ON => 'badge badge-success',
 309          );
 310  
 311          $statuschoices = array(
 312              TEXTFILTER_DISABLED => get_string('disabled', 'admin'),
 313              TEXTFILTER_OFF => get_string('offbutavailable', 'core_filters'),
 314              0 => get_string('disabled', 'admin'),
 315              1 => get_string('enabled', 'admin'),
 316          );
 317  
 318          return [
 319              'tool' => get_string($tool, 'h5p'),
 320              'tool_description' => get_string($tool . '_description', 'h5p'),
 321              'link' => $link,
 322              'status' => $statuschoices[$status],
 323              'status_class' => $statusclasses[$status],
 324              'status_action' => $statusaction,
 325          ];
 326      }
 327  
 328      /**
 329       * Get a query string with the theme revision number to include at the end
 330       * of URLs. This is used to force the browser to reload the asset when the
 331       * theme caches are cleared.
 332       *
 333       * @return string
 334       */
 335      public static function get_cache_buster(): string {
 336          global $CFG;
 337          return '?ver=' . $CFG->themerev;
 338      }
 339  
 340      /**
 341       * Get the settings needed by the H5P library.
 342       *
 343       * @return array The settings.
 344       */
 345      public static function get_core_settings(): array {
 346          global $CFG, $USER;
 347  
 348          $basepath = $CFG->wwwroot . '/';
 349          $systemcontext = context_system::instance();
 350  
 351          // Generate AJAX paths.
 352          $ajaxpaths = [];
 353          $ajaxpaths['xAPIResult'] = '';
 354          $ajaxpaths['contentUserData'] = '';
 355  
 356          $factory = new factory();
 357          $core = $factory->get_core();
 358  
 359          // When there is a logged in user, her information will be passed to the player. It will be used for tracking.
 360          $usersettings = [];
 361          if (isloggedin()) {
 362              $usersettings['name'] = fullname($USER, has_capability('moodle/site:viewfullnames', $systemcontext));
 363              $usersettings['id'] = $USER->id;
 364          }
 365          $settings = array(
 366              'baseUrl' => $basepath,
 367              'url' => "{$basepath}pluginfile.php/{$systemcontext->instanceid}/core_h5p",
 368              'urlLibraries' => "{$basepath}pluginfile.php/{$systemcontext->id}/core_h5p/libraries",
 369              'postUserStatistics' => false,
 370              'ajax' => $ajaxpaths,
 371              'saveFreq' => false,
 372              'siteUrl' => $CFG->wwwroot,
 373              'l10n' => array('H5P' => $core->getLocalization()),
 374              'user' => $usersettings,
 375              'hubIsEnabled' => false,
 376              'reportingIsEnabled' => false,
 377              'crossorigin' => !empty($CFG->h5pcrossorigin) ? $CFG->h5pcrossorigin : null,
 378              'libraryConfig' => $core->h5pF->getLibraryConfig(),
 379              'pluginCacheBuster' => self::get_cache_buster(),
 380              'libraryUrl' => autoloader::get_h5p_core_library_url('js')->out(),
 381          );
 382  
 383          return $settings;
 384      }
 385  
 386      /**
 387       * Get the core H5P assets, including all core H5P JavaScript and CSS.
 388       *
 389       * @return Array core H5P assets.
 390       */
 391      public static function get_core_assets(): array {
 392          global $CFG, $PAGE;
 393  
 394          // Get core settings.
 395          $settings = self::get_core_settings();
 396          $settings['core'] = [
 397              'styles' => [],
 398              'scripts' => []
 399          ];
 400          $settings['loadedJs'] = [];
 401          $settings['loadedCss'] = [];
 402  
 403          // Make sure files are reloaded for each plugin update.
 404          $cachebuster = self::get_cache_buster();
 405  
 406          // Use relative URL to support both http and https.
 407          $liburl = autoloader::get_h5p_core_library_url()->out();
 408          $relpath = '/' . preg_replace('/^[^:]+:\/\/[^\/]+\//', '', $liburl);
 409  
 410          // Add core stylesheets.
 411          foreach (core::$styles as $style) {
 412              $settings['core']['styles'][] = $relpath . $style . $cachebuster;
 413              $PAGE->requires->css(new \moodle_url($liburl . $style . $cachebuster));
 414          }
 415          // Add core JavaScript.
 416          foreach (core::get_scripts() as $script) {
 417              $settings['core']['scripts'][] = $script->out(false);
 418              $PAGE->requires->js($script, true);
 419          }
 420  
 421          return $settings;
 422      }
 423  
 424      /**
 425       * Prepare the library name to be used as a cache key (remove whitespaces and replace dots to underscores).
 426       *
 427       * @param  string $library Library name.
 428       * @return string Library name in a cache simple key format (a-zA-Z0-9_).
 429       */
 430      public static function get_cache_librarykey(string $library): string {
 431          // Remove whitespaces and replace '.' to '_'.
 432          return str_replace('.', '_', str_replace(' ', '', $library));
 433      }
 434  
 435      /**
 436       * Parse a JS array to a PHP array.
 437       *
 438       * @param  string $jscontent The JS array to parse to PHP array.
 439       * @return array The JS array converted to PHP array.
 440       */
 441      public static function parse_js_array(string $jscontent): array {
 442          // Convert all line-endings to UNIX format first.
 443          $jscontent = str_replace(array("\r\n", "\r"), "\n", $jscontent);
 444          $jsarray = preg_split('/,\n\s+/', substr($jscontent, 0, -1));
 445          $jsarray = preg_replace('~{?\\n~', '', $jsarray);
 446  
 447          $strings = [];
 448          foreach ($jsarray as $key => $value) {
 449              $splitted = explode(":", $value, 2);
 450              $value = preg_replace("/^['|\"](.*)['|\"]$/", "$1", trim($splitted[1], ' ,'));
 451              $strings[ trim($splitted[0]) ] = str_replace("\'", "'", $value);
 452          }
 453  
 454          return $strings;
 455      }
 456  
 457      /**
 458       * Get the information related to the H5P export file.
 459       * The information returned will be:
 460       * - filename, filepath, mimetype, filesize, timemodified and fileurl.
 461       *
 462       * @param  string $exportfilename The H5P export filename (with slug).
 463       * @param  \moodle_url $url The URL of the exported file.
 464       * @param  factory $factory The \core_h5p\factory object
 465       * @return array|null The information export file otherwise null.
 466       */
 467      public static function get_export_info(string $exportfilename, \moodle_url $url = null, ?factory $factory = null): ?array {
 468  
 469          if (!$factory) {
 470              $factory = new factory();
 471          }
 472          $core = $factory->get_core();
 473  
 474          // Get export file.
 475          if (!$fileh5p = $core->fs->get_export_file($exportfilename)) {
 476              return null;
 477          }
 478  
 479          // Build the export info array.
 480          $file = [];
 481          $file['filename'] = $fileh5p->get_filename();
 482          $file['filepath'] = $fileh5p->get_filepath();
 483          $file['mimetype'] = $fileh5p->get_mimetype();
 484          $file['filesize'] = $fileh5p->get_filesize();
 485          $file['timemodified'] = $fileh5p->get_timemodified();
 486  
 487          if (!$url) {
 488              $url  = \moodle_url::make_webservice_pluginfile_url(
 489                  $fileh5p->get_contextid(),
 490                  $fileh5p->get_component(),
 491                  $fileh5p->get_filearea(),
 492                  '',
 493                  '',
 494                  $fileh5p->get_filename()
 495              );
 496          }
 497  
 498          $file['fileurl'] = $url->out(false);
 499  
 500          return $file;
 501      }
 502  }