MDL-67795 h5p: move methods from player to helper
[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);
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 }
153c4562
SA
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 *
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.
191 */
192 public static function get_content_from_pluginfile_url(string $url, bool $preventredirect = true): array {
193 global $DB;
194
195 // Deconstruct the URL and get the pathname associated.
196 $pathnamehash = self::get_pluginfile_hash($url, $preventredirect);
197 if (!$pathnamehash) {
198 return [false, false];
199 }
200
201 // Get the file.
202 $fs = get_file_storage();
203 $file = $fs->get_file_by_hash($pathnamehash);
204 if (!$file) {
205 return [false, false];
206 }
207
208 $h5p = $DB->get_record('h5p', ['pathnamehash' => $pathnamehash]);
209 return [$file, $h5p];
210 }
211
212 /**
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.
216 *
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
222 *
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.
226 */
227 public static function create_content_from_pluginfile_url(string $url, \stdClass $config, factory $factory,
228 \stdClass &$messages, bool $preventredirect = true): array {
229 global $USER;
230
231 $core = $factory->get_core();
232 list($file, $h5p) = self::get_content_from_pluginfile_url($url, $preventredirect);
233
234 if (!$file) {
235 $core->h5pF->setErrorMessage(get_string('h5pfilenotfound', 'core_h5p'));
236 return [false, false];
237 }
238
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);
244 $h5p = false;
245 }
246
247 $context = \context::instance_by_id($file->get_contextid());
248 if ($h5p) {
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]);
255 }
256 return [$file, $h5p->id];
257 } else {
258 // The H5P content hasn't been deployed previously.
259
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];
265 }
266
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);
270
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)) {
275 try {
276 // Validate and store the H5P content before displaying it.
277 $h5pid = helper::save_h5p($factory, $file, $config, $onlyupdatelibs, false);
278 } finally {
279 $lock->release();
280 }
281 } else {
282 $core->h5pF->setErrorMessage(get_string('lockh5pdeploy', 'core_h5p'));
283 return [$file, false];
284 };
285
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;
295 break;
296 }
297 }
298 }
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]);
305 }
306
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'));
309 }
310 return [$file, false];
311
312 }
313 return [$file, $h5pid];
314 }
315 }
316
317 /**
318 * Delete an H5P package.
319 *
320 * @param stdClass $content The H5P package to delete with, at least content['id].
321 * @param factory $factory The \core_h5p\factory object
322 */
323 public static function delete_content(\stdClass $content, factory $factory): void {
324 $h5pstorage = $factory->get_storage();
325
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);
330 }
331
332 /**
333 * Delete an H5P package deployed from the defined $url.
334 *
335 * @param string $url pluginfile URL of the H5P package to delete.
336 * @param factory $factory The \core_h5p\factory object
337 */
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);
341 if ($h5p) {
342 self::delete_content($h5p, $factory);
343 }
344 }
345
346 /**
347 * Get the pathnamehash from an H5P internal URL.
348 *
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
351 *
352 * @return string|false pathnamehash for the file in the internal URL.
353 */
354 protected static function get_pluginfile_hash(string $url, bool $preventredirect = true) {
355 global $USER, $CFG;
356
357 // Decode the URL before start processing it.
358 $url = new \moodle_url(urldecode($url));
359
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();
363
364 // We only need the slasharguments.
365 $path = substr($path, strpos($path, '.php/') + 5);
366 $parts = explode('/', $path);
367 $filename = array_pop($parts);
368
369 // If the request is made by tokenpluginfile.php we need to avoid userprivateaccesskey.
370 if (strpos($url, '/tokenpluginfile.php')) {
371 array_shift($parts);
372 }
373
374 // Get the contextid, component and filearea.
375 $contextid = array_shift($parts);
376 $component = array_shift($parts);
377 $filearea = array_shift($parts);
378
379 // Ignore draft files, because they are considered temporary files, so shouldn't be displayed.
380 if ($filearea == 'draft') {
381 return false;
382 }
383
384 // Get the context.
385 try {
386 list($context, $course, $cm) = get_context_info_array($contextid);
387 } catch (\moodle_exception $e) {
388 throw new \moodle_exception('invalidcontextid', 'core_h5p');
389 }
390
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');
394 }
395
396 // For CONTEXT_COURSECAT No login necessary - unless login forced everywhere.
397 if ($context->contextlevel == CONTEXT_COURSECAT) {
398 if ($CFG->forcelogin) {
399 require_login(null, true, null, false, true);
400 }
401 }
402
403 // For CONTEXT_BLOCK.
404 if ($context->contextlevel == CONTEXT_BLOCK) {
405 if ($context->get_course_context(false)) {
406 // If block is in course context, then check if user has capability to access course.
407 require_course_login($course, true, null, false, true);
408 } else if ($CFG->forcelogin) {
409 // No login necessary - unless login forced everywhere.
410 require_login(null, true, null, false, true);
411 } else {
412 // Get parent context and see if user have proper permission.
413 $parentcontext = $context->get_parent_context();
414 if ($parentcontext->contextlevel === CONTEXT_COURSECAT) {
415 // Check if category is visible and user can view this category.
416 if (!core_course_category::get($parentcontext->instanceid, IGNORE_MISSING)) {
417 send_file_not_found();
418 }
419 } else if ($parentcontext->contextlevel === CONTEXT_USER && $parentcontext->instanceid != $USER->id) {
420 // The block is in the context of a user, it is only visible to the user who it belongs to.
421 send_file_not_found();
422 }
423 if ($filearea !== 'content') {
424 send_file_not_found();
425 }
426 }
427 }
428
429 // For CONTEXT_MODULE and CONTEXT_COURSE check if the user is enrolled in the course.
430 // And for CONTEXT_MODULE has permissions view this .h5p file.
431 if ($context->contextlevel == CONTEXT_MODULE ||
432 $context->contextlevel == CONTEXT_COURSE) {
433 // Require login to the course first (without login to the module).
434 require_course_login($course, true, null, !$preventredirect, $preventredirect);
435
436 // Now check if module is available OR it is restricted but the intro is shown on the course page.
437 if ($context->contextlevel == CONTEXT_MODULE) {
438 $cminfo = \cm_info::create($cm);
439 if (!$cminfo->uservisible) {
440 if (!$cm->showdescription || !$cminfo->is_visible_on_course_page()) {
441 // Module intro is not visible on the course page and module is not available, show access error.
442 require_course_login($course, true, $cminfo, !$preventredirect, $preventredirect);
443 }
444 }
445 }
446 }
447
448 // Some components, such as mod_page or mod_resource, add the revision to the URL to prevent caching problems.
449 // So the URL contains this revision number as itemid but a 0 is always stored in the files table.
450 // In order to get the proper hash, a callback should be done (looking for those exceptions).
451 $pathdata = null;
452 if ($context->contextlevel == CONTEXT_MODULE || $context->contextlevel == CONTEXT_BLOCK) {
453 $pathdata = component_callback($component, 'get_path_from_pluginfile', [$filearea, $parts], null);
454 }
455 if (null === $pathdata) {
456 // Look for the components and fileareas which have empty itemid defined in xxx_pluginfile.
457 $hasnullitemid = false;
458 $hasnullitemid = $hasnullitemid || ($component === 'user' && ($filearea === 'private' || $filearea === 'profile'));
459 $hasnullitemid = $hasnullitemid || (substr($component, 0, 4) === 'mod_' && $filearea === 'intro');
460 $hasnullitemid = $hasnullitemid || ($component === 'course' &&
461 ($filearea === 'summary' || $filearea === 'overviewfiles'));
462 $hasnullitemid = $hasnullitemid || ($component === 'coursecat' && $filearea === 'description');
463 $hasnullitemid = $hasnullitemid || ($component === 'backup' &&
464 ($filearea === 'course' || $filearea === 'activity' || $filearea === 'automated'));
465 if ($hasnullitemid) {
466 $itemid = 0;
467 } else {
468 $itemid = array_shift($parts);
469 }
470
471 if (empty($parts)) {
472 $filepath = '/';
473 } else {
474 $filepath = '/' . implode('/', $parts) . '/';
475 }
476 } else {
477 // The itemid and filepath have been returned by the component callback.
478 [
479 'itemid' => $itemid,
480 'filepath' => $filepath,
481 ] = $pathdata;
482 }
483
484 $fs = get_file_storage();
485 $pathnamehash = $fs->get_pathname_hash($contextid, $component, $filearea, $itemid, $filepath, $filename);
486 return $pathnamehash;
487 }
64a2bd19 488}