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   * H5P core class.
  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  defined('MOODLE_INTERNAL') || die();
  28  
  29  require_once("$CFG->libdir/filelib.php");
  30  
  31  use Moodle\H5PCore;
  32  use Moodle\H5PFrameworkInterface;
  33  use Moodle\H5PHubEndpoints;
  34  use stdClass;
  35  use moodle_url;
  36  use core_h5p\local\library\autoloader;
  37  
  38  /**
  39   * H5P core class, containing functions and storage shared by the other H5P classes.
  40   *
  41   * @package    core_h5p
  42   * @copyright  2019 Sara Arjona <sara@moodle.com>
  43   * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  44   */
  45  class core extends H5PCore {
  46  
  47      /** @var array The array containing all the present libraries */
  48      protected $libraries;
  49  
  50      /**
  51       * Constructor for core_h5p/core.
  52       *
  53       * @param H5PFrameworkInterface $framework The frameworks implementation of the H5PFrameworkInterface
  54       * @param string|H5PFileStorage $path The H5P file storage directory or class
  55       * @param string $url The URL to the file storage directory
  56       * @param string $language The language code. Defaults to english
  57       * @param boolean $export Whether export is enabled
  58       */
  59      public function __construct(H5PFrameworkInterface $framework, $path, string $url, string $language = 'en',
  60              bool $export = false) {
  61  
  62          parent::__construct($framework, $path, $url, $language, $export);
  63  
  64          // Aggregate the assets by default.
  65          $this->aggregateAssets = true;
  66      }
  67  
  68      /**
  69       * Get the path to the dependency.
  70       *
  71       * @param array $dependency An array containing the information of the requested dependency library
  72       * @return string The path to the dependency library
  73       */
  74      protected function getDependencyPath(array $dependency): string {
  75          $library = $this->find_library($dependency);
  76  
  77          return "libraries/{$library->id}/{$library->machinename}-{$library->majorversion}.{$library->minorversion}";
  78      }
  79  
  80      /**
  81       * Get the paths to the content dependencies.
  82       *
  83       * @param int $id The H5P content ID
  84       * @return array An array containing the path of each content dependency
  85       */
  86      public function get_dependency_roots(int $id): array {
  87          $roots = [];
  88          $dependencies = $this->h5pF->loadContentDependencies($id);
  89          $context = \context_system::instance();
  90          foreach ($dependencies as $dependency) {
  91              $library = $this->find_library($dependency);
  92              $roots[self::libraryToString($dependency, true)] = (moodle_url::make_pluginfile_url(
  93                  $context->id,
  94                  'core_h5p',
  95                  'libraries',
  96                  $library->id,
  97                  "/" . self::libraryToString($dependency, true),
  98                  ''
  99              ))->out(false);
 100          }
 101  
 102          return $roots;
 103      }
 104  
 105      /**
 106       * Get a particular dependency library.
 107       *
 108       * @param array $dependency An array containing information of the dependency library
 109       * @return stdClass|null The library object if the library dependency exists, null otherwise
 110       */
 111      protected function find_library(array $dependency): ?\stdClass {
 112          global $DB;
 113          if (null === $this->libraries) {
 114              $this->libraries = $DB->get_records('h5p_libraries');
 115          }
 116  
 117          $major = $dependency['majorVersion'];
 118          $minor = $dependency['minorVersion'];
 119          $patch = $dependency['patchVersion'];
 120  
 121          foreach ($this->libraries as $library) {
 122              if ($library->machinename !== $dependency['machineName']) {
 123                  continue;
 124              }
 125  
 126              if ($library->majorversion != $major) {
 127                  continue;
 128              }
 129              if ($library->minorversion != $minor) {
 130                  continue;
 131              }
 132              if ($library->patchversion != $patch) {
 133                  continue;
 134              }
 135  
 136              return $library;
 137          }
 138  
 139          return null;
 140      }
 141  
 142      /**
 143       * Get the list of JS scripts to include on the page.
 144       *
 145       * @return array The array containg urls of the core JavaScript files
 146       */
 147      public static function get_scripts(): array {
 148          global $PAGE;
 149  
 150          $jsrev = $PAGE->requires->get_jsrev();
 151          $urls = [];
 152          foreach (self::$scripts as $script) {
 153              $urls[] = autoloader::get_h5p_core_library_url($script, [
 154                  'ver' => $jsrev,
 155              ]);
 156          }
 157          $urls[] = new moodle_url("/h5p/js/h5p_overrides.js", [
 158              'ver' => $jsrev,
 159          ]);
 160  
 161          return $urls;
 162      }
 163  
 164      /**
 165       * Fetch and install the latest H5P content types libraries from the official H5P repository.
 166       * If the latest version of a content type library is present in the system, nothing is done for that content type.
 167       *
 168       * @return stdClass
 169       */
 170      public function fetch_latest_content_types(): ?\stdClass {
 171  
 172          $contenttypes = $this->get_latest_content_types();
 173          if (!empty($contenttypes->error)) {
 174              return $contenttypes;
 175          }
 176  
 177          $typesinstalled = [];
 178  
 179          $factory = new factory();
 180          $framework = $factory->get_framework();
 181  
 182          foreach ($contenttypes->contentTypes as $type) {
 183              // Don't fetch content types that require a higher H5P core API version.
 184              if (!$this->is_required_core_api($type->coreApiVersionNeeded)) {
 185                  continue;
 186              }
 187  
 188              $library = [
 189                  'machineName' => $type->id,
 190                  'majorVersion' => $type->version->major,
 191                  'minorVersion' => $type->version->minor,
 192                  'patchVersion' => $type->version->patch,
 193              ];
 194              // Add example and tutorial to the library, to store this information too.
 195              if (isset($type->example)) {
 196                  $library['example'] = $type->example;
 197              }
 198              if (isset($type->tutorial)) {
 199                  $library['tutorial'] = $type->tutorial;
 200              }
 201  
 202              $shoulddownload = true;
 203              if ($framework->getLibraryId($type->id, $type->version->major, $type->version->minor)) {
 204                  if (!$framework->isPatchedLibrary($library)) {
 205                      $shoulddownload = false;
 206                  }
 207              }
 208  
 209              if ($shoulddownload) {
 210                  $installed['id'] = $this->fetch_content_type($library);
 211                  if ($installed['id']) {
 212                      $installed['name'] = H5PCore::libraryToString($library);
 213                      $typesinstalled[] = $installed;
 214                  }
 215              }
 216          }
 217  
 218          $result = new stdClass();
 219          $result->error = '';
 220          $result->typesinstalled = $typesinstalled;
 221  
 222          return $result;
 223      }
 224  
 225      /**
 226       * Given an H5P content type machine name, fetch and install the required library from the official H5P repository.
 227       *
 228       * @param array $library Library machineName, majorversion and minorversion.
 229       * @return int|null Returns the id of the content type library installed, null otherwise.
 230       */
 231      public function fetch_content_type(array $library): ?int {
 232          global $DB;
 233  
 234          $factory = new factory();
 235  
 236          // Download the latest content type from the H5P official repository.
 237          $fs = get_file_storage();
 238          $file = $fs->create_file_from_url(
 239              (object) [
 240                  'component' => 'core_h5p',
 241                  'filearea' => 'library_sources',
 242                  'itemid' => 0,
 243                  'contextid' => (\context_system::instance())->id,
 244                  'filepath' => '/',
 245                  'filename' => $library['machineName'],
 246              ],
 247              $this->get_api_endpoint($library['machineName']),
 248              null,
 249              true
 250          );
 251  
 252          if (!$file) {
 253              return null;
 254          }
 255  
 256          helper::save_h5p($factory, $file, (object) [], false, true);
 257  
 258          $file->delete();
 259  
 260          $librarykey = static::libraryToString($library);
 261          $libraryid = $factory->get_storage()->h5pC->librariesJsonData[$librarykey]["libraryId"];
 262  
 263          // Update example and tutorial (if any of them are defined in $library).
 264          $params = ['id' => $libraryid];
 265          if (array_key_exists('example', $library)) {
 266              $params['example'] = $library['example'];
 267          }
 268          if (array_key_exists('tutorial', $library)) {
 269              $params['tutorial'] = $library['tutorial'];
 270          }
 271          if (count($params) > 1) {
 272              $DB->update_record('h5p_libraries', $params);
 273          }
 274  
 275          return $libraryid;
 276      }
 277  
 278      /**
 279       * Get H5P endpoints.
 280       *
 281       * If $endpoint = 'content' and $library is null, moodle_url is the endpoint of the latest version of the H5P content
 282       * types; however, if $library is the machine name of a content type, moodle_url is the endpoint to download the content type.
 283       * The SITES endpoint ($endpoint = 'site') may be use to get a site UUID or send site data.
 284       *
 285       * @param string|null $library The machineName of the library whose endpoint is requested.
 286       * @param string $endpoint The endpoint required. Valid values: "site", "content".
 287       * @return moodle_url The endpoint moodle_url object.
 288       */
 289      public function get_api_endpoint(?string $library = null, string $endpoint = 'content'): moodle_url {
 290          if ($endpoint == 'site') {
 291              $h5purl = H5PHubEndpoints::createURL(H5PHubEndpoints::SITES );
 292          } else if ($endpoint == 'content') {
 293              $h5purl = H5PHubEndpoints::createURL(H5PHubEndpoints::CONTENT_TYPES ) . $library;
 294          }
 295  
 296          return new moodle_url($h5purl);
 297      }
 298  
 299      /**
 300       * Get the latest version of the H5P content types available in the official repository.
 301       *
 302       * @return stdClass An object with 2 properties:
 303       *     - string error: error message when there is any problem, empty otherwise
 304       *     - array contentTypes: an object for each H5P content type with its information
 305       */
 306      public function get_latest_content_types(): \stdClass {
 307          global $CFG;
 308  
 309          $siteuuid = $this->get_site_uuid() ?? md5($CFG->wwwroot);
 310          $postdata = ['uuid' => $siteuuid];
 311  
 312          // Get the latest content-types json.
 313          $endpoint = $this->get_api_endpoint();
 314          $request = download_file_content($endpoint, null, $postdata, true);
 315  
 316          if (!empty($request->error) || $request->status != '200' || empty($request->results)) {
 317              if (empty($request->error)) {
 318                  $request->error = get_string('fetchtypesfailure', 'core_h5p');
 319              }
 320              return $request;
 321          }
 322  
 323          $contenttypes = json_decode($request->results);
 324          $contenttypes->error = '';
 325  
 326          return $contenttypes;
 327      }
 328  
 329      /**
 330       * Get the site UUID. If site UUID is not defined, try to register the site.
 331       *
 332       * return $string The site UUID, null if it is not set.
 333       */
 334      public function get_site_uuid(): ?string {
 335          // Check if the site_uuid is already set.
 336          $siteuuid = get_config('core_h5p', 'site_uuid');
 337  
 338          if (!$siteuuid) {
 339              $siteuuid = $this->register_site();
 340          }
 341  
 342          return $siteuuid;
 343      }
 344  
 345      /**
 346       * Get H5P generated site UUID.
 347       *
 348       * return ?string Returns H5P generated site UUID, null if can't get it.
 349       */
 350      private function register_site(): ?string {
 351          $endpoint = $this->get_api_endpoint(null, 'site');
 352          $siteuuid = download_file_content($endpoint, null, '');
 353  
 354          // Successful UUID retrieval from H5P.
 355          if ($siteuuid) {
 356              $json = json_decode($siteuuid);
 357              if (isset($json->uuid)) {
 358                  set_config('site_uuid', $json->uuid, 'core_h5p');
 359                  return $json->uuid;
 360              }
 361          }
 362  
 363          return null;
 364      }
 365  
 366      /**
 367       * Checks that the required H5P core API version or higher is installed.
 368       *
 369       * @param stdClass $coreapi Object with properties major and minor for the core API version required.
 370       * @return bool True if the required H5P core API version is installed. False if not.
 371       */
 372      public function is_required_core_api($coreapi): bool {
 373          if (isset($coreapi) && !empty($coreapi)) {
 374              if (($coreapi->major > H5PCore::$coreApi['majorVersion']) ||
 375                  (($coreapi->major == H5PCore::$coreApi['majorVersion']) && ($coreapi->minor > H5PCore::$coreApi['minorVersion']))) {
 376                  return false;
 377              }
 378          }
 379          return true;
 380      }
 381  
 382      /**
 383       * Get the library string from a DB library record.
 384       *
 385       * @param  stdClass $record The DB library record.
 386       * @param  bool $foldername If true, use hyphen instead of space in returned string.
 387       * @return string The string name on the form {machineName} {majorVersion}.{minorVersion}.
 388       */
 389      public static function record_to_string(stdClass $record, bool $foldername = false): string {
 390          return static::libraryToString([
 391              'machineName' => $record->machinename,
 392              'majorVersion' => $record->majorversion,
 393              'minorVersion' => $record->minorversion,
 394          ], $foldername);
 395      }
 396  }