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