MDL-67814 core_h5p: moved common methods from player to helper class
[moodle.git] / h5p / classes / helper.php
CommitLineData
5a266a57
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 * 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
25namespace core_h5p;
26
a0ce8f87
VDF
27use context_system;
28use core_h5p\local\library\autoloader;
29
5a266a57
SA
30defined('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 */
38class 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();
1c66ef98 57 $core->h5pF->set_file($file);
5a266a57
SA
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 $h5pstorage->savePackage($content, null, $skipcontent, $options);
79
80 return $h5pstorage->contentId;
81 }
5a266a57
SA
82 return false;
83 }
84
85
86 /**
87 * Get the representation of display options as int.
88 *
89 * @param core $core The \core_h5p\core object
90 * @param stdClass $config Button options config
91 *
92 * @return int The representation of display options as int
93 */
94 public static function get_display_options(core $core, \stdClass $config): int {
95 $export = isset($config->export) ? $config->export : 0;
96 $embed = isset($config->embed) ? $config->embed : 0;
97 $copyright = isset($config->copyright) ? $config->copyright : 0;
98 $frame = ($export || $embed || $copyright);
99 if (!$frame) {
100 $frame = isset($config->frame) ? $config->frame : 0;
101 }
102
103 $disableoptions = [
104 core::DISPLAY_OPTION_FRAME => $frame,
105 core::DISPLAY_OPTION_DOWNLOAD => $export,
106 core::DISPLAY_OPTION_EMBED => $embed,
107 core::DISPLAY_OPTION_COPYRIGHT => $copyright,
108 ];
109
110 return $core->getStorableDisplayOptions($disableoptions, 0);
111 }
112
f3c7e00f
FR
113 /**
114 * Convert the int representation of display options into stdClass
115 *
116 * @param core $core The \core_h5p\core object
117 * @param int $displayint integer value representing display options
118 *
119 * @return int The representation of display options as int
120 */
121 public static function decode_display_options(core $core, int $displayint = null): \stdClass {
122 $config = new \stdClass();
123 if ($displayint === null) {
124 $displayint = self::get_display_options($core, $config);
125 }
126 $displayarray = $core->getDisplayOptionsForEdit($displayint);
127 $config->export = $displayarray[core::DISPLAY_OPTION_DOWNLOAD] ?? 0;
128 $config->embed = $displayarray[core::DISPLAY_OPTION_EMBED] ?? 0;
129 $config->copyright = $displayarray[core::DISPLAY_OPTION_COPYRIGHT] ?? 0;
130 return $config;
131 }
132
5a266a57
SA
133 /**
134 * Checks if the author of the .h5p file is "trustable". If the file hasn't been uploaded by a user with the
135 * required capability, the content won't be deployed.
136 *
137 * @param stored_file $file The .h5p file to be deployed
138 * @return bool Returns true if the file can be deployed, false otherwise.
139 */
140 public static function can_deploy_package(\stored_file $file): bool {
ab8f1c3b
AN
141 if (null === $file->get_userid()) {
142 // If there is no userid, it is owned by the system.
143 return true;
144 }
145
5a266a57
SA
146 $context = \context::instance_by_id($file->get_contextid());
147 if (has_capability('moodle/h5p:deploy', $context, $file->get_userid())) {
148 return true;
149 }
150
151 return false;
152 }
153
154 /**
155 * Checks if the content-type libraries can be upgraded.
156 * The H5P content-type libraries can only be upgraded if the author of the .h5p file can manage content-types or if all the
157 * content-types exist, to avoid users without the required capability to upload malicious content.
158 *
159 * @param stored_file $file The .h5p file to be deployed
160 * @return bool Returns true if the content-type libraries can be created/updated, false otherwise.
161 */
162 public static function can_update_library(\stored_file $file): bool {
ab8f1c3b
AN
163 if (null === $file->get_userid()) {
164 // If there is no userid, it is owned by the system.
165 return true;
5a266a57
SA
166 }
167
5a266a57 168 // Check if the owner of the .h5p file has the capability to manage content-types.
ab8f1c3b 169 $context = \context::instance_by_id($file->get_contextid());
5a266a57
SA
170 if (has_capability('moodle/h5p:updatelibraries', $context, $file->get_userid())) {
171 return true;
172 }
173
174 return false;
175 }
176
177 /**
178 * Convenience to take a fixture test file and create a stored_file.
179 *
180 * @param string $filepath The filepath of the file
181 * @param int $userid The author of the file
182 * @param \context $context The context where the file will be created
183 * @return stored_file The file created
184 */
185 public static function create_fake_stored_file_from_path(string $filepath, int $userid = 0,
186 \context $context = null): \stored_file {
187 if (is_null($context)) {
a0ce8f87 188 $context = context_system::instance();
5a266a57
SA
189 }
190 $filerecord = [
191 'contextid' => $context->id,
192 'component' => 'core_h5p',
193 'filearea' => 'unittest',
194 'itemid' => rand(),
195 'filepath' => '/',
196 'filename' => basename($filepath),
197 ];
198 if (!is_null($userid)) {
199 $filerecord['userid'] = $userid;
200 }
201
202 $fs = get_file_storage();
203 return $fs->create_file_from_pathname($filerecord, $filepath);
204 }
205
4e7a035f
AA
206 /**
207 * Get information about different H5P tools and their status.
208 *
209 * @return array Data to render by the template
210 */
211 public static function get_h5p_tools_info(): array {
212 $tools = array();
213
214 // Getting information from available H5P tools one by one because their enabled/disabled options are totally different.
215 // Check the atto button status.
216 $link = \editor_atto\plugininfo\atto::get_manage_url();
217 $status = strpos(get_config('editor_atto', 'toolbar'), 'h5p') > -1;
218 $tools[] = self::convert_info_into_array('atto_h5p', $link, $status);
219
220 // Check the Display H5P filter status.
221 $link = \core\plugininfo\filter::get_manage_url();
a0ce8f87 222 $status = filter_get_active_state('displayh5p', context_system::instance()->id);
4e7a035f
AA
223 $tools[] = self::convert_info_into_array('filter_displayh5p', $link, $status);
224
225 // Check H5P scheduled task.
226 $link = '';
227 $status = 0;
228 $statusaction = '';
229 if ($task = \core\task\manager::get_scheduled_task('\core\task\h5p_get_content_types_task')) {
230 $status = !$task->get_disabled();
231 $link = new \moodle_url(
232 '/admin/tool/task/scheduledtasks.php',
233 array('action' => 'edit', 'task' => get_class($task))
234 );
235 if ($status && \tool_task\run_from_cli::is_runnable() && get_config('tool_task', 'enablerunnow')) {
236 $statusaction = \html_writer::link(
237 new \moodle_url('/admin/tool/task/schedule_task.php',
238 array('task' => get_class($task))),
239 get_string('runnow', 'tool_task'));
240 }
241 }
242 $tools[] = self::convert_info_into_array('task_h5p', $link, $status, $statusaction);
243
244 return $tools;
245 }
246
247 /**
248 * Convert information into needed mustache template data array
249 * @param string $tool The name of the tool
250 * @param \moodle_url $link The URL to management page
251 * @param int $status The current status of the tool
252 * @param string $statusaction A link to 'Run now' option for the task
253 * @return array
254 */
255 static private function convert_info_into_array(string $tool,
256 \moodle_url $link,
257 int $status,
258 string $statusaction = ''): array {
259
260 $statusclasses = array(
261 TEXTFILTER_DISABLED => 'badge badge-danger',
262 TEXTFILTER_OFF => 'badge badge-warning',
263 0 => 'badge badge-danger',
264 TEXTFILTER_ON => 'badge badge-success',
265 );
266
267 $statuschoices = array(
268 TEXTFILTER_DISABLED => get_string('disabled', 'admin'),
269 TEXTFILTER_OFF => get_string('offbutavailable', 'core_filters'),
270 0 => get_string('disabled', 'admin'),
271 1 => get_string('enabled', 'admin'),
272 );
273
274 return [
275 'tool' => get_string($tool, 'h5p'),
276 'tool_description' => get_string($tool . '_description', 'h5p'),
277 'link' => $link,
278 'status' => $statuschoices[$status],
279 'status_class' => $statusclasses[$status],
280 'status_action' => $statusaction,
281 ];
282 }
a0ce8f87
VDF
283
284 /**
285 * Get a query string with the theme revision number to include at the end
286 * of URLs. This is used to force the browser to reload the asset when the
287 * theme caches are cleared.
288 *
289 * @return string
290 */
291 public static function get_cache_buster(): string {
292 global $CFG;
293 return '?ver=' . $CFG->themerev;
294 }
295
296 /**
297 * Get the settings needed by the H5P library.
298 *
299 * @return array The settings.
300 */
301 public static function get_core_settings(): array {
302 global $CFG;
303
304 $basepath = $CFG->wwwroot . '/';
305 $systemcontext = context_system::instance();
306
307 // Generate AJAX paths.
308 $ajaxpaths = [];
309 $ajaxpaths['xAPIResult'] = '';
310 $ajaxpaths['contentUserData'] = '';
311
312 $factory = new factory();
313 $core = $factory->get_core();
314
315 $settings = array(
316 'baseUrl' => $basepath,
317 'url' => "{$basepath}pluginfile.php/{$systemcontext->instanceid}/core_h5p",
318 'urlLibraries' => "{$basepath}pluginfile.php/{$systemcontext->id}/core_h5p/libraries",
319 'postUserStatistics' => false,
320 'ajax' => $ajaxpaths,
321 'saveFreq' => false,
322 'siteUrl' => $CFG->wwwroot,
323 'l10n' => array('H5P' => $core->getLocalization()),
324 'user' => [],
325 'hubIsEnabled' => true,
326 'reportingIsEnabled' => false,
327 'crossorigin' => null,
328 'libraryConfig' => $core->h5pF->getLibraryConfig(),
329 'pluginCacheBuster' => self::get_cache_buster(),
330 'libraryUrl' => autoloader::get_h5p_core_library_url('core/js')
331 );
332
333 return $settings;
334 }
335
336 /**
337 * Get the core H5P assets, including all core H5P JavaScript and CSS.
338 *
339 * @return Array core H5P assets.
340 */
341 public static function get_core_assets(): array {
342 global $CFG, $PAGE;
343
344 // Get core settings.
345 $settings = self::get_core_settings();
346 $settings['core'] = [
347 'styles' => [],
348 'scripts' => []
349 ];
350 $settings['loadedJs'] = [];
351 $settings['loadedCss'] = [];
352
353 // Make sure files are reloaded for each plugin update.
354 $cachebuster = self::get_cache_buster();
355
356 // Use relative URL to support both http and https.
357 $liburl = autoloader::get_h5p_core_library_url()->out();
358 $relpath = '/' . preg_replace('/^[^:]+:\/\/[^\/]+\//', '', $liburl);
359
360 // Add core stylesheets.
361 foreach (core::$styles as $style) {
362 $settings['core']['styles'][] = $relpath . $style . $cachebuster;
363 $PAGE->requires->css(new \moodle_url($liburl . $style . $cachebuster));
364 }
365 // Add core JavaScript.
366 foreach (core::get_scripts() as $script) {
367 $settings['core']['scripts'][] = $script->out(false);
368 $PAGE->requires->js($script, true);
369 }
370
371 return $settings;
372 }
373
374 /**
375 * Add required assets for displaying the editor.
376 *
377 * @param int $id Id of the content being edited. null for creating new content.
378 * @param string $mformid Id of Moodle form
379 *
380 * @return void
381 */
382 public static function add_editor_assets_to_page(?int $id = null, string $mformid = null): void {
383 global $PAGE, $CFG;
384
385 $libeditorpath = 'lib/h5peditor';
386
387 // Require classes from H5P third party library.
388 autoloader::register();
389
390 $context = context_system::instance();
391
392 $settings = self::get_core_assets();
393
394 // Use jQuery and styles from core.
395 $assets = array(
396 'css' => $settings['core']['styles'],
397 'js' => $settings['core']['scripts']
398 );
399
400 // Use relative URL to support both http and https.
401 $url = $CFG->wwwroot . '/'. $libeditorpath . '/';
402 $url = '/' . preg_replace('/^[^:]+:\/\/[^\/]+\//', '', $url);
403
404 // Make sure files are reloaded for each plugin update.
405 $cachebuster = self::get_cache_buster();
406
407 // Add editor styles.
408 foreach (H5peditor::$styles as $style) {
409 $assets['css'][] = $url . $style . $cachebuster;
410 }
411
412 // Add editor JavaScript.
413 foreach (H5peditor::$scripts as $script) {
414 // We do not want the creator of the iframe inside the iframe.
415 if ($script !== 'scripts/h5peditor-editor.js') {
416 $assets['js'][] = $url . $script . $cachebuster;
417 }
418 }
419
420 // Add JavaScript with library framework integration (editor part).
421 $PAGE->requires->js(new moodle_url('/'. $libeditorpath .'/scripts/h5peditor-editor.js' . $cachebuster), true);
422 $PAGE->requires->js(new moodle_url('/'. $libeditorpath .'/scripts/h5peditor-init.js' . $cachebuster), true);
423 $PAGE->requires->js(new moodle_url('/h5p/editor.js' . $cachebuster), true);
424
425 // Add translations.
426 $language = framework::get_language();
427 $languagescript = "language/{$language}.js";
428
429 if (!file_exists("{$CFG->dirroot}/" . $libeditorpath . "/{$languagescript}")) {
430 $languagescript = 'language/en.js';
431 }
432 $PAGE->requires->js(new moodle_url('/' . $libeditorpath .'/' . $languagescript . $cachebuster), true);
433
434 // Add JavaScript settings.
435 $root = $CFG->wwwroot;
436 $filespathbase = "{$root}/pluginfile.php/{$context->id}/core_h5p/";
437
438 $factory = new factory();
439 $contentvalidator = $factory->get_content_validator();
440
441 $editorajaxtoken = H5PCore::createToken(editor_ajax::EDITOR_AJAX_TOKEN);
442 $settings['editor'] = array(
443 'filesPath' => $filespathbase . 'editor',
444 'fileIcon' => array(
445 'path' => $url . 'images/binary-file.png',
446 'width' => 50,
447 'height' => 50,
448 ),
449 'ajaxPath' => $CFG->wwwroot . '/h5p/' . "ajax.php?contextId={$context->id}&token={$editorajaxtoken}&action=",
450 'libraryUrl' => $url,
451 'copyrightSemantics' => $contentvalidator->getCopyrightSemantics(),
452 'metadataSemantics' => $contentvalidator->getMetadataSemantics(),
453 'assets' => $assets,
454 'apiVersion' => H5PCore::$coreApi,
455 'language' => $language,
456 'formId' => $mformid,
457 );
458
459 if ($id !== null) {
460 $settings['editor']['nodeVersionId'] = $id;
461
462 // Override content URL.
463 $contenturl = "{$root}/pluginfile.php/{$context->id}/core_h5p/content/{$id}";
464 $settings['contents']['cid-' . $id]['contentUrl'] = $contenturl;
465 }
466
467 $PAGE->requires->data_for_js('H5PIntegration', $settings, true);
468 }
5a266a57 469}