See Release Notes
Long Term Support Release
Differences Between: [Versions 39 and 310] [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 helper class for the H5P area. 19 * 20 * @package core_h5p 21 * @copyright 2019 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 context_system; 28 use core_h5p\local\library\autoloader; 29 30 defined('MOODLE_INTERNAL') || die(); 31 32 /** 33 * Helper class for the H5P area. 34 * 35 * @copyright 2019 Sara Arjona <sara@moodle.com> 36 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later 37 */ 38 class helper { 39 40 /** 41 * Store an H5P file. 42 * 43 * @param factory $factory The \core_h5p\factory object 44 * @param stored_file $file Moodle file instance 45 * @param stdClass $config Button options config 46 * @param bool $onlyupdatelibs Whether new libraries can be installed or only the existing ones can be updated 47 * @param bool $skipcontent Should the content be skipped (so only the libraries will be saved)? 48 * 49 * @return int|false|null The H5P identifier or null if there is an error when saving or false if it's not a valid H5P package 50 */ 51 public static function save_h5p(factory $factory, \stored_file $file, \stdClass $config, bool $onlyupdatelibs = false, 52 bool $skipcontent = false) { 53 // This may take a long time. 54 \core_php_time_limit::raise(); 55 56 $core = $factory->get_core(); 57 $core->h5pF->set_file($file); 58 $path = $core->fs->getTmpPath(); 59 $core->h5pF->getUploadedH5pFolderPath($path); 60 // Add manually the extension to the file to avoid the validation fails. 61 $path .= '.h5p'; 62 $core->h5pF->getUploadedH5pPath($path); 63 64 // Copy the .h5p file to the temporary folder. 65 $file->copy_content_to($path); 66 67 // Check if the h5p file is valid before saving it. 68 $h5pvalidator = $factory->get_validator(); 69 if ($h5pvalidator->isValidPackage($skipcontent, $onlyupdatelibs)) { 70 $h5pstorage = $factory->get_storage(); 71 72 $content = [ 73 'pathnamehash' => $file->get_pathnamehash(), 74 'contenthash' => $file->get_contenthash(), 75 ]; 76 $options = ['disable' => self::get_display_options($core, $config)]; 77 78 // Add the 'title' if exists from 'h5p.json' data to keep it for the editor. 79 if (!empty($h5pvalidator->h5pC->mainJsonData['title'])) { 80 $content['title'] = $h5pvalidator->h5pC->mainJsonData['title']; 81 } 82 $h5pstorage->savePackage($content, null, $skipcontent, $options); 83 84 return $h5pstorage->contentId; 85 } 86 return false; 87 } 88 89 /** 90 * Get the error messages stored in our H5P framework. 91 * 92 * @param stdClass $messages The error, exception and info messages, raised while preparing and running an H5P content. 93 * @param factory $factory The \core_h5p\factory object 94 * 95 * @return stdClass with framework error messages. 96 */ 97 public static function get_messages(\stdClass $messages, factory $factory): \stdClass { 98 $core = $factory->get_core(); 99 100 // Check if there are some errors and store them in $messages. 101 if (empty($messages->error)) { 102 $messages->error = $core->h5pF->getMessages('error') ?: false; 103 } else { 104 $messages->error = array_merge($messages->error, $core->h5pF->getMessages('error')); 105 } 106 107 if (empty($messages->info)) { 108 $messages->info = $core->h5pF->getMessages('info') ?: false; 109 } else { 110 $messages->info = array_merge($messages->info, $core->h5pF->getMessages('info')); 111 } 112 113 return $messages; 114 } 115 116 /** 117 * Get the representation of display options as int. 118 * 119 * @param core $core The \core_h5p\core object 120 * @param stdClass $config Button options config 121 * 122 * @return int The representation of display options as int 123 */ 124 public static function get_display_options(core $core, \stdClass $config): int { 125 $export = isset($config->export) ? $config->export : 0; 126 $embed = isset($config->embed) ? $config->embed : 0; 127 $copyright = isset($config->copyright) ? $config->copyright : 0; 128 $frame = ($export || $embed || $copyright); 129 if (!$frame) { 130 $frame = isset($config->frame) ? $config->frame : 0; 131 } 132 133 $disableoptions = [ 134 core::DISPLAY_OPTION_FRAME => $frame, 135 core::DISPLAY_OPTION_DOWNLOAD => $export, 136 core::DISPLAY_OPTION_EMBED => $embed, 137 core::DISPLAY_OPTION_COPYRIGHT => $copyright, 138 ]; 139 140 return $core->getStorableDisplayOptions($disableoptions, 0); 141 } 142 143 /** 144 * Convert the int representation of display options into stdClass 145 * 146 * @param core $core The \core_h5p\core object 147 * @param int $displayint integer value representing display options 148 * 149 * @return int The representation of display options as int 150 */ 151 public static function decode_display_options(core $core, int $displayint = null): \stdClass { 152 $config = new \stdClass(); 153 if ($displayint === null) { 154 $displayint = self::get_display_options($core, $config); 155 } 156 $displayarray = $core->getDisplayOptionsForEdit($displayint); 157 $config->export = $displayarray[core::DISPLAY_OPTION_DOWNLOAD] ?? 0; 158 $config->embed = $displayarray[core::DISPLAY_OPTION_EMBED] ?? 0; 159 $config->copyright = $displayarray[core::DISPLAY_OPTION_COPYRIGHT] ?? 0; 160 return $config; 161 } 162 163 /** 164 * Checks if the author of the .h5p file is "trustable". If the file hasn't been uploaded by a user with the 165 * required capability, the content won't be deployed. 166 * 167 * @param stored_file $file The .h5p file to be deployed 168 * @return bool Returns true if the file can be deployed, false otherwise. 169 */ 170 public static function can_deploy_package(\stored_file $file): bool { 171 if (null === $file->get_userid()) { 172 // If there is no userid, it is owned by the system. 173 return true; 174 } 175 176 $context = \context::instance_by_id($file->get_contextid()); 177 if (has_capability('moodle/h5p:deploy', $context, $file->get_userid())) { 178 return true; 179 } 180 181 return false; 182 } 183 184 /** 185 * Checks if the content-type libraries can be upgraded. 186 * The H5P content-type libraries can only be upgraded if the author of the .h5p file can manage content-types or if all the 187 * content-types exist, to avoid users without the required capability to upload malicious content. 188 * 189 * @param stored_file $file The .h5p file to be deployed 190 * @return bool Returns true if the content-type libraries can be created/updated, false otherwise. 191 */ 192 public static function can_update_library(\stored_file $file): bool { 193 if (null === $file->get_userid()) { 194 // If there is no userid, it is owned by the system. 195 return true; 196 } 197 198 // Check if the owner of the .h5p file has the capability to manage content-types. 199 $context = \context::instance_by_id($file->get_contextid()); 200 if (has_capability('moodle/h5p:updatelibraries', $context, $file->get_userid())) { 201 return true; 202 } 203 204 return false; 205 } 206 207 /** 208 * Convenience to take a fixture test file and create a stored_file. 209 * 210 * @param string $filepath The filepath of the file 211 * @param int $userid The author of the file 212 * @param \context $context The context where the file will be created 213 * @return stored_file The file created 214 */ 215 public static function create_fake_stored_file_from_path(string $filepath, int $userid = 0, 216 \context $context = null): \stored_file { 217 if (is_null($context)) { 218 $context = context_system::instance(); 219 } 220 $filerecord = [ 221 'contextid' => $context->id, 222 'component' => 'core_h5p', 223 'filearea' => 'unittest', 224 'itemid' => rand(), 225 'filepath' => '/', 226 'filename' => basename($filepath), 227 ]; 228 if (!is_null($userid)) { 229 $filerecord['userid'] = $userid; 230 } 231 232 $fs = get_file_storage(); 233 return $fs->create_file_from_pathname($filerecord, $filepath); 234 } 235 236 /** 237 * Get information about different H5P tools and their status. 238 * 239 * @return array Data to render by the template 240 */ 241 public static function get_h5p_tools_info(): array { 242 $tools = array(); 243 244 // Getting information from available H5P tools one by one because their enabled/disabled options are totally different. 245 // Check the atto button status. 246 $link = \editor_atto\plugininfo\atto::get_manage_url(); 247 $status = strpos(get_config('editor_atto', 'toolbar'), 'h5p') > -1; 248 $tools[] = self::convert_info_into_array('atto_h5p', $link, $status); 249 250 // Check the Display H5P filter status. 251 $link = \core\plugininfo\filter::get_manage_url(); 252 $status = filter_get_active_state('displayh5p', context_system::instance()->id); 253 $tools[] = self::convert_info_into_array('filter_displayh5p', $link, $status); 254 255 // Check H5P scheduled task. 256 $link = ''; 257 $status = 0; 258 $statusaction = ''; 259 if ($task = \core\task\manager::get_scheduled_task('\core\task\h5p_get_content_types_task')) { 260 $status = !$task->get_disabled(); 261 $link = new \moodle_url( 262 '/admin/tool/task/scheduledtasks.php', 263 array('action' => 'edit', 'task' => get_class($task)) 264 ); 265 if ($status && \core\task\manager::is_runnable() && get_config('tool_task', 'enablerunnow')) { 266 $statusaction = \html_writer::link( 267 new \moodle_url('/admin/tool/task/schedule_task.php', 268 array('task' => get_class($task))), 269 get_string('runnow', 'tool_task')); 270 } 271 } 272 $tools[] = self::convert_info_into_array('task_h5p', $link, $status, $statusaction); 273 274 return $tools; 275 } 276 277 /** 278 * Convert information into needed mustache template data array 279 * @param string $tool The name of the tool 280 * @param \moodle_url $link The URL to management page 281 * @param int $status The current status of the tool 282 * @param string $statusaction A link to 'Run now' option for the task 283 * @return array 284 */ 285 static private function convert_info_into_array(string $tool, 286 \moodle_url $link, 287 int $status, 288 string $statusaction = ''): array { 289 290 $statusclasses = array( 291 TEXTFILTER_DISABLED => 'badge badge-danger', 292 TEXTFILTER_OFF => 'badge badge-warning', 293 0 => 'badge badge-danger', 294 TEXTFILTER_ON => 'badge badge-success', 295 ); 296 297 $statuschoices = array( 298 TEXTFILTER_DISABLED => get_string('disabled', 'admin'), 299 TEXTFILTER_OFF => get_string('offbutavailable', 'core_filters'), 300 0 => get_string('disabled', 'admin'), 301 1 => get_string('enabled', 'admin'), 302 ); 303 304 return [ 305 'tool' => get_string($tool, 'h5p'), 306 'tool_description' => get_string($tool . '_description', 'h5p'), 307 'link' => $link, 308 'status' => $statuschoices[$status], 309 'status_class' => $statusclasses[$status], 310 'status_action' => $statusaction, 311 ]; 312 } 313 314 /** 315 * Get a query string with the theme revision number to include at the end 316 * of URLs. This is used to force the browser to reload the asset when the 317 * theme caches are cleared. 318 * 319 * @return string 320 */ 321 public static function get_cache_buster(): string { 322 global $CFG; 323 return '?ver=' . $CFG->themerev; 324 } 325 326 /** 327 * Get the settings needed by the H5P library. 328 * 329 * @return array The settings. 330 */ 331 public static function get_core_settings(): array { 332 global $CFG, $USER; 333 334 $basepath = $CFG->wwwroot . '/'; 335 $systemcontext = context_system::instance(); 336 337 // Generate AJAX paths. 338 $ajaxpaths = []; 339 $ajaxpaths['xAPIResult'] = ''; 340 $ajaxpaths['contentUserData'] = ''; 341 342 $factory = new factory(); 343 $core = $factory->get_core(); 344 345 // When there is a logged in user, her information will be passed to the player. It will be used for tracking. 346 $usersettings = []; 347 if (isloggedin()) { 348 $usersettings['name'] = fullname($USER, has_capability('moodle/site:viewfullnames', $systemcontext)); 349 $usersettings['mail'] = $USER->email; 350 } 351 $settings = array( 352 'baseUrl' => $basepath, 353 'url' => "{$basepath}pluginfile.php/{$systemcontext->instanceid}/core_h5p", 354 'urlLibraries' => "{$basepath}pluginfile.php/{$systemcontext->id}/core_h5p/libraries", 355 'postUserStatistics' => false, 356 'ajax' => $ajaxpaths, 357 'saveFreq' => false, 358 'siteUrl' => $CFG->wwwroot, 359 'l10n' => array('H5P' => $core->getLocalization()), 360 'user' => $usersettings, 361 'hubIsEnabled' => true, 362 'reportingIsEnabled' => false, 363 'crossorigin' => null, 364 'libraryConfig' => $core->h5pF->getLibraryConfig(), 365 'pluginCacheBuster' => self::get_cache_buster(), 366 'libraryUrl' => autoloader::get_h5p_core_library_url('js')->out(), 367 ); 368 369 return $settings; 370 } 371 372 /** 373 * Get the core H5P assets, including all core H5P JavaScript and CSS. 374 * 375 * @return Array core H5P assets. 376 */ 377 public static function get_core_assets(): array { 378 global $CFG, $PAGE; 379 380 // Get core settings. 381 $settings = self::get_core_settings(); 382 $settings['core'] = [ 383 'styles' => [], 384 'scripts' => [] 385 ]; 386 $settings['loadedJs'] = []; 387 $settings['loadedCss'] = []; 388 389 // Make sure files are reloaded for each plugin update. 390 $cachebuster = self::get_cache_buster(); 391 392 // Use relative URL to support both http and https. 393 $liburl = autoloader::get_h5p_core_library_url()->out(); 394 $relpath = '/' . preg_replace('/^[^:]+:\/\/[^\/]+\//', '', $liburl); 395 396 // Add core stylesheets. 397 foreach (core::$styles as $style) { 398 $settings['core']['styles'][] = $relpath . $style . $cachebuster; 399 $PAGE->requires->css(new \moodle_url($liburl . $style . $cachebuster)); 400 } 401 // Add core JavaScript. 402 foreach (core::get_scripts() as $script) { 403 $settings['core']['scripts'][] = $script->out(false); 404 $PAGE->requires->js($script, true); 405 } 406 407 return $settings; 408 } 409 410 /** 411 * Prepare the library name to be used as a cache key (remove whitespaces and replace dots to underscores). 412 * 413 * @param string $library Library name. 414 * @return string Library name in a cache simple key format (a-zA-Z0-9_). 415 */ 416 public static function get_cache_librarykey(string $library): string { 417 // Remove whitespaces and replace '.' to '_'. 418 return str_replace('.', '_', str_replace(' ', '', $library)); 419 } 420 421 /** 422 * Parse a JS array to a PHP array. 423 * 424 * @param string $jscontent The JS array to parse to PHP array. 425 * @return array The JS array converted to PHP array. 426 */ 427 public static function parse_js_array(string $jscontent): array { 428 // Convert all line-endings to UNIX format first. 429 $jscontent = str_replace(array("\r\n", "\r"), "\n", $jscontent); 430 $jsarray = preg_split('/,\n\s+/', substr($jscontent, 0, -1)); 431 $jsarray = preg_replace('~{?\\n~', '', $jsarray); 432 433 $strings = []; 434 foreach ($jsarray as $key => $value) { 435 $splitted = explode(":", $value, 2); 436 $value = preg_replace("/^['|\"](.*)['|\"]$/", "$1", trim($splitted[1], ' ,')); 437 $strings[ trim($splitted[0]) ] = str_replace("\'", "'", $value); 438 } 439 440 return $strings; 441 } 442 443 /** 444 * Get the information related to the H5P export file. 445 * The information returned will be: 446 * - filename, filepath, mimetype, filesize, timemodified and fileurl. 447 * 448 * @param string $exportfilename The H5P export filename (with slug). 449 * @param \moodle_url $url The URL of the exported file. 450 * @param factory $factory The \core_h5p\factory object 451 * @return array|null The information export file otherwise null. 452 */ 453 public static function get_export_info(string $exportfilename, \moodle_url $url = null, ?factory $factory = null): ?array { 454 455 if (!$factory) { 456 $factory = new factory(); 457 } 458 $core = $factory->get_core(); 459 460 // Get export file. 461 if (!$fileh5p = $core->fs->get_export_file($exportfilename)) { 462 return null; 463 } 464 465 // Build the export info array. 466 $file = []; 467 $file['filename'] = $fileh5p->get_filename(); 468 $file['filepath'] = $fileh5p->get_filepath(); 469 $file['mimetype'] = $fileh5p->get_mimetype(); 470 $file['filesize'] = $fileh5p->get_filesize(); 471 $file['timemodified'] = $fileh5p->get_timemodified(); 472 473 if (!$url) { 474 $url = \moodle_url::make_webservice_pluginfile_url( 475 $fileh5p->get_contextid(), 476 $fileh5p->get_component(), 477 $fileh5p->get_filearea(), 478 '', 479 '', 480 $fileh5p->get_filename() 481 ); 482 } 483 484 $file['fileurl'] = $url->out(false); 485 486 return $file; 487 } 488 }
title
Description
Body
title
Description
Body
title
Description
Body
title
Body