Proyectos de Subversion Moodle

Rev

Ir a la última revisión | | 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;
29
 
30
defined('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
 */
38
class 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
 
54
        if (api::is_valid_package($file, $onlyupdatelibs, $skipcontent, $factory, false)) {
55
            $core = $factory->get_core();
56
            $h5pvalidator = $factory->get_validator();
57
            $h5pstorage = $factory->get_storage();
58
 
59
            $content = [
60
                'pathnamehash' => $file->get_pathnamehash(),
61
                'contenthash' => $file->get_contenthash(),
62
            ];
63
            $options = ['disable' => self::get_display_options($core, $config)];
64
 
65
            // Add the 'title' if exists from 'h5p.json' data to keep it for the editor.
66
            if (!empty($h5pvalidator->h5pC->mainJsonData['title'])) {
67
                $content['title'] = $h5pvalidator->h5pC->mainJsonData['title'];
68
            }
69
 
70
            // If exists, add the metadata from 'h5p.json' to avoid loosing this information.
71
            $data = $h5pvalidator->h5pC->mainJsonData;
72
            if (!empty($data)) {
73
                // The metadata fields are defined in 'joubel/core/h5p-metadata.class.php'.
74
                $metadatafields = [
75
                    'title',
76
                    'a11yTitle',
77
                    'changes',
78
                    'authors',
79
                    'source',
80
                    'license',
81
                    'licenseVersion',
82
                    'licenseExtras',
83
                    'authorComments',
84
                    'yearFrom',
85
                    'yearTo',
86
                    'defaultLanguage',
87
                ];
88
                $content['metadata'] = array_reduce($metadatafields, function ($array, $field) use ($data) {
89
                    if (array_key_exists($field, $data)) {
90
                        $array[$field] = $data[$field];
91
                    }
92
                    return $array;
93
                }, []);
94
            }
95
            $h5pstorage->savePackage($content, null, $skipcontent, $options);
96
 
97
            return $h5pstorage->contentId;
98
        }
99
 
100
        return false;
101
    }
102
 
103
    /**
104
     * Get the error messages stored in our H5P framework.
105
     *
106
     * @param \stdClass $messages The error, exception and info messages, raised while preparing and running an H5P content.
107
     * @param factory $factory The \core_h5p\factory object
108
     *
109
     * @return \stdClass with framework error messages.
110
     */
111
    public static function get_messages(\stdClass $messages, factory $factory): \stdClass {
112
        $core = $factory->get_core();
113
 
114
        // Check if there are some errors and store them in $messages.
115
        if (empty($messages->error)) {
116
            $messages->error = $core->h5pF->getMessages('error') ?: false;
117
        } else {
118
            $messages->error = array_merge($messages->error, $core->h5pF->getMessages('error'));
119
        }
120
 
121
        if (empty($messages->info)) {
122
            $messages->info = $core->h5pF->getMessages('info') ?: false;
123
        } else {
124
            $messages->info = array_merge($messages->info, $core->h5pF->getMessages('info'));
125
        }
126
 
127
        return $messages;
128
    }
129
 
130
    /**
131
     * Get the representation of display options as int.
132
     *
133
     * @param core $core The \core_h5p\core object
134
     * @param stdClass $config Button options config
135
     *
136
     * @return int The representation of display options as int
137
     */
138
    public static function get_display_options(core $core, \stdClass $config): int {
139
        $export = isset($config->export) ? $config->export : 0;
140
        $embed = isset($config->embed) ? $config->embed : 0;
141
        $copyright = isset($config->copyright) ? $config->copyright : 0;
142
        $frame = ($export || $embed || $copyright);
143
        if (!$frame) {
144
            $frame = isset($config->frame) ? $config->frame : 0;
145
        }
146
 
147
        $disableoptions = [
148
            core::DISPLAY_OPTION_FRAME     => $frame,
149
            core::DISPLAY_OPTION_DOWNLOAD  => $export,
150
            core::DISPLAY_OPTION_EMBED     => $embed,
151
            core::DISPLAY_OPTION_COPYRIGHT => $copyright,
152
        ];
153
 
154
        return $core->getStorableDisplayOptions($disableoptions, 0);
155
    }
156
 
