Search moodle.org's
Developer Documentation

See Release Notes

  • Bug fixes for general core bugs in 3.10.x will end 8 November 2021 (12 months).
  • Bug fixes for security issues in 3.10.x will end 9 May 2022 (18 months).
  • PHP version: minimum PHP 7.2.0 Note: minimum PHP version has increased since Moodle 3.8. PHP 7.3.x and 7.4.x are supported too.

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

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