MDL-67795 h5p: move methods from player to helper
[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
153c4562
SA
86 /**
87 * Get the error messages stored in our H5P framework.
88 *
89 * @param stdClass $messages The error, exception and info messages, raised while preparing and running an H5P content.
90 * @param factory $factory The \core_h5p\factory object
91 *
92 * @return stdClass with framework error messages.
93 */
94 public static function get_messages(\stdClass $messages, factory $factory): \stdClass {
95 $core = $factory->get_core();
96
97 // Check if there are some errors and store them in $messages.
98 if (empty($messages->error)) {
99 $messages->error = $core->h5pF->getMessages('error') ?: false;
100 } else {
101 $messages->error = array_merge($messages->error, $core->h5pF->getMessages('error'));
102 }
103
104 if (empty($messages->info)) {
105 $messages->info = $core->h5pF->getMessages('info') ?: false;
106 } else {
107 $messages->info = array_merge($messages->info, $core->h5pF->getMessages('info'));
108 }
109
110 return $messages;
111 }
112
5a266a57
SA
113 /**
114 * Get the representation of display options as int.
115 *
116 * @param core $core The \core_h5p\core object
117 * @param stdClass $config Button options config
118 *
119 * @return int The representation of display options as int
120 */
121 public static function get_display_options(core $core, \stdClass $config): int {
122 $export = isset($config->export) ? $config->export : 0;
123 $embed = isset($config->embed) ? $config->embed : 0;
124 $copyright = isset($config->copyright) ? $config->copyright : 0;
125 $frame = ($export || $embed || $copyright);
126 if (!$frame) {
127 $frame = isset($config->frame) ? $config->frame : 0;
128 }
129
130 $disableoptions = [
131 core::DISPLAY_OPTION_FRAME => $frame,
132 core::DISPLAY_OPTION_DOWNLOAD => $export,
133 core::DISPLAY_OPTION_EMBED => $embed,
134 core::DISPLAY_OPTION_COPYRIGHT => $copyright,
135 ];
136
137 return $core->getStorableDisplayOptions($disableoptions, 0);
138 }
139
f3c7e00f
FR
140 /**
141 * Convert the int representation of display options into stdClass
142 *
143 * @param core $core The \core_h5p\core object
144 * @param int $displayint integer value representing display options
145 *
146 * @return int The representation of display options as int
147 */
148 public static function decode_display_options(core $core, int $displayint = null): \stdClass {
149 $config = new \stdClass();
150 if ($displayint === null) {
151 $displayint = self::get_display_options($core, $config);
152 }
153 $displayarray = $core->getDisplayOptionsForEdit($displayint);
154 $config->export = $displayarray[core::DISPLAY_OPTION_DOWNLOAD] ?? 0;
155 $config->embed = $displayarray[core::DISPLAY_OPTION_EMBED] ?? 0;
156 $config->copyright = $displayarray[core::DISPLAY_OPTION_COPYRIGHT] ?? 0;
157 return $config;
158 }
159
5a266a57
SA
160 /**
161 * Checks if the author of the .h5p file is "trustable". If the file hasn't been uploaded by a user with the
162 * required capability, the content won't be deployed.
163 *
164 * @param stored_file $file The .h5p file to be deployed
165 * @return bool Returns true if the file can be deployed, false otherwise.
166 */
167 public static function can_deploy_package(\stored_file $file): bool {
ab8f1c3b
AN
168 if (null === $file->get_userid()) {
169 // If there is no userid, it is owned by the system.
170 return true;
171 }
172
5a266a57
SA
173 $context = \context::instance_by_id($file->get_contextid());
174 if (has_capability('moodle/h5p:deploy', $context, $file->get_userid())) {
175 return true;
176 }
177
178 return false;
179 }
180
181 /**
182 * Checks if the content-type libraries can be upgraded.
183 * The H5P content-type libraries can only be upgraded if the author of the .h5p file can manage content-types or if all the
184 * content-types exist, to avoid users without the required capability to upload malicious content.
185 *
186 * @param stored_file $file The .h5p file to be deployed
187 * @return bool Returns true if the content-type libraries can be created/updated, false otherwise.
188 */
189 public static function can_update_library(\stored_file $file): bool {
ab8f1c3b
AN
190 if (null === $file->get_userid()) {
191 // If there is no userid, it is owned by the system.
192 return true;
5a266a57
SA
193 }
194
5a266a57 195 // Check if the owner of the .h5p file has the capability to manage content-types.
ab8f1c3b 196 $context = \context::instance_by_id($file->get_contextid());
5a266a57
SA
197 if (has_capability('moodle/h5p:updatelibraries', $context, $file->get_userid())) {
198 return true;
199 }
200
201 return false;
202 }
203
204 /**
205 * Convenience to take a fixture test file and create a stored_file.
206 *
207 * @param string $filepath The filepath of the file
208 * @param int $userid The author of the file
209 * @param \context $context The context where the file will be created
210 * @return stored_file The file created
211 */
212 public static function create_fake_stored_file_from_path(string $filepath, int $userid = 0,
213 \context $context = null): \stored_file {
214 if (is_null($context)) {
a0ce8f87 215 $context = context_system::instance();
5a266a57
SA
216 }
217 $filerecord = [
218 'contextid' => $context->id,
219 'component' => 'core_h5p',
220 'filearea' => 'unittest',
221 'itemid' => rand(),
222 'filepath' => '/',
223 'filename' => basename($filepath),
224 ];
225 if (!is_null($userid)) {
226 $filerecord['userid'] = $userid;
227 }
228
229 $fs = get_file_storage();
230 return $fs->create_file_from_pathname($filerecord, $filepath);
231 }
232
4e7a035f
AA
233 /**
234 * Get information about different H5P tools and their status.
235 *
236 * @return array Data to render by the template
237 */
238 public static function get_h5p_tools_info(): array {
239 $tools = array();
240
241 // Getting information from available H5P tools one by one because their enabled/disabled options are totally different.
242 // Check the atto button status.
243 $link = \editor_atto\plugininfo\atto::get_manage_url();
244 $status = strpos(get_config('editor_atto', 'toolbar'), 'h5p') > -1;
245 $tools[] = self::convert_info_into_array('atto_h5p', $link, $status);
246
247 // Check the Display H5P filter status.
248 $link = \core\plugininfo\filter::get_manage_url();
a0ce8f87 249 $status = filter_get_active_state('displayh5p', context_system::instance()->id);
4e7a035f
AA
250 $tools[] = self::convert_info_into_array('filter_displayh5p', $link, $status);
251
252 // Check H5P scheduled task.
253 $link = '';
254 $status = 0;
255 $statusaction = '';
256 if ($task = \core\task\manager::get_scheduled_task('\core\task\h5p_get_content_types_task')) {
257 $status = !$task->get_disabled();
258 $link = new \moodle_url(
259 '/admin/tool/task/scheduledtasks.php',
260 array('action' => 'edit', 'task' => get_class($task))
261 );
262 if ($status && \tool_task\run_from_cli::is_runnable() && get_config('tool_task', 'enablerunnow')) {
263 $statusaction = \html_writer::link(
264 new \moodle_url('/admin/tool/task/schedule_task.php',
265 array('task' => get_class($task))),
266 get_string('runnow', 'tool_task'));
267 }
268 }
269 $tools[] = self::convert_info_into_array('task_h5p', $link, $status, $statusaction);
270
271 return $tools;
272 }
273
274 /**
275 * Convert information into needed mustache template data array
276 * @param string $tool The name of the tool
277 * @param \moodle_url $link The URL to management page
278 * @param int $status The current status of the tool
279 * @param string $statusaction A link to 'Run now' option for the task
280 * @return array
281 */
282 static private function convert_info_into_array(string $tool,
283 \moodle_url $link,
284 int $status,
285 string $statusaction = ''): array {
286
287 $statusclasses = array(
288 TEXTFILTER_DISABLED => 'badge badge-danger',
289 TEXTFILTER_OFF => 'badge badge-warning',
290 0 => 'badge badge-danger',
291 TEXTFILTER_ON => 'badge badge-success',
292 );
293
294 $statuschoices = array(
295 TEXTFILTER_DISABLED => get_string('disabled', 'admin'),
296 TEXTFILTER_OFF => get_string('offbutavailable', 'core_filters'),
297 0 => get_string('disabled', 'admin'),
298 1 => get_string('enabled', 'admin'),
299 );
300
301 return [
302 'tool' => get_string($tool, 'h5p'),
303 'tool_description' => get_string($tool . '_description', 'h5p'),
304 'link' => $link,
305 'status' => $statuschoices[$status],
306 'status_class' => $statusclasses[$status],
307 'status_action' => $statusaction,
308 ];
309 }
a0ce8f87
VDF
310
311 /**
312 * Get a query string with the theme revision number to include at the end
313 * of URLs. This is used to force the browser to reload the asset when the
314 * theme caches are cleared.
315 *
316 * @return string
317 */
318 public static function get_cache_buster(): string {
319 global $CFG;
320 return '?ver=' . $CFG->themerev;
321 }
322
323 /**
324 * Get the settings needed by the H5P library.
325 *
326 * @return array The settings.
327 */
328 public static function get_core_settings(): array {
2ac1d9ae 329 global $CFG, $USER;
a0ce8f87
VDF
330
331 $basepath = $CFG->wwwroot . '/';
332 $systemcontext = context_system::instance();
333
334 // Generate AJAX paths.
335 $ajaxpaths = [];
336 $ajaxpaths['xAPIResult'] = '';
337 $ajaxpaths['contentUserData'] = '';
338
339 $factory = new factory();
340 $core = $factory->get_core();
341
0a05ca36
SA
342 // When there is a logged in user, her information will be passed to the player. It will be used for tracking.
343 $usersettings = isloggedin() ? ['name' => $USER->username, 'mail' => $USER->email] : [];
a0ce8f87
VDF
344 $settings = array(
345 'baseUrl' => $basepath,
346 'url' => "{$basepath}pluginfile.php/{$systemcontext->instanceid}/core_h5p",
347 'urlLibraries' => "{$basepath}pluginfile.php/{$systemcontext->id}/core_h5p/libraries",
348 'postUserStatistics' => false,
349 'ajax' => $ajaxpaths,
350 'saveFreq' => false,
351 'siteUrl' => $CFG->wwwroot,
352 'l10n' => array('H5P' => $core->getLocalization()),
0a05ca36 353 'user' => $usersettings,
a0ce8f87
VDF
354 'hubIsEnabled' => true,
355 'reportingIsEnabled' => false,
356 'crossorigin' => null,
357 'libraryConfig' => $core->h5pF->getLibraryConfig(),
358 'pluginCacheBuster' => self::get_cache_buster(),
359 'libraryUrl' => autoloader::get_h5p_core_library_url('core/js')
360 );
361
362 return $settings;
363 }
364
365 /**
366 * Get the core H5P assets, including all core H5P JavaScript and CSS.
367 *
368 * @return Array core H5P assets.
369 */
370 public static function get_core_assets(): array {
371 global $CFG, $PAGE;
372
373 // Get core settings.
374 $settings = self::get_core_settings();
375 $settings['core'] = [
376 'styles' => [],
377 'scripts' => []
378 ];
379 $settings['loadedJs'] = [];
380 $settings['loadedCss'] = [];
381
382 // Make sure files are reloaded for each plugin update.
383 $cachebuster = self::get_cache_buster();
384
385 // Use relative URL to support both http and https.
386 $liburl = autoloader::get_h5p_core_library_url()->out();
387 $relpath = '/' . preg_replace('/^[^:]+:\/\/[^\/]+\//', '', $liburl);
388
389 // Add core stylesheets.
390 foreach (core::$styles as $style) {
391 $settings['core']['styles'][] = $relpath . $style . $cachebuster;
392 $PAGE->requires->css(new \moodle_url($liburl . $style . $cachebuster));
393 }
394 // Add core JavaScript.
395 foreach (core::get_scripts() as $script) {
396 $settings['core']['scripts'][] = $script->out(false);
397 $PAGE->requires->js($script, true);
398 }
399
400 return $settings;
401 }
5a266a57 402}