Differences Between: [Versions 310 and 400] [Versions 311 and 400] [Versions 39 and 400] [Versions 400 and 401] [Versions 400 and 402] [Versions 400 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 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 * Get the original file and H5P DB instance for a given H5P pluginfile URL. If it doesn't exist, it's not created. 221 * If the file has been added as a reference, this method will return the original linked file. 222 * 223 * @param string $url H5P pluginfile URL. 224 * @param bool $preventredirect Set to true in scripts that can not redirect (CLI, RSS feeds, etc.), throws exceptions. 225 * @param bool $skipcapcheck Whether capabilities should be checked or not to get the pluginfile URL because sometimes they 226 * might be controlled before calling this method. 227 * 228 * @return array of [\stored_file|false, \stdClass|false, \stored_file|false]: 229 * - \stored_file: original local file for the given url (if it has been added as a reference, this method 230 * will return the linked file) or false if there isn't any H5P file with this URL. 231 * - \stdClass: an H5P object or false if there isn't any H5P with this URL. 232 * - \stored_file: file associated to the given url (if it's different from original) or false when both files 233 * (original and file) are the same. 234 * @since Moodle 4.0 235 */ 236 public static function get_original_content_from_pluginfile_url(string $url, bool $preventredirect = true, 237 bool $skipcapcheck = false): array { 238 239 $file = false; 240 list($originalfile, $h5p) = self::get_content_from_pluginfile_url($url, $preventredirect, $skipcapcheck); 241 if ($originalfile) { 242 if ($reference = $originalfile->get_reference()) { 243 $file = $originalfile; 244 // If the file has been added as a reference to any other file, get it. 245 $fs = new \file_storage(); 246 $referenced = \file_storage::unpack_reference($reference); 247 $originalfile = $fs->get_file( 248 $referenced['contextid'], 249 $referenced['component'], 250 $referenced['filearea'], 251 $referenced['itemid'], 252 $referenced['filepath'], 253 $referenced['filename'] 254 ); 255 $h5p = self::get_content_from_pathnamehash($originalfile->get_pathnamehash()); 256 if (empty($h5p)) { 257 $h5p = false; 258 } 259 } 260 } 261 262 return [$originalfile, $h5p, $file]; 263 } 264 265 /** 266 * Check if the user can edit an H5P file. It will return true in the following situations: 267 * - The user is the author of the file. 268 * - The component is different from user (i.e. private files). 269 * - If the component is contentbank, the user can edit this file (calling the ContentBank API). 270 * - If the component is mod_xxx or block_xxx, the user has the addinstance capability. 271 * - If the component implements the can_edit_content in the h5p\canedit class and the callback to this method returns true. 272 * 273 * @param \stored_file $file The H5P file to check. 274 * 275 * @return boolean Whether the user can edit or not the given file. 276 * @since Moodle 4.0 277 */ 278 public static function can_edit_content(\stored_file $file): bool { 279 global $USER; 280 281 list($type, $component) = \core_component::normalize_component($file->get_component()); 282 283 // Private files. 284 $currentuserisauthor = $file->get_userid() == $USER->id; 285 $isuserfile = $component === 'user'; 286 if ($currentuserisauthor && $isuserfile) { 287 // The user can edit the content because it's a private user file and she is the owner. 288 return true; 289 } 290 291 // Check if the plugin where the file belongs implements the custom can_edit_content method and call it if that's the case. 292 $classname = '\\' . $file->get_component() . '\\h5p\\canedit'; 293 $methodname = 'can_edit_content'; 294 if (method_exists($classname, $methodname)) { 295 return $classname::{$methodname}($file); 296 } 297 298 // For mod/block files, check if the user has the addinstance capability of the component where the file belongs. 299 if ($type === 'mod' || $type === 'block') { 300 // For any other component, check whether the user can add/edit them. 301 $context = \context::instance_by_id($file->get_contextid()); 302 $plugins = \core_component::get_plugin_list($type); 303 $isvalid = array_key_exists($component, $plugins); 304 if ($isvalid && has_capability("$type/$component:addinstance", $context)) { 305 // The user can edit the content because she has the capability for creating instances where the file belongs. 306 return true; 307 } 308 } 309 310 // For contentbank files, use the API to check if the user has access. 311 if ($component == 'contentbank') { 312 $cb = new \core_contentbank\contentbank(); 313 $content = $cb->get_content_from_id($file->get_itemid()); 314 $contenttype = $content->get_content_type_instance(); 315 if ($contenttype instanceof \contenttype_h5p\contenttype) { 316 // Only H5P contenttypes should be considered here. 317 if ($contenttype->can_edit($content)) { 318 // The user has permissions to edit the H5P in the content bank. 319 return true; 320 } 321 } 322 } 323 324 return false; 325 } 326 327 /** 328 * Create, if it doesn't exist, the H5P DB instance id for a H5P pluginfile URL. If it exists: 329 * - If the content is not the same, remove the existing content and re-deploy the H5P content again. 330 * - If the content is the same, returns the H5P identifier. 331 * 332 * @param string $url H5P pluginfile URL. 333 * @param stdClass $config Configuration for H5P buttons. 334 * @param factory $factory The \core_h5p\factory object 335 * @param stdClass $messages The error, exception and info messages, raised while preparing and running an H5P content. 336 * @param bool $preventredirect Set to true in scripts that can not redirect (CLI, RSS feeds, etc.), throws exceptions 337 * @param bool $skipcapcheck Whether capabilities should be checked or not to get the pluginfile URL because sometimes they 338 * might be controlled before calling this method. 339 * 340 * @return array of [file, h5pid]: 341 * - file local file for this $url. 342 * - h5pid is the H5P identifier or false if there isn't any H5P with this URL. 343 */ 344 public static function create_content_from_pluginfile_url(string $url, \stdClass $config, factory $factory, 345 \stdClass &$messages, bool $preventredirect = true, bool $skipcapcheck = false): array { 346 global $USER; 347 348 $core = $factory->get_core(); 349 list($file, $h5p) = self::get_content_from_pluginfile_url($url, $preventredirect, $skipcapcheck); 350 351 if (!$file) { 352 $core->h5pF->setErrorMessage(get_string('h5pfilenotfound', 'core_h5p')); 353 return [false, false]; 354 } 355 356 $contenthash = $file->get_contenthash(); 357 if ($h5p && $h5p->contenthash != $contenthash) { 358 // The content exists and it is different from the one deployed previously. The existing one should be removed before 359 // deploying the new version. 360 self::delete_content($h5p, $factory); 361 $h5p = false; 362 } 363 364 $context = \context::instance_by_id($file->get_contextid()); 365 if ($h5p) { 366 // The H5P content has been deployed previously. 367 368 // If the main library for this H5P content is disabled, the content won't be displayed. 369 $mainlibrary = (object) ['id' => $h5p->mainlibraryid]; 370 if (!self::is_library_enabled($mainlibrary)) { 371 $core->h5pF->setErrorMessage(get_string('mainlibrarydisabled', 'core_h5p')); 372 return [$file, false]; 373 } else { 374 $displayoptions = helper::get_display_options($core, $config); 375 // Check if the user can set the displayoptions. 376 if ($displayoptions != $h5p->displayoptions && has_capability('moodle/h5p:setdisplayoptions', $context)) { 377 // If displayoptions has changed and user has permission to modify it, update this information in DB. 378 $core->h5pF->updateContentFields($h5p->id, ['displayoptions' => $displayoptions]); 379 } 380 return [$file, $h5p->id]; 381 } 382 } else { 383 // The H5P content hasn't been deployed previously. 384 385 // Check if the user uploading the H5P content is "trustable". If the file hasn't been uploaded by a user with this 386 // capability, the content won't be deployed and an error message will be displayed. 387 if (!helper::can_deploy_package($file)) { 388 $core->h5pF->setErrorMessage(get_string('nopermissiontodeploy', 'core_h5p')); 389 return [$file, false]; 390 } 391 392 // The H5P content can be only deployed if the author of the .h5p file can update libraries or if all the 393 // content-type libraries exist, to avoid users without the h5p:updatelibraries capability upload malicious content. 394 $onlyupdatelibs = !helper::can_update_library($file); 395 396 // Start lock to prevent synchronous access to save the same H5P. 397 $lockfactory = lock_config::get_lock_factory('core_h5p'); 398 $lockkey = 'core_h5p_' . $file->get_pathnamehash(); 399 if ($lock = $lockfactory->get_lock($lockkey, 10)) { 400 try { 401 // Validate and store the H5P content before displaying it. 402 $h5pid = helper::save_h5p($factory, $file, $config, $onlyupdatelibs, false); 403 } finally { 404 $lock->release(); 405 } 406 } else { 407 $core->h5pF->setErrorMessage(get_string('lockh5pdeploy', 'core_h5p')); 408 return [$file, false]; 409 }; 410 411 if (!$h5pid && $file->get_userid() != $USER->id && has_capability('moodle/h5p:updatelibraries', $context)) { 412 // The user has permission to update libraries but the package has been uploaded by a different 413 // user without this permission. Check if there is some missing required library error. 414 $missingliberror = false; 415 $messages = helper::get_messages($messages, $factory); 416 if (!empty($messages->error)) { 417 foreach ($messages->error as $error) { 418 if ($error->code == 'missing-required-library') { 419 $missingliberror = true; 420 break; 421 } 422 } 423 } 424 if ($missingliberror) { 425 // The message about the permissions to upload libraries should be removed. 426 $infomsg = "Note that the libraries may exist in the file you uploaded, but you're not allowed to upload " . 427 "new libraries. Contact the site administrator about this."; 428 if (($key = array_search($infomsg, $messages->info)) !== false) { 429 unset($messages->info[$key]); 430 } 431 432 // No library will be installed and an error will be displayed, because this content is not trustable. 433 $core->h5pF->setInfoMessage(get_string('notrustablefile', 'core_h5p')); 434 } 435 return [$file, false]; 436 437 } 438 return [$file, $h5pid]; 439 } 440 } 441 442 /** 443 * Delete an H5P package. 444 * 445 * @param stdClass $content The H5P package to delete with, at least content['id]. 446 * @param factory $factory The \core_h5p\factory object 447 */ 448 public static function delete_content(\stdClass $content, factory $factory): void { 449 $h5pstorage = $factory->get_storage(); 450 451 // Add an empty slug to the content if it's not defined, because the H5P library requires this field exists. 452 // It's not used when deleting a package, so the real slug value is not required at this point. 453 $content->slug = $content->slug ?? ''; 454 $h5pstorage->deletePackage( (array) $content); 455 } 456 457 /** 458 * Delete an H5P package deployed from the defined $url. 459 * 460 * @param string $url pluginfile URL of the H5P package to delete. 461 * @param factory $factory The \core_h5p\factory object 462 */ 463 public static function delete_content_from_pluginfile_url(string $url, factory $factory): void { 464 global $DB; 465 466 // Get the H5P to delete. 467 $pathnamehash = self::get_pluginfile_hash($url); 468 $h5p = $DB->get_record('h5p', ['pathnamehash' => $pathnamehash]); 469 if ($h5p) { 470 self::delete_content($h5p, $factory); 471 } 472 } 473 474 /** 475 * If user can access pathnamehash from an H5P internal URL. 476 * 477 * @param string $url H5P pluginfile URL poiting to an H5P file. 478 * @param bool $preventredirect Set to true in scripts that can not redirect (CLI, RSS feeds, etc.), throws exceptions 479 * 480 * @return bool if user can access pluginfile hash. 481 * @throws \moodle_exception 482 * @throws \coding_exception 483 * @throws \require_login_exception 484 */ 485 protected static function can_access_pluginfile_hash(string $url, bool $preventredirect = true): bool { 486 global $USER, $CFG; 487 488 // Decode the URL before start processing it. 489 $url = new \moodle_url(urldecode($url)); 490 491 // Remove params from the URL (such as the 'forcedownload=1'), to avoid errors. 492 $url->remove_params(array_keys($url->params())); 493 $path = $url->out_as_local_url(); 494 495 // We only need the slasharguments. 496 $path = substr($path, strpos($path, '.php/') + 5); 497 $parts = explode('/', $path); 498 499 // If the request is made by tokenpluginfile.php we need to avoid userprivateaccesskey. 500 if (strpos($url, '/tokenpluginfile.php')) { 501 array_shift($parts); 502 } 503 504 // Get the contextid, component and filearea. 505 $contextid = array_shift($parts); 506 $component = array_shift($parts); 507 $filearea = array_shift($parts); 508 509 // Get the context. 510 try { 511 list($context, $course, $cm) = get_context_info_array($contextid); 512 } catch (\moodle_exception $e) { 513 throw new \moodle_exception('invalidcontextid', 'core_h5p'); 514 } 515 516 // For CONTEXT_USER, such as the private files, raise an exception if the owner of the file is not the current user. 517 if ($context->contextlevel == CONTEXT_USER && $USER->id !== $context->instanceid) { 518 throw new \moodle_exception('h5pprivatefile', 'core_h5p'); 519 } 520 521 if (!is_siteadmin($USER)) { 522 // For CONTEXT_COURSECAT No login necessary - unless login forced everywhere. 523 if ($context->contextlevel == CONTEXT_COURSECAT) { 524 if ($CFG->forcelogin) { 525 require_login(null, true, null, false, true); 526 } 527 } 528 529 // For CONTEXT_BLOCK. 530 if ($context->contextlevel == CONTEXT_BLOCK) { 531 if ($context->get_course_context(false)) { 532 // If block is in course context, then check if user has capability to access course. 533 require_course_login($course, true, null, false, true); 534 } else if ($CFG->forcelogin) { 535 // No login necessary - unless login forced everywhere. 536 require_login(null, true, null, false, true); 537 } else { 538 // Get parent context and see if user have proper permission. 539 $parentcontext = $context->get_parent_context(); 540 if ($parentcontext->contextlevel === CONTEXT_COURSECAT) { 541 // Check if category is visible and user can view this category. 542 if (!\core_course_category::get($parentcontext->instanceid, IGNORE_MISSING)) { 543 send_file_not_found(); 544 } 545 } else if ($parentcontext->contextlevel === CONTEXT_USER && $parentcontext->instanceid != $USER->id) { 546 // The block is in the context of a user, it is only visible to the user who it belongs to. 547 send_file_not_found(); 548 } 549 if ($filearea !== 'content') { 550 send_file_not_found(); 551 } 552 } 553 } 554 555 // For CONTEXT_MODULE and CONTEXT_COURSE check if the user is enrolled in the course. 556 // And for CONTEXT_MODULE has permissions view this .h5p file. 557 if ($context->contextlevel == CONTEXT_MODULE || 558 $context->contextlevel == CONTEXT_COURSE) { 559 // Require login to the course first (without login to the module). 560 require_course_login($course, true, null, !$preventredirect, $preventredirect); 561 562 // Now check if module is available OR it is restricted but the intro is shown on the course page. 563 if ($context->contextlevel == CONTEXT_MODULE) { 564 $cminfo = \cm_info::create($cm); 565 if (!$cminfo->uservisible) { 566 if (!$cm->showdescription || !$cminfo->is_visible_on_course_page()) { 567 // Module intro is not visible on the course page and module is not available, show access error. 568 require_course_login($course, true, $cminfo, !$preventredirect, $preventredirect); 569 } 570 } 571 } 572 } 573 } 574 575 return true; 576 } 577 578 /** 579 * Get the pathnamehash from an H5P internal URL. 580 * 581 * @param string $url H5P pluginfile URL poiting to an H5P file. 582 * 583 * @return string|false pathnamehash for the file in the internal URL. 584 * 585 * @throws \moodle_exception 586 */ 587 protected static function get_pluginfile_hash(string $url) { 588 589 // Decode the URL before start processing it. 590 $url = new \moodle_url(urldecode($url)); 591 592 // Remove params from the URL (such as the 'forcedownload=1'), to avoid errors. 593 $url->remove_params(array_keys($url->params())); 594 $path = $url->out_as_local_url(); 595 596 // We only need the slasharguments. 597 $path = substr($path, strpos($path, '.php/') + 5); 598 $parts = explode('/', $path); 599 $filename = array_pop($parts); 600 601 // If the request is made by tokenpluginfile.php we need to avoid userprivateaccesskey. 602 if (strpos($url, '/tokenpluginfile.php')) { 603 array_shift($parts); 604 } 605 606 // Get the contextid, component and filearea. 607 $contextid = array_shift($parts); 608 $component = array_shift($parts); 609 $filearea = array_shift($parts); 610 611 // Ignore draft files, because they are considered temporary files, so shouldn't be displayed. 612 if ($filearea == 'draft') { 613 return false; 614 } 615 616 // Get the context. 617 try { 618 list($context, $course, $cm) = get_context_info_array($contextid); 619 } catch (\moodle_exception $e) { 620 throw new \moodle_exception('invalidcontextid', 'core_h5p'); 621 } 622 623 // Some components, such as mod_page or mod_resource, add the revision to the URL to prevent caching problems. 624 // So the URL contains this revision number as itemid but a 0 is always stored in the files table. 625 // In order to get the proper hash, a callback should be done (looking for those exceptions). 626 $pathdata = null; 627 if ($context->contextlevel == CONTEXT_MODULE || $context->contextlevel == CONTEXT_BLOCK) { 628 $pathdata = component_callback($component, 'get_path_from_pluginfile', [$filearea, $parts], null); 629 } 630 if (null === $pathdata) { 631 // Look for the components and fileareas which have empty itemid defined in xxx_pluginfile. 632 $hasnullitemid = false; 633 $hasnullitemid = $hasnullitemid || ($component === 'user' && ($filearea === 'private' || $filearea === 'profile')); 634 $hasnullitemid = $hasnullitemid || (substr($component, 0, 4) === 'mod_' && $filearea === 'intro'); 635 $hasnullitemid = $hasnullitemid || ($component === 'course' && 636 ($filearea === 'summary' || $filearea === 'overviewfiles')); 637 $hasnullitemid = $hasnullitemid || ($component === 'coursecat' && $filearea === 'description'); 638 $hasnullitemid = $hasnullitemid || ($component === 'backup' && 639 ($filearea === 'course' || $filearea === 'activity' || $filearea === 'automated')); 640 if ($hasnullitemid) { 641 $itemid = 0; 642 } else { 643 $itemid = array_shift($parts); 644 } 645 646 if (empty($parts)) { 647 $filepath = '/'; 648 } else { 649 $filepath = '/' . implode('/', $parts) . '/'; 650 } 651 } else { 652 // The itemid and filepath have been returned by the component callback. 653 [ 654 'itemid' => $itemid, 655 'filepath' => $filepath, 656 ] = $pathdata; 657 } 658 659 $fs = get_file_storage(); 660 $pathnamehash = $fs->get_pathname_hash($contextid, $component, $filearea, $itemid, $filepath, $filename); 661 return $pathnamehash; 662 } 663 664 /** 665 * Returns the H5P content object corresponding to an H5P content file. 666 * 667 * @param string $pathnamehash The pathnamehash of the file associated to an H5P content. 668 * 669 * @return null|\stdClass H5P content object or null if not found. 670 */ 671 public static function get_content_from_pathnamehash(string $pathnamehash): ?\stdClass { 672 global $DB; 673 674 $h5p = $DB->get_record('h5p', ['pathnamehash' => $pathnamehash]); 675 676 return ($h5p) ? $h5p : null; 677 } 678 679 /** 680 * Return the H5P export information file when the file has been deployed. 681 * Otherwise, return null if H5P file: 682 * i) has not been deployed. 683 * ii) has changed the content. 684 * 685 * The information returned will be: 686 * - filename, filepath, mimetype, filesize, timemodified and fileurl. 687 * 688 * @param int $contextid ContextId of the H5P activity. 689 * @param factory $factory The \core_h5p\factory object. 690 * @param string $component component 691 * @param string $filearea file area 692 * @return array|null Return file info otherwise null. 693 */ 694 public static function get_export_info_from_context_id(int $contextid, 695 factory $factory, 696 string $component, 697 string $filearea): ?array { 698 699 $core = $factory->get_core(); 700 $fs = get_file_storage(); 701 $files = $fs->get_area_files($contextid, $component, $filearea, 0, 'id', false); 702 $file = reset($files); 703 704 if ($h5p = self::get_content_from_pathnamehash($file->get_pathnamehash())) { 705 if ($h5p->contenthash == $file->get_contenthash()) { 706 $content = $core->loadContent($h5p->id); 707 $slug = $content['slug'] ? $content['slug'] . '-' : ''; 708 $filename = "{$slug}{$content['id']}.h5p"; 709 $deployedfile = helper::get_export_info($filename, null, $factory); 710 711 return $deployedfile; 712 } 713 } 714 715 return null; 716 } 717 718 /** 719 * Enable or disable a library. 720 * 721 * @param int $libraryid The id of the library to enable/disable. 722 * @param bool $isenabled True if the library should be enabled; false otherwise. 723 */ 724 public static function set_library_enabled(int $libraryid, bool $isenabled): void { 725 global $DB; 726 727 $library = $DB->get_record('h5p_libraries', ['id' => $libraryid], '*', MUST_EXIST); 728 if ($library->runnable) { 729 // For now, only runnable libraries can be enabled/disabled. 730 $record = [ 731 'id' => $libraryid, 732 'enabled' => $isenabled, 733 ]; 734 $DB->update_record('h5p_libraries', $record); 735 } 736 } 737 738 /** 739 * Check whether a library is enabled or not. When machinename is passed, it will return false if any of the versions 740 * for this machinename is disabled. 741 * If the library doesn't exist, it will return true. 742 * 743 * @param \stdClass $librarydata Supported fields for library: 'id' and 'machichename'. 744 * @return bool 745 * @throws \moodle_exception 746 */ 747 public static function is_library_enabled(\stdClass $librarydata): bool { 748 global $DB; 749 750 $params = []; 751 if (property_exists($librarydata, 'machinename')) { 752 $params['machinename'] = $librarydata->machinename; 753 } 754 if (property_exists($librarydata, 'id')) { 755 $params['id'] = $librarydata->id; 756 } 757 758 if (empty($params)) { 759 throw new \moodle_exception("Missing 'machinename' or 'id' in librarydata parameter"); 760 } 761 762 $libraries = $DB->get_records('h5p_libraries', $params); 763 764 // If any of the libraries with these values have been disabled, return false. 765 foreach ($libraries as $id => $library) { 766 if (!$library->enabled) { 767 return false; 768 } 769 } 770 771 return true; 772 } 773 774 /** 775 * Check whether an H5P package is valid or not. 776 * 777 * @param \stored_file $file The file with the H5P content. 778 * @param bool $onlyupdatelibs Whether new libraries can be installed or only the existing ones can be updated 779 * @param bool $skipcontent Should the content be skipped (so only the libraries will be saved)? 780 * @param factory|null $factory The \core_h5p\factory object 781 * @param bool $deletefiletree Should the temporary files be deleted before returning? 782 * @return bool True if the H5P file is valid (expected format, valid libraries...); false otherwise. 783 */ 784 public static function is_valid_package(\stored_file $file, bool $onlyupdatelibs, bool $skipcontent = false, 785 ?factory $factory = null, bool $deletefiletree = true): bool { 786 787 // This may take a long time. 788 \core_php_time_limit::raise(); 789 790 $isvalid = false; 791 792 if (empty($factory)) { 793 $factory = new factory(); 794 } 795 $core = $factory->get_core(); 796 $h5pvalidator = $factory->get_validator(); 797 798 // Set the H5P file path. 799 $core->h5pF->set_file($file); 800 $path = $core->fs->getTmpPath(); 801 $core->h5pF->getUploadedH5pFolderPath($path); 802 // Add manually the extension to the file to avoid the validation fails. 803 $path .= '.h5p'; 804 $core->h5pF->getUploadedH5pPath($path); 805 // Copy the .h5p file to the temporary folder. 806 $file->copy_content_to($path); 807 808 if ($h5pvalidator->isValidPackage($skipcontent, $onlyupdatelibs)) { 809 if ($skipcontent) { 810 $isvalid = true; 811 } else if (!empty($h5pvalidator->h5pC->mainJsonData['mainLibrary'])) { 812 $mainlibrary = (object) ['machinename' => $h5pvalidator->h5pC->mainJsonData['mainLibrary']]; 813 if (self::is_library_enabled($mainlibrary)) { 814 $isvalid = true; 815 } else { 816 // If the main library of the package is disabled, the H5P content will be considered invalid. 817 $core->h5pF->setErrorMessage(get_string('mainlibrarydisabled', 'core_h5p')); 818 } 819 } 820 } 821 822 if ($deletefiletree) { 823 // Remove temp content folder. 824 H5PCore::deleteFileTree($path); 825 } 826 827 return $isvalid; 828 } 829 }
title
Description
Body
title
Description
Body
title
Description
Body
title
Body