Search moodle.org's
Developer Documentation

See Release Notes

  • Bug fixes for general core bugs in 3.10.x will end 8 November 2021 (12 months).
  • Bug fixes for security issues in 3.10.x will end 9 May 2022 (18 months).
  • PHP version: minimum PHP 7.2.0 Note: minimum PHP version has increased since Moodle 3.8. PHP 7.3.x and 7.4.x are supported too.

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

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