157
    /**
158
     * Convert the int representation of display options into stdClass
159
     *
160
     * @param core $core The \core_h5p\core object
161
     * @param int $displayint integer value representing display options
162
     *
163
     * @return int The representation of display options as int
164
     */
165
    public static function decode_display_options(core $core, int $displayint = null): \stdClass {
166
        $config = new \stdClass();
167
        if ($displayint === null) {
168
            $displayint = self::get_display_options($core, $config);
169
        }
170
        $displayarray = $core->getDisplayOptionsForEdit($displayint);
171
        $config->export = $displayarray[core::DISPLAY_OPTION_DOWNLOAD] ?? 0;
172
        $config->embed = $displayarray[core::DISPLAY_OPTION_EMBED] ?? 0;
173
        $config->copyright = $displayarray[core::DISPLAY_OPTION_COPYRIGHT] ?? 0;
174
        return $config;
175
    }
176
 
177
    /**
178
     * Checks if the author of the .h5p file is "trustable". If the file hasn't been uploaded by a user with the
179
     * required capability, the content won't be deployed.
180
     *
181
     * @param  stored_file $file The .h5p file to be deployed
182
     * @return bool Returns true if the file can be deployed, false otherwise.
183
     */
184
    public static function can_deploy_package(\stored_file $file): bool {
185
        if (null === $file->get_userid()) {
186
            // If there is no userid, it is owned by the system.
187
            return true;
188
        }
189
 
190
        $context = \context::instance_by_id($file->get_contextid());
191
        if (has_capability('moodle/h5p:deploy', $context, $file->get_userid())) {
192
            return true;
193
        }
194
 
195
        return false;
196
    }
197
 
198
    /**
199
     * Checks if the content-type libraries can be upgraded.
200
     * The H5P content-type libraries can only be upgraded if the author of the .h5p file can manage content-types or if all the
201
     * content-types exist, to avoid users without the required capability to upload malicious content.
202
     *
203
     * @param  stored_file $file The .h5p file to be deployed
204
     * @return bool Returns true if the content-type libraries can be created/updated, false otherwise.
205
     */
206
    public static function can_update_library(\stored_file $file): bool {
207
        if (null === $file->get_userid()) {
208
            // If there is no userid, it is owned by the system.
209
            return true;
210
        }
211
 
212
        // Check if the owner of the .h5p file has the capability to manage content-types.
213
        $context = \context::instance_by_id($file->get_contextid());
214
        if (has_capability('moodle/h5p:updatelibraries', $context, $file->get_userid())) {
215
            return true;
216
        }
217
 
218
        return false;
219
    }
220
 
221
    /**
222
     * Convenience to take a fixture test file and create a stored_file.
223
     *
224
     * @param string $filepath The filepath of the file
225
     * @param  int   $userid  The author of the file
226
     * @param  \context $context The context where the file will be created
227
     * @return \stored_file The file created
228
     */
229
    public static function create_fake_stored_file_from_path(string $filepath, int $userid = 0,
230
            \context $context = null): \stored_file {
231
        if (is_null($context)) {
232
            $context = context_system::instance();
233
        }
234
        $filerecord = [
235
            'contextid' => $context->id,
236
            'component' => 'core_h5p',
237
            'filearea'  => 'unittest',
238
            'itemid'    => rand(),
239
            'filepath'  => '/',
240
            'filename'  => basename($filepath),
241
        ];
242
        if (!is_null($userid)) {
243
            $filerecord['userid'] = $userid;
244
        }
245
 
246
        $fs = get_file_storage();
247
        return $fs->create_file_from_pathname($filerecord, $filepath);
248
    }
249
 
250
    /**
251
     * Get information about different H5P tools and their status.
252
     *
253
     * @return array Data to render by the template
254
     */
255
    public static function get_h5p_tools_info(): array {
256
        $tools = array();
257
 
258
        // Getting information from available H5P tools one by one because their enabled/disabled options are totally different.
259
        // Check the atto button status.
260
        $link = \editor_atto\plugininfo\atto::get_manage_url();
261
        $status = strpos(get_config('editor_atto', 'toolbar'), 'h5p') > -1;
262
        $tools[] = self::convert_info_into_array('atto_h5p', $link, $status);
263
 
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
     */
474
    public static function get_export_info(string $exportfilename, \moodle_url $url = null, ?factory $factory = null): ?array {
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
}