Proyectos de Subversion Moodle

Rev

| 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
 * The mod_hvp view assets convenience class for viewing and embedding H5Ps
19
 *
20
 * @package    mod_hvp
21
 * @copyright  2017 Joubel
22
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
23
 */
24
 
25
namespace mod_hvp;
26
 
27
use moodle_url;
28
 
29
defined('MOODLE_INTERNAL') || die();
30
 
31
/**
32
 * Handles finding and attaching assets for view
33
 * @package mod_hvp
34
 */
35
class view_assets {
36
 
37
    private $cm;
38
    private $course;
39
    private $core;
40
    private $content;
41
    private $jsrequires;
42
    private $cssrequires;
43
 
44
    protected $settings;
45
    protected $embedtype;
46
    protected $files;
47
 
48
    public function __construct($cm, $course, $options = []) {
49
        $this->cm          = $cm;
50
        $this->course      = $course;
51
        $this->core        = framework::instance();
52
        $this->content     = $this->core->loadContent($cm->instance);
53
        $this->settings    = hvp_get_core_assets(\context_module::instance($cm->id));
54
        $this->jsrequires  = [];
55
        $this->cssrequires = [];
56
 
57
        $context        = \context_module::instance($this->cm->id);
58
        $displayoptions = $this->core->getDisplayOptionsForView($this->content['disable'], $context->instanceid);
59
        if (isset($options['disabledownload']) && $options['disabledownload']) {
60
            $displayoptions[\H5PCore::DISPLAY_OPTION_DOWNLOAD] = false;
61
        }
62
        if (isset($options['disablefullscreen']) && $options['disablefullscreen']) {
63
            $this->settings['fullscreenDisabled'] = true;
64
        }
65
 
66
        // Add JavaScript settings for this content.
67
        $cid                                  = 'cid-' . $this->content['id'];
68
        $root = self::getsiteroot();
69
        $this->settings['contents'][ $cid ]   = array(
70
            'library'         => \H5PCore::libraryToString($this->content['library']),
71
            'jsonContent'     => $this->getfilteredparameters(),
72
            'fullScreen'      => $this->content['library']['fullscreen'],
73
            'exportUrl'       => $this->getexportsettings($displayoptions[ \H5PCore::DISPLAY_OPTION_DOWNLOAD ]),
74
            'embedCode'       => $this->getembedcode($displayoptions[ \H5PCore::DISPLAY_OPTION_EMBED ]),
75
            'resizeCode'      => $this->getresizecode($displayoptions[ \H5PCore::DISPLAY_OPTION_EMBED ]),
76
            'title'           => $this->content['title'],
77
            'displayOptions'  => $displayoptions,
78
            'url'             => "{$root}/mod/hvp/view.php?id={$this->cm->id}",
79
            'contentUrl'      => "{$root}/pluginfile.php/{$context->id}/mod_hvp/content/{$this->content['id']}",
80
            'metadata'        => $this->content['metadata'],
81
            'contentUserData' => array(
82
 
83
            )
84
        );
85
 
86
        $this->embedtype = isset($options->forceembedtype) ? $options->forceembedtype : \H5PCore::determineEmbedType(
87
            $this->content['embedType'], $this->content['library']['embedTypes']
88
        );
89
 
90
        $this->files = $this->getdependencyfiles();
91
        $this->generateassets();
92
    }
93
 
94
    /**
95
     * Filtered and potentially altered parameters
96
     *
97
     * @return Object|string
98
     */
99
    private function getfilteredparameters() {
100
        global $PAGE;
101
 
102
        $safeparameters = $this->core->filterParameters($this->content);
103
        $decodedparams  = json_decode($safeparameters);
104
        $hvpoutput      = $PAGE->get_renderer('mod_hvp');
105
        $hvpoutput->hvp_alter_filtered_parameters(
106
            $decodedparams,
107
            $this->content['library']['name'],
108
            $this->content['library']['majorVersion'],
109
            $this->content['library']['minorVersion']
110
        );
111
        $safeparameters = json_encode($decodedparams);
112
 
113
        return $safeparameters;
114
    }
115
 
116
    /**
117
     * Export path for settings
118
     *
119
     * @param $downloadenabled
120
     *
121
     * @return string
122
     */
123
    private function getexportsettings($downloadenabled) {
124
        global $CFG;
125
 
126
        if ( ! $downloadenabled || (isset($CFG->mod_hvp_export) && $CFG->mod_hvp_export === false)) {
127
            return '';
128
        }
129
 
130
        $modulecontext = \context_module::instance($this->cm->id);
131
        $slug          = $this->content['slug'] ? $this->content['slug'] . '-' : '';
132
        $url           = \moodle_url::make_pluginfile_url($modulecontext->id,
133
            'mod_hvp',
134
            'exports',
135
            '',
136
            '',
137
            "{$slug}{$this->content['id']}.h5p"
138
        );
139
 
140
        return $url->out();
141
    }
142
 
143
    /**
144
     * Embed code for settings
145
     *
146
     * @param $embedenabled
147
     *
148
     * @return string
149
     */
150
    private function getembedcode($embedenabled) {
151
        if ( ! $embedenabled) {
152
            return '';
153
        }
154
 
155
        $root = self::getsiteroot();
156
        $embedurl = new \moodle_url("{$root}/mod/hvp/embed.php?id={$this->cm->id}");
157
        $title = isset($this->content['metadata']['a11yTitle'])
158
            ? $this->content['metadata']['a11yTitle']
159
            : (isset($this->content['metadata']['title'])
160
                ? $this->content['metadata']['title']
161
                : ''
162
            );
163
 
164
        return "<iframe src=\"{$embedurl->out()}\" width=\":w\" height=\":h\" frameborder=\"0\" " .
165
               "allowfullscreen=\"allowfullscreen\" title=\"{$title}\"></iframe>";
166
    }
167
 
168
    /**
169
     * Resizing script for settings
170
     *
171
     * @param $embedenabled
172
     *
173
     * @return string
174
     */
175
    private function getresizecode($embedenabled) {
176
        if ( ! $embedenabled) {
177
            return '';
178
        }
179
 
180
        $resizeurl = new \moodle_url(self::getsiteroot() . '/mod/hvp/library/js/h5p-resizer.js');
181
 
182
        return "<script src=\"{$resizeurl->out()}\" charset=\"UTF-8\"></script>";
183
    }
184
 
185
    /**
186
     * Finds library dependencies of view
187
     *
188
     * @return array Files that the view has dependencies to
189
     */
190
    private function getdependencyfiles() {
191
        global $PAGE;
192
 
193
        $preloadeddeps = $this->core->loadContentDependencies($this->content['id'], 'preloaded');
194
        $files         = $this->core->getDependenciesFiles($preloadeddeps);
195
 
196
        // Add additional asset files if required.
197
        $hvpoutput = $PAGE->get_renderer('mod_hvp');
198
        $hvpoutput->hvp_alter_scripts($files['scripts'], $preloadeddeps, $this->embedtype);
199
        $hvpoutput->hvp_alter_styles($files['styles'], $preloadeddeps, $this->embedtype);
200
 
201
        return $files;
202
    }
203
 
204
    /**
205
     * Generates assets depending on embed type
206
     */
207
    private function generateassets() {
208
        if ($this->embedtype === 'div') {
209
            $context = \context_system::instance();
210
            $hvppath = "/pluginfile.php/{$context->id}/mod_hvp";
211
 
212
            // Schedule JavaScripts for loading through Moodle.
213
            foreach ($this->files['scripts'] as $script) {
214
                $url = $script->path . $script->version;
215
 
216
                // Add URL prefix if not external.
217
                $isexternal = strpos($script->path, '://');
218
                if ($isexternal === false) {
219
                    $url = $hvppath . $url;
220
                }
221
                $this->settings['loadedJs'][] = $url;
222
                $this->jsrequires[]           = new \moodle_url($isexternal ? $url : self::getsiteroot() . $url);
223
            }
224
 
225
            // Schedule stylesheets for loading through Moodle.
226
            foreach ($this->files['styles'] as $style) {
227
                $url = $style->path . $style->version;
228
 
229
                // Add URL prefix if not external.
230
                $isexternal = strpos($style->path, '://');
231
                if ($isexternal === false) {
232
                    $url = $hvppath . $url;
233
                }
234
                $this->settings['loadedCss'][] = $url;
235
                $this->cssrequires[]           = new \moodle_url($isexternal ? $url : self::getsiteroot() . $url);
236
            }
237
        } else {
238
            // JavaScripts and stylesheets will be loaded through h5p.js.
239
            $cid                                           = 'cid-' . $this->content['id'];
240
            $this->settings['contents'][ $cid ]['scripts'] = $this->core->getAssetsUrls($this->files['scripts']);
241
            $this->settings['contents'][ $cid ]['styles']  = $this->core->getAssetsUrls($this->files['styles']);
242
        }
243
    }
244
 
245
    public function getcontent() {
246
        return $this->content;
247
    }
248
 
249
    /**
250
     * Logs viewed to all handlers
251
     */
252
    public function logviewed() {
253
        $this->logh5pviewedevent();
254
        $this->logcompletioncriteriaviewed();
255
        $this->triggermoduleviewedevent();
256
    }
257
 
258
    /**
259
     * Logs content viewed to H5P core
260
     */
261
    public function logh5pviewedevent() {
262
        new event(
263
            'content', null,
264
            $this->content['id'], $this->content['title'],
265
            $this->content['library']['name'],
266
            $this->content['library']['majorVersion'] . '.' . $this->content['library']['minorVersion']
267
        );
268
    }
269
 
270
    /**
271
     * Logs activity viewed to completion criterias
272
     */
273
    public function logcompletioncriteriaviewed() {
274
        $completion = new \completion_info($this->course);
275
        $completion->set_module_viewed($this->cm);
276
    }
277
 
278
    /**
279
     * Allows observers to act on viewed event
280
     */
281
    public function triggermoduleviewedevent() {
282
        $event = event\course_module_viewed::create(array(
283
            'objectid' => $this->cm->instance,
284
            'context'  => \context_module::instance($this->cm->id)
285
        ));
286
        $event->add_record_snapshot('course_modules', $this->cm);
287
        $event->trigger();
288
    }
289
 
290
 
291
    /**
292
     * Adds js assets to current page
293
     */
294
    public function addassetstopage() {
295
        global $PAGE;
296
 
297
        foreach ($this->jsrequires as $script) {
298
            $PAGE->requires->js($script, true);
299
        }
300
 
301
        foreach ($this->cssrequires as $css) {
302
            $PAGE->requires->css($css);
303
        }
304
 
305
        // Print JavaScript settings to page.
306
        $PAGE->requires->data_for_js('H5PIntegration', $this->settings, true);
307
 
308
        // Add xAPI collector script.
309
        $PAGE->requires->js(new \moodle_url(self::getsiteroot() . '/mod/hvp/xapi-collector.js'), true);
310
    }
311
 
312
    /**
313
     * Outputs h5p view
314
     */
315
    public function outputview() {
316
        if ($this->embedtype === 'div') {
317
            echo "<div class=\"h5p-content\" data-content-id=\"{$this->content['id']}\"></div>";
318
        } else {
319
            $title = isset($this->content['metadata']['a11yTitle'])
320
                ? $this->content['metadata']['a11yTitle']
321
                : (isset($this->content['metadata']['title'])
322
                    ? $this->content['metadata']['title']
323
                    : ''
324
                );
325
 
326
            echo "<div class=\"h5p-iframe-wrapper\">" .
327
                 "<iframe id=\"h5p-iframe-{$this->content['id']}\"" .
328
                 " class=\"h5p-iframe\"" .
329
                 " data-content-id=\"{$this->content['id']}\"" .
330
                 " style=\"height:1px\"" .
331
                 " src=\"about:blank\"" .
332
                 " frameBorder=\"0\"" .
333
                 " scrolling=\"no\"" .
334
                 " title=\"{$title}\">" .
335
                 "</iframe>" .
336
                 "</div>";
337
        }
338
    }
339
 
340
    /**
341
     * Checks if content is valid, prints an error if not
342
     */
343
    public function validatecontent() {
344
        if ($this->content === null) {
345
            print_error('invalidhvp', 'mod_hvp');
346
        }
347
    }
348
 
349
    /**
350
     * Gets the site root absolute address
351
     *
352
     * @return string Root address for the site
353
     */
354
    public static function getsiteroot() {
355
        global $CFG;
356
        // In Moodle 3.4 version wwwroot is always the same as httpswwwroot.
357
        if ($CFG->version < 2017111300) {
358
            return $CFG->httpswwwroot;
359
        }
360
 
361
        return $CFG->wwwroot;
362
    }
363
}