Proyectos de Subversion Moodle

Rev

Rev 11 | | Comparar con el anterior | Ultima modificación | Ver Log |

Rev Autor Línea Nro. Línea
1 efrain 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
 
25
namespace core_h5p;
26
 
27
use context_system;
28
use core_h5p\local\library\autoloader;
11 efrain 29
use core_user;
1 efrain 30
 
31
defined('MOODLE_INTERNAL') || die();
32
 
33
/**
34
 * Helper class for the H5P area.
35
 *
36
 * @copyright  2019 Sara Arjona <sara@moodle.com>
37
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
38
 */
39
class helper {
40
 
41
    /**
42
     * Store an H5P file.
43
     *
44
     * @param factory $factory The \core_h5p\factory object
45
     * @param \stored_file $file Moodle file instance
46
     * @param \stdClass $config Button options config
47
     * @param bool $onlyupdatelibs Whether new libraries can be installed or only the existing ones can be updated
48
     * @param bool $skipcontent Should the content be skipped (so only the libraries will be saved)?
49
     *
50
     * @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
51
     */
52
    public static function save_h5p(factory $factory, \stored_file $file, \stdClass $config, bool $onlyupdatelibs = false,
53
            bool $skipcontent = false) {
54
 
55
        if (api::is_valid_package($file, $onlyupdatelibs, $skipcontent, $factory, false)) {
56
            $core = $factory->get_core();
57
            $h5pvalidator = $factory->get_validator();
58
            $h5pstorage = $factory->get_storage();
59
 
60
            $content = [
61
                'pathnamehash' => $file->get_pathnamehash(),
62
                'contenthash' => $file->get_contenthash(),
63
            ];
64
            $options = ['disable' => self::get_display_options($core, $config)];
65
 
66
            // Add the 'title' if exists from 'h5p.json' data to keep it for the editor.
67
            if (!empty($h5pvalidator->h5pC->mainJsonData['title'])) {
68
                $content['title'] = $h5pvalidator->h5pC->mainJsonData['title'];
69
            }
70
 
71
            // If exists, add the metadata from 'h5p.json' to avoid loosing this information.
72
            $data = $h5pvalidator->h5pC->mainJsonData;
73
            if (!empty($data)) {
74
                // The metadata fields are defined in 'joubel/core/h5p-metadata.class.php'.
75
                $metadatafields = [
76
                    'title',
77
                    'a11yTitle',
78
                    'changes',
79
                    'authors',
80
                    'source',
81
                    'license',
82
                    'licenseVersion',
83
                    'licenseExtras',
84
                    'authorComments',
85
                    'yearFrom',
86
                    'yearTo',
87
                    'defaultLanguage',
88
                ];
89
                $content['metadata'] = array_reduce($metadatafields, function ($array, $field) use ($data) {
90
                    if (array_key_exists($field, $data)) {
91
                        $array[$field] = $data[$field];
92
                    }
93
                    return $array;
94
                }, []);
95
            }
96
            $h5pstorage->savePackage($content, null, $skipcontent, $options);
97
 
98
            return $h5pstorage->contentId;
99
        }
100
 
101
        return false;
102
    }
103
 
104
    /**
105
     * Get the error messages stored in our H5P framework.
106
     *
107
     * @param \stdClass $messages The error, exception and info messages, raised while preparing and running an H5P content.
108
     * @param factory $factory The \core_h5p\factory object
109
     *
110
     * @return \stdClass with framework error messages.
111
     */
112
    public static function get_messages(\stdClass $messages, factory $factory): \stdClass {
113
        $core = $factory->get_core();
114
 
115
        // Check if there are some errors and store them in $messages.
116
        if (empty($messages->error)) {
117
            $messages->error = $core->h5pF->getMessages('error') ?: false;
118
        } else {
119
            $messages->error = array_merge($messages->error, $core->h5pF->getMessages('error'));
120
        }
121
 
122
        if (empty($messages->info)) {
123
            $messages->info = $core->h5pF->getMessages('info') ?: false;
124
        } else {
125
            $messages->info = array_merge($messages->info, $core->h5pF->getMessages('info'));
126
        }
127
 
128
        return $messages;
129
    }
130
 
131
    /**
132
     * Get the representation of display options as int.
133
     *
134
     * @param core $core The \core_h5p\core object
135
     * @param stdClass $config Button options config
136
     *
137
     * @return int The representation of display options as int
138
     */
139
    public static function get_display_options(core $core, \stdClass $config): int {
140
        $export = isset($config->export) ? $config->export : 0;
141
        $embed = isset($config->embed) ? $config->embed : 0;
142
        $copyright = isset($config->copyright) ? $config->copyright : 0;
143
        $frame = ($export || $embed || $copyright);
144
        if (!$frame) {
145
            $frame = isset($config->frame) ? $config->frame : 0;
146
        }
147
 
148
        $disableoptions = [
149
            core::DISPLAY_OPTION_FRAME     => $frame,
150
            core::DISPLAY_OPTION_DOWNLOAD  => $export,
151
            core::DISPLAY_OPTION_EMBED     => $embed,
152
            core::DISPLAY_OPTION_COPYRIGHT => $copyright,
153
        ];
154
 
155
        return $core->getStorableDisplayOptions($disableoptions, 0);
156
    }
157
 
158
    /**
159
     * Convert the int representation of display options into stdClass
160
     *
161
     * @param core $core The \core_h5p\core object
162
     * @param int $displayint integer value representing display options
163
     *
164
     * @return int The representation of display options as int
165
     */
1441 ariadna 166
    public static function decode_display_options(core $core, ?int $displayint = null): \stdClass {
1 efrain 167
        $config = new \stdClass();
168
        if ($displayint === null) {
169
            $displayint = self::get_display_options($core, $config);
170
        }
171
        $displayarray = $core->getDisplayOptionsForEdit($displayint);
172
        $config->export = $displayarray[core::DISPLAY_OPTION_DOWNLOAD] ?? 0;
173
        $config->embed = $displayarray[core::DISPLAY_OPTION_EMBED] ?? 0;
174
        $config->copyright = $displayarray[core::DISPLAY_OPTION_COPYRIGHT] ?? 0;
175
        return $config;
176
    }
177
 
178
    /**
179
     * Checks if the author of the .h5p file is "trustable". If the file hasn't been uploaded by a user with the
11 efrain 180
     * required capability, the content won't be deployed, unless the user has been deleted, in this
181
     * case we check the capability against current user.
1 efrain 182
     *
183
     * @param  stored_file $file The .h5p file to be deployed
184
     * @return bool Returns true if the file can be deployed, false otherwise.
185
     */
186
    public static function can_deploy_package(\stored_file $file): bool {
11 efrain 187
        $userid = $file->get_userid();
188
        if (null === $userid) {
1 efrain 189
            // If there is no userid, it is owned by the system.
190
            return true;
191
        }
192
 
193
        $context = \context::instance_by_id($file->get_contextid());
11 efrain 194
        $fileuser = core_user::get_user($userid);
195
        if (empty($fileuser) || $fileuser->deleted) {
196
            $userid = null;
1 efrain 197
        }
11 efrain 198
        return has_capability('moodle/h5p:deploy', $context, $userid);
1 efrain 199
    }
200
 
201
    /**
202
     * Checks if the content-type libraries can be upgraded.
203
     * The H5P content-type libraries can only be upgraded if the author of the .h5p file can manage content-types or if all the
11 efrain 204
     * content-types exist, to avoid users without the required capability to upload malicious content. If user has been deleted
205
     * we check against current user.
1 efrain 206
     *
207
     * @param  stored_file $file The .h5p file to be deployed
208
     * @return bool Returns true if the content-type libraries can be created/updated, false otherwise.
209
     */
210
    public static function can_update_library(\stored_file $file): bool {
11 efrain 211
        $userid = $file->get_userid();
212
        if (null === $userid) {
1 efrain 213
            // If there is no userid, it is owned by the system.
214
            return true;
215
        }
216
        // Check if the owner of the .h5p file has the capability to manage content-types.
217
        $context = \context::instance_by_id($file->get_contextid());
11 efrain 218
        $fileuser = core_user::get_user($userid);
219
        if (empty($fileuser) || $fileuser->deleted) {
220
            $userid = null;
1 efrain 221
        }
222
 
11 efrain 223
        return has_capability('moodle/h5p:updatelibraries', $context, $userid);
1 efrain 224
    }
225
 
226
    /**
227
     * Convenience to take a fixture test file and create a stored_file.
228
     *
229
     * @param string $filepath The filepath of the file
230
     * @param  int   $userid  The author of the file
231
     * @param  \context $context The context where the file will be created
232
     * @return \stored_file The file created
233
     */
234
    public static function create_fake_stored_file_from_path(string $filepath, int $userid = 0,
1441 ariadna 235
            ?\context $context = null): \stored_file {
1 efrain 236
        if (is_null($context)) {
237
            $context = context_system::instance();
238
        }
239
        $filerecord = [
240
            'contextid' => $context->id,
241
            'component' => 'core_h5p',
242
            'filearea'  => 'unittest',
243
            'itemid'    => rand(),
244
            'filepath'  => '/',
245
            'filename'  => basename($filepath),
246
        ];
247
        if (!is_null($userid)) {
248
            $filerecord['userid'] = $userid;
249
        }
250
 
251
        $fs = get_file_storage();
252
        return $fs->create_file_from_pathname($filerecord, $filepath);
253
    }
254
 
255
    /**
256
     * Get information about different H5P tools and their status.
257
     *
258
     * @return array Data to render by the template
259
     */
260
    public static function get_h5p_tools_info(): array {
261
        $tools = array();
262
 
263
        // Getting information from available H5P tools one by one because their enabled/disabled options are totally different.
264
        // Check the Display H5P filter status.
265
        $link = \core\plugininfo\filter::get_manage_url();
266
        $status = filter_get_active_state('displayh5p', context_system::instance()->id);
267
        $tools[] = self::convert_info_into_array('filter_displayh5p', $link, $status);
268
 
269
        // Check H5P scheduled task.
270
        $link = '';
271
        $status = 0;
272
        $statusaction = '';
273
        if ($task = \core\task\manager::get_scheduled_task('\core\task\h5p_get_content_types_task')) {
274
            $status = !$task->get_disabled();
275
            $link = new \moodle_url(
276
                '/admin/tool/task/scheduledtasks.php',
277
                array('action' => 'edit', 'task' => get_class($task))
278
            );
279
            if ($status && \core\task\manager::is_runnable() && get_config('tool_task', 'enablerunnow')) {
280
                $statusaction = \html_writer::link(
281
                    new \moodle_url('/admin/tool/task/schedule_task.php',
282
                        array('task' => get_class($task))),
283
                    get_string('runnow', 'tool_task'));
284
            }
285
        }
286
        $tools[] = self::convert_info_into_array('task_h5p', $link, $status, $statusaction);
287
 
288
        return $tools;
289
    }
290
 
291
    /**
292
     * Convert information into needed mustache template data array
293
     * @param string $tool The name of the tool
294
     * @param \moodle_url $link The URL to management page
295
     * @param int $status The current status of the tool
296
     * @param string $statusaction A link to 'Run now' option for the task
297
     * @return array
298
     */
299
    private static function convert_info_into_array(string $tool,
300
        \moodle_url $link,
301
        int $status,
302
        string $statusaction = ''): array {
303
 
304
        $statusclasses = array(
305
            TEXTFILTER_DISABLED => 'badge bg-danger text-white',
306
            TEXTFILTER_OFF => 'badge bg-warning text-dark',
307
 
308
            TEXTFILTER_ON => 'badge bg-success text-white',
309
        );
310
 
311
        $statuschoices = array(
312
            TEXTFILTER_DISABLED => get_string('disabled', 'admin'),
313
            TEXTFILTER_OFF => get_string('offbutavailable', 'core_filters'),
314
 
315
            1 => get_string('enabled', 'admin'),
316
        );
317
 
318
        return [
319
            'tool' => get_string($tool, 'h5p'),
320
            'tool_description' => get_string($tool . '_description', 'h5p'),
321
            'link' => $link,
322
            'status' => $statuschoices[$status],
323
            'status_class' => $statusclasses[$status],
324
            'status_action' => $statusaction,
325
        ];
326
    }
327
 
328
    /**
329
     * Get a query string with the theme revision number to include at the end
330
     * of URLs. This is used to force the browser to reload the asset when the
331
     * theme caches are cleared.
332
     *
333
     * @return string
334
     */
335
    public static function get_cache_buster(): string {
336
        global $CFG;
337
        return '?ver=' . $CFG->themerev;
338
    }
339
 
340
    /**
341
     * Get the settings needed by the H5P library.
342
     *
343
     * @param string|null $component
344
     * @return array The settings.
345
     */
346
    public static function get_core_settings(?string $component = null): array {
347
        global $CFG, $USER;
348
 
349
        $basepath = $CFG->wwwroot . '/';
350
        $systemcontext = context_system::instance();
351
 
352
        // H5P doesn't currently support xAPI State. It implements a mechanism in contentUserDataAjax() in h5p.js to update user
353
        // data. However, in our case, we're overriding this method to call the xAPI State web services.
354
        $ajaxpaths = [
355
            'contentUserData' => '',
356
        ];
357
 
358
        $factory = new factory();
359
        $core = $factory->get_core();
360
 
361
        // When there is a logged in user, her information will be passed to the player. It will be used for tracking.
362
        $usersettings = [];
363
        if (isloggedin()) {
364
            $usersettings['name'] = fullname($USER, has_capability('moodle/site:viewfullnames', $systemcontext));
365
            $usersettings['id'] = $USER->id;
366
        }
367
        $savefreq = false;
368
        if ($component !== null && get_config($component, 'enablesavestate')) {
369
            $savefreq = get_config($component, 'savestatefreq');
370
        }
371
        $settings = array(
372
            'baseUrl' => $basepath,
373
            'url' => "{$basepath}pluginfile.php/{$systemcontext->instanceid}/core_h5p",
374
            'urlLibraries' => "{$basepath}pluginfile.php/{$systemcontext->id}/core_h5p/libraries",
375
            'postUserStatistics' => false,
376
            'ajax' => $ajaxpaths,
377
            'saveFreq' => $savefreq,
378
            'siteUrl' => $CFG->wwwroot,
379
            'l10n' => array('H5P' => $core->getLocalization()),
380
            'user' => $usersettings,
381
            'hubIsEnabled' => false,
382
            'reportingIsEnabled' => false,
383
            'crossorigin' => !empty($CFG->h5pcrossorigin) ? $CFG->h5pcrossorigin : null,
384
            'libraryConfig' => $core->h5pF->getLibraryConfig(),
385
            'pluginCacheBuster' => self::get_cache_buster(),
386
            'libraryUrl' => autoloader::get_h5p_core_library_url('js')->out(),
387
        );
388
 
389
        return $settings;
390
    }
391
 
392
    /**
393
     * Get the core H5P assets, including all core H5P JavaScript and CSS.
394
     *
395
     * @param string|null $component
396
     * @return Array core H5P assets.
397
     */
398
    public static function get_core_assets(?string $component = null): array {
399
        global $PAGE;
400
 
401
        // Get core settings.
402
        $settings = self::get_core_settings($component);
403
        $settings['core'] = [
404
            'styles' => [],
405
            'scripts' => []
406
        ];
407
        $settings['loadedJs'] = [];
408
        $settings['loadedCss'] = [];
409
 
410
        // Make sure files are reloaded for each plugin update.
411
        $cachebuster = self::get_cache_buster();
412
 
413
        // Use relative URL to support both http and https.
414
        $liburl = autoloader::get_h5p_core_library_url()->out();
415
        $relpath = '/' . preg_replace('/^[^:]+:\/\/[^\/]+\//', '', $liburl);
416
 
417
        // Add core stylesheets.
418
        foreach (core::$styles as $style) {
419
            $settings['core']['styles'][] = $relpath . $style . $cachebuster;
420
            $PAGE->requires->css(new \moodle_url($liburl . $style . $cachebuster));
421
        }
422
        // Add core JavaScript.
423
        foreach (core::get_scripts() as $script) {
424
            $settings['core']['scripts'][] = $script->out(false);
425
            $PAGE->requires->js($script, true);
426
        }
427
 
428
        return $settings;
429
    }
430
 
431
    /**
432
     * Prepare the library name to be used as a cache key (remove whitespaces and replace dots to underscores).
433
     *
434
     * @param  string $library Library name.
435
     * @return string Library name in a cache simple key format (a-zA-Z0-9_).
436
     */
437
    public static function get_cache_librarykey(string $library): string {
438
        // Remove whitespaces and replace '.' to '_'.
439
        return str_replace('.', '_', str_replace(' ', '', $library));
440
    }
441
 
442
    /**
443
     * Parse a JS array to a PHP array.
444
     *
445
     * @param  string $jscontent The JS array to parse to PHP array.
446
     * @return array The JS array converted to PHP array.
447
     */
448
    public static function parse_js_array(string $jscontent): array {
449
        // Convert all line-endings to UNIX format first.
450
        $jscontent = str_replace(array("\r\n", "\r"), "\n", $jscontent);
451
        $jsarray = preg_split('/,\n\s+/', substr($jscontent, 0, -1));
452
        $jsarray = preg_replace('~{?\\n~', '', $jsarray);
453
 
454
        $strings = [];
455
        foreach ($jsarray as $key => $value) {
456
            $splitted = explode(":", $value, 2);
457
            $value = preg_replace("/^['|\"](.*)['|\"]$/", "$1", trim($splitted[1], ' ,'));
458
            $strings[ trim($splitted[0]) ] = str_replace("\'", "'", $value);
459
        }
460
 
461
        return $strings;
462
    }
463
 
464
    /**
465
     * Get the information related to the H5P export file.
466
     * The information returned will be:
467
     * - filename, filepath, mimetype, filesize, timemodified and fileurl.
468
     *
469
     * @param  string $exportfilename The H5P export filename (with slug).
470
     * @param  \moodle_url $url The URL of the exported file.
471
     * @param  factory $factory The \core_h5p\factory object
472
     * @return array|null The information export file otherwise null.
473
     */
1441 ariadna 474
    public static function get_export_info(string $exportfilename, ?\moodle_url $url = null, ?factory $factory = null): ?array {
1 efrain 475
 
476
        if (!$factory) {
477
            $factory = new factory();
478
        }
479
        $core = $factory->get_core();
480
 
481
        // Get export file.
482
        if (!$fileh5p = $core->fs->get_export_file($exportfilename)) {
483
            return null;
484
        }
485
 
486
        // Build the export info array.
487
        $file = [];
488
        $file['filename'] = $fileh5p->get_filename();
489
        $file['filepath'] = $fileh5p->get_filepath();
490
        $file['mimetype'] = $fileh5p->get_mimetype();
491
        $file['filesize'] = $fileh5p->get_filesize();
492
        $file['timemodified'] = $fileh5p->get_timemodified();
493
 
494
        if (!$url) {
495
            $url  = \moodle_url::make_webservice_pluginfile_url(
496
                $fileh5p->get_contextid(),
497
                $fileh5p->get_component(),
498
                $fileh5p->get_filearea(),
499
                '',
500
                '',
501
                $fileh5p->get_filename()
502
            );
503
        }
504
 
505
        $file['fileurl'] = $url->out(false);
506
 
507
        return $file;
508
    }
509
}