MDL-67707 course: add support for PARAM_ALPHANUM module names
[moodle.git] / h5p / classes / player.php
CommitLineData
35b62d00
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 * H5P player class.
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
25namespace core_h5p;
26
27defined('MOODLE_INTERNAL') || die();
28
08fda3e0
SA
29use core_h5p\local\library\autoloader;
30
35b62d00
SA
31/**
32 * H5P player class, for displaying any local H5P content.
33 *
34 * @package core_h5p
35 * @copyright 2019 Sara Arjona <sara@moodle.com>
36 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
37 */
38class player {
39
40 /**
41 * @var string The local H5P URL containing the .h5p file to display.
42 */
43 private $url;
44
45 /**
9e67f5e3 46 * @var core The H5PCore object.
35b62d00
SA
47 */
48 private $core;
49
50 /**
51 * @var int H5P DB id.
52 */
53 private $h5pid;
54
55 /**
56 * @var array JavaScript requirements for this H5P.
57 */
58 private $jsrequires = [];
59
60 /**
61 * @var array CSS requirements for this H5P.
62 */
63 private $cssrequires = [];
64
65 /**
66 * @var array H5P content to display.
67 */
68 private $content;
69
70 /**
71 * @var string Type of embed object, div or iframe.
72 */
73 private $embedtype;
74
75 /**
76 * @var context The context object where the .h5p belongs.
77 */
78 private $context;
79
df74cd4a 80 /**
c07f31ae 81 * @var factory The \core_h5p\factory object.
df74cd4a
MG
82 */
83 private $factory;
84
c07f31ae
SA
85 /**
86 * @var stdClass The error, exception and info messages, raised while preparing and running the player.
87 */
88 private $messages;
89
74346211
SA
90 /**
91 * @var bool Set to true in scripts that can not redirect (CLI, RSS feeds, etc.), throws exceptions.
92 */
93 private $preventredirect;
94
35b62d00
SA
95 /**
96 * Inits the H5P player for rendering the content.
97 *
98 * @param string $url Local URL of the H5P file to display.
99 * @param stdClass $config Configuration for H5P buttons.
74346211 100 * @param bool $preventredirect Set to true in scripts that can not redirect (CLI, RSS feeds, etc.), throws exceptions
35b62d00 101 */
74346211 102 public function __construct(string $url, \stdClass $config, bool $preventredirect = true) {
35b62d00
SA
103 if (empty($url)) {
104 throw new \moodle_exception('h5pinvalidurl', 'core_h5p');
105 }
106 $this->url = new \moodle_url($url);
74346211 107 $this->preventredirect = $preventredirect;
35b62d00 108
df74cd4a
MG
109 $this->factory = new \core_h5p\factory();
110
c07f31ae
SA
111 $this->messages = new \stdClass();
112
df74cd4a
MG
113 // Create \core_h5p\core instance.
114 $this->core = $this->factory->get_core();
35b62d00
SA
115
116 // Get the H5P identifier linked to this URL.
117 if ($this->h5pid = $this->get_h5p_id($url, $config)) {
118 // Load the content of the H5P content associated to this $url.
119 $this->content = $this->core->loadContent($this->h5pid);
120
121 // Get the embedtype to use for displaying the H5P content.
9e67f5e3 122 $this->embedtype = core::determineEmbedType($this->content['embedType'], $this->content['library']['embedTypes']);
35b62d00
SA
123 }
124 }
125
126 /**
127 * Get the error messages stored in our H5P framework.
128 *
129 * @return stdClass with framework error messages.
130 */
284af93b 131 public function get_messages(): \stdClass {
c07f31ae
SA
132 // Check if there are some errors and store them in $messages.
133 if (empty($this->messages->error)) {
134 $this->messages->error = $this->core->h5pF->getMessages('error') ?: false;
135 } else {
136 $this->messages->error = array_merge($this->messages->error, $this->core->h5pF->getMessages('error'));
137 }
35b62d00 138
c07f31ae
SA
139 if (empty($this->messages->info)) {
140 $this->messages->info = $this->core->h5pF->getMessages('info') ?: false;
141 } else {
142 $this->messages->info = array_merge($this->messages->info, $this->core->h5pF->getMessages('info'));
35b62d00 143 }
c07f31ae
SA
144
145 return $this->messages;
35b62d00
SA
146 }
147
148 /**
149 * Create the H5PIntegration variable that will be included in the page. This variable is used as the
150 * main H5P config variable.
151 */
152 public function add_assets_to_page() {
153 global $PAGE;
154
155 $cid = $this->get_cid();
156 $systemcontext = \context_system::instance();
157
9e67f5e3 158 $disable = array_key_exists('disable', $this->content) ? $this->content['disable'] : core::DISABLE_NONE;
35b62d00
SA
159 $displayoptions = $this->core->getDisplayOptionsForView($disable, $this->h5pid);
160
161 $contenturl = \moodle_url::make_pluginfile_url($systemcontext->id, \core_h5p\file_storage::COMPONENT,
162 \core_h5p\file_storage::CONTENT_FILEAREA, $this->h5pid, null, null);
65ae2441 163 $exporturl = $this->get_export_settings($displayoptions[ core::DISPLAY_OPTION_DOWNLOAD ]);
35b62d00 164 $contentsettings = [
9e67f5e3 165 'library' => core::libraryToString($this->content['library']),
35b62d00 166 'fullScreen' => $this->content['library']['fullscreen'],
65ae2441 167 'exportUrl' => ($exporturl instanceof \moodle_url) ? $exporturl->out(false) : '',
35b62d00 168 'embedCode' => $this->get_embed_code($this->url->out(),
9e67f5e3 169 $displayoptions[ core::DISPLAY_OPTION_EMBED ]),
35b62d00
SA
170 'resizeCode' => $this->get_resize_code(),
171 'title' => $this->content['slug'],
172 'displayOptions' => $displayoptions,
173 'url' => self::get_embed_url($this->url->out())->out(),
174 'contentUrl' => $contenturl->out(),
175 'metadata' => $this->content['metadata'],
176 'contentUserData' => [0 => ['state' => '{}']]
177 ];
178 // Get the core H5P assets, needed by the H5P classes to render the H5P content.
179 $settings = $this->get_assets();
180 $settings['contents'][$cid] = array_merge($settings['contents'][$cid], $contentsettings);
181
182 foreach ($this->jsrequires as $script) {
183 $PAGE->requires->js($script, true);
184 }
185
186 foreach ($this->cssrequires as $css) {
187 $PAGE->requires->css($css);
188 }
189
190 // Print JavaScript settings to page.
191 $PAGE->requires->data_for_js('H5PIntegration', $settings, true);
192 }
193
194 /**
195 * Outputs H5P wrapper HTML.
196 *
197 * @return string The HTML code to display this H5P content.
198 */
284af93b 199 public function output(): string {
fba5bba8 200 global $OUTPUT, $USER;
35b62d00
SA
201
202 $template = new \stdClass();
203 $template->h5pid = $this->h5pid;
204 if ($this->embedtype === 'div') {
fba5bba8 205 $h5phtml = $OUTPUT->render_from_template('core_h5p/h5pdiv', $template);
35b62d00 206 } else {
fba5bba8 207 $h5phtml = $OUTPUT->render_from_template('core_h5p/h5piframe', $template);
35b62d00 208 }
fba5bba8 209
210 // Trigger capability_assigned event.
211 \core_h5p\event\h5p_viewed::create([
212 'objectid' => $this->h5pid,
213 'userid' => $USER->id,
214 'context' => $this->context,
215 'other' => [
216 'url' => $this->url->out(),
217 'time' => time()
218 ]
219 ])->trigger();
220
221 return $h5phtml;
35b62d00
SA
222 }
223
224 /**
225 * Get the title of the H5P content to display.
226 *
227 * @return string the title
228 */
284af93b 229 public function get_title(): string {
35b62d00
SA
230 return $this->content['title'];
231 }
232
233 /**
234 * Get the context where the .h5p file belongs.
235 *
236 * @return context The context.
237 */
284af93b 238 public function get_context(): \context {
35b62d00
SA
239 return $this->context;
240 }
241
242 /**
243 * Get the H5P DB instance id for a H5P pluginfile URL. The H5P file will be saved if it doesn't exist previously or
244 * if its content has changed. Besides, the displayoptions in the $config will be also updated when they have changed and
245 * the user has the right permissions.
246 *
247 * @param string $url H5P pluginfile URL.
248 * @param stdClass $config Configuration for H5P buttons.
249 *
250 * @return int|false H5P DB identifier.
251 */
252 private function get_h5p_id(string $url, \stdClass $config) {
c07f31ae 253 global $DB, $USER;
35b62d00
SA
254
255 $fs = get_file_storage();
256
257 // Deconstruct the URL and get the pathname associated.
258 $pathnamehash = $this->get_pluginfile_hash($url);
259 if (!$pathnamehash) {
260 $this->core->h5pF->setErrorMessage(get_string('h5pfilenotfound', 'core_h5p'));
261 return false;
262 }
263
264 // Get the file.
265 $file = $fs->get_file_by_hash($pathnamehash);
266 if (!$file) {
267 $this->core->h5pF->setErrorMessage(get_string('h5pfilenotfound', 'core_h5p'));
268 return false;
269 }
270
271 $h5p = $DB->get_record('h5p', ['pathnamehash' => $pathnamehash]);
272 $contenthash = $file->get_contenthash();
273 if ($h5p && $h5p->contenthash != $contenthash) {
274 // The content exists and it is different from the one deployed previously. The existing one should be removed before
275 // deploying the new version.
276 $this->delete_h5p($h5p);
277 $h5p = false;
278 }
279
8fda136d 280 if ($h5p) {
35b62d00
SA
281 // The H5P content has been deployed previously.
282 $displayoptions = $this->get_display_options($config);
283 // Check if the user can set the displayoptions.
284 if ($displayoptions != $h5p->displayoptions && has_capability('moodle/h5p:setdisplayoptions', $this->context)) {
285 // If the displayoptions has changed and the user has permission to modify it, update this information in the DB.
286 $this->core->h5pF->updateContentFields($h5p->id, ['displayoptions' => $displayoptions]);
287 }
288 return $h5p->id;
8fda136d
SA
289 } else {
290 // The H5P content hasn't been deployed previously.
291
292 // Check if the user uploading the H5P content is "trustable". If the file hasn't been uploaded by a user with this
293 // capability, the content won't be deployed and an error message will be displayed.
c07f31ae 294 if (!helper::can_deploy_package($file)) {
8fda136d
SA
295 $this->core->h5pF->setErrorMessage(get_string('nopermissiontodeploy', 'core_h5p'));
296 return false;
297 }
298
c07f31ae
SA
299 // The H5P content can be only deployed if the author of the .h5p file can update libraries or if all the
300 // content-type libraries exist, to avoid users without the h5p:updatelibraries capability upload malicious content.
301 $onlyupdatelibs = !helper::can_update_library($file);
302
8fda136d 303 // Validate and store the H5P content before displaying it.
c07f31ae
SA
304 $h5pid = helper::save_h5p($this->factory, $file, $config, $onlyupdatelibs, false);
305 if (!$h5pid && $file->get_userid() != $USER->id && has_capability('moodle/h5p:updatelibraries', $this->context)) {
306 // The user has permission to update libraries but the package has been uploaded by a different
307 // user without this permission. Check if there is some missing required library error.
308 $missingliberror = false;
309 $messages = $this->get_messages();
310 if (!empty($messages->error)) {
311 foreach ($messages->error as $error) {
312 if ($error->code == 'missing-required-library') {
313 $missingliberror = true;
314 break;
315 }
316 }
317 }
318 if ($missingliberror) {
319 // The message about the permissions to upload libraries should be removed.
320 $infomsg = "Note that the libraries may exist in the file you uploaded, but you're not allowed to upload " .
321 "new libraries. Contact the site administrator about this.";
322 if (($key = array_search($infomsg, $messages->info)) !== false) {
323 unset($messages->info[$key]);
324 }
325
326 // No library will be installed and an error will be displayed, because this content is not trustable.
327 $this->core->h5pF->setInfoMessage(get_string('notrustablefile', 'core_h5p'));
328 }
329 return false;
330
331 }
332 return $h5pid;
35b62d00
SA
333 }
334 }
335
336 /**
337 * Get the pathnamehash from an H5P internal URL.
338 *
339 * @param string $url H5P pluginfile URL poiting to an H5P file.
340 *
341 * @return string|false pathnamehash for the file in the internal URL.
342 */
343 private function get_pluginfile_hash(string $url) {
c0c489bb 344 global $USER, $CFG;
35b62d00
SA
345
346 // Decode the URL before start processing it.
347 $url = new \moodle_url(urldecode($url));
348
349 // Remove params from the URL (such as the 'forcedownload=1'), to avoid errors.
350 $url->remove_params(array_keys($url->params()));
351 $path = $url->out_as_local_url();
352
5d81efd1 353 // We only need the slasharguments.
354 $path = substr($path, strpos($path, '.php/') + 5);
35b62d00
SA
355 $parts = explode('/', $path);
356 $filename = array_pop($parts);
35b62d00 357
5d81efd1 358 // If the request is made by tokenpluginfile.php we need to avoid userprivateaccesskey.
359 if (strpos($this->url, '/tokenpluginfile.php')) {
360 array_shift($parts);
361 }
35b62d00
SA
362 // Get the contextid, component and filearea.
363 $contextid = array_shift($parts);
364 $component = array_shift($parts);
365 $filearea = array_shift($parts);
366
367 // Ignore draft files, because they are considered temporary files, so shouldn't be displayed.
368 if ($filearea == 'draft') {
369 return false;
370 }
371
372 // Get the context.
373 try {
374 list($this->context, $course, $cm) = get_context_info_array($contextid);
375 } catch (\moodle_exception $e) {
376 throw new \moodle_exception('invalidcontextid', 'core_h5p');
377 }
378
379 // For CONTEXT_USER, such as the private files, raise an exception if the owner of the file is not the current user.
380 if ($this->context->contextlevel == CONTEXT_USER && $USER->id !== $this->context->instanceid) {
381 throw new \moodle_exception('h5pprivatefile', 'core_h5p');
382 }
383
c0c489bb 384 // For CONTEXT_COURSECAT No login necessary - unless login forced everywhere.
385 if ($this->context->contextlevel == CONTEXT_COURSECAT) {
386 if ($CFG->forcelogin) {
387 require_login(null, true, null, false, true);
388 }
389 }
390
391 // For CONTEXT_BLOCK.
392 if ($this->context->contextlevel == CONTEXT_BLOCK) {
393 if ($this->context->get_course_context(false)) {
394 // If block is in course context, then check if user has capability to access course.
395 require_course_login($course, true, null, false, true);
396 } else if ($CFG->forcelogin) {
397 // No login necessary - unless login forced everywhere.
398 require_login(null, true, null, false, true);
399 } else {
400 // Get parent context and see if user have proper permission.
401 $parentcontext = $this->context->get_parent_context();
402 if ($parentcontext->contextlevel === CONTEXT_COURSECAT) {
403 // Check if category is visible and user can view this category.
404 if (!core_course_category::get($parentcontext->instanceid, IGNORE_MISSING)) {
405 send_file_not_found();
406 }
407 } else if ($parentcontext->contextlevel === CONTEXT_USER && $parentcontext->instanceid != $USER->id) {
408 // The block is in the context of a user, it is only visible to the user who it belongs to.
409 send_file_not_found();
410 }
411 if ($filearea !== 'content') {
412 send_file_not_found();
413 }
414 }
415 }
416
417 // For CONTEXT_MODULE and CONTEXT_COURSE check if the user is enrolled in the course.
418 // And for CONTEXT_MODULE has permissions view this .h5p file.
419 if ($this->context->contextlevel == CONTEXT_MODULE ||
420 $this->context->contextlevel == CONTEXT_COURSE) {
35b62d00 421 // Require login to the course first (without login to the module).
74346211 422 require_course_login($course, true, null, !$this->preventredirect, $this->preventredirect);
35b62d00
SA
423
424 // Now check if module is available OR it is restricted but the intro is shown on the course page.
c0c489bb 425 if ($this->context->contextlevel == CONTEXT_MODULE) {
426 $cminfo = \cm_info::create($cm);
427 if (!$cminfo->uservisible) {
428 if (!$cm->showdescription || !$cminfo->is_visible_on_course_page()) {
429 // Module intro is not visible on the course page and module is not available, show access error.
6f44f094 430 require_course_login($course, true, $cminfo, !$this->preventredirect, $this->preventredirect);
c0c489bb 431 }
35b62d00
SA
432 }
433 }
434 }
435
436 // Some components, such as mod_page or mod_resource, add the revision to the URL to prevent caching problems.
437 // So the URL contains this revision number as itemid but a 0 is always stored in the files table.
438 // In order to get the proper hash, a callback should be done (looking for those exceptions).
3f6c7446 439 $pathdata = null;
440 if ($this->context->contextlevel == CONTEXT_MODULE || $this->context->contextlevel == CONTEXT_BLOCK) {
441 $pathdata = component_callback($component, 'get_path_from_pluginfile', [$filearea, $parts], null);
442 }
35b62d00
SA
443 if (null === $pathdata) {
444 // Look for the components and fileareas which have empty itemid defined in xxx_pluginfile.
445 $hasnullitemid = false;
446 $hasnullitemid = $hasnullitemid || ($component === 'user' && ($filearea === 'private' || $filearea === 'profile'));
3f6c7446 447 $hasnullitemid = $hasnullitemid || (substr($component, 0, 4) === 'mod_' && $filearea === 'intro');
35b62d00
SA
448 $hasnullitemid = $hasnullitemid || ($component === 'course' &&
449 ($filearea === 'summary' || $filearea === 'overviewfiles'));
450 $hasnullitemid = $hasnullitemid || ($component === 'coursecat' && $filearea === 'description');
451 $hasnullitemid = $hasnullitemid || ($component === 'backup' &&
452 ($filearea === 'course' || $filearea === 'activity' || $filearea === 'automated'));
453 if ($hasnullitemid) {
454 $itemid = 0;
455 } else {
456 $itemid = array_shift($parts);
457 }
458
459 if (empty($parts)) {
460 $filepath = '/';
461 } else {
462 $filepath = '/' . implode('/', $parts) . '/';
463 }
464 } else {
465 // The itemid and filepath have been returned by the component callback.
466 [
467 'itemid' => $itemid,
468 'filepath' => $filepath,
469 ] = $pathdata;
470 }
471
472 $fs = get_file_storage();
473 return $fs->get_pathname_hash($contextid, $component, $filearea, $itemid, $filepath, $filename);
474 }
475
35b62d00
SA
476 /**
477 * Get the representation of display options as int.
478 * @param stdClass $config Button options config.
479 *
480 * @return int The representation of display options as int.
481 */
284af93b 482 private function get_display_options(\stdClass $config): int {
35b62d00
SA
483 $export = isset($config->export) ? $config->export : 0;
484 $embed = isset($config->embed) ? $config->embed : 0;
485 $copyright = isset($config->copyright) ? $config->copyright : 0;
486 $frame = ($export || $embed || $copyright);
487 if (!$frame) {
488 $frame = isset($config->frame) ? $config->frame : 0;
489 }
490
491 $disableoptions = [
9e67f5e3
AN
492 core::DISPLAY_OPTION_FRAME => $frame,
493 core::DISPLAY_OPTION_DOWNLOAD => $export,
494 core::DISPLAY_OPTION_EMBED => $embed,
495 core::DISPLAY_OPTION_COPYRIGHT => $copyright,
35b62d00
SA
496 ];
497
498 return $this->core->getStorableDisplayOptions($disableoptions, 0);
499 }
500
501 /**
502 * Delete an H5P package.
503 *
504 * @param stdClass $content The H5P package to delete.
505 */
506 private function delete_h5p(\stdClass $content) {
df74cd4a 507 $h5pstorage = $this->factory->get_storage();
35b62d00
SA
508 // Add an empty slug to the content if it's not defined, because the H5P library requires this field exists.
509 // It's not used when deleting a package, so the real slug value is not required at this point.
510 $content->slug = $content->slug ?? '';
511 $h5pstorage->deletePackage( (array) $content);
512 }
513
514 /**
515 * Export path for settings
516 *
517 * @param bool $downloadenabled Whether the option to export the H5P content is enabled.
518 *
65ae2441 519 * @return \moodle_url|null The URL of the exported file.
35b62d00 520 */
284af93b 521 private function get_export_settings(bool $downloadenabled): ?\moodle_url {
35b62d00 522
5d81efd1 523 if (!$downloadenabled) {
65ae2441 524 return null;
35b62d00
SA
525 }
526
527 $systemcontext = \context_system::instance();
528 $slug = $this->content['slug'] ? $this->content['slug'] . '-' : '';
5d81efd1 529 // We have to build the right URL.
530 // Depending the request was made through webservice/pluginfile.php or pluginfile.php.
531 if (strpos($this->url, '/webservice/pluginfile.php')) {
532 $url = \moodle_url::make_webservice_pluginfile_url(
533 $systemcontext->id,
534 \core_h5p\file_storage::COMPONENT,
535 \core_h5p\file_storage::EXPORT_FILEAREA,
536 '',
537 '',
538 "{$slug}{$this->content['id']}.h5p"
539 );
540 } else {
541 // If the request is made by tokenpluginfile.php we need to indicates to generate a token for current user.
542 $includetoken = false;
543 if (strpos($this->url, '/tokenpluginfile.php')) {
544 $includetoken = true;
545 }
546 $url = \moodle_url::make_pluginfile_url(
547 $systemcontext->id,
548 \core_h5p\file_storage::COMPONENT,
549 \core_h5p\file_storage::EXPORT_FILEAREA,
550 '',
551 '',
552 "{$slug}{$this->content['id']}.h5p",
553 false,
554 $includetoken
555 );
556 }
35b62d00 557
65ae2441 558 return $url;
35b62d00
SA
559 }
560
561 /**
562 * Get a query string with the theme revision number to include at the end
563 * of URLs. This is used to force the browser to reload the asset when the
564 * theme caches are cleared.
565 *
566 * @return string
567 */
284af93b 568 private function get_cache_buster(): string {
35b62d00
SA
569 global $CFG;
570 return '?ver=' . $CFG->themerev;
571 }
572
573 /**
574 * Get the identifier for the H5P content, to be used in the arrays as index.
575 *
576 * @return string The identifier.
577 */
284af93b 578 private function get_cid(): string {
35b62d00
SA
579 return 'cid-' . $this->h5pid;
580 }
581
582 /**
583 * Get the core H5P assets, including all core H5P JavaScript and CSS.
584 *
585 * @return Array core H5P assets.
586 */
284af93b 587 private function get_assets(): array {
35b62d00
SA
588 global $CFG;
589
590 // Get core settings.
591 $settings = $this->get_core_settings();
592 $settings['core'] = [
593 'styles' => [],
594 'scripts' => []
595 ];
596 $settings['loadedJs'] = [];
597 $settings['loadedCss'] = [];
598
599 // Make sure files are reloaded for each plugin update.
600 $cachebuster = $this->get_cache_buster();
601
602 // Use relative URL to support both http and https.
08fda3e0 603 $liburl = autoloader::get_h5p_core_library_url()->out();
35b62d00
SA
604 $relpath = '/' . preg_replace('/^[^:]+:\/\/[^\/]+\//', '', $liburl);
605
606 // Add core stylesheets.
9e67f5e3 607 foreach (core::$styles as $style) {
35b62d00 608 $settings['core']['styles'][] = $relpath . $style . $cachebuster;
08fda3e0
SA
609 $this->cssrequires[] = autoloader::get_h5p_core_library_url($style, [
610 'ver' => $cachebuster,
611 ]);
35b62d00
SA
612 }
613 // Add core JavaScript.
9e67f5e3
AN
614 foreach (core::get_scripts() as $script) {
615 $settings['core']['scripts'][] = $script->out(false);
616 $this->jsrequires[] = $script;
35b62d00
SA
617 }
618
619 $cid = $this->get_cid();
620 // The filterParameters function should be called before getting the dependencyfiles because it rebuild content
621 // dependency cache and export file.
622 $settings['contents'][$cid]['jsonContent'] = $this->core->filterParameters($this->content);
623
624 $files = $this->get_dependency_files();
625 if ($this->embedtype === 'div') {
626 $systemcontext = \context_system::instance();
627 $h5ppath = "/pluginfile.php/{$systemcontext->id}/core_h5p";
628
629 // Schedule JavaScripts for loading through Moodle.
630 foreach ($files['scripts'] as $script) {
631 $url = $script->path . $script->version;
632
633 // Add URL prefix if not external.
634 $isexternal = strpos($script->path, '://');
635 if ($isexternal === false) {
636 $url = $h5ppath . $url;
637 }
638 $settings['loadedJs'][] = $url;
639 $this->jsrequires[] = new \moodle_url($isexternal ? $url : $CFG->wwwroot . $url);
640 }
641
642 // Schedule stylesheets for loading through Moodle.
643 foreach ($files['styles'] as $style) {
644 $url = $style->path . $style->version;
645
646 // Add URL prefix if not external.
647 $isexternal = strpos($style->path, '://');
648 if ($isexternal === false) {
649 $url = $h5ppath . $url;
650 }
651 $settings['loadedCss'][] = $url;
652 $this->cssrequires[] = new \moodle_url($isexternal ? $url : $CFG->wwwroot . $url);
653 }
654
655 } else {
656 // JavaScripts and stylesheets will be loaded through h5p.js.
657 $settings['contents'][$cid]['scripts'] = $this->core->getAssetsUrls($files['scripts']);
658 $settings['contents'][$cid]['styles'] = $this->core->getAssetsUrls($files['styles']);
659 }
660 return $settings;
661 }
662
663 /**
664 * Get the settings needed by the H5P library.
665 *
666 * @return array The settings.
667 */
284af93b 668 private function get_core_settings(): array {
35b62d00
SA
669 global $CFG;
670
671 $basepath = $CFG->wwwroot . '/';
672 $systemcontext = \context_system::instance();
673
674 // Generate AJAX paths.
675 $ajaxpaths = [];
676 $ajaxpaths['xAPIResult'] = '';
677 $ajaxpaths['contentUserData'] = '';
678
679 $settings = array(
680 'baseUrl' => $basepath,
681 'url' => "{$basepath}pluginfile.php/{$systemcontext->instanceid}/core_h5p",
682 'urlLibraries' => "{$basepath}pluginfile.php/{$systemcontext->id}/core_h5p/libraries",
683 'postUserStatistics' => false,
684 'ajax' => $ajaxpaths,
685 'saveFreq' => false,
686 'siteUrl' => $CFG->wwwroot,
687 'l10n' => array('H5P' => $this->core->getLocalization()),
688 'user' => [],
689 'hubIsEnabled' => false,
690 'reportingIsEnabled' => false,
691 'crossorigin' => null,
692 'libraryConfig' => $this->core->h5pF->getLibraryConfig(),
693 'pluginCacheBuster' => $this->get_cache_buster(),
08fda3e0 694 'libraryUrl' => autoloader::get_h5p_core_library_url('js'),
9e67f5e3 695 'moodleLibraryPaths' => $this->core->get_dependency_roots($this->h5pid),
35b62d00
SA
696 );
697
698 return $settings;
699 }
700
701 /**
702 * Finds library dependencies of view
703 *
704 * @return array Files that the view has dependencies to
705 */
284af93b 706 private function get_dependency_files(): array {
35b62d00
SA
707 $preloadeddeps = $this->core->loadContentDependencies($this->h5pid, 'preloaded');
708 $files = $this->core->getDependenciesFiles($preloadeddeps);
709
710 return $files;
711 }
712
713 /**
714 * Resizing script for settings
715 *
716 * @return string The HTML code with the resize script.
717 */
284af93b 718 private function get_resize_code(): string {
35b62d00
SA
719 global $OUTPUT;
720
721 $template = new \stdClass();
08fda3e0 722 $template->resizeurl = autoloader::get_h5p_core_library_url('js/h5p-resizer.js');
35b62d00
SA
723
724 return $OUTPUT->render_from_template('core_h5p/h5presize', $template);
725 }
726
727 /**
728 * Embed code for settings
729 *
730 * @param string $url The URL of the .h5p file.
731 * @param bool $embedenabled Whether the option to embed the H5P content is enabled.
732 *
733 * @return string The HTML code to reuse this H5P content in a different place.
734 */
284af93b 735 private function get_embed_code(string $url, bool $embedenabled): string {
35b62d00
SA
736 global $OUTPUT;
737
738 if ( ! $embedenabled) {
739 return '';
740 }
741
742 $template = new \stdClass();
743 $template->embedurl = self::get_embed_url($url)->out();
744
745 return $OUTPUT->render_from_template('core_h5p/h5pembed', $template);
746 }
747
748 /**
749 * Get the encoded URL for embeding this H5P content.
750 * @param string $url The URL of the .h5p file.
751 *
752 * @return \moodle_url The embed URL.
753 */
284af93b 754 public static function get_embed_url(string $url): \moodle_url {
35b62d00
SA
755 return new \moodle_url('/h5p/embed.php', ['url' => $url]);
756 }
65ae2441 757
758 /**
759 * Return the export file for Mobile App.
760 *
761 * @return array
762 */
284af93b 763 public function get_export_file(): array {
65ae2441 764 // Get the export url.
765 $exporturl = $this->get_export_settings(true);
766 // Get the filename of the export url.
767 $path = $exporturl->out_as_local_url();
768 $parts = explode('/', $path);
769 $filename = array_pop($parts);
770 // Get the the export file.
771 $systemcontext = \context_system::instance();
772 $fs = get_file_storage();
773 $fileh5p = $fs->get_file($systemcontext->id,
774 \core_h5p\file_storage::COMPONENT,
775 \core_h5p\file_storage::EXPORT_FILEAREA,
776 0,
777 '/',
778 $filename);
779 // Get the options that the Mobile App needs.
780 $file = [];
781 $file['filename'] = $fileh5p->get_filename();
782 $file['filepath'] = $fileh5p->get_filepath();
783 $file['mimetype'] = $fileh5p->get_mimetype();
784 $file['filesize'] = $fileh5p->get_filesize();
785 $file['timemodified'] = $fileh5p->get_timemodified();
786 $file['fileurl'] = $exporturl->out(false);
787
788 return $file;
789 }
35b62d00 790}