Search moodle.org's
Developer Documentation

See Release Notes
Long Term Support Release

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