Proyectos de Subversion Moodle

Rev

Rev 1 | | 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
 * Manager for media files
19
 *
20
 * @package   core_media
21
 * @copyright 2016 Marina Glancy
22
 * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
23
 */
24
 
25
defined('MOODLE_INTERNAL') || die();
26
 
27
/**
28
 * Manager for media files.
29
 *
30
 * Used in file resources, media filter, and any other places that need to
31
 * output embedded media.
32
 *
33
 * Usage:
34
 * $manager = core_media_manager::instance();
35
 *
36
 *
37
 * @package   core_media
38
 * @copyright 2016 Marina Glancy
39
 * @author    2011 The Open University
40
 * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
41
 */
42
final class core_media_manager {
43
    /**
44
     * Option: Disable text link fallback.
45
     *
46
     * Use this option if you are going to print a visible link anyway so it is
47
     * pointless to have one as fallback.
48
     *
49
     * To enable, set value to true.
50
     */
51
    const OPTION_NO_LINK = 'nolink';
52
 
53
    /**
54
     * Option: When embedding, if there is no matching embed, do not use the
55
     * default link fallback player; instead return blank.
56
     *
57
     * This is different from OPTION_NO_LINK because this option still uses the
58
     * fallback link if there is some kind of embedding. Use this option if you
59
     * are going to check if the return value is blank and handle it specially.
60
     *
61
     * To enable, set value to true.
62
     */
63
    const OPTION_FALLBACK_TO_BLANK = 'embedorblank';
64
 
65
    /**
66
     * Option: Enable players which are only suitable for use when we trust the
67
     * user who embedded the content.
68
     *
69
     * In the past, this option enabled the SWF player (which was removed).
70
     * However, this setting will remain because it might be used by third-party plugins.
71
     *
72
     * To enable, set value to true.
73
     */
74
    const OPTION_TRUSTED = 'trusted';
75
 
76
    /**
77
     * Option: Put a div around the output (if not blank) so that it displays
78
     * as a block using the 'resourcecontent' CSS class.
79
     *
80
     * To enable, set value to true.
81
     */
82
    const OPTION_BLOCK = 'block';
83
 
84
    /**
85
     * Option: When the request for media players came from a text filter this option will contain the
86
     * original HTML snippet, usually one of the tags: <a> or <video> or <audio>
87
     *
88
     * Players that support other HTML5 features such as tracks may find them in this option.
89
     */
90
    const OPTION_ORIGINAL_TEXT = 'originaltext';
91
 
92
    /** @var array Array of available 'player' objects */
93
    private $players;
94
 
95
    /** @var string Regex pattern for links which may contain embeddable content */
96
    private $embeddablemarkers;
97
 
98
    /** @var core_media_manager caches a singleton instance */
99
    static private $instance;
100
 
101
    /** @var moodle_page page this instance was initialised for */
102
    private $page;
103
 
104
    /**
105
     * Returns a singleton instance of a manager
106
     *
107
     * Note as of Moodle 3.3, this will call setup for you.
108
     *
109
     * @return core_media_manager
110
     */
111
    public static function instance($page = null) {
112
        // Use the passed $page if given, otherwise the $PAGE global.
113
        if (!$page) {
114
            global $PAGE;
115
            $page = $PAGE;
116
        }
117
        if (self::$instance === null || ($page && self::$instance->page !== $page)) {
118
            self::$instance = new self($page);
119
        }
120
        return self::$instance;
121
    }
122
 
123
    /**
124
     * Construct a new core_media_manager instance
125
     *
126
     * @param moodle_page $page The page we are going to add requirements to.
127
     * @see core_media_manager::instance()
128
     */
129
    private function __construct($page) {
130
        if ($page) {
131
            $this->page = $page;
132
            $players = $this->get_players();
133
            foreach ($players as $player) {
134
                $player->setup($page);
135
            }
136
        } else {
137
            debugging('Could not determine the $PAGE. Media plugins will not be set up', DEBUG_DEVELOPER);
138
        }
139
    }
140
 
141
    /**
142
     * Resets cached singleton instance. To be used after $CFG->media_plugins_sortorder is modified
143
     */
144
    public static function reset_caches() {
145
        self::$instance = null;
146
    }
147
 
148
    /**
149
     * Obtains the list of core_media_player objects currently in use to render
150
     * items.
151
     *
152
     * The list is in rank order (highest first) and does not include players
153
     * which are disabled.
154
     *
155
     * @return core_media_player[] Array of core_media_player objects in rank order
156
     */
157
    private function get_players() {
158
        // Save time by only building the list once.
159
        if (!$this->players) {
160
            $sortorder = \core\plugininfo\media::get_enabled_plugins();
161
 
162
            $this->players = [];
163
            foreach ($sortorder as $name) {
164
                $classname = "media_" . $name . "_plugin";
165
                if (class_exists($classname)) {
166
                    $this->players[] = new $classname();
167
                }
168
            }
169
        }
170
        return $this->players;
171
    }
172
 
173
    /**
174
     * Renders a media file (audio or video) using suitable embedded player.
175
     *
176
     * See embed_alternatives function for full description of parameters.
177
     * This function calls through to that one.
178
     *
179
     * When using this function you can also specify width and height in the
180
     * URL by including ?d=100x100 at the end. If specified in the URL, this
181
     * will override the $width and $height parameters.
182
     *
183
     * @param moodle_url $url Full URL of media file
184
     * @param string $name Optional user-readable name to display in download link
185
     * @param int $width Width in pixels (optional)
186
     * @param int $height Height in pixels (optional)
187
     * @param array $options Array of key/value pairs
188
     * @return string HTML content of embed
189
     */
190
    public function embed_url(moodle_url $url, $name = '', $width = 0, $height = 0,
191
                              $options = array()) {
192
 
193
        // Get width and height from URL if specified (overrides parameters in
194
        // function call).
195
        $rawurl = $url->out(false);
196
        if (preg_match('/[?#]d=([\d]{1,4}%?)x([\d]{1,4}%?)/', $rawurl, $matches)) {
197
            $width = $matches[1];
198
            $height = $matches[2];
199
            $url = new moodle_url(str_replace($matches[0], '', $rawurl));
200
        }
201
 
202
        // Defer to array version of function.
203
        return $this->embed_alternatives(array($url), $name, $width, $height, $options);
204
    }
205
 
206
    /**
207
     * Renders media files (audio or video) using suitable embedded player.
208
     * The list of URLs should be alternative versions of the same content in
209
     * multiple formats. If there is only one format it should have a single
210
     * entry.
211
     *
212
     * If the media files are not in a supported format, this will give students
213
     * a download link to each format. The download link uses the filename
214
     * unless you supply the optional name parameter.
215
     *
216
     * Width and height are optional. If specified, these are suggested sizes
217
     * and should be the exact values supplied by the user, if they come from
218
     * user input. These will be treated as relating to the size of the video
219
     * content, not including any player control bar.
220
     *
221
     * For audio files, height will be ignored. For video files, a few formats
222
     * work if you specify only width, but in general if you specify width
223
     * you must specify height as well.
224
     *
225
     * The $options array is passed through to the core_media_player classes
226
     * that render the object tag. The keys can contain values from
227
     * core_media::OPTION_xx.
228
     *
229
     * @param array $alternatives Array of moodle_url to media files
230
     * @param string $name Optional user-readable name to display in download link
231
     * @param int $width Width in pixels (optional)
232
     * @param int $height Height in pixels (optional)
233
     * @param array $options Array of key/value pairs
234
     * @return string HTML content of embed
235
     */
236
    public function embed_alternatives($alternatives, $name = '', $width = 0, $height = 0,
237
                                       $options = array()) {
238
 
239
        // Get list of player plugins.
240
        $players = $this->get_players();
241
 
242
        // Set up initial text which will be replaced by first player that
243
        // supports any of the formats.
244
        $out = core_media_player::PLACEHOLDER;
245
 
246
        // Loop through all players that support any of these URLs.
247
        foreach ($players as $player) {
248
            $supported = $player->list_supported_urls($alternatives, $options);
249
            if ($supported) {
250
                // Embed.
251
                $text = $player->embed($supported, $name, $width, $height, $options);
252
 
253
                // Put this in place of the 'fallback' slot in the previous text.
254
                $out = str_replace(core_media_player::PLACEHOLDER, $text, $out);
255
 
256
                // Check if we need to continue looking for players.
257
                if (strpos($out, core_media_player::PLACEHOLDER) === false) {
258
                    break;
259
                }
260
            }
261
        }
262
 
263
        if (!empty($options[self::OPTION_FALLBACK_TO_BLANK]) && $out === core_media_player::PLACEHOLDER) {
264
            // In case of OPTION_FALLBACK_TO_BLANK and no player matched do not fallback to link, just return empty string.
265
            return '';
266
        }
267
 
268
        // Remove 'fallback' slot from final version and return it.
269
        $fallback = $this->fallback_to_link($alternatives, $name, $options);
270
        $out = str_replace(core_media_player::PLACEHOLDER, $fallback, $out);
271
        $out = str_replace(core_media_player::LINKPLACEHOLDER, $fallback, $out);
272
        if (!empty($options[self::OPTION_BLOCK]) && $out !== '') {
273
            $out = html_writer::tag('div', $out, array('class' => 'resourcecontent'));
274
        }
275
        return $out;
276
    }
277
 
278
    /**
279
     * Returns links to the specified URLs unless OPTION_NO_LINK is passed.
280
     *
281
     * @param array $urls URLs of media files
282
     * @param string $name Display name; '' to use default
283
     * @param array $options Options array
284
     * @return string HTML code for embed
285
     */
286
    private function fallback_to_link($urls, $name, $options) {
287
        // If link is turned off, return empty.
288
        if (!empty($options[self::OPTION_NO_LINK])) {
289
            return '';
290
        }
291
 
292
        // Build up link content.
293
        $output = '';
294
        foreach ($urls as $url) {
295
            if (strval($name) !== '' && $output === '') {
296
                $title = $name;
297
            } else {
298
                $title = $this->get_filename($url);
299
            }
300
            $printlink = html_writer::link($url, $title, array('class' => 'mediafallbacklink'));
301
            if ($output) {
302
                // Where there are multiple available formats, there are fallback links
303
                // for all formats, separated by /.
304
                $output .= ' / ';
305
            }
306
            $output .= $printlink;
307
        }
308
        return $output;
309
    }
310
 
311
    /**
312
     * Checks whether a file can be embedded. If this returns true you will get
313
     * an embedded player; if this returns false, you will just get a download
314
     * link.
315
     *
316
     * This is a wrapper for can_embed_urls.
317
     *
318
     * @param moodle_url $url URL of media file
319
     * @param array $options Options (same as when embedding)
320
     * @return bool True if file can be embedded
321
     */
322
    public function can_embed_url(moodle_url $url, $options = array()) {
323
        return $this->can_embed_urls(array($url), $options);
324
    }
325
 
326
    /**
327
     * Checks whether a file can be embedded. If this returns true you will get
328
     * an embedded player; if this returns false, you will just get a download
329
     * link.
330
     *
331
     * @param array $urls URL of media file and any alternatives (moodle_url)
332
     * @param array $options Options (same as when embedding)
333
     * @return bool True if file can be embedded
334
     */
335
    public function can_embed_urls(array $urls, $options = array()) {
336
        // Check all players to see if any of them support it.
337
        foreach ($this->get_players() as $player) {
338
            // First player that supports it, return true.
339
            if ($player->list_supported_urls($urls, $options)) {
340
                return true;
341
            }
342
        }
343
        return false;
344
    }
345
 
346
    /**
347
     * Obtains a list of markers that can be used in a regular expression when
348
     * searching for URLs that can be embedded by any player type.
349
     *
350
     * This string is used to improve peformance of regex matching by ensuring
351
     * that the (presumably C) regex code can do a quick keyword check on the
352
     * URL part of a link to see if it matches one of these, rather than having
353
     * to go into PHP code for every single link to see if it can be embedded.
354
     *
355
     * @return string String suitable for use in regex such as '(\.mp4|\.flv)'
356
     */
357
    public function get_embeddable_markers() {
358
        if (empty($this->embeddablemarkers)) {
359
            $markers = '';
360
            foreach ($this->get_players() as $player) {
361
                foreach ($player->get_embeddable_markers() as $marker) {
362
                    if ($markers !== '') {
363
                        $markers .= '|';
364
                    }
365
                    $markers .= preg_quote($marker);
366
                }
367
            }
368
            $this->embeddablemarkers = $markers;
369
        }
370
        return $this->embeddablemarkers;
371
    }
372
 
373
    /**
374
     * Given a string containing multiple URLs separated by #, this will split
375
     * it into an array of moodle_url objects suitable for using when calling
376
     * embed_alternatives.
377
     *
378
     * Note that the input string should NOT be html-escaped (i.e. if it comes
379
     * from html, call html_entity_decode first).
380
     *
381
     * @param string $combinedurl String of 1 or more alternatives separated by #
382
     * @param int $width Output variable: width (will be set to 0 if not specified)
383
     * @param int $height Output variable: height (0 if not specified)
384
     * @return array Array of 1 or more moodle_url objects
385
     */
386
    public function split_alternatives($combinedurl, &$width, &$height) {
387
        global $CFG;
388
        $urls = explode('#', $combinedurl);
389
        $width = 0;
390
        $height = 0;
391
        $returnurls = array();
392
 
393
        foreach ($urls as $url) {
394
            $matches = null;
395
 
396
            // You can specify the size as a separate part of the array like
397
            // #d=640x480 without actually including a url in it.
398
            if (preg_match('/^d=([\d]{1,4})x([\d]{1,4})$/i', $url, $matches)) {
399
                $width  = $matches[1];
400
                $height = $matches[2];
401
                continue;
402
            }
403
 
404
            // Can also include the ?d= as part of one of the URLs (if you use
405
            // more than one they will be ignored except the last).
406
            if (preg_match('/\?d=([\d]{1,4})x([\d]{1,4})$/i', $url, $matches)) {
407
                $width  = $matches[1];
408
                $height = $matches[2];
409
 
410
                // Trim from URL.
411
                $url = str_replace($matches[0], '', $url);
412
            }
413
 
414
            // Clean up url.
415
            $url = fix_utf8($url);
416
            include_once($CFG->dirroot . '/lib/validateurlsyntax.php');
417
            if (!validateUrlSyntax($url, 's?H?S?F?R?E?u-P-a?I?p?f?q?r?')) {
418
                continue;
419
            }
420
 
421
            // Turn it into moodle_url object.
422
            $returnurls[] = new moodle_url($url);
423
        }
424
 
425
        return $returnurls;
426
    }
427
 
428
    /**
429
     * Returns the file extension for a URL.
430
     * @param moodle_url $url URL
431
     */
432
    public function get_extension(moodle_url $url) {
433
        // Note: Does not use core_text (. is UTF8-safe).
434
        $filename = self::get_filename($url);
435
        $dot = strrpos($filename, '.');
436
        if ($dot === false) {
437
            return '';
438
        } else {
439
            return strtolower(substr($filename, $dot + 1));
440
        }
441
    }
442
 
443
    /**
444
     * Obtains the filename from the moodle_url.
445
     * @param moodle_url $url URL
446
     * @return string Filename only (not escaped)
447
     */
448
    public function get_filename(moodle_url $url) {
449
        // Use the 'file' parameter if provided (for links created when
450
        // slasharguments was off). If not present, just use URL path.
451
        $path = $url->get_param('file');
452
        if (!$path) {
453
            $path = $url->get_path();
454
        }
455
 
456
        // Remove everything before last / if present. Does not use textlib as / is UTF8-safe.
457
        $slash = strrpos($path, '/');
458
        if ($slash !== false) {
459
            $path = substr($path, $slash + 1);
460
        }
461
        return $path;
462
    }
463
 
464
    /**
465
     * Guesses MIME type for a moodle_url based on file extension.
466
     * @param moodle_url $url URL
467
     * @return string MIME type
468
     */
469
    public function get_mimetype(moodle_url $url) {
470
        return mimeinfo('type', $this->get_filename($url));
471
    }
472
 
473
}