2 // This file is part of Moodle - http://moodle.org/
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.
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.
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/>.
18 * Contains API class for the H5P area.
21 * @copyright 2020 Sara Arjona <sara@moodle.com>
22 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
27 defined('MOODLE_INTERNAL') || die();
29 use core\lock\lock_config;
32 * Contains API class for the H5P area.
34 * @copyright 2020 Sara Arjona <sara@moodle.com>
35 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
40 * Delete a library and also all the libraries depending on it and the H5P contents using it. For the H5P content, only the
41 * database entries in {h5p} are removed (the .h5p files are not removed in order to let users to deploy them again).
43 * @param factory $factory The H5P factory.
44 * @param \stdClass $library The library to delete.
46 public static function delete_library(factory $factory, \stdClass $library): void {
49 // Get the H5P contents using this library, to remove them from DB. The .h5p files won't be removed
50 // so they will be displayed by the player next time a user with the proper permissions accesses it.
51 $sql = 'SELECT DISTINCT hcl.h5pid
52 FROM {h5p_contents_libraries} hcl
53 WHERE hcl.libraryid = :libraryid';
54 $params = ['libraryid' => $library->id];
55 $h5pcontents = $DB->get_records_sql($sql, $params);
56 foreach ($h5pcontents as $h5pcontent) {
57 $factory->get_framework()->deleteContentData($h5pcontent->h5pid);
60 $fs = $factory->get_core()->fs;
61 $framework = $factory->get_framework();
62 // Delete the library from the file system.
63 $fs->delete_library(array('libraryId' => $library->id));
64 // Delete also the cache assets to rebuild them next time.
65 $framework->deleteCachedAssets($library->id);
67 // Remove library data from database.
68 $DB->delete_records('h5p_library_dependencies', array('libraryid' => $library->id));
69 $DB->delete_records('h5p_libraries', array('id' => $library->id));
71 // Remove the libraries using this library.
72 $requiredlibraries = self::get_dependent_libraries($library->id);
73 foreach ($requiredlibraries as $requiredlibrary) {
74 self::delete_library($factory, $requiredlibrary);
79 * Get all the libraries using a defined library.
81 * @param int $libraryid The library to get its dependencies.
82 * @return array List of libraryid with all the libraries required by a defined library.
84 public static function get_dependent_libraries(int $libraryid): array {
89 WHERE id IN (SELECT DISTINCT hl.id
90 FROM {h5p_library_dependencies} hld
91 JOIN {h5p_libraries} hl ON hl.id = hld.libraryid
92 WHERE hld.requiredlibraryid = :libraryid)';
93 $params = ['libraryid' => $libraryid];
95 return $DB->get_records_sql($sql, $params);
99 * Get a library from an identifier.
101 * @param int $libraryid The library identifier.
102 * @return \stdClass The library object having the library identifier defined.
103 * @throws dml_exception A DML specific exception is thrown if the libraryid doesn't exist.
105 public static function get_library(int $libraryid): \stdClass {
108 return $DB->get_record('h5p_libraries', ['id' => $libraryid], '*', MUST_EXIST);
112 * Returns a library as an object with properties that correspond to the fetched row's field names.
114 * @param array $params An associative array with the values of the machinename, majorversion and minorversion fields.
115 * @param bool $configurable A library that has semantics so it can be configured in the editor.
116 * @param string $fields Library attributes to retrieve.
118 * @return \stdClass|null An object with one attribute for each field name in $fields param.
120 public static function get_library_details(array $params, bool $configurable, string $fields = ''): ?\stdClass {
123 $select = "machinename = :machinename
124 AND majorversion = :majorversion
125 AND minorversion = :minorversion";
128 $select .= " AND semantics IS NOT NULL";
131 $fields = $fields ?: '*';
133 $record = $DB->get_record_select('h5p_libraries', $select, $params, $fields);
135 return $record ?: null;
139 * Get all the H5P content type libraries versions.
141 * @param string|null $fields Library fields to return.
143 * @return array An array with an object for each content type library installed.
145 public static function get_contenttype_libraries(?string $fields = ''): array {
149 $fields = $fields ?: '*';
150 $select = "runnable = :runnable
151 AND semantics IS NOT NULL";
152 $params = ['runnable' => 1];
153 $sort = 'title, majorversion DESC, minorversion DESC';
155 $records = $DB->get_records_select('h5p_libraries', $select, $params, $sort, $fields);
158 foreach ($records as $library) {
159 // Remove unique index.
162 // Convert snakes to camels.
163 $library->majorVersion = (int) $library->majorversion;
164 unset($library->major_version);
165 $library->minorVersion = (int) $library->minorversion;
166 unset($library->minorversion);
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;
172 $added[$library->name] = true;
176 $libraries[] = $library;
183 * Get the H5P DB instance id for a H5P pluginfile URL. If it doesn't exist, it's not created.
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
188 * @return array of [file, stdClass|false]:
189 * - file local file for this $url.
190 * - stdClass is an H5P object or false if there isn't any H5P with this URL.
192 public static function get_content_from_pluginfile_url(string $url, bool $preventredirect = true): array {
195 // Deconstruct the URL and get the pathname associated.
196 $pathnamehash = self::get_pluginfile_hash($url, $preventredirect);
197 if (!$pathnamehash) {
198 return [false, false];
202 $fs = get_file_storage();
203 $file = $fs->get_file_by_hash($pathnamehash);
205 return [false, false];
208 $h5p = $DB->get_record('h5p', ['pathnamehash' => $pathnamehash]);
209 return [$file, $h5p];
213 * Create, if it doesn't exist, the H5P DB instance id for a H5P pluginfile URL. If it exists:
214 * - If the content is not the same, remove the existing content and re-deploy the H5P content again.
215 * - If the content is the same, returns the H5P identifier.
217 * @param string $url H5P pluginfile URL.
218 * @param stdClass $config Configuration for H5P buttons.
219 * @param factory $factory The \core_h5p\factory object
220 * @param stdClass $messages The error, exception and info messages, raised while preparing and running an H5P content.
221 * @param bool $preventredirect Set to true in scripts that can not redirect (CLI, RSS feeds, etc.), throws exceptions
223 * @return array of [file, h5pid]:
224 * - file local file for this $url.
225 * - h5pid is the H5P identifier or false if there isn't any H5P with this URL.
227 public static function create_content_from_pluginfile_url(string $url, \stdClass $config, factory $factory,
228 \stdClass &$messages, bool $preventredirect = true): array {
231 $core = $factory->get_core();
232 list($file, $h5p) = self::get_content_from_pluginfile_url($url, $preventredirect);
235 $core->h5pF->setErrorMessage(get_string('h5pfilenotfound', 'core_h5p'));
236 return [false, false];
239 $contenthash = $file->get_contenthash();
240 if ($h5p && $h5p->contenthash != $contenthash) {
241 // The content exists and it is different from the one deployed previously. The existing one should be removed before
242 // deploying the new version.
243 self::delete_content($h5p, $factory);
247 $context = \context::instance_by_id($file->get_contextid());
249 // The H5P content has been deployed previously.
250 $displayoptions = helper::get_display_options($core, $config);
251 // Check if the user can set the displayoptions.
252 if ($displayoptions != $h5p->displayoptions && has_capability('moodle/h5p:setdisplayoptions', $context)) {
253 // If the displayoptions has changed and the user has permission to modify it, update this information in the DB.
254 $core->h5pF->updateContentFields($h5p->id, ['displayoptions' => $displayoptions]);
256 return [$file, $h5p->id];
258 // The H5P content hasn't been deployed previously.
260 // Check if the user uploading the H5P content is "trustable". If the file hasn't been uploaded by a user with this
261 // capability, the content won't be deployed and an error message will be displayed.
262 if (!helper::can_deploy_package($file)) {
263 $core->h5pF->setErrorMessage(get_string('nopermissiontodeploy', 'core_h5p'));
264 return [$file, false];
267 // The H5P content can be only deployed if the author of the .h5p file can update libraries or if all the
268 // content-type libraries exist, to avoid users without the h5p:updatelibraries capability upload malicious content.
269 $onlyupdatelibs = !helper::can_update_library($file);
271 // Start lock to prevent synchronous access to save the same H5P.
272 $lockfactory = lock_config::get_lock_factory('core_h5p');
273 $lockkey = 'core_h5p_' . $file->get_pathnamehash();
274 if ($lock = $lockfactory->get_lock($lockkey, 10)) {
276 // Validate and store the H5P content before displaying it.
277 $h5pid = helper::save_h5p($factory, $file, $config, $onlyupdatelibs, false);
282 $core->h5pF->setErrorMessage(get_string('lockh5pdeploy', 'core_h5p'));
283 return [$file, false];
286 if (!$h5pid && $file->get_userid() != $USER->id && has_capability('moodle/h5p:updatelibraries', $context)) {
287 // The user has permission to update libraries but the package has been uploaded by a different
288 // user without this permission. Check if there is some missing required library error.
289 $missingliberror = false;
290 $messages = helper::get_messages($messages, $factory);
291 if (!empty($messages->error)) {
292 foreach ($messages->error as $error) {
293 if ($error->code == 'missing-required-library') {
294 $missingliberror = true;
299 if ($missingliberror) {
300 // The message about the permissions to upload libraries should be removed.
301 $infomsg = "Note that the libraries may exist in the file you uploaded, but you're not allowed to upload " .
302 "new libraries. Contact the site administrator about this.";
303 if (($key = array_search($infomsg, $messages->info)) !== false) {
304 unset($messages->info[$key]);
307 // No library will be installed and an error will be displayed, because this content is not trustable.
308 $core->h5pF->setInfoMessage(get_string('notrustablefile', 'core_h5p'));
310 return [$file, false];
313 return [$file, $h5pid];
318 * Delete an H5P package.
320 * @param stdClass $content The H5P package to delete with, at least content['id].
321 * @param factory $factory The \core_h5p\factory object
323 public static function delete_content(\stdClass $content, factory $factory): void {
324 $h5pstorage = $factory->get_storage();
326 // Add an empty slug to the content if it's not defined, because the H5P library requires this field exists.
327 // It's not used when deleting a package, so the real slug value is not required at this point.
328 $content->slug = $content->slug ?? '';
329 $h5pstorage->deletePackage( (array) $content);
333 * Delete an H5P package deployed from the defined $url.
335 * @param string $url pluginfile URL of the H5P package to delete.
336 * @param factory $factory The \core_h5p\factory object
338 public static function delete_content_from_pluginfile_url(string $url, factory $factory): void {
339 // Get the H5P to delete.
340 list($file, $h5p) = self::get_content_from_pluginfile_url($url);
342 self::delete_content($h5p, $factory);
347 * Get the pathnamehash from an H5P internal URL.
349 * @param string $url H5P pluginfile URL poiting to an H5P file.
350 * @param bool $preventredirect Set to true in scripts that can not redirect (CLI, RSS feeds, etc.), throws exceptions
352 * @return string|false pathnamehash for the file in the internal URL.
354 protected static function get_pluginfile_hash(string $url, bool $preventredirect = true) {
357 // Decode the URL before start processing it.
358 $url = new \moodle_url(urldecode($url));
360 // Remove params from the URL (such as the 'forcedownload=1'), to avoid errors.
361 $url->remove_params(array_keys($url->params()));
362 $path = $url->out_as_local_url();
364 // We only need the slasharguments.
365 $path = substr($path, strpos($path, '.php/') + 5);
366 $parts = explode('/', $path);
367 $filename = array_pop($parts);
369 // If the request is made by tokenpluginfile.php we need to avoid userprivateaccesskey.
370 if (strpos($url, '/tokenpluginfile.php')) {
374 // Get the contextid, component and filearea.
375 $contextid = array_shift($parts);
376 $component = array_shift($parts);
377 $filearea = array_shift($parts);
379 // Ignore draft files, because they are considered temporary files, so shouldn't be displayed.
380 if ($filearea == 'draft') {
386 list($context, $course, $cm) = get_context_info_array($contextid);
387 } catch (\moodle_exception $e) {
388 throw new \moodle_exception('invalidcontextid', 'core_h5p');
391 // For CONTEXT_USER, such as the private files, raise an exception if the owner of the file is not the current user.
392 if ($context->contextlevel == CONTEXT_USER && $USER->id !== $context->instanceid) {
393 throw new \moodle_exception('h5pprivatefile', 'core_h5p');
396 if (!is_siteadmin($USER)) {
397 // For CONTEXT_COURSECAT No login necessary - unless login forced everywhere.
398 if ($context->contextlevel == CONTEXT_COURSECAT) {
399 if ($CFG->forcelogin) {
400 require_login(null, true, null, false, true);
404 // For CONTEXT_BLOCK.
405 if ($context->contextlevel == CONTEXT_BLOCK) {
406 if ($context->get_course_context(false)) {
407 // If block is in course context, then check if user has capability to access course.
408 require_course_login($course, true, null, false, true);
409 } else if ($CFG->forcelogin) {
410 // No login necessary - unless login forced everywhere.
411 require_login(null, true, null, false, true);
413 // Get parent context and see if user have proper permission.
414 $parentcontext = $context->get_parent_context();
415 if ($parentcontext->contextlevel === CONTEXT_COURSECAT) {
416 // Check if category is visible and user can view this category.
417 if (!core_course_category::get($parentcontext->instanceid, IGNORE_MISSING)) {
418 send_file_not_found();
420 } else if ($parentcontext->contextlevel === CONTEXT_USER && $parentcontext->instanceid != $USER->id) {
421 // The block is in the context of a user, it is only visible to the user who it belongs to.
422 send_file_not_found();
424 if ($filearea !== 'content') {
425 send_file_not_found();
430 // For CONTEXT_MODULE and CONTEXT_COURSE check if the user is enrolled in the course.
431 // And for CONTEXT_MODULE has permissions view this .h5p file.
432 if ($context->contextlevel == CONTEXT_MODULE ||
433 $context->contextlevel == CONTEXT_COURSE) {
434 // Require login to the course first (without login to the module).
435 require_course_login($course, true, null, !$preventredirect, $preventredirect);
437 // Now check if module is available OR it is restricted but the intro is shown on the course page.
438 if ($context->contextlevel == CONTEXT_MODULE) {
439 $cminfo = \cm_info::create($cm);
440 if (!$cminfo->uservisible) {
441 if (!$cm->showdescription || !$cminfo->is_visible_on_course_page()) {
442 // Module intro is not visible on the course page and module is not available, show access error.
443 require_course_login($course, true, $cminfo, !$preventredirect, $preventredirect);
450 // Some components, such as mod_page or mod_resource, add the revision to the URL to prevent caching problems.
451 // So the URL contains this revision number as itemid but a 0 is always stored in the files table.
452 // In order to get the proper hash, a callback should be done (looking for those exceptions).
454 if ($context->contextlevel == CONTEXT_MODULE || $context->contextlevel == CONTEXT_BLOCK) {
455 $pathdata = component_callback($component, 'get_path_from_pluginfile', [$filearea, $parts], null);
457 if (null === $pathdata) {
458 // Look for the components and fileareas which have empty itemid defined in xxx_pluginfile.
459 $hasnullitemid = false;
460 $hasnullitemid = $hasnullitemid || ($component === 'user' && ($filearea === 'private' || $filearea === 'profile'));
461 $hasnullitemid = $hasnullitemid || (substr($component, 0, 4) === 'mod_' && $filearea === 'intro');
462 $hasnullitemid = $hasnullitemid || ($component === 'course' &&
463 ($filearea === 'summary' || $filearea === 'overviewfiles'));
464 $hasnullitemid = $hasnullitemid || ($component === 'coursecat' && $filearea === 'description');
465 $hasnullitemid = $hasnullitemid || ($component === 'backup' &&
466 ($filearea === 'course' || $filearea === 'activity' || $filearea === 'automated'));
467 if ($hasnullitemid) {
470 $itemid = array_shift($parts);
476 $filepath = '/' . implode('/', $parts) . '/';
479 // The itemid and filepath have been returned by the component callback.
482 'filepath' => $filepath,
486 $fs = get_file_storage();
487 $pathnamehash = $fs->get_pathname_hash($contextid, $component, $filearea, $itemid, $filepath, $filename);
488 return $pathnamehash;
492 * Returns the H5P content object corresponding to an H5P content file.
494 * @param string $pathnamehash The pathnamehash of the file associated to an H5P content.
496 * @return null|\stdClass H5P content object or null if not found.
498 public static function get_content_from_pathnamehash(string $pathnamehash): ?\stdClass {
501 $h5p = $DB->get_record('h5p', ['pathnamehash' => $pathnamehash]);
503 return ($h5p) ? $h5p : null;
507 * Return the H5P export information file when the file has been deployed.
508 * Otherwise, return null if H5P file:
509 * i) has not been deployed.
510 * ii) has changed the content.
512 * The information returned will be:
513 * - filename, filepath, mimetype, filesize, timemodified and fileurl.
515 * @param int $contextid ContextId of the H5P activity.
516 * @param factory $factory The \core_h5p\factory object.
517 * @param string $component component
518 * @param string $filearea file area
519 * @return array|null Return file info otherwise null.
521 public static function get_export_info_from_context_id(int $contextid,
524 string $filearea): ?array {
526 $core = $factory->get_core();
527 $fs = get_file_storage();
528 $files = $fs->get_area_files($contextid, $component, $filearea, 0, 'id', false);
529 $file = reset($files);
531 if ($h5p = self::get_content_from_pathnamehash($file->get_pathnamehash())) {
532 if ($h5p->contenthash == $file->get_contenthash()) {
533 $content = $core->loadContent($h5p->id);
534 $slug = $content['slug'] ? $content['slug'] . '-' : '';
535 $filename = "{$slug}{$content['id']}.h5p";
536 $deployedfile = helper::get_export_info($filename, null, $factory);
538 return $deployedfile;