Search moodle.org's
Developer Documentation

  • 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 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 API class for the H5P area.
      19   *
      20   * @package    core_h5p
      21   * @copyright  2020 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 core\lock\lock_config;
      28  use Moodle\H5PCore;
      29  
      30  /**
      31   * Contains API class for the H5P area.
      32   *
      33   * @copyright  2020 Sara Arjona <sara@moodle.com>
      34   * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
      35   */
      36  class api {
      37  
      38      /**
      39       * Delete a library and also all the libraries depending on it and the H5P contents using it. For the H5P content, only the
      40       * database entries in {h5p} are removed (the .h5p files are not removed in order to let users to deploy them again).
      41       *
      42       * @param  factory   $factory The H5P factory.
      43       * @param  \stdClass $library The library to delete.
      44       */
      45      public static function delete_library(factory $factory, \stdClass $library): void {
      46          global $DB;
      47  
      48          // Get the H5P contents using this library, to remove them from DB. The .h5p files won't be removed
      49          // so they will be displayed by the player next time a user with the proper permissions accesses it.
      50          $sql = 'SELECT DISTINCT hcl.h5pid
      51                    FROM {h5p_contents_libraries} hcl
      52                   WHERE hcl.libraryid = :libraryid';
      53          $params = ['libraryid' => $library->id];
      54          $h5pcontents = $DB->get_records_sql($sql, $params);
      55          foreach ($h5pcontents as $h5pcontent) {
      56              $factory->get_framework()->deleteContentData($h5pcontent->h5pid);
      57          }
      58  
      59          $fs = $factory->get_core()->fs;
      60          $framework = $factory->get_framework();
      61          // Delete the library from the file system.
      62          $fs->delete_library(array('libraryId' => $library->id));
      63          // Delete also the cache assets to rebuild them next time.
      64          $framework->deleteCachedAssets($library->id);
      65  
      66          // Remove library data from database.
      67          $DB->delete_records('h5p_library_dependencies', array('libraryid' => $library->id));
      68          $DB->delete_records('h5p_libraries', array('id' => $library->id));
      69  
      70          // Remove the libraries using this library.
      71          $requiredlibraries = self::get_dependent_libraries($library->id);
      72          foreach ($requiredlibraries as $requiredlibrary) {
      73              self::delete_library($factory, $requiredlibrary);
      74          }
      75      }
      76  
      77      /**
      78       * Get all the libraries using a defined library.
      79       *
      80       * @param  int    $libraryid The library to get its dependencies.
      81       * @return array  List of libraryid with all the libraries required by a defined library.
      82       */
      83      public static function get_dependent_libraries(int $libraryid): array {
      84          global $DB;
      85  
      86          $sql = 'SELECT *
      87                    FROM {h5p_libraries}
      88                   WHERE id IN (SELECT DISTINCT hl.id
      89                                  FROM {h5p_library_dependencies} hld
      90                                  JOIN {h5p_libraries} hl ON hl.id = hld.libraryid
      91                                 WHERE hld.requiredlibraryid = :libraryid)';
      92          $params = ['libraryid' => $libraryid];
      93  
      94          return $DB->get_records_sql($sql, $params);
      95      }
      96  
      97      /**
      98       * Get a library from an identifier.
      99       *
     100       * @param  int    $libraryid The library identifier.
     101       * @return \stdClass The library object having the library identifier defined.
     102       * @throws dml_exception A DML specific exception is thrown if the libraryid doesn't exist.
     103       */
     104      public static function get_library(int $libraryid): \stdClass {
     105          global $DB;
     106  
     107          return $DB->get_record('h5p_libraries', ['id' => $libraryid], '*', MUST_EXIST);
     108      }
     109  
     110      /**
     111       * Returns a library as an object with properties that correspond to the fetched row's field names.
     112       *
     113       * @param array $params An associative array with the values of the machinename, majorversion and minorversion fields.
     114       * @param bool $configurable A library that has semantics so it can be configured in the editor.
     115       * @param string $fields Library attributes to retrieve.
     116       *
     117       * @return \stdClass|null An object with one attribute for each field name in $fields param.
     118       */
     119      public static function get_library_details(array $params, bool $configurable, string $fields = ''): ?\stdClass {
     120          global $DB;
     121  
     122          $select = "machinename = :machinename
     123                     AND majorversion = :majorversion
     124                     AND minorversion = :minorversion";
     125  
     126          if ($configurable) {
     127              $select .= " AND semantics IS NOT NULL";
     128          }
     129  
     130          $fields = $fields ?: '*';
     131  
     132          $record = $DB->get_record_select('h5p_libraries', $select, $params, $fields);
     133  
     134          return $record ?: null;
     135      }
     136  
     137      /**
     138       * Get all the H5P content type libraries versions.
     139       *
     140       * @param string|null $fields Library fields to return.
     141       *
     142       * @return array An array with an object for each content type library installed.
     143       */
     144      public static function get_contenttype_libraries(?string $fields = ''): array {
     145          global $DB;
     146  
     147          $libraries = [];
     148          $fields = $fields ?: '*';
     149          $select = "runnable = :runnable
     150                     AND semantics IS NOT NULL";
     151          $params = ['runnable' => 1];
     152          $sort = 'title, majorversion DESC, minorversion DESC';
     153  
     154          $records = $DB->get_records_select('h5p_libraries', $select, $params, $sort, $fields);
     155  
     156          $added = [];
     157          foreach ($records as $library) {
     158              // Remove unique index.
     159              unset($library->id);
     160  
     161              // Convert snakes to camels.
     162              $library->majorVersion = (int) $library->majorversion;
     163              unset($library->major_version);
     164              $library->minorVersion = (int) $library->minorversion;
     165              unset($library->minorversion);
     166              $library->metadataSettings = json_decode($library->metadatasettings);
     167  
     168              // If we already add this library means that it is an old version,as the previous query was sorted by version.
     169              if (isset($added[$library->name])) {
     170                  $library->isOld = true;
     171              } else {
     172                  $added[$library->name] = true;
     173              }
     174  
     175              // Add new library.
     176              $libraries[] = $library;
     177          }
     178  
     179          return $libraries;
     180      }
     181  
     182      /**
     183       * Get the H5P DB instance id for a H5P pluginfile URL. If it doesn't exist, it's not created.
     184       *
     185       * @param string $url H5P pluginfile URL.
     186       * @param bool $preventredirect Set to true in scripts that can not redirect (CLI, RSS feeds, etc.), throws exceptions
     187       * @param bool $skipcapcheck Whether capabilities should be checked or not to get the pluginfile URL because sometimes they
     188       *     might be controlled before calling this method.
     189       *
     190       * @return array of [file, stdClass|false]:
     191       *             - file local file for this $url.
     192       *             - stdClass is an H5P object or false if there isn't any H5P with this URL.
     193       */
     194      public static function get_content_from_pluginfile_url(string $url, bool $preventredirect = true,
     195          bool $skipcapcheck = false): array {
     196  
     197          global $DB;
     198  
     199          // Deconstruct the URL and get the pathname associated.
     200          if ($skipcapcheck || self::can_access_pluginfile_hash($url, $preventredirect)) {
     201              $pathnamehash = self::get_pluginfile_hash($url);
     202          }
     203  
     204          if (!$pathnamehash) {
     205              return [false, false];
     206          }
     207  
     208          // Get the file.
     209          $fs = get_file_storage();
     210          $file = $fs->get_file_by_hash($pathnamehash);
     211          if (!$file) {
     212              return [false, false];
     213          }
     214  
     215          $h5p = $DB->get_record('h5p', ['pathnamehash' => $pathnamehash]);
     216          return [$file, $h5p];
     217      }
     218  
     219      /**
     220       * Create, if it doesn't exist, the H5P DB instance id for a H5P pluginfile URL. If it exists:
     221       * - If the content is not the same, remove the existing content and re-deploy the H5P content again.
     222       * - If the content is the same, returns the H5P identifier.
     223       *
     224       * @param string $url H5P pluginfile URL.
     225       * @param stdClass $config Configuration for H5P buttons.
     226       * @param factory $factory The \core_h5p\factory object
     227       * @param stdClass $messages The error, exception and info messages, raised while preparing and running an H5P content.
     228       * @param bool $preventredirect Set to true in scripts that can not redirect (CLI, RSS feeds, etc.), throws exceptions
     229       * @param bool $skipcapcheck Whether capabilities should be checked or not to get the pluginfile URL because sometimes they
     230       *     might be controlled before calling this method.
     231       *
     232       * @return array of [file, h5pid]:
     233       *             - file local file for this $url.
     234       *             - h5pid is the H5P identifier or false if there isn't any H5P with this URL.
     235       */
     236      public static function create_content_from_pluginfile_url(string $url, \stdClass $config, factory $factory,
     237          \stdClass &$messages, bool $preventredirect = true, bool $skipcapcheck = false): array {
     238          global $USER;
     239  
     240          $core = $factory->get_core();
     241          list($file, $h5p) = self::get_content_from_pluginfile_url($url, $preventredirect, $skipcapcheck);
     242  
     243          if (!$file) {
     244              $core->h5pF->setErrorMessage(get_string('h5pfilenotfound', 'core_h5p'));
     245              return [false, false];
     246          }
     247  
     248          $contenthash = $file->get_contenthash();
     249          if ($h5p && $h5p->contenthash != $contenthash) {
     250              // The content exists and it is different from the one deployed previously. The existing one should be removed before
     251              // deploying the new version.
     252              self::delete_content($h5p, $factory);
     253              $h5p = false;
     254          }
     255  
     256          $context = \context::instance_by_id($file->get_contextid());
     257          if ($h5p) {
     258              // The H5P content has been deployed previously.
     259  
     260              // If the main library for this H5P content is disabled, the content won't be displayed.
     261              $mainlibrary = (object) ['id' => $h5p->mainlibraryid];
     262              if (!self::is_library_enabled($mainlibrary)) {
     263                  $core->h5pF->setErrorMessage(get_string('mainlibrarydisabled', 'core_h5p'));
     264                  return [$file, false];
     265              } else {
     266                  $displayoptions = helper::get_display_options($core, $config);
     267                  // Check if the user can set the displayoptions.
     268                  if ($displayoptions != $h5p->displayoptions && has_capability('moodle/h5p:setdisplayoptions', $context)) {
     269                      // If displayoptions has changed and user has permission to modify it, update this information in DB.
     270                      $core->h5pF->updateContentFields($h5p->id, ['displayoptions' => $displayoptions]);
     271                  }
     272                  return [$file, $h5p->id];
     273              }
     274          } else {
     275              // The H5P content hasn't been deployed previously.
     276  
     277              // Check if the user uploading the H5P content is "trustable". If the file hasn't been uploaded by a user with this
     278              // capability, the content won't be deployed and an error message will be displayed.
     279              if (!helper::can_deploy_package($file)) {
     280                  $core->h5pF->setErrorMessage(get_string('nopermissiontodeploy', 'core_h5p'));
     281                  return [$file, false];
     282              }
     283  
     284              // The H5P content can be only deployed if the author of the .h5p file can update libraries or if all the
     285              // content-type libraries exist, to avoid users without the h5p:updatelibraries capability upload malicious content.
     286              $onlyupdatelibs = !helper::can_update_library($file);
     287  
     288              // Start lock to prevent synchronous access to save the same H5P.
     289              $lockfactory = lock_config::get_lock_factory('core_h5p');
     290              $lockkey = 'core_h5p_' . $file->get_pathnamehash();
     291              if ($lock = $lockfactory->get_lock($lockkey, 10)) {
     292                  try {
     293                      // Validate and store the H5P content before displaying it.
     294                      $h5pid = helper::save_h5p($factory, $file, $config, $onlyupdatelibs, false);
     295                  } finally {
     296                      $lock->release();
     297                  }
     298              } else {
     299                  $core->h5pF->setErrorMessage(get_string('lockh5pdeploy', 'core_h5p'));
     300                  return [$file, false];
     301              };
     302  
     303              if (!$h5pid && $file->get_userid() != $USER->id && has_capability('moodle/h5p:updatelibraries', $context)) {
     304                  // The user has permission to update libraries but the package has been uploaded by a different
     305                  // user without this permission. Check if there is some missing required library error.
     306                  $missingliberror = false;
     307                  $messages = helper::get_messages($messages, $factory);
     308                  if (!empty($messages->error)) {
     309                      foreach ($messages->error as $error) {
     310                          if ($error->code == 'missing-required-library') {
     311                              $missingliberror = true;
     312                              break;
     313                          }
     314                      }
     315                  }
     316                  if ($missingliberror) {
     317                      // The message about the permissions to upload libraries should be removed.
     318                      $infomsg = "Note that the libraries may exist in the file you uploaded, but you're not allowed to upload " .
     319                          "new libraries. Contact the site administrator about this.";
     320                      if (($key = array_search($infomsg, $messages->info)) !== false) {
     321                          unset($messages->info[$key]);
     322                      }
     323  
     324                      // No library will be installed and an error will be displayed, because this content is not trustable.
     325                      $core->h5pF->setInfoMessage(get_string('notrustablefile', 'core_h5p'));
     326                  }
     327                  return [$file, false];
     328  
     329              }
     330              return [$file, $h5pid];
     331          }
     332      }
     333  
     334      /**
     335       * Delete an H5P package.
     336       *
     337       * @param stdClass $content The H5P package to delete with, at least content['id].
     338       * @param factory $factory The \core_h5p\factory object
     339       */
     340      public static function delete_content(\stdClass $content, factory $factory): void {
     341          $h5pstorage = $factory->get_storage();
     342  
     343          // Add an empty slug to the content if it's not defined, because the H5P library requires this field exists.
     344          // It's not used when deleting a package, so the real slug value is not required at this point.
     345          $content->slug = $content->slug ?? '';
     346          $h5pstorage->deletePackage( (array) $content);
     347      }
     348  
     349      /**
     350       * Delete an H5P package deployed from the defined $url.
     351       *
     352       * @param string $url pluginfile URL of the H5P package to delete.
     353       * @param factory $factory The \core_h5p\factory object
     354       */
     355      public static function delete_content_from_pluginfile_url(string $url, factory $factory): void {
     356          global $DB;
     357  
     358          // Get the H5P to delete.
     359          $pathnamehash = self::get_pluginfile_hash($url);
     360          $h5p = $DB->get_record('h5p', ['pathnamehash' => $pathnamehash]);
     361          if ($h5p) {
     362              self::delete_content($h5p, $factory);
     363          }
     364      }
     365  
     366      /**
     367       * If user can access pathnamehash from an H5P internal URL.
     368       *
     369       * @param  string $url H5P pluginfile URL poiting to an H5P file.
     370       * @param bool $preventredirect Set to true in scripts that can not redirect (CLI, RSS feeds, etc.), throws exceptions
     371       *
     372       * @return bool if user can access pluginfile hash.
     373       * @throws \moodle_exception
     374       * @throws \coding_exception
     375       * @throws \require_login_exception
     376       */
     377      protected static function can_access_pluginfile_hash(string $url, bool $preventredirect = true): bool {
     378          global $USER, $CFG;
     379  
     380          // Decode the URL before start processing it.
     381          $url = new \moodle_url(urldecode($url));
     382  
     383          // Remove params from the URL (such as the 'forcedownload=1'), to avoid errors.
     384          $url->remove_params(array_keys($url->params()));
     385          $path = $url->out_as_local_url();
     386  
     387          // We only need the slasharguments.
     388          $path = substr($path, strpos($path, '.php/') + 5);
     389          $parts = explode('/', $path);
     390  
     391          // If the request is made by tokenpluginfile.php we need to avoid userprivateaccesskey.
     392          if (strpos($url, '/tokenpluginfile.php')) {
     393              array_shift($parts);
     394          }
     395  
     396          // Get the contextid, component and filearea.
     397          $contextid = array_shift($parts);
     398          $component = array_shift($parts);
     399          $filearea = array_shift($parts);
     400  
     401          // Get the context.
     402          try {
     403              list($context, $course, $cm) = get_context_info_array($contextid);
     404          } catch (\moodle_exception $e) {
     405              throw new \moodle_exception('invalidcontextid', 'core_h5p');
     406          }
     407  
     408          // For CONTEXT_USER, such as the private files, raise an exception if the owner of the file is not the current user.
     409          if ($context->contextlevel == CONTEXT_USER && $USER->id !== $context->instanceid) {
     410              throw new \moodle_exception('h5pprivatefile', 'core_h5p');
     411          }
     412  
     413          if (!is_siteadmin($USER)) {
     414              // For CONTEXT_COURSECAT No login necessary - unless login forced everywhere.
     415              if ($context->contextlevel == CONTEXT_COURSECAT) {
     416                  if ($CFG->forcelogin) {
     417                      require_login(null, true, null, false, true);
     418                  }
     419              }
     420  
     421              // For CONTEXT_BLOCK.
     422              if ($context->contextlevel == CONTEXT_BLOCK) {
     423                  if ($context->get_course_context(false)) {
     424                      // If block is in course context, then check if user has capability to access course.
     425                      require_course_login($course, true, null, false, true);
     426                  } else if ($CFG->forcelogin) {
     427                      // No login necessary - unless login forced everywhere.
     428                      require_login(null, true, null, false, true);
     429                  } else {
     430                      // Get parent context and see if user have proper permission.
     431                      $parentcontext = $context->get_parent_context();
     432                      if ($parentcontext->contextlevel === CONTEXT_COURSECAT) {
     433                          // Check if category is visible and user can view this category.
     434                          if (!\core_course_category::get($parentcontext->instanceid, IGNORE_MISSING)) {
     435                              send_file_not_found();
     436                          }
     437                      } else if ($parentcontext->contextlevel === CONTEXT_USER && $parentcontext->instanceid != $USER->id) {
     438                          // The block is in the context of a user, it is only visible to the user who it belongs to.
     439                          send_file_not_found();
     440                      }
     441                      if ($filearea !== 'content') {
     442                          send_file_not_found();
     443                      }
     444                  }
     445              }
     446  
     447              // For CONTEXT_MODULE and CONTEXT_COURSE check if the user is enrolled in the course.
     448              // And for CONTEXT_MODULE has permissions view this .h5p file.
     449              if ($context->contextlevel == CONTEXT_MODULE ||
     450                  $context->contextlevel == CONTEXT_COURSE) {
     451                  // Require login to the course first (without login to the module).
     452                  require_course_login($course, true, null, !$preventredirect, $preventredirect);
     453  
     454                  // Now check if module is available OR it is restricted but the intro is shown on the course page.
     455                  if ($context->contextlevel == CONTEXT_MODULE) {
     456                      $cminfo = \cm_info::create($cm);
     457                      if (!$cminfo->uservisible) {
     458                          if (!$cm->showdescription || !$cminfo->is_visible_on_course_page()) {
     459                              // Module intro is not visible on the course page and module is not available, show access error.
     460                              require_course_login($course, true, $cminfo, !$preventredirect, $preventredirect);
     461                          }
     462                      }
     463                  }
     464              }
     465          }
     466  
     467          return true;
     468      }
     469  
     470      /**
     471       * Get the pathnamehash from an H5P internal URL.
     472       *
     473       * @param  string $url H5P pluginfile URL poiting to an H5P file.
     474       *
     475       * @return string|false pathnamehash for the file in the internal URL.
     476       *
     477       * @throws \moodle_exception
     478       */
     479      protected static function get_pluginfile_hash(string $url) {
     480  
     481          // Decode the URL before start processing it.
     482          $url = new \moodle_url(urldecode($url));
     483  
     484          // Remove params from the URL (such as the 'forcedownload=1'), to avoid errors.
     485          $url->remove_params(array_keys($url->params()));
     486          $path = $url->out_as_local_url();
     487  
     488          // We only need the slasharguments.
     489          $path = substr($path, strpos($path, '.php/') + 5);
     490          $parts = explode('/', $path);
     491          $filename = array_pop($parts);
     492  
     493          // If the request is made by tokenpluginfile.php we need to avoid userprivateaccesskey.
     494          if (strpos($url, '/tokenpluginfile.php')) {
     495              array_shift($parts);
     496          }
     497  
     498          // Get the contextid, component and filearea.
     499          $contextid = array_shift($parts);
     500          $component = array_shift($parts);
     501          $filearea = array_shift($parts);
     502  
     503          // Ignore draft files, because they are considered temporary files, so shouldn't be displayed.
     504          if ($filearea == 'draft') {
     505              return false;
     506          }
     507  
     508          // Get the context.
     509          try {
     510              list($context, $course, $cm) = get_context_info_array($contextid);
     511          } catch (\moodle_exception $e) {
     512              throw new \moodle_exception('invalidcontextid', 'core_h5p');
     513          }
     514  
     515          // Some components, such as mod_page or mod_resource, add the revision to the URL to prevent caching problems.
     516          // So the URL contains this revision number as itemid but a 0 is always stored in the files table.
     517          // In order to get the proper hash, a callback should be done (looking for those exceptions).
     518          $pathdata = null;
     519          if ($context->contextlevel == CONTEXT_MODULE || $context->contextlevel == CONTEXT_BLOCK) {
     520              $pathdata = component_callback($component, 'get_path_from_pluginfile', [$filearea, $parts], null);
     521          }
     522          if (null === $pathdata) {
     523              // Look for the components and fileareas which have empty itemid defined in xxx_pluginfile.
     524              $hasnullitemid = false;
     525              $hasnullitemid = $hasnullitemid || ($component === 'user' && ($filearea === 'private' || $filearea === 'profile'));
     526              $hasnullitemid = $hasnullitemid || (substr($component, 0, 4) === 'mod_' && $filearea === 'intro');
     527              $hasnullitemid = $hasnullitemid || ($component === 'course' &&
     528                      ($filearea === 'summary' || $filearea === 'overviewfiles'));
     529              $hasnullitemid = $hasnullitemid || ($component === 'coursecat' && $filearea === 'description');
     530              $hasnullitemid = $hasnullitemid || ($component === 'backup' &&
     531                      ($filearea === 'course' || $filearea === 'activity' || $filearea === 'automated'));
     532              if ($hasnullitemid) {
     533                  $itemid = 0;
     534              } else {
     535                  $itemid = array_shift($parts);
     536              }
     537  
     538              if (empty($parts)) {
     539                  $filepath = '/';
     540              } else {
     541                  $filepath = '/' . implode('/', $parts) . '/';
     542              }
     543          } else {
     544              // The itemid and filepath have been returned by the component callback.
     545              [
     546                  'itemid' => $itemid,
     547                  'filepath' => $filepath,
     548              ] = $pathdata;
     549          }
     550  
     551          $fs = get_file_storage();
     552          $pathnamehash = $fs->get_pathname_hash($contextid, $component, $filearea, $itemid, $filepath, $filename);
     553          return $pathnamehash;
     554      }
     555  
     556      /**
     557       * Returns the H5P content object corresponding to an H5P content file.
     558       *
     559       * @param string $pathnamehash The pathnamehash of the file associated to an H5P content.
     560       *
     561       * @return null|\stdClass H5P content object or null if not found.
     562       */
     563      public static function get_content_from_pathnamehash(string $pathnamehash): ?\stdClass {
     564          global $DB;
     565  
     566          $h5p = $DB->get_record('h5p', ['pathnamehash' => $pathnamehash]);
     567  
     568          return ($h5p) ? $h5p : null;
     569      }
     570  
     571      /**
     572       * Return the H5P export information file when the file has been deployed.
     573       * Otherwise, return null if H5P file:
     574       * i) has not been deployed.
     575       * ii) has changed the content.
     576       *
     577       * The information returned will be:
     578       * - filename, filepath, mimetype, filesize, timemodified and fileurl.
     579       *
     580       * @param int $contextid ContextId of the H5P activity.
     581       * @param factory $factory The \core_h5p\factory object.
     582       * @param string $component component
     583       * @param string $filearea file area
     584       * @return array|null Return file info otherwise null.
     585       */
     586      public static function get_export_info_from_context_id(int $contextid,
     587          factory $factory,
     588          string $component,
     589          string $filearea): ?array {
     590  
     591          $core = $factory->get_core();
     592          $fs = get_file_storage();
     593          $files = $fs->get_area_files($contextid, $component, $filearea, 0, 'id', false);
     594          $file = reset($files);
     595  
     596          if ($h5p = self::get_content_from_pathnamehash($file->get_pathnamehash())) {
     597              if ($h5p->contenthash == $file->get_contenthash()) {
     598                  $content = $core->loadContent($h5p->id);
     599                  $slug = $content['slug'] ? $content['slug'] . '-' : '';
     600                  $filename = "{$slug}{$content['id']}.h5p";
     601                  $deployedfile = helper::get_export_info($filename, null, $factory);
     602  
     603                  return $deployedfile;
     604              }
     605          }
     606  
     607          return null;
     608      }
     609  
     610      /**
     611       * Enable or disable a library.
     612       *
     613       * @param int $libraryid The id of the library to enable/disable.
     614       * @param bool $isenabled True if the library should be enabled; false otherwise.
     615       */
     616      public static function set_library_enabled(int $libraryid, bool $isenabled): void {
     617          global $DB;
     618  
     619          $library = $DB->get_record('h5p_libraries', ['id' => $libraryid], '*', MUST_EXIST);
     620          if ($library->runnable) {
     621              // For now, only runnable libraries can be enabled/disabled.
     622              $record = [
     623                  'id' => $libraryid,
     624                  'enabled' => $isenabled,
     625              ];
     626              $DB->update_record('h5p_libraries', $record);
     627          }
     628      }
     629  
     630      /**
     631       * Check whether a library is enabled or not. When machinename is passed, it will return false if any of the versions
     632       * for this machinename is disabled.
     633       * If the library doesn't exist, it will return true.
     634       *
     635       * @param \stdClass $librarydata Supported fields for library: 'id' and 'machichename'.
     636       * @return bool
     637       * @throws \moodle_exception
     638       */
     639      public static function is_library_enabled(\stdClass $librarydata): bool {
     640          global $DB;
     641  
     642          $params = [];
     643          if (property_exists($librarydata, 'machinename')) {
     644              $params['machinename'] = $librarydata->machinename;
     645          }
     646          if (property_exists($librarydata, 'id')) {
     647              $params['id'] = $librarydata->id;
     648          }
     649  
     650          if (empty($params)) {
     651              throw new \moodle_exception("Missing 'machinename' or 'id' in librarydata parameter");
     652          }
     653  
     654          $libraries = $DB->get_records('h5p_libraries', $params);
     655  
     656          // If any of the libraries with these values have been disabled, return false.
     657          foreach ($libraries as $id => $library) {
     658              if (!$library->enabled) {
     659                  return false;
     660              }
     661          }
     662  
     663          return true;
     664      }
     665  
     666      /**
     667       * Check whether an H5P package is valid or not.
     668       *
     669       * @param \stored_file $file The file with the H5P content.
     670       * @param bool $onlyupdatelibs Whether new libraries can be installed or only the existing ones can be updated
     671       * @param bool $skipcontent Should the content be skipped (so only the libraries will be saved)?
     672       * @param factory|null $factory The \core_h5p\factory object
     673       * @param bool $deletefiletree Should the temporary files be deleted before returning?
     674       * @return bool True if the H5P file is valid (expected format, valid libraries...); false otherwise.
     675       */
     676      public static function is_valid_package(\stored_file $file, bool $onlyupdatelibs, bool $skipcontent = false,
     677              ?factory $factory = null, bool $deletefiletree = true): bool {
     678  
     679          // This may take a long time.
     680          \core_php_time_limit::raise();
     681  
     682          $isvalid = false;
     683  
     684          if (empty($factory)) {
     685              $factory = new factory();
     686          }
     687          $core = $factory->get_core();
     688          $h5pvalidator = $factory->get_validator();
     689  
     690          // Set the H5P file path.
     691          $core->h5pF->set_file($file);
     692          $path = $core->fs->getTmpPath();
     693          $core->h5pF->getUploadedH5pFolderPath($path);
     694          // Add manually the extension to the file to avoid the validation fails.
     695          $path .= '.h5p';
     696          $core->h5pF->getUploadedH5pPath($path);
     697          // Copy the .h5p file to the temporary folder.
     698          $file->copy_content_to($path);
     699  
     700          if ($h5pvalidator->isValidPackage($skipcontent, $onlyupdatelibs)) {
     701              if ($skipcontent) {
     702                  $isvalid = true;
     703              } else if (!empty($h5pvalidator->h5pC->mainJsonData['mainLibrary'])) {
     704                  $mainlibrary = (object) ['machinename' => $h5pvalidator->h5pC->mainJsonData['mainLibrary']];
     705                  if (self::is_library_enabled($mainlibrary)) {
     706                      $isvalid = true;
     707                  } else {
     708                      // If the main library of the package is disabled, the H5P content will be considered invalid.
     709                      $core->h5pF->setErrorMessage(get_string('mainlibrarydisabled', 'core_h5p'));
     710                  }
     711              }
     712          }
     713  
     714          if ($deletefiletree) {
     715              // Remove temp content folder.
     716              H5PCore::deleteFileTree($path);
     717          }
     718  
     719          return $isvalid;
     720      }
     721  }