MDL-66609 core_h5p: Change core files when upgrading lib
[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
29/**
30 * H5P player class, for displaying any local H5P content.
31 *
32 * @package core_h5p
33 * @copyright 2019 Sara Arjona <sara@moodle.com>
34 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
35 */
36class player {
37
38 /**
39 * @var string The local H5P URL containing the .h5p file to display.
40 */
41 private $url;
42
43 /**
9e67f5e3 44 * @var core The H5PCore object.
35b62d00
SA
45 */
46 private $core;
47
48 /**
49 * @var int H5P DB id.
50 */
51 private $h5pid;
52
53 /**
54 * @var array JavaScript requirements for this H5P.
55 */
56 private $jsrequires = [];
57
58 /**
59 * @var array CSS requirements for this H5P.
60 */
61 private $cssrequires = [];
62
63 /**
64 * @var array H5P content to display.
65 */
66 private $content;
67
68 /**
69 * @var string Type of embed object, div or iframe.
70 */
71 private $embedtype;
72
73 /**
74 * @var context The context object where the .h5p belongs.
75 */
76 private $context;
77
78 /**
79 * Inits the H5P player for rendering the content.
80 *
81 * @param string $url Local URL of the H5P file to display.
82 * @param stdClass $config Configuration for H5P buttons.
83 */
84 public function __construct(string $url, \stdClass $config) {
85 if (empty($url)) {
86 throw new \moodle_exception('h5pinvalidurl', 'core_h5p');
87 }
88 $this->url = new \moodle_url($url);
89
90 // Create H5PFramework instance.
91 $this->core = \core_h5p\framework::instance();
92
93 // Get the H5P identifier linked to this URL.
94 if ($this->h5pid = $this->get_h5p_id($url, $config)) {
95 // Load the content of the H5P content associated to this $url.
96 $this->content = $this->core->loadContent($this->h5pid);
97
98 // Get the embedtype to use for displaying the H5P content.
9e67f5e3 99 $this->embedtype = core::determineEmbedType($this->content['embedType'], $this->content['library']['embedTypes']);
35b62d00
SA
100 }
101 }
102
103 /**
104 * Get the error messages stored in our H5P framework.
105 *
106 * @return stdClass with framework error messages.
107 */
108 public function get_messages() : \stdClass {
109 $messages = new \stdClass();
110 $messages->error = $this->core->h5pF->getMessages('error');
111
112 if (empty($messages->error)) {
113 $messages->error = false;
114 }
115 return $messages;
116 }
117
118 /**
119 * Create the H5PIntegration variable that will be included in the page. This variable is used as the
120 * main H5P config variable.
121 */
122 public function add_assets_to_page() {
123 global $PAGE;
124
125 $cid = $this->get_cid();
126 $systemcontext = \context_system::instance();
127
9e67f5e3 128 $disable = array_key_exists('disable', $this->content) ? $this->content['disable'] : core::DISABLE_NONE;
35b62d00
SA
129 $displayoptions = $this->core->getDisplayOptionsForView($disable, $this->h5pid);
130
131 $contenturl = \moodle_url::make_pluginfile_url($systemcontext->id, \core_h5p\file_storage::COMPONENT,
132 \core_h5p\file_storage::CONTENT_FILEAREA, $this->h5pid, null, null);
133
134 $contentsettings = [
9e67f5e3 135 'library' => core::libraryToString($this->content['library']),
35b62d00 136 'fullScreen' => $this->content['library']['fullscreen'],
9e67f5e3 137 'exportUrl' => $this->get_export_settings($displayoptions[ core::DISPLAY_OPTION_DOWNLOAD ]),
35b62d00 138 'embedCode' => $this->get_embed_code($this->url->out(),
9e67f5e3 139 $displayoptions[ core::DISPLAY_OPTION_EMBED ]),
35b62d00
SA
140 'resizeCode' => $this->get_resize_code(),
141 'title' => $this->content['slug'],
142 'displayOptions' => $displayoptions,
143 'url' => self::get_embed_url($this->url->out())->out(),
144 'contentUrl' => $contenturl->out(),
145 'metadata' => $this->content['metadata'],
146 'contentUserData' => [0 => ['state' => '{}']]
147 ];
148 // Get the core H5P assets, needed by the H5P classes to render the H5P content.
149 $settings = $this->get_assets();
150 $settings['contents'][$cid] = array_merge($settings['contents'][$cid], $contentsettings);
151
152 foreach ($this->jsrequires as $script) {
153 $PAGE->requires->js($script, true);
154 }
155
156 foreach ($this->cssrequires as $css) {
157 $PAGE->requires->css($css);
158 }
159
160 // Print JavaScript settings to page.
161 $PAGE->requires->data_for_js('H5PIntegration', $settings, true);
162 }
163
164 /**
165 * Outputs H5P wrapper HTML.
166 *
167 * @return string The HTML code to display this H5P content.
168 */
169 public function output() : string {
170 global $OUTPUT;
171
172 $template = new \stdClass();
173 $template->h5pid = $this->h5pid;
174 if ($this->embedtype === 'div') {
175 return $OUTPUT->render_from_template('core_h5p/h5pdiv', $template);
176 } else {
177 return $OUTPUT->render_from_template('core_h5p/h5piframe', $template);
178 }
179 }
180
181 /**
182 * Get the title of the H5P content to display.
183 *
184 * @return string the title
185 */
186 public function get_title() : string {
187 return $this->content['title'];
188 }
189
190 /**
191 * Get the context where the .h5p file belongs.
192 *
193 * @return context The context.
194 */
195 public function get_context() : \context {
196 return $this->context;
197 }
198
199 /**
200 * Get the H5P DB instance id for a H5P pluginfile URL. The H5P file will be saved if it doesn't exist previously or
201 * if its content has changed. Besides, the displayoptions in the $config will be also updated when they have changed and
202 * the user has the right permissions.
203 *
204 * @param string $url H5P pluginfile URL.
205 * @param stdClass $config Configuration for H5P buttons.
206 *
207 * @return int|false H5P DB identifier.
208 */
209 private function get_h5p_id(string $url, \stdClass $config) {
210 global $DB;
211
212 $fs = get_file_storage();
213
214 // Deconstruct the URL and get the pathname associated.
215 $pathnamehash = $this->get_pluginfile_hash($url);
216 if (!$pathnamehash) {
217 $this->core->h5pF->setErrorMessage(get_string('h5pfilenotfound', 'core_h5p'));
218 return false;
219 }
220
221 // Get the file.
222 $file = $fs->get_file_by_hash($pathnamehash);
223 if (!$file) {
224 $this->core->h5pF->setErrorMessage(get_string('h5pfilenotfound', 'core_h5p'));
225 return false;
226 }
227
228 $h5p = $DB->get_record('h5p', ['pathnamehash' => $pathnamehash]);
229 $contenthash = $file->get_contenthash();
230 if ($h5p && $h5p->contenthash != $contenthash) {
231 // The content exists and it is different from the one deployed previously. The existing one should be removed before
232 // deploying the new version.
233 $this->delete_h5p($h5p);
234 $h5p = false;
235 }
236
237 if (!$h5p) {
238 // The H5P content hasn't been deployed previously. It has to be validated and stored before displaying it.
239 return $this->save_h5p($file, $config);
240 } else {
241 // The H5P content has been deployed previously.
242 $displayoptions = $this->get_display_options($config);
243 // Check if the user can set the displayoptions.
244 if ($displayoptions != $h5p->displayoptions && has_capability('moodle/h5p:setdisplayoptions', $this->context)) {
245 // If the displayoptions has changed and the user has permission to modify it, update this information in the DB.
246 $this->core->h5pF->updateContentFields($h5p->id, ['displayoptions' => $displayoptions]);
247 }
248 return $h5p->id;
249 }
250 }
251
252 /**
253 * Get the pathnamehash from an H5P internal URL.
254 *
255 * @param string $url H5P pluginfile URL poiting to an H5P file.
256 *
257 * @return string|false pathnamehash for the file in the internal URL.
258 */
259 private function get_pluginfile_hash(string $url) {
260 global $USER;
261
262 // Decode the URL before start processing it.
263 $url = new \moodle_url(urldecode($url));
264
265 // Remove params from the URL (such as the 'forcedownload=1'), to avoid errors.
266 $url->remove_params(array_keys($url->params()));
267 $path = $url->out_as_local_url();
268
269 $parts = explode('/', $path);
270 $filename = array_pop($parts);
271 // First is an empty row and then the pluginfile.php part. Both can be ignored.
272 array_shift($parts);
273 array_shift($parts);
274
275 // Get the contextid, component and filearea.
276 $contextid = array_shift($parts);
277 $component = array_shift($parts);
278 $filearea = array_shift($parts);
279
280 // Ignore draft files, because they are considered temporary files, so shouldn't be displayed.
281 if ($filearea == 'draft') {
282 return false;
283 }
284
285 // Get the context.
286 try {
287 list($this->context, $course, $cm) = get_context_info_array($contextid);
288 } catch (\moodle_exception $e) {
289 throw new \moodle_exception('invalidcontextid', 'core_h5p');
290 }
291
292 // For CONTEXT_USER, such as the private files, raise an exception if the owner of the file is not the current user.
293 if ($this->context->contextlevel == CONTEXT_USER && $USER->id !== $this->context->instanceid) {
294 throw new \moodle_exception('h5pprivatefile', 'core_h5p');
295 }
296
297 // For CONTEXT_MODULE, check if the user is enrolled in the course and has permissions view this .h5p file.
298 if ($this->context->contextlevel == CONTEXT_MODULE) {
299 // Require login to the course first (without login to the module).
300 require_course_login($course, true, null, false, true);
301
302 // Now check if module is available OR it is restricted but the intro is shown on the course page.
303 $cminfo = \cm_info::create($cm);
304 if (!$cminfo->uservisible) {
305 if (!$cm->showdescription || !$cminfo->is_visible_on_course_page()) {
306 // Module intro is not visible on the course page and module is not available, show access error.
307 require_course_login($course, true, $cminfo, false, true);
308 }
309 }
310 }
311
312 // Some components, such as mod_page or mod_resource, add the revision to the URL to prevent caching problems.
313 // So the URL contains this revision number as itemid but a 0 is always stored in the files table.
314 // In order to get the proper hash, a callback should be done (looking for those exceptions).
315 $pathdata = component_callback($component, 'get_path_from_pluginfile', [$filearea, $parts], null);
316 if (null === $pathdata) {
317 // Look for the components and fileareas which have empty itemid defined in xxx_pluginfile.
318 $hasnullitemid = false;
319 $hasnullitemid = $hasnullitemid || ($component === 'user' && ($filearea === 'private' || $filearea === 'profile'));
320 $hasnullitemid = $hasnullitemid || ($component === 'mod' && $filearea === 'intro');
321 $hasnullitemid = $hasnullitemid || ($component === 'course' &&
322 ($filearea === 'summary' || $filearea === 'overviewfiles'));
323 $hasnullitemid = $hasnullitemid || ($component === 'coursecat' && $filearea === 'description');
324 $hasnullitemid = $hasnullitemid || ($component === 'backup' &&
325 ($filearea === 'course' || $filearea === 'activity' || $filearea === 'automated'));
326 if ($hasnullitemid) {
327 $itemid = 0;
328 } else {
329 $itemid = array_shift($parts);
330 }
331
332 if (empty($parts)) {
333 $filepath = '/';
334 } else {
335 $filepath = '/' . implode('/', $parts) . '/';
336 }
337 } else {
338 // The itemid and filepath have been returned by the component callback.
339 [
340 'itemid' => $itemid,
341 'filepath' => $filepath,
342 ] = $pathdata;
343 }
344
345 $fs = get_file_storage();
346 return $fs->get_pathname_hash($contextid, $component, $filearea, $itemid, $filepath, $filename);
347 }
348
349 /**
350 * Store an H5P file
351 *
352 * @param stored_file $file Moodle file instance
353 * @param stdClass $config Button options config.
354 *
355 * @return int|false The H5P identifier or false if it's not a valid H5P package.
356 */
357 private function save_h5p($file, \stdClass $config) : int {
358 // This may take a long time.
359 \core_php_time_limit::raise();
360
361 $path = $this->core->fs->getTmpPath();
362 $this->core->h5pF->getUploadedH5pFolderPath($path);
363 // Add manually the extension to the file to avoid the validation fails.
364 $path .= '.h5p';
365 $this->core->h5pF->getUploadedH5pPath($path);
366
367 // Copy the .h5p file to the temporary folder.
368 $file->copy_content_to($path);
369
370 // Check if the h5p file is valid before saving it.
371 $h5pvalidator = \core_h5p\framework::instance('validator');
372 if ($h5pvalidator->isValidPackage(false, false)) {
373 $h5pstorage = \core_h5p\framework::instance('storage');
374
375 $options = ['disable' => $this->get_display_options($config)];
376 $content = [
377 'pathnamehash' => $file->get_pathnamehash(),
378 'contenthash' => $file->get_contenthash(),
379 ];
380
381 $h5pstorage->savePackage($content, null, false, $options);
382 return $h5pstorage->contentId;
383 }
384
385 return false;
386 }
387
388 /**
389 * Get the representation of display options as int.
390 * @param stdClass $config Button options config.
391 *
392 * @return int The representation of display options as int.
393 */
394 private function get_display_options(\stdClass $config) : int {
395 $export = isset($config->export) ? $config->export : 0;
396 $embed = isset($config->embed) ? $config->embed : 0;
397 $copyright = isset($config->copyright) ? $config->copyright : 0;
398 $frame = ($export || $embed || $copyright);
399 if (!$frame) {
400 $frame = isset($config->frame) ? $config->frame : 0;
401 }
402
403 $disableoptions = [
9e67f5e3
AN
404 core::DISPLAY_OPTION_FRAME => $frame,
405 core::DISPLAY_OPTION_DOWNLOAD => $export,
406 core::DISPLAY_OPTION_EMBED => $embed,
407 core::DISPLAY_OPTION_COPYRIGHT => $copyright,
35b62d00
SA
408 ];
409
410 return $this->core->getStorableDisplayOptions($disableoptions, 0);
411 }
412
413 /**
414 * Delete an H5P package.
415 *
416 * @param stdClass $content The H5P package to delete.
417 */
418 private function delete_h5p(\stdClass $content) {
419 $h5pstorage = \core_h5p\framework::instance('storage');
420 // Add an empty slug to the content if it's not defined, because the H5P library requires this field exists.
421 // It's not used when deleting a package, so the real slug value is not required at this point.
422 $content->slug = $content->slug ?? '';
423 $h5pstorage->deletePackage( (array) $content);
424 }
425
426 /**
427 * Export path for settings
428 *
429 * @param bool $downloadenabled Whether the option to export the H5P content is enabled.
430 *
431 * @return string The URL of the exported file.
432 */
433 private function get_export_settings(bool $downloadenabled) : string {
434
435 if ( ! $downloadenabled) {
436 return '';
437 }
438
439 $systemcontext = \context_system::instance();
440 $slug = $this->content['slug'] ? $this->content['slug'] . '-' : '';
441 $url = \moodle_url::make_pluginfile_url(
442 $systemcontext->id,
443 \core_h5p\file_storage::COMPONENT,
444 \core_h5p\file_storage::EXPORT_FILEAREA,
445 '',
446 '',
447 "{$slug}{$this->content['id']}.h5p"
448 );
449
450 return $url->out();
451 }
452
453 /**
454 * Get a query string with the theme revision number to include at the end
455 * of URLs. This is used to force the browser to reload the asset when the
456 * theme caches are cleared.
457 *
458 * @return string
459 */
460 private function get_cache_buster() : string {
461 global $CFG;
462 return '?ver=' . $CFG->themerev;
463 }
464
465 /**
466 * Get the identifier for the H5P content, to be used in the arrays as index.
467 *
468 * @return string The identifier.
469 */
470 private function get_cid() : string {
471 return 'cid-' . $this->h5pid;
472 }
473
474 /**
475 * Get the core H5P assets, including all core H5P JavaScript and CSS.
476 *
477 * @return Array core H5P assets.
478 */
479 private function get_assets() : array {
480 global $CFG;
481
482 // Get core settings.
483 $settings = $this->get_core_settings();
484 $settings['core'] = [
485 'styles' => [],
486 'scripts' => []
487 ];
488 $settings['loadedJs'] = [];
489 $settings['loadedCss'] = [];
490
491 // Make sure files are reloaded for each plugin update.
492 $cachebuster = $this->get_cache_buster();
493
494 // Use relative URL to support both http and https.
495 $liburl = $CFG->wwwroot . '/lib/h5p/';
496 $relpath = '/' . preg_replace('/^[^:]+:\/\/[^\/]+\//', '', $liburl);
497
498 // Add core stylesheets.
9e67f5e3 499 foreach (core::$styles as $style) {
35b62d00
SA
500 $settings['core']['styles'][] = $relpath . $style . $cachebuster;
501 $this->cssrequires[] = new \moodle_url($liburl . $style . $cachebuster);
502 }
503 // Add core JavaScript.
9e67f5e3
AN
504 foreach (core::get_scripts() as $script) {
505 $settings['core']['scripts'][] = $script->out(false);
506 $this->jsrequires[] = $script;
35b62d00
SA
507 }
508
509 $cid = $this->get_cid();
510 // The filterParameters function should be called before getting the dependencyfiles because it rebuild content
511 // dependency cache and export file.
512 $settings['contents'][$cid]['jsonContent'] = $this->core->filterParameters($this->content);
513
514 $files = $this->get_dependency_files();
515 if ($this->embedtype === 'div') {
516 $systemcontext = \context_system::instance();
517 $h5ppath = "/pluginfile.php/{$systemcontext->id}/core_h5p";
518
519 // Schedule JavaScripts for loading through Moodle.
520 foreach ($files['scripts'] as $script) {
521 $url = $script->path . $script->version;
522
523 // Add URL prefix if not external.
524 $isexternal = strpos($script->path, '://');
525 if ($isexternal === false) {
526 $url = $h5ppath . $url;
527 }
528 $settings['loadedJs'][] = $url;
529 $this->jsrequires[] = new \moodle_url($isexternal ? $url : $CFG->wwwroot . $url);
530 }
531
532 // Schedule stylesheets for loading through Moodle.
533 foreach ($files['styles'] as $style) {
534 $url = $style->path . $style->version;
535
536 // Add URL prefix if not external.
537 $isexternal = strpos($style->path, '://');
538 if ($isexternal === false) {
539 $url = $h5ppath . $url;
540 }
541 $settings['loadedCss'][] = $url;
542 $this->cssrequires[] = new \moodle_url($isexternal ? $url : $CFG->wwwroot . $url);
543 }
544
545 } else {
546 // JavaScripts and stylesheets will be loaded through h5p.js.
547 $settings['contents'][$cid]['scripts'] = $this->core->getAssetsUrls($files['scripts']);
548 $settings['contents'][$cid]['styles'] = $this->core->getAssetsUrls($files['styles']);
549 }
550 return $settings;
551 }
552
553 /**
554 * Get the settings needed by the H5P library.
555 *
556 * @return array The settings.
557 */
558 private function get_core_settings() : array {
559 global $CFG;
560
561 $basepath = $CFG->wwwroot . '/';
562 $systemcontext = \context_system::instance();
563
564 // Generate AJAX paths.
565 $ajaxpaths = [];
566 $ajaxpaths['xAPIResult'] = '';
567 $ajaxpaths['contentUserData'] = '';
568
569 $settings = array(
570 'baseUrl' => $basepath,
571 'url' => "{$basepath}pluginfile.php/{$systemcontext->instanceid}/core_h5p",
572 'urlLibraries' => "{$basepath}pluginfile.php/{$systemcontext->id}/core_h5p/libraries",
573 'postUserStatistics' => false,
574 'ajax' => $ajaxpaths,
575 'saveFreq' => false,
576 'siteUrl' => $CFG->wwwroot,
577 'l10n' => array('H5P' => $this->core->getLocalization()),
578 'user' => [],
579 'hubIsEnabled' => false,
580 'reportingIsEnabled' => false,
581 'crossorigin' => null,
582 'libraryConfig' => $this->core->h5pF->getLibraryConfig(),
583 'pluginCacheBuster' => $this->get_cache_buster(),
584 'libraryUrl' => $basepath . 'lib/h5p/js',
9e67f5e3 585 'moodleLibraryPaths' => $this->core->get_dependency_roots($this->h5pid),
35b62d00
SA
586 );
587
588 return $settings;
589 }
590
591 /**
592 * Finds library dependencies of view
593 *
594 * @return array Files that the view has dependencies to
595 */
596 private function get_dependency_files() : array {
597 $preloadeddeps = $this->core->loadContentDependencies($this->h5pid, 'preloaded');
598 $files = $this->core->getDependenciesFiles($preloadeddeps);
599
600 return $files;
601 }
602
603 /**
604 * Resizing script for settings
605 *
606 * @return string The HTML code with the resize script.
607 */
608 private function get_resize_code() : string {
609 global $OUTPUT;
610
611 $template = new \stdClass();
612 $template->resizeurl = new \moodle_url('/lib/h5p/js/h5p-resizer.js');
613
614 return $OUTPUT->render_from_template('core_h5p/h5presize', $template);
615 }
616
617 /**
618 * Embed code for settings
619 *
620 * @param string $url The URL of the .h5p file.
621 * @param bool $embedenabled Whether the option to embed the H5P content is enabled.
622 *
623 * @return string The HTML code to reuse this H5P content in a different place.
624 */
625 private function get_embed_code(string $url, bool $embedenabled) : string {
626 global $OUTPUT;
627
628 if ( ! $embedenabled) {
629 return '';
630 }
631
632 $template = new \stdClass();
633 $template->embedurl = self::get_embed_url($url)->out();
634
635 return $OUTPUT->render_from_template('core_h5p/h5pembed', $template);
636 }
637
638 /**
639 * Get the encoded URL for embeding this H5P content.
640 * @param string $url The URL of the .h5p file.
641 *
642 * @return \moodle_url The embed URL.
643 */
644 public static function get_embed_url(string $url) : \moodle_url {
645 return new \moodle_url('/h5p/embed.php', ['url' => $url]);
646 }
647}