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