Search moodle.org's
Developer Documentation

See Release Notes

  • Bug fixes for general core bugs in 4.0.x will end 8 May 2023 (12 months).
  • Bug fixes for security issues in 4.0.x will end 13 November 2023 (18 months).
  • PHP version: minimum PHP 7.3.0 Note: the minimum PHP version has increased since Moodle 3.10. PHP 7.4.x is also supported.

Differences Between: [Versions 310 and 400] [Versions 311 and 400] [Versions 39 and 400] [Versions 400 and 402] [Versions 400 and 403]

   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   * Main class for plugin 'media_videojs'
  19   *
  20   * @package   media_videojs
  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   * Player that creates HTML5 <video> tag.
  29   *
  30   * @package   media_videojs
  31   * @copyright 2016 Marina Glancy
  32   * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  33   */
  34  class media_videojs_plugin extends core_media_player_native {
  35      /** @var array caches last moodle_page used to include AMD modules */
  36      protected $loadedonpage = [];
  37      /** @var string language file to use */
  38      protected $language = 'en';
  39      /** @var array caches supported extensions */
  40      protected $extensions = null;
  41      /** @var bool is this a youtube link */
  42      protected $youtube = false;
  43      /** @var bool Need to use Ogv.JS Tech plugin or not. */
  44      protected $ogvtech = false;
  45      /** @var array Ogv.JS supported extensions */
  46      protected $ogvsupportedextensions = [
  47          '.ogv',
  48          '.webm',
  49          '.oga',
  50          '.ogg'
  51      ];
  52  
  53      /**
  54       * Generates code required to embed the player.
  55       *
  56       * @param moodle_url[] $urls
  57       * @param string $name
  58       * @param int $width
  59       * @param int $height
  60       * @param array $options
  61       * @return string
  62       */
  63      public function embed($urls, $name, $width, $height, $options) {
  64          global $CFG;
  65          require_once($CFG->libdir . '/filelib.php');
  66  
  67          $sources = array();
  68          $mediamanager = core_media_manager::instance();
  69          $datasetup = [];
  70  
  71          $text = null;
  72          $isaudio = null;
  73          $hastracks = false;
  74          $hasposter = false;
  75          if (array_key_exists(core_media_manager::OPTION_ORIGINAL_TEXT, $options) &&
  76                  preg_match('/^<(video|audio)\b/i', $options[core_media_manager::OPTION_ORIGINAL_TEXT], $matches)) {
  77              // Original text already had media tag - get some data from it.
  78              $text = $options[core_media_manager::OPTION_ORIGINAL_TEXT];
  79              $isaudio = strtolower($matches[1]) === 'audio';
  80              $hastracks = preg_match('/<track\b/i', $text);
  81              $hasposter = self::get_attribute($text, 'poster') !== null;
  82          }
  83  
  84          // Try to guess if HTML5 player will be engaged for the user and then set it to responsive.
  85          $responsive = (!$this->youtube) ? null : true;
  86  
  87          // Build list of source tags.
  88          foreach ($urls as $url) {
  89              $extension = $mediamanager->get_extension($url);
  90              $mimetype = $mediamanager->get_mimetype($url);
  91              if ($mimetype === 'video/quicktime' && (core_useragent::is_chrome() || core_useragent::is_edge())) {
  92                  // Fix for VideoJS/Chrome bug https://github.com/videojs/video.js/issues/423 .
  93                  $mimetype = 'video/mp4';
  94              }
  95              // If this is RTMP stream, adjust mimetype to those VideoJS suggests to use (either flash or mp4).
  96              if ($url->get_scheme() === 'rtmp') {
  97                  if ($mimetype === 'video/x-flv') {
  98                      $mimetype = 'rtmp/flv';
  99                  } else {
 100                      $mimetype = 'rtmp/mp4';
 101                  }
 102              }
 103              $source = html_writer::empty_tag('source', array('src' => $url, 'type' => $mimetype));
 104              $sources[] = $source;
 105              if ($isaudio === null) {
 106                  $isaudio = in_array('.' . $extension, file_get_typegroup('extension', 'audio'));
 107              }
 108              if ($responsive === null) {
 109                  $responsive = core_useragent::supports_html5($extension);
 110              }
 111          }
 112          $sources = implode("\n", $sources);
 113  
 114          // Find the title, prevent double escaping.
 115          $title = $this->get_name($name, $urls);
 116          $title = preg_replace(['/&amp;/', '/&gt;/', '/&lt;/'], ['&', '>', '<'], $title);
 117  
 118          if ($this->youtube) {
 119              $datasetup[] = '"techOrder": ["youtube"]';
 120              $datasetup[] = '"sources": [{"type": "video/youtube", "src":"' . $urls[0] . '"}]';
 121  
 122              // Check if we have a time parameter.
 123              if ($time = $urls[0]->get_param('t')) {
 124                  $datasetup[] = '"youtube": {"start": "' . self::get_start_time($time) . '"}';
 125              }
 126  
 127              $sources = ''; // Do not specify <source> tags - it may confuse browser.
 128              $isaudio = false; // Just in case.
 129          }
 130  
 131          if ($this->ogvtech) {
 132              $datasetup[] = '"techOrder": ["OgvJS"]';
 133          }
 134  
 135          // Add a language.
 136          if ($this->language) {
 137              $datasetup[] = '"language": "' . $this->language . '"';
 138          }
 139  
 140          // Set responsive option.
 141          if ($responsive) {
 142              $datasetup[] = '"fluid": true';
 143          }
 144  
 145          if ($isaudio && !$hastracks) {
 146              // We don't need a full screen toggle for the audios (except when tracks are present).
 147              $datasetup[] = '"controlBar": {"fullscreenToggle": false}';
 148          }
 149  
 150          if ($isaudio && !$height && !$hastracks && !$hasposter) {
 151              // Hide poster area for audios without tracks or poster.
 152              // See discussion on https://github.com/videojs/video.js/issues/2777 .
 153              // Maybe TODO: if there are only chapter tracks we still don't need poster area.
 154              $datasetup[] = '"aspectRatio": "1:0"';
 155          }
 156  
 157          // Additional setup for playback rate and user actions.
 158          $datasetup[] = '"playbackRates": [0.5, 0.75, 1, 1.25, 1.5, 1.75, 2]';
 159          $datasetup[] = '"userActions": {"hotkeys": true}';
 160  
 161          // Attributes for the video/audio tag.
 162          // We use data-setup-lazy as the attribute name for the config instead of
 163          // data-setup because data-setup will cause video.js to load the player as soon as the library is loaded,
 164          // which is BEFORE we have a chance to load any additional libraries (youtube).
 165          // The data-setup-lazy is just a tag name that video.js does not recognise so we can manually initialise
 166          // it when we are sure the dependencies are loaded.
 167          static $playercounter = 1;
 168          $attributes = [
 169              'data-setup-lazy' => '{' . join(', ', $datasetup) . '}',
 170              'id' => 'id_videojs_' . uniqid() . '_' . $playercounter++,
 171              'class' => get_config('media_videojs', $isaudio ? 'audiocssclass' : 'videocssclass')
 172          ];
 173  
 174          if (!$responsive) {
 175              // Note we ignore limitsize setting if not responsive.
 176              parent::pick_video_size($width, $height);
 177              $attributes += ['width' => $width] + ($height ? ['height' => $height] : []);
 178          }
 179  
 180          if (core_useragent::is_ios(10)) {
 181              // Hides native controls and plays videos inline instead of fullscreen,
 182              // see https://github.com/videojs/video.js/issues/3761 and
 183              // https://github.com/videojs/video.js/issues/3762 .
 184              // iPhone with iOS 9 still displays double controls and plays fullscreen.
 185              // iPhone with iOS before 9 display only native controls.
 186              $attributes += ['playsinline' => 'true'];
 187          }
 188  
 189          if ($text !== null) {
 190              // Original text already had media tag - add necessary attributes and replace sources
 191              // with the supported URLs only.
 192              if (($class = self::get_attribute($text, 'class')) !== null) {
 193                  $attributes['class'] .= ' ' . $class;
 194              }
 195              $text = self::remove_attributes($text, ['id', 'width', 'height', 'class']);
 196              if (self::get_attribute($text, 'title') === null) {
 197                  $attributes['title'] = $title;
 198              }
 199              $text = self::add_attributes($text, $attributes);
 200              $text = self::replace_sources($text, $sources);
 201          } else {
 202              // Create <video> or <audio> tag with necessary attributes and all sources.
 203              // We don't want fallback to another player because list_supported_urls() is already smart.
 204              // Otherwise we could end up with nested <audio> or <video> tags. Fallback to link only.
 205              $attributes += ['preload' => 'auto', 'controls' => 'true', 'title' => $title];
 206              $text = html_writer::tag($isaudio ? 'audio' : 'video', $sources . self::LINKPLACEHOLDER, $attributes);
 207          }
 208  
 209          // Limit the width of the video if width is specified.
 210          // We do not do it in the width attributes of the video because it does not work well
 211          // together with responsive behavior.
 212          if ($responsive) {
 213              self::pick_video_size($width, $height);
 214              if ($width) {
 215                  $text = html_writer::div($text, null, ['style' => 'max-width:' . $width . 'px;']);
 216              }
 217          }
 218  
 219          return html_writer::div($text, 'mediaplugin mediaplugin_videojs d-block');
 220      }
 221  
 222      /**
 223       * Utility function that sets width and height to defaults if not specified
 224       * as a parameter to the function (will be specified either if, (a) the calling
 225       * code passed it, or (b) the URL included it).
 226       * @param int $width Width passed to function (updated with final value)
 227       * @param int $height Height passed to function (updated with final value)
 228       */
 229      protected static function pick_video_size(&$width, &$height) {
 230          if (!get_config('media_videojs', 'limitsize')) {
 231              return;
 232          }
 233          parent::pick_video_size($width, $height);
 234      }
 235  
 236      /**
 237       * Method to convert Youtube time parameter string, which can contain human readable time
 238       * intervals such as '1h5m', '1m10s', etc or a numeric seconds value
 239       *
 240       * @param string $timestr
 241       * @return int
 242       */
 243      protected static function get_start_time(string $timestr): int {
 244          if (is_numeric($timestr)) {
 245              // We can return the time string itself if it's already numeric.
 246              return (int) $timestr;
 247          }
 248  
 249          try {
 250              // Parse the time string as an ISO 8601 time interval.
 251              $timeinterval = new DateInterval('PT' . core_text::strtoupper($timestr));
 252  
 253              return ($timeinterval->h * HOURSECS) + ($timeinterval->i * MINSECS) + $timeinterval->s;
 254          } catch (Exception $ex) {
 255              // Invalid time interval.
 256              return 0;
 257          }
 258      }
 259  
 260      public function get_supported_extensions() {
 261          global $CFG;
 262          require_once($CFG->libdir . '/filelib.php');
 263          if ($this->extensions === null) {
 264              // Get extensions set by user in UI config.
 265              $filetypes = preg_split('/\s*,\s*/',
 266                  strtolower(trim(get_config('media_videojs', 'videoextensions') . ',' .
 267                  get_config('media_videojs', 'audioextensions'))));
 268  
 269              $this->extensions = file_get_typegroup('extension', $filetypes);
 270              if ($this->extensions) {
 271                  // Get extensions supported by player.
 272                  $supportedextensions = array_merge(file_get_typegroup('extension', 'html_video'),
 273                      file_get_typegroup('extension', 'html_audio'), file_get_typegroup('extension', 'media_source'));
 274                  $this->extensions = array_intersect($this->extensions, $supportedextensions);
 275              }
 276          }
 277          return $this->extensions;
 278      }
 279  
 280      public function list_supported_urls(array $urls, array $options = array()) {
 281          $result = [];
 282          // Youtube.
 283          $this->youtube = false;
 284          if (count($urls) == 1 && get_config('media_videojs', 'youtube')) {
 285              $url = reset($urls);
 286  
 287              // Check against regex.
 288              if (preg_match($this->get_regex_youtube(), $url->out(false), $this->matches)) {
 289                  $this->youtube = true;
 290                  return array($url);
 291              }
 292          }
 293  
 294          $extensions = $this->get_supported_extensions();
 295          foreach ($urls as $url) {
 296              // Skip the URL that is using RTMP (which might have been picked to the list by its valid extension).
 297              if ($url->get_scheme() === 'rtmp') {
 298                  continue;
 299              }
 300  
 301              $ext = '.' . core_media_manager::instance()->get_extension($url);
 302              // Handle HLS and MPEG-DASH if supported.
 303              $isstream = in_array($ext, file_get_typegroup('extension', 'media_source'));
 304              if ($isstream && in_array($ext, $extensions) && core_useragent::supports_media_source_extensions($ext)) {
 305                  $result[] = $url;
 306                  continue;
 307              }
 308  
 309              // Ogv.JS Tech.
 310              $this->ogvtech = false;
 311              if (in_array($ext, $this->ogvsupportedextensions) &&
 312                  (core_useragent::is_safari() || core_useragent::is_ios())) {
 313                  $this->ogvtech = true;
 314                  $result[] = $url;
 315                  continue;
 316              }
 317  
 318              return parent::list_supported_urls($urls, $options);
 319          }
 320          return $result;
 321      }
 322  
 323      /**
 324       * Default rank
 325       * @return int
 326       */
 327      public function get_rank() {
 328          return 2000;
 329      }
 330  
 331      /**
 332       * Tries to match the current language to existing language files
 333       *
 334       * Matched language is stored in $this->language
 335       *
 336       * @return string JS code with a setting
 337       */
 338      protected function find_language() {
 339          global $CFG;
 340          $this->language = current_language();
 341          $basedir = $CFG->dirroot . '/media/player/videojs/videojs/lang/';
 342          $langfiles = get_directory_list($basedir);
 343          $candidates = [];
 344          foreach ($langfiles as $langfile) {
 345              if (strtolower(pathinfo($langfile, PATHINFO_EXTENSION)) !== 'json') {
 346                  continue;
 347              }
 348              $lang = basename($langfile, '.json');
 349              if (strtolower($langfile) === $this->language . '.json') {
 350                  // Found an exact match for the language. It is stored in $this->language.
 351                  return;
 352              }
 353              if (substr($this->language, 0, 2) === strtolower(substr($langfile, 0, 2))) {
 354                  // Not an exact match but similar, for example "pt_br" is similar to "pt".
 355                  $candidates[$lang] = $langfile;
 356              }
 357          }
 358  
 359          if ($candidates) {
 360              // Exact match was not found, take the first candidate.
 361              $this->language = key($candidates);
 362          } else {
 363              // Could not match, use default language of video player (English).
 364              $this->language = 'en';
 365          }
 366      }
 367  
 368      /**
 369       * Returns the requested language pack in the json format.
 370       *
 371       * @param string $lang The language code
 372       * @return false|string The read data or false on failure
 373       */
 374      public static function get_language_content(string $lang) {
 375          global $CFG;
 376          $langfile = "{$CFG->dirroot}/media/player/videojs/videojs/lang/{$lang}.json";
 377  
 378          return file_exists($langfile) ? file_get_contents($langfile) : '';
 379      }
 380  
 381      public function supports($usedextensions = []) {
 382          $supports = parent::supports($usedextensions);
 383          if (get_config('media_videojs', 'youtube')) {
 384              $supports .= ($supports ? '<br>' : '') . get_string('youtube', 'media_videojs');
 385          }
 386          return $supports;
 387      }
 388  
 389      public function get_embeddable_markers() {
 390          $markers = parent::get_embeddable_markers();
 391          // Add YouTube support if enabled.
 392          if (get_config('media_videojs', 'youtube')) {
 393              $markers = array_merge($markers, array('youtube.com', 'youtube-nocookie.com', 'youtu.be', 'y2u.be'));
 394          }
 395  
 396          return $markers;
 397      }
 398  
 399      /**
 400       * Returns regular expression used to match URLs for single youtube video
 401       * @return string PHP regular expression e.g. '~^https?://example.org/~'
 402       */
 403      protected function get_regex_youtube() {
 404          // Regex for standard youtube link.
 405          $link = '(youtube(-nocookie)?\.com/(?:watch\?v=|v/))';
 406          // Regex for shortened youtube link.
 407          $shortlink = '((youtu|y2u)\.be/)';
 408  
 409          // Initial part of link.
 410          $start = '~^https?://(www\.)?(' . $link . '|' . $shortlink . ')';
 411          // Middle bit: Video key value.
 412          $middle = '([a-z0-9\-_]+)';
 413          return $start . $middle . core_media_player_external::END_LINK_REGEX_PART;
 414      }
 415  
 416      /**
 417       * Setup page requirements.
 418       *
 419       * @param moodle_page $page The page we are going to add requirements to.
 420       */
 421      public function setup($page) {
 422          if (during_initial_install() || is_major_upgrade_required()) {
 423              return;
 424          }
 425  
 426          // Load dynamic loader. It will scan page for videojs media and load necessary modules.
 427          // Loader will be loaded on absolutely every page, however the videojs will only be loaded
 428          // when video is present on the page or added later to it in AJAX.
 429          $this->find_language();
 430          $page->requires->js_amd_inline(<<<EOT
 431  require(["media_videojs/loader"], function(loader) {
 432      loader.setUp('$this->language');
 433  });
 434  EOT
 435          );
 436      }
 437  }