See Release Notes
Long Term Support Release
Differences Between: [Versions 39 and 311] [Versions 39 and 400] [Versions 39 and 401] [Versions 39 and 402] [Versions 39 and 403]
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 defined('MOODLE_INTERNAL') || die(); 28 29 use core\lock\lock_config; 30 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 */ 37 class 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 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)'; 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 } 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 $library->metadataSettings = json_decode($library->metadatasettings); 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 } 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 if (self::can_access_pluginfile_hash($url, $preventredirect)) { 198 $pathnamehash = self::get_pluginfile_hash($url); 199 } 200 201 if (!$pathnamehash) { 202 return [false, false]; 203 } 204 205 // Get the file. 206 $fs = get_file_storage(); 207 $file = $fs->get_file_by_hash($pathnamehash); 208 if (!$file) { 209 return [false, false]; 210 } 211 212 $h5p = $DB->get_record('h5p', ['pathnamehash' => $pathnamehash]); 213 return [$file, $h5p]; 214 } 215 216 /** 217 * Create, if it doesn't exist, the H5P DB instance id for a H5P pluginfile URL. If it exists: 218 * - If the content is not the same, remove the existing content and re-deploy the H5P content again. 219 * - If the content is the same, returns the H5P identifier. 220 * 221 * @param string $url H5P pluginfile URL. 222 * @param stdClass $config Configuration for H5P buttons. 223 * @param factory $factory The \core_h5p\factory object 224 * @param stdClass $messages The error, exception and info messages, raised while preparing and running an H5P content. 225 * @param bool $preventredirect Set to true in scripts that can not redirect (CLI, RSS feeds, etc.), throws exceptions 226 * 227 * @return array of [file, h5pid]: 228 * - file local file for this $url. 229 * - h5pid is the H5P identifier or false if there isn't any H5P with this URL. 230 */ 231 public static function create_content_from_pluginfile_url(string $url, \stdClass $config, factory $factory, 232 \stdClass &$messages, bool $preventredirect = true): array { 233 global $USER; 234 235 $core = $factory->get_core(); 236 list($file, $h5p) = self::get_content_from_pluginfile_url($url, $preventredirect); 237 238 if (!$file) { 239 $core->h5pF->setErrorMessage(get_string('h5pfilenotfound', 'core_h5p')); 240 return [false, false]; 241 } 242 243 $contenthash = $file->get_contenthash(); 244 if ($h5p && $h5p->contenthash != $contenthash) { 245 // The content exists and it is different from the one deployed previously. The existing one should be removed before 246 // deploying the new version. 247 self::delete_content($h5p, $factory); 248 $h5p = false; 249 } 250 251 $context = \context::instance_by_id($file->get_contextid()); 252 if ($h5p) { 253 // The H5P content has been deployed previously. 254 $displayoptions = helper::get_display_options($core, $config); 255 // Check if the user can set the displayoptions. 256 if ($displayoptions != $h5p->displayoptions && has_capability('moodle/h5p:setdisplayoptions', $context)) { 257 // If the displayoptions has changed and the user has permission to modify it, update this information in the DB. 258 $core->h5pF->updateContentFields($h5p->id, ['displayoptions' => $displayoptions]); 259 } 260 return [$file, $h5p->id]; 261 } else { 262 // The H5P content hasn't been deployed previously. 263 264 // Check if the user uploading the H5P content is "trustable". If the file hasn't been uploaded by a user with this 265 // capability, the content won't be deployed and an error message will be displayed. 266 if (!helper::can_deploy_package($file)) { 267 $core->h5pF->setErrorMessage(get_string('nopermissiontodeploy', 'core_h5p')); 268 return [$file, false]; 269 } 270 271 // The H5P content can be only deployed if the author of the .h5p file can update libraries or if all the 272 // content-type libraries exist, to avoid users without the h5p:updatelibraries capability upload malicious content. 273 $onlyupdatelibs = !helper::can_update_library($file); 274 275 // Start lock to prevent synchronous access to save the same H5P. 276 $lockfactory = lock_config::get_lock_factory('core_h5p'); 277 $lockkey = 'core_h5p_' . $file->get_pathnamehash(); 278 if ($lock = $lockfactory->get_lock($lockkey, 10)) { 279 try { 280 // Validate and store the H5P content before displaying it. 281 $h5pid = helper::save_h5p($factory, $file, $config, $onlyupdatelibs, false); 282 } finally { 283 $lock->release(); 284 } 285 } else { 286 $core->h5pF->setErrorMessage(get_string('lockh5pdeploy', 'core_h5p')); 287 return [$file, false]; 288 }; 289 290 if (!$h5pid && $file->get_userid() != $USER->id && has_capability('moodle/h5p:updatelibraries', $context)) { 291 // The user has permission to update libraries but the package has been uploaded by a different 292 // user without this permission. Check if there is some missing required library error. 293 $missingliberror = false; 294 $messages = helper::get_messages($messages, $factory); 295 if (!empty($messages->error)) { 296 foreach ($messages->error as $error) { 297 if ($error->code == 'missing-required-library') { 298 $missingliberror = true; 299 break; 300 } 301 } 302 } 303 if ($missingliberror) { 304 // The message about the permissions to upload libraries should be removed. 305 $infomsg = "Note that the libraries may exist in the file you uploaded, but you're not allowed to upload " . 306 "new libraries. Contact the site administrator about this."; 307 if (($key = array_search($infomsg, $messages->info)) !== false) { 308 unset($messages->info[$key]); 309 } 310 311 // No library will be installed and an error will be displayed, because this content is not trustable. 312 $core->h5pF->setInfoMessage(get_string('notrustablefile', 'core_h5p')); 313 } 314 return [$file, false]; 315 316 } 317 return [$file, $h5pid]; 318 } 319 } 320 321 /** 322 * Delete an H5P package. 323 * 324 * @param stdClass $content The H5P package to delete with, at least content['id]. 325 * @param factory $factory The \core_h5p\factory object 326 */ 327 public static function delete_content(\stdClass $content, factory $factory): void { 328 $h5pstorage = $factory->get_storage(); 329 330 // Add an empty slug to the content if it's not defined, because the H5P library requires this field exists. 331 // It's not used when deleting a package, so the real slug value is not required at this point. 332 $content->slug = $content->slug ?? ''; 333 $h5pstorage->deletePackage( (array) $content); 334 } 335 336 /** 337 * Delete an H5P package deployed from the defined $url. 338 * 339 * @param string $url pluginfile URL of the H5P package to delete. 340 * @param factory $factory The \core_h5p\factory object 341 */ 342 public static function delete_content_from_pluginfile_url(string $url, factory $factory): void { 343 global $DB; 344 345 // Get the H5P to delete. 346 $pathnamehash = self::get_pluginfile_hash($url); 347 $h5p = $DB->get_record('h5p', ['pathnamehash' => $pathnamehash]); 348 if ($h5p) { 349 self::delete_content($h5p, $factory); 350 } 351 } 352 353 /** 354 * If user can access pathnamehash from an H5P internal URL. 355 * 356 * @param string $url H5P pluginfile URL poiting to an H5P file. 357 * @param bool $preventredirect Set to true in scripts that can not redirect (CLI, RSS feeds, etc.), throws exceptions 358 * 359 * @return bool if user can access pluginfile hash. 360 * @throws \moodle_exception 361 * @throws \coding_exception 362 * @throws \require_login_exception 363 */ 364 protected static function can_access_pluginfile_hash(string $url, bool $preventredirect = true): bool { 365 global $USER, $CFG; 366 367 // Decode the URL before start processing it. 368 $url = new \moodle_url(urldecode($url)); 369 370 // Remove params from the URL (such as the 'forcedownload=1'), to avoid errors. 371 $url->remove_params(array_keys($url->params())); 372 $path = $url->out_as_local_url(); 373 374 // We only need the slasharguments. 375 $path = substr($path, strpos($path, '.php/') + 5); 376 $parts = explode('/', $path); 377 378 // If the request is made by tokenpluginfile.php we need to avoid userprivateaccesskey. 379 if (strpos($url, '/tokenpluginfile.php')) { 380 array_shift($parts); 381 } 382 383 // Get the contextid, component and filearea. 384 $contextid = array_shift($parts); 385 $component = array_shift($parts); 386 $filearea = array_shift($parts); 387 388 // Get the context. 389 try { 390 list($context, $course, $cm) = get_context_info_array($contextid); 391 } catch (\moodle_exception $e) { 392 throw new \moodle_exception('invalidcontextid', 'core_h5p'); 393 } 394 395 // For CONTEXT_USER, such as the private files, raise an exception if the owner of the file is not the current user. 396 if ($context->contextlevel == CONTEXT_USER && $USER->id !== $context->instanceid) { 397 throw new \moodle_exception('h5pprivatefile', 'core_h5p'); 398 } 399 400 if (!is_siteadmin($USER)) { 401 // For CONTEXT_COURSECAT No login necessary - unless login forced everywhere. 402 if ($context->contextlevel == CONTEXT_COURSECAT) { 403 if ($CFG->forcelogin) { 404 require_login(null, true, null, false, true); 405 } 406 } 407 408 // For CONTEXT_BLOCK. 409 if ($context->contextlevel == CONTEXT_BLOCK) { 410 if ($context->get_course_context(false)) { 411 // If block is in course context, then check if user has capability to access course. 412 require_course_login($course, true, null, false, true); 413 } else if ($CFG->forcelogin) { 414 // No login necessary - unless login forced everywhere. 415 require_login(null, true, null, false, true); 416 } else { 417 // Get parent context and see if user have proper permission. 418 $parentcontext = $context->get_parent_context(); 419 if ($parentcontext->contextlevel === CONTEXT_COURSECAT) { 420 // Check if category is visible and user can view this category. 421 if (!\core_course_category::get($parentcontext->instanceid, IGNORE_MISSING)) { 422 send_file_not_found(); 423 } 424 } else if ($parentcontext->contextlevel === CONTEXT_USER && $parentcontext->instanceid != $USER->id) { 425 // The block is in the context of a user, it is only visible to the user who it belongs to. 426 send_file_not_found(); 427 } 428 if ($filearea !== 'content') { 429 send_file_not_found(); 430 } 431 } 432 } 433 434 // For CONTEXT_MODULE and CONTEXT_COURSE check if the user is enrolled in the course. 435 // And for CONTEXT_MODULE has permissions view this .h5p file. 436 if ($context->contextlevel == CONTEXT_MODULE || 437 $context->contextlevel == CONTEXT_COURSE) { 438 // Require login to the course first (without login to the module). 439 require_course_login($course, true, null, !$preventredirect, $preventredirect); 440 441 // Now check if module is available OR it is restricted but the intro is shown on the course page. 442 if ($context->contextlevel == CONTEXT_MODULE) { 443 $cminfo = \cm_info::create($cm); 444 if (!$cminfo->uservisible) { 445 if (!$cm->showdescription || !$cminfo->is_visible_on_course_page()) { 446 // Module intro is not visible on the course page and module is not available, show access error. 447 require_course_login($course, true, $cminfo, !$preventredirect, $preventredirect); 448 } 449 } 450 } 451 } 452 } 453 454 return true; 455 } 456 457 /** 458 * Get the pathnamehash from an H5P internal URL. 459 * 460 * @param string $url H5P pluginfile URL poiting to an H5P file. 461 * 462 * @return string|false pathnamehash for the file in the internal URL. 463 * 464 * @throws \moodle_exception 465 */ 466 protected static function get_pluginfile_hash(string $url) { 467 468 // Decode the URL before start processing it. 469 $url = new \moodle_url(urldecode($url)); 470 471 // Remove params from the URL (such as the 'forcedownload=1'), to avoid errors. 472 $url->remove_params(array_keys($url->params())); 473 $path = $url->out_as_local_url(); 474 475 // We only need the slasharguments. 476 $path = substr($path, strpos($path, '.php/') + 5); 477 $parts = explode('/', $path); 478 $filename = array_pop($parts); 479 480 // If the request is made by tokenpluginfile.php we need to avoid userprivateaccesskey. 481 if (strpos($url, '/tokenpluginfile.php')) { 482 array_shift($parts); 483 } 484 485 // Get the contextid, component and filearea. 486 $contextid = array_shift($parts); 487 $component = array_shift($parts); 488 $filearea = array_shift($parts); 489 490 // Ignore draft files, because they are considered temporary files, so shouldn't be displayed. 491 if ($filearea == 'draft') { 492 return false; 493 } 494 495 // Get the context. 496 try { 497 list($context, $course, $cm) = get_context_info_array($contextid); 498 } catch (\moodle_exception $e) { 499 throw new \moodle_exception('invalidcontextid', 'core_h5p'); 500 } 501 502 // Some components, such as mod_page or mod_resource, add the revision to the URL to prevent caching problems. 503 // So the URL contains this revision number as itemid but a 0 is always stored in the files table. 504 // In order to get the proper hash, a callback should be done (looking for those exceptions). 505 $pathdata = null; 506 if ($context->contextlevel == CONTEXT_MODULE || $context->contextlevel == CONTEXT_BLOCK) { 507 $pathdata = component_callback($component, 'get_path_from_pluginfile', [$filearea, $parts], null); 508 } 509 if (null === $pathdata) { 510 // Look for the components and fileareas which have empty itemid defined in xxx_pluginfile. 511 $hasnullitemid = false; 512 $hasnullitemid = $hasnullitemid || ($component === 'user' && ($filearea === 'private' || $filearea === 'profile')); 513 $hasnullitemid = $hasnullitemid || (substr($component, 0, 4) === 'mod_' && $filearea === 'intro'); 514 $hasnullitemid = $hasnullitemid || ($component === 'course' && 515 ($filearea === 'summary' || $filearea === 'overviewfiles')); 516 $hasnullitemid = $hasnullitemid || ($component === 'coursecat' && $filearea === 'description'); 517 $hasnullitemid = $hasnullitemid || ($component === 'backup' && 518 ($filearea === 'course' || $filearea === 'activity' || $filearea === 'automated')); 519 if ($hasnullitemid) { 520 $itemid = 0; 521 } else { 522 $itemid = array_shift($parts); 523 } 524 525 if (empty($parts)) { 526 $filepath = '/'; 527 } else { 528 $filepath = '/' . implode('/', $parts) . '/'; 529 } 530 } else { 531 // The itemid and filepath have been returned by the component callback. 532 [ 533 'itemid' => $itemid, 534 'filepath' => $filepath, 535 ] = $pathdata; 536 } 537 538 $fs = get_file_storage(); 539 $pathnamehash = $fs->get_pathname_hash($contextid, $component, $filearea, $itemid, $filepath, $filename); 540 return $pathnamehash; 541 } 542 543 /** 544 * Returns the H5P content object corresponding to an H5P content file. 545 * 546 * @param string $pathnamehash The pathnamehash of the file associated to an H5P content. 547 * 548 * @return null|\stdClass H5P content object or null if not found. 549 */ 550 public static function get_content_from_pathnamehash(string $pathnamehash): ?\stdClass { 551 global $DB; 552 553 $h5p = $DB->get_record('h5p', ['pathnamehash' => $pathnamehash]); 554 555 return ($h5p) ? $h5p : null; 556 } 557 558 /** 559 * Return the H5P export information file when the file has been deployed. 560 * Otherwise, return null if H5P file: 561 * i) has not been deployed. 562 * ii) has changed the content. 563 * 564 * The information returned will be: 565 * - filename, filepath, mimetype, filesize, timemodified and fileurl. 566 * 567 * @param int $contextid ContextId of the H5P activity. 568 * @param factory $factory The \core_h5p\factory object. 569 * @param string $component component 570 * @param string $filearea file area 571 * @return array|null Return file info otherwise null. 572 */ 573 public static function get_export_info_from_context_id(int $contextid, 574 factory $factory, 575 string $component, 576 string $filearea): ?array { 577 578 $core = $factory->get_core(); 579 $fs = get_file_storage(); 580 $files = $fs->get_area_files($contextid, $component, $filearea, 0, 'id', false); 581 $file = reset($files); 582 583 if ($h5p = self::get_content_from_pathnamehash($file->get_pathnamehash())) { 584 if ($h5p->contenthash == $file->get_contenthash()) { 585 $content = $core->loadContent($h5p->id); 586 $slug = $content['slug'] ? $content['slug'] . '-' : ''; 587 $filename = "{$slug}{$content['id']}.h5p"; 588 $deployedfile = helper::get_export_info($filename, null, $factory); 589 590 return $deployedfile; 591 } 592 } 593 594 return null; 595 } 596 }
title
Description
Body
title
Description
Body
title
Description
Body
title
Body