MDL-68921 core_h5p: Add H5P libraries metadata settings
[moodle.git] / h5p / classes / api.php
CommitLineData
64a2bd19
SA
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
25namespace core_h5p;
26
27defined('MOODLE_INTERNAL') || die();
28
153c4562
SA
29use core\lock\lock_config;
30
64a2bd19
SA
31/**
32 * Contains API class for the H5P area.
33 *
34 * @copyright 2020 Sara Arjona <sara@moodle.com>
35 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
36 */
37class api {
38
39 /**
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).
42 *
43 * @param factory $factory The H5P factory.
44 * @param \stdClass $library The library to delete.
45 */
46 public static function delete_library(factory $factory, \stdClass $library): void {
47 global $DB;
48
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);
58 }
59
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);
66
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));
70
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);
75 }
76 }
77
78 /**
79 * Get all the libraries using a defined library.
80 *
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.
83 */
84 public static function get_dependent_libraries(int $libraryid): array {
85 global $DB;
86
770cfadd
SA
87 $sql = 'SELECT *
88 FROM {h5p_libraries}
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)';
64a2bd19
SA
93 $params = ['libraryid' => $libraryid];
94
95 return $DB->get_records_sql($sql, $params);
96 }
97
98 /**
99 * Get a library from an identifier.
100 *
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.
104 */
105 public static function get_library(int $libraryid): \stdClass {
106 global $DB;
107
108 return $DB->get_record('h5p_libraries', ['id' => $libraryid], '*', MUST_EXIST);
109 }
6da050d7
VDF
110
111 /**
112 * Returns a library as an object with properties that correspond to the fetched row's field names.
113 *
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.
117 *
118 * @return \stdClass|null An object with one attribute for each field name in $fields param.
119 */
120 public static function get_library_details(array $params, bool $configurable, string $fields = ''): ?\stdClass {
121 global $DB;
122
123 $select = "machinename = :machinename
124 AND majorversion = :majorversion
125 AND minorversion = :minorversion";
126
127 if ($configurable) {
128 $select .= " AND semantics IS NOT NULL";
129 }
130
131 $fields = $fields ?: '*';
132
133 $record = $DB->get_record_select('h5p_libraries', $select, $params, $fields);
134
135 return $record ?: null;
136 }
137
138 /**
139 * Get all the H5P content type libraries versions.
140 *
141 * @param string|null $fields Library fields to return.
142 *
143 * @return array An array with an object for each content type library installed.
144 */
145 public static function get_contenttype_libraries(?string $fields = ''): array {
146 global $DB;
147
148 $libraries = [];
149 $fields = $fields ?: '*';
150 $select = "runnable = :runnable
151 AND semantics IS NOT NULL";
152 $params = ['runnable' => 1];
153 $sort = 'title, majorversion DESC, minorversion DESC';
154
155 $records = $DB->get_records_select('h5p_libraries', $select, $params, $sort, $fields);
156
157 $added = [];
158 foreach ($records as $library) {
159 // Remove unique index.
160 unset($library->id);
161
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);
fde9d442 167 $library->metadataSettings = json_decode($library->metadatasettings);
6da050d7
VDF
168
169 // If we already add this library means that it is an old version,as the previous query was sorted by version.
170 if (isset($added[$library->name])) {
171 $library->isOld = true;
172 } else {
173 $added[$library->name] = true;
174 }
175
176 // Add new library.
177 $libraries[] = $library;
178 }
179
180 return $libraries;
181 }
153c4562
SA
182
183 /**
184 * Get the H5P DB instance id for a H5P pluginfile URL. If it doesn't exist, it's not created.
185 *
186 * @param string $url H5P pluginfile URL.
187 * @param bool $preventredirect Set to true in scripts that can not redirect (CLI, RSS feeds, etc.), throws exceptions
188 *
189 * @return array of [file, stdClass|false]:
190 * - file local file for this $url.
191 * - stdClass is an H5P object or false if there isn't any H5P with this URL.
192 */
193 public static function get_content_from_pluginfile_url(string $url, bool $preventredirect = true): array {
194 global $DB;
195
196 // Deconstruct the URL and get the pathname associated.
197 $pathnamehash = self::get_pluginfile_hash($url, $preventredirect);
198 if (!$pathnamehash) {
199 return [false, false];
200 }
201
202 // Get the file.
203 $fs = get_file_storage();
204 $file = $fs->get_file_by_hash($pathnamehash);
205 if (!$file) {
206 return [false, false];
207 }
208
209 $h5p = $DB->get_record('h5p', ['pathnamehash' => $pathnamehash]);
210 return [$file, $h5p];
211 }
212
213 /**
214 * Create, if it doesn't exist, the H5P DB instance id for a H5P pluginfile URL. If it exists:
215 * - If the content is not the same, remove the existing content and re-deploy the H5P content again.
216 * - If the content is the same, returns the H5P identifier.
217 *
218 * @param string $url H5P pluginfile URL.
219 * @param stdClass $config Configuration for H5P buttons.
220 * @param factory $factory The \core_h5p\factory object
221 * @param stdClass $messages The error, exception and info messages, raised while preparing and running an H5P content.
222 * @param bool $preventredirect Set to true in scripts that can not redirect (CLI, RSS feeds, etc.), throws exceptions
223 *
224 * @return array of [file, h5pid]:
225 * - file local file for this $url.
226 * - h5pid is the H5P identifier or false if there isn't any H5P with this URL.
227 */
228 public static function create_content_from_pluginfile_url(string $url, \stdClass $config, factory $factory,
229 \stdClass &$messages, bool $preventredirect = true): array {
230 global $USER;
231
232 $core = $factory->get_core();
233 list($file, $h5p) = self::get_content_from_pluginfile_url($url, $preventredirect);
234
235 if (!$file) {
236 $core->h5pF->setErrorMessage(get_string('h5pfilenotfound', 'core_h5p'));
237 return [false, false];
238 }
239
240 $contenthash = $file->get_contenthash();
241 if ($h5p && $h5p->contenthash != $contenthash) {
242 // The content exists and it is different from the one deployed previously. The existing one should be removed before
243 // deploying the new version.
244 self::delete_content($h5p, $factory);
245 $h5p = false;
246 }
247
248 $context = \context::instance_by_id($file->get_contextid());
249 if ($h5p) {
250 // The H5P content has been deployed previously.
251 $displayoptions = helper::get_display_options($core, $config);
252 // Check if the user can set the displayoptions.
253 if ($displayoptions != $h5p->displayoptions && has_capability('moodle/h5p:setdisplayoptions', $context)) {
254 // If the displayoptions has changed and the user has permission to modify it, update this information in the DB.
255 $core->h5pF->updateContentFields($h5p->id, ['displayoptions' => $displayoptions]);
256 }
257 return [$file, $h5p->id];
258 } else {
259 // The H5P content hasn't been deployed previously.
260
261 // Check if the user uploading the H5P content is "trustable". If the file hasn't been uploaded by a user with this
262 // capability, the content won't be deployed and an error message will be displayed.
263 if (!helper::can_deploy_package($file)) {
264 $core->h5pF->setErrorMessage(get_string('nopermissiontodeploy', 'core_h5p'));
265 return [$file, false];
266 }
267
268 // The H5P content can be only deployed if the author of the .h5p file can update libraries or if all the
269 // content-type libraries exist, to avoid users without the h5p:updatelibraries capability upload malicious content.
270 $onlyupdatelibs = !helper::can_update_library($file);
271
272 // Start lock to prevent synchronous access to save the same H5P.
273 $lockfactory = lock_config::get_lock_factory('core_h5p');
274 $lockkey = 'core_h5p_' . $file->get_pathnamehash();
275 if ($lock = $lockfactory->get_lock($lockkey, 10)) {
276 try {
277 // Validate and store the H5P content before displaying it.
278 $h5pid = helper::save_h5p($factory, $file, $config, $onlyupdatelibs, false);
279 } finally {
280 $lock->release();
281 }
282 } else {
283 $core->h5pF->setErrorMessage(get_string('lockh5pdeploy', 'core_h5p'));
284 return [$file, false];
285 };
286
287 if (!$h5pid && $file->get_userid() != $USER->id && has_capability('moodle/h5p:updatelibraries', $context)) {
288 // The user has permission to update libraries but the package has been uploaded by a different
289 // user without this permission. Check if there is some missing required library error.
290 $missingliberror = false;
291 $messages = helper::get_messages($messages, $factory);
292 if (!empty($messages->error)) {
293 foreach ($messages->error as $error) {
294 if ($error->code == 'missing-required-library') {
295 $missingliberror = true;
296 break;
297 }
298 }
299 }
300 if ($missingliberror) {
301 // The message about the permissions to upload libraries should be removed.
302 $infomsg = "Note that the libraries may exist in the file you uploaded, but you're not allowed to upload " .
303 "new libraries. Contact the site administrator about this.";
304 if (($key = array_search($infomsg, $messages->info)) !== false) {
305 unset($messages->info[$key]);
306 }
307
308 // No library will be installed and an error will be displayed, because this content is not trustable.
309 $core->h5pF->setInfoMessage(get_string('notrustablefile', 'core_h5p'));
310 }
311 return [$file, false];
312
313 }
314 return [$file, $h5pid];
315 }
316 }
317
318 /**
319 * Delete an H5P package.
320 *
321 * @param stdClass $content The H5P package to delete with, at least content['id].
322 * @param factory $factory The \core_h5p\factory object
323 */
324 public static function delete_content(\stdClass $content, factory $factory): void {
325 $h5pstorage = $factory->get_storage();
326
327 // Add an empty slug to the content if it's not defined, because the H5P library requires this field exists.
328 // It's not used when deleting a package, so the real slug value is not required at this point.
329 $content->slug = $content->slug ?? '';
330 $h5pstorage->deletePackage( (array) $content);
331 }
332
333 /**
334 * Delete an H5P package deployed from the defined $url.
335 *
336 * @param string $url pluginfile URL of the H5P package to delete.
337 * @param factory $factory The \core_h5p\factory object
338 */
339 public static function delete_content_from_pluginfile_url(string $url, factory $factory): void {
340 // Get the H5P to delete.
341 list($file, $h5p) = self::get_content_from_pluginfile_url($url);
342 if ($h5p) {
343 self::delete_content($h5p, $factory);
344 }
345 }
346
347 /**
348 * Get the pathnamehash from an H5P internal URL.
349 *
350 * @param string $url H5P pluginfile URL poiting to an H5P file.
351 * @param bool $preventredirect Set to true in scripts that can not redirect (CLI, RSS feeds, etc.), throws exceptions
352 *
353 * @return string|false pathnamehash for the file in the internal URL.
354 */
355 protected static function get_pluginfile_hash(string $url, bool $preventredirect = true) {
356 global $USER, $CFG;
357
358 // Decode the URL before start processing it.
359 $url = new \moodle_url(urldecode($url));
360
361 // Remove params from the URL (such as the 'forcedownload=1'), to avoid errors.
362 $url->remove_params(array_keys($url->params()));
363 $path = $url->out_as_local_url();
364
365 // We only need the slasharguments.
366 $path = substr($path, strpos($path, '.php/') + 5);
367 $parts = explode('/', $path);
368 $filename = array_pop($parts);
369
370 // If the request is made by tokenpluginfile.php we need to avoid userprivateaccesskey.
371 if (strpos($url, '/tokenpluginfile.php')) {
372 array_shift($parts);
373 }
374
375 // Get the contextid, component and filearea.
376 $contextid = array_shift($parts);
377 $component = array_shift($parts);
378 $filearea = array_shift($parts);
379
380 // Ignore draft files, because they are considered temporary files, so shouldn't be displayed.
381 if ($filearea == 'draft') {
382 return false;
383 }
384
385 // Get the context.
386 try {
387 list($context, $course, $cm) = get_context_info_array($contextid);
388 } catch (\moodle_exception $e) {
389 throw new \moodle_exception('invalidcontextid', 'core_h5p');
390 }
391
392 // For CONTEXT_USER, such as the private files, raise an exception if the owner of the file is not the current user.
393 if ($context->contextlevel == CONTEXT_USER && $USER->id !== $context->instanceid) {
394 throw new \moodle_exception('h5pprivatefile', 'core_h5p');
395 }
396
58f85a6c
SA
397 if (!is_siteadmin($USER)) {
398 // For CONTEXT_COURSECAT No login necessary - unless login forced everywhere.
399 if ($context->contextlevel == CONTEXT_COURSECAT) {
400 if ($CFG->forcelogin) {
401 require_login(null, true, null, false, true);
402 }
153c4562 403 }
153c4562 404
58f85a6c
SA
405 // For CONTEXT_BLOCK.
406 if ($context->contextlevel == CONTEXT_BLOCK) {
407 if ($context->get_course_context(false)) {
408 // If block is in course context, then check if user has capability to access course.
409 require_course_login($course, true, null, false, true);
410 } else if ($CFG->forcelogin) {
411 // No login necessary - unless login forced everywhere.
412 require_login(null, true, null, false, true);
413 } else {
414 // Get parent context and see if user have proper permission.
415 $parentcontext = $context->get_parent_context();
416 if ($parentcontext->contextlevel === CONTEXT_COURSECAT) {
417 // Check if category is visible and user can view this category.
418 if (!core_course_category::get($parentcontext->instanceid, IGNORE_MISSING)) {
419 send_file_not_found();
420 }
421 } else if ($parentcontext->contextlevel === CONTEXT_USER && $parentcontext->instanceid != $USER->id) {
422 // The block is in the context of a user, it is only visible to the user who it belongs to.
423 send_file_not_found();
424 }
425 if ($filearea !== 'content') {
153c4562
SA
426 send_file_not_found();
427 }
153c4562
SA
428 }
429 }
153c4562 430
58f85a6c
SA
431 // For CONTEXT_MODULE and CONTEXT_COURSE check if the user is enrolled in the course.
432 // And for CONTEXT_MODULE has permissions view this .h5p file.
433 if ($context->contextlevel == CONTEXT_MODULE ||
434 $context->contextlevel == CONTEXT_COURSE) {
435 // Require login to the course first (without login to the module).
436 require_course_login($course, true, null, !$preventredirect, $preventredirect);
437
438 // Now check if module is available OR it is restricted but the intro is shown on the course page.
439 if ($context->contextlevel == CONTEXT_MODULE) {
440 $cminfo = \cm_info::create($cm);
441 if (!$cminfo->uservisible) {
442 if (!$cm->showdescription || !$cminfo->is_visible_on_course_page()) {
443 // Module intro is not visible on the course page and module is not available, show access error.
444 require_course_login($course, true, $cminfo, !$preventredirect, $preventredirect);
445 }
153c4562
SA
446 }
447 }
448 }
449 }
450
451 // Some components, such as mod_page or mod_resource, add the revision to the URL to prevent caching problems.
452 // So the URL contains this revision number as itemid but a 0 is always stored in the files table.
453 // In order to get the proper hash, a callback should be done (looking for those exceptions).
454 $pathdata = null;
455 if ($context->contextlevel == CONTEXT_MODULE || $context->contextlevel == CONTEXT_BLOCK) {
456 $pathdata = component_callback($component, 'get_path_from_pluginfile', [$filearea, $parts], null);
457 }
458 if (null === $pathdata) {
459 // Look for the components and fileareas which have empty itemid defined in xxx_pluginfile.
460 $hasnullitemid = false;
461 $hasnullitemid = $hasnullitemid || ($component === 'user' && ($filearea === 'private' || $filearea === 'profile'));
462 $hasnullitemid = $hasnullitemid || (substr($component, 0, 4) === 'mod_' && $filearea === 'intro');
463 $hasnullitemid = $hasnullitemid || ($component === 'course' &&
464 ($filearea === 'summary' || $filearea === 'overviewfiles'));
465 $hasnullitemid = $hasnullitemid || ($component === 'coursecat' && $filearea === 'description');
466 $hasnullitemid = $hasnullitemid || ($component === 'backup' &&
467 ($filearea === 'course' || $filearea === 'activity' || $filearea === 'automated'));
468 if ($hasnullitemid) {
469 $itemid = 0;
470 } else {
471 $itemid = array_shift($parts);
472 }
473
474 if (empty($parts)) {
475 $filepath = '/';
476 } else {
477 $filepath = '/' . implode('/', $parts) . '/';
478 }
479 } else {
480 // The itemid and filepath have been returned by the component callback.
481 [
482 'itemid' => $itemid,
483 'filepath' => $filepath,
484 ] = $pathdata;
485 }
486
487 $fs = get_file_storage();
488 $pathnamehash = $fs->get_pathname_hash($contextid, $component, $filearea, $itemid, $filepath, $filename);
489 return $pathnamehash;
490 }
296ae788
VDF
491
492 /**
493 * Returns the H5P content object corresponding to an H5P content file.
494 *
495 * @param string $pathnamehash The pathnamehash of the file associated to an H5P content.
496 *
497 * @return null|\stdClass H5P content object or null if not found.
498 */
499 public static function get_content_from_pathnamehash(string $pathnamehash): ?\stdClass {
500 global $DB;
501
502 $h5p = $DB->get_record('h5p', ['pathnamehash' => $pathnamehash]);
503
504 return ($h5p) ? $h5p : null;
505 }
14b463c9 506
507 /**
508 * Return the H5P export information file when the file has been deployed.
509 * Otherwise, return null if H5P file:
510 * i) has not been deployed.
511 * ii) has changed the content.
512 *
513 * The information returned will be:
514 * - filename, filepath, mimetype, filesize, timemodified and fileurl.
515 *
516 * @param int $contextid ContextId of the H5P activity.
517 * @param factory $factory The \core_h5p\factory object.
518 * @param string $component component
519 * @param string $filearea file area
520 * @return array|null Return file info otherwise null.
521 */
522 public static function get_export_info_from_context_id(int $contextid,
523 factory $factory,
524 string $component,
525 string $filearea): ?array {
526
527 $core = $factory->get_core();
528 $fs = get_file_storage();
529 $files = $fs->get_area_files($contextid, $component, $filearea, 0, 'id', false);
530 $file = reset($files);
531
532 if ($h5p = self::get_content_from_pathnamehash($file->get_pathnamehash())) {
533 if ($h5p->contenthash == $file->get_contenthash()) {
534 $content = $core->loadContent($h5p->id);
535 $slug = $content['slug'] ? $content['slug'] . '-' : '';
536 $filename = "{$slug}{$content['id']}.h5p";
537 $deployedfile = helper::get_export_info($filename, null, $factory);
538
539 return $deployedfile;
540 }
541 }
542
543 return null;
544 }
64a2bd19 545}