PageRenderTime 24ms CodeModel.GetById 19ms RepoModel.GetById 1ms app.codeStats 0ms

/media/player/videojs/classes/plugin.php

https://github.com/colchambers/moodle
PHP | 352 lines | 206 code | 34 blank | 112 comment | 43 complexity | 5465b167e986d3e40977c32fd137ad14 MD5 | raw file
  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. * Main class for plugin 'media_videojs'
  18. *
  19. * @package media_videojs
  20. * @copyright 2016 Marina Glancy
  21. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  22. */
  23. defined('MOODLE_INTERNAL') || die();
  24. /**
  25. * Player that creates HTML5 <video> tag.
  26. *
  27. * @package media_videojs
  28. * @copyright 2016 Marina Glancy
  29. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  30. */
  31. class media_videojs_plugin extends core_media_player_native {
  32. /** @var array caches last moodle_page used to include AMD modules */
  33. protected $loadedonpage = [];
  34. /** @var string language file to use */
  35. protected $language = 'en';
  36. /** @var array caches supported extensions */
  37. protected $extensions = null;
  38. /** @var bool is this a youtube link */
  39. protected $youtube = false;
  40. /**
  41. * Generates code required to embed the player.
  42. *
  43. * @param moodle_url[] $urls
  44. * @param string $name
  45. * @param int $width
  46. * @param int $height
  47. * @param array $options
  48. * @return string
  49. */
  50. public function embed($urls, $name, $width, $height, $options) {
  51. global $CFG;
  52. require_once($CFG->libdir . '/filelib.php');
  53. $sources = array();
  54. $mediamanager = core_media_manager::instance();
  55. $datasetup = [];
  56. $text = null;
  57. $isaudio = null;
  58. $hastracks = false;
  59. $hasposter = false;
  60. if (array_key_exists(core_media_manager::OPTION_ORIGINAL_TEXT, $options) &&
  61. preg_match('/^<(video|audio)\b/i', $options[core_media_manager::OPTION_ORIGINAL_TEXT], $matches)) {
  62. // Original text already had media tag - get some data from it.
  63. $text = $options[core_media_manager::OPTION_ORIGINAL_TEXT];
  64. $isaudio = strtolower($matches[1]) === 'audio';
  65. $hastracks = preg_match('/<track\b/i', $text);
  66. $hasposter = self::get_attribute($text, 'poster') !== null;
  67. }
  68. // Currently Flash in VideoJS does not support responsive layout. If Flash is enabled try to guess
  69. // if HTML5 player will be engaged for the user and then set it to responsive.
  70. $responsive = (get_config('media_videojs', 'useflash') && !$this->youtube) ? null : true;
  71. // Build list of source tags.
  72. foreach ($urls as $url) {
  73. $extension = $mediamanager->get_extension($url);
  74. $mimetype = $mediamanager->get_mimetype($url);
  75. if ($mimetype === 'video/quicktime' && (core_useragent::is_chrome() || core_useragent::is_edge())) {
  76. // Fix for VideoJS/Chrome bug https://github.com/videojs/video.js/issues/423 .
  77. $mimetype = 'video/mp4';
  78. }
  79. $source = html_writer::empty_tag('source', array('src' => $url, 'type' => $mimetype));
  80. $sources[] = $source;
  81. if ($isaudio === null) {
  82. $isaudio = in_array('.' . $extension, file_get_typegroup('extension', 'audio'));
  83. }
  84. if ($responsive === null) {
  85. $responsive = core_useragent::supports_html5($extension);
  86. }
  87. }
  88. $sources = implode("\n", $sources);
  89. // Find the title, prevent double escaping.
  90. $title = $this->get_name($name, $urls);
  91. $title = preg_replace(['/&amp;/', '/&gt;/', '/&lt;/'], ['&', '>', '<'], $title);
  92. if ($this->youtube) {
  93. $datasetup[] = '"techOrder": ["youtube"]';
  94. $datasetup[] = '"sources": [{"type": "video/youtube", "src":"' . $urls[0] . '"}]';
  95. $sources = ''; // Do not specify <source> tags - it may confuse browser.
  96. $isaudio = false; // Just in case.
  97. }
  98. // Add a language.
  99. if ($this->language) {
  100. $datasetup[] = '"language": "' . $this->language . '"';
  101. }
  102. // Set responsive option.
  103. if ($responsive) {
  104. $datasetup[] = '"fluid": true';
  105. }
  106. if ($isaudio && !$hastracks) {
  107. // We don't need a full screen toggle for the audios (except when tracks are present).
  108. $datasetup[] = '"controlBar": {"fullscreenToggle": false}';
  109. }
  110. if ($isaudio && !$height && !$hastracks && !$hasposter) {
  111. // Hide poster area for audios without tracks or poster.
  112. // See discussion on https://github.com/videojs/video.js/issues/2777 .
  113. // Maybe TODO: if there are only chapter tracks we still don't need poster area.
  114. $datasetup[] = '"aspectRatio": "1:0"';
  115. }
  116. // Attributes for the video/audio tag.
  117. $attributes = [
  118. 'data-setup' => '{' . join(', ', $datasetup) . '}',
  119. 'id' => 'id_videojs_' . uniqid(),
  120. 'class' => get_config('media_videojs', $isaudio ? 'audiocssclass' : 'videocssclass')
  121. ];
  122. if (!$responsive) {
  123. // Note we ignore limitsize setting if not responsive.
  124. parent::pick_video_size($width, $height);
  125. $attributes += ['width' => $width] + ($height ? ['height' => $height] : []);
  126. }
  127. if (core_useragent::is_ios(10)) {
  128. // Hides native controls and plays videos inline instead of fullscreen,
  129. // see https://github.com/videojs/video.js/issues/3761 and
  130. // https://github.com/videojs/video.js/issues/3762 .
  131. // iPhone with iOS 9 still displays double controls and plays fullscreen.
  132. // iPhone with iOS before 9 display only native controls.
  133. $attributes += ['playsinline' => 'true'];
  134. }
  135. if ($text !== null) {
  136. // Original text already had media tag - add necessary attributes and replace sources
  137. // with the supported URLs only.
  138. if (($class = self::get_attribute($text, 'class')) !== null) {
  139. $attributes['class'] .= ' ' . $class;
  140. }
  141. $text = self::remove_attributes($text, ['id', 'width', 'height', 'class']);
  142. if (self::get_attribute($text, 'title') === null) {
  143. $attributes['title'] = $title;
  144. }
  145. $text = self::add_attributes($text, $attributes);
  146. $text = self::replace_sources($text, $sources);
  147. } else {
  148. // Create <video> or <audio> tag with necessary attributes and all sources.
  149. // We don't want fallback to another player because list_supported_urls() is already smart.
  150. // Otherwise we could end up with nested <audio> or <video> tags. Fallback to link only.
  151. $attributes += ['preload' => 'auto', 'controls' => 'true', 'title' => $title];
  152. $text = html_writer::tag($isaudio ? 'audio' : 'video', $sources . self::LINKPLACEHOLDER, $attributes);
  153. }
  154. // Limit the width of the video if width is specified.
  155. // We do not do it in the width attributes of the video because it does not work well
  156. // together with responsive behavior.
  157. if ($responsive) {
  158. self::pick_video_size($width, $height);
  159. if ($width) {
  160. $text = html_writer::div($text, null, ['style' => 'max-width:' . $width . 'px;']);
  161. }
  162. }
  163. return html_writer::div($text, 'mediaplugin mediaplugin_videojs');
  164. }
  165. /**
  166. * Utility function that sets width and height to defaults if not specified
  167. * as a parameter to the function (will be specified either if, (a) the calling
  168. * code passed it, or (b) the URL included it).
  169. * @param int $width Width passed to function (updated with final value)
  170. * @param int $height Height passed to function (updated with final value)
  171. */
  172. protected static function pick_video_size(&$width, &$height) {
  173. if (!get_config('media_videojs', 'limitsize')) {
  174. return;
  175. }
  176. parent::pick_video_size($width, $height);
  177. }
  178. public function get_supported_extensions() {
  179. global $CFG;
  180. require_once($CFG->libdir . '/filelib.php');
  181. if ($this->extensions === null) {
  182. $filetypes = preg_split('/\s*,\s*/',
  183. strtolower(trim(get_config('media_videojs', 'videoextensions') . ',' .
  184. get_config('media_videojs', 'audioextensions'))));
  185. $this->extensions = file_get_typegroup('extension', $filetypes);
  186. if ($this->extensions && !get_config('media_videojs', 'useflash')) {
  187. // If Flash is disabled only return extensions natively supported by browsers.
  188. $nativeextensions = array_merge(file_get_typegroup('extension', 'html_video'),
  189. file_get_typegroup('extension', 'html_audio'));
  190. $this->extensions = array_intersect($this->extensions, $nativeextensions);
  191. }
  192. }
  193. return $this->extensions;
  194. }
  195. public function list_supported_urls(array $urls, array $options = array()) {
  196. $result = [];
  197. // Youtube.
  198. $this->youtube = false;
  199. if (count($urls) == 1 && get_config('media_videojs', 'youtube')) {
  200. $url = reset($urls);
  201. // Check against regex.
  202. if (preg_match($this->get_regex_youtube(), $url->out(false), $this->matches)) {
  203. $this->youtube = true;
  204. return array($url);
  205. }
  206. }
  207. if (!get_config('media_videojs', 'useflash')) {
  208. return parent::list_supported_urls($urls, $options);
  209. }
  210. // If Flash fallback is enabled we can not check if/when browser supports flash.
  211. $extensions = $this->get_supported_extensions();
  212. foreach ($urls as $url) {
  213. $ext = core_media_manager::instance()->get_extension($url);
  214. if (in_array('.' . $ext, $extensions)) {
  215. $result[] = $url;
  216. }
  217. }
  218. return $result;
  219. }
  220. /**
  221. * Default rank
  222. * @return int
  223. */
  224. public function get_rank() {
  225. return 2000;
  226. }
  227. /**
  228. * Tries to match the current language to existing language files
  229. *
  230. * Matched language is stored in $this->language
  231. *
  232. * @return string JS code with a setting
  233. */
  234. protected function find_language() {
  235. global $CFG;
  236. $this->language = current_language();
  237. $basedir = $CFG->dirroot . '/media/player/videojs/videojs/lang/';
  238. $langfiles = get_directory_list($basedir);
  239. $candidates = [];
  240. foreach ($langfiles as $langfile) {
  241. if (strtolower(pathinfo($langfile, PATHINFO_EXTENSION)) !== 'js') {
  242. continue;
  243. }
  244. $lang = basename($langfile, '.js');
  245. if (strtolower($langfile) === $this->language . '.js') {
  246. // Found an exact match for the language.
  247. $js = file_get_contents($basedir . $langfile);
  248. break;
  249. }
  250. if (substr($this->language, 0, 2) === strtolower(substr($langfile, 0, 2))) {
  251. // Not an exact match but similar, for example "pt_br" is similar to "pt".
  252. $candidates[$lang] = $langfile;
  253. }
  254. }
  255. if (empty($js) && $candidates) {
  256. // Exact match was not found, take the first candidate.
  257. $this->language = key($candidates);
  258. $js = file_get_contents($basedir . $candidates[$this->language]);
  259. }
  260. // Add it as a language for Video.JS.
  261. if (!empty($js)) {
  262. return "$js\n";
  263. }
  264. // Could not match, use default language of video player (English).
  265. $this->language = null;
  266. return "";
  267. }
  268. public function supports($usedextensions = []) {
  269. $supports = parent::supports($usedextensions);
  270. if (get_config('media_videojs', 'youtube')) {
  271. $supports .= ($supports ? '<br>' : '') . get_string('youtube', 'media_videojs');
  272. }
  273. return $supports;
  274. }
  275. public function get_embeddable_markers() {
  276. $markers = parent::get_embeddable_markers();
  277. if (get_config('media_videojs', 'youtube')) {
  278. $markers = array_merge($markers, array('youtube.com', 'youtube-nocookie.com', 'youtu.be', 'y2u.be'));
  279. }
  280. return $markers;
  281. }
  282. /**
  283. * Returns regular expression used to match URLs for single youtube video
  284. * @return string PHP regular expression e.g. '~^https?://example.org/~'
  285. */
  286. protected function get_regex_youtube() {
  287. // Regex for standard youtube link.
  288. $link = '(youtube(-nocookie)?\.com/(?:watch\?v=|v/))';
  289. // Regex for shortened youtube link.
  290. $shortlink = '((youtu|y2u)\.be/)';
  291. // Initial part of link.
  292. $start = '~^https?://(www\.)?(' . $link . '|' . $shortlink . ')';
  293. // Middle bit: Video key value.
  294. $middle = '([a-z0-9\-_]+)';
  295. return $start . $middle . core_media_player_external::END_LINK_REGEX_PART;
  296. }
  297. /**
  298. * Setup page requirements.
  299. *
  300. * @param moodle_page $page The page we are going to add requirements to.
  301. */
  302. public function setup($page) {
  303. // Load dynamic loader. It will scan page for videojs media and load necessary modules.
  304. // Loader will be loaded on absolutely every page, however the videojs will only be loaded
  305. // when video is present on the page or added later to it in AJAX.
  306. $path = new moodle_url('/media/player/videojs/videojs/video-js.swf');
  307. $contents = 'videojs.options.flash.swf = "' . $path . '";' . "\n";
  308. $contents .= $this->find_language(current_language());
  309. $page->requires->js_amd_inline(<<<EOT
  310. require(["media_videojs/loader"], function(loader) {
  311. loader.setUp(function(videojs) {
  312. $contents
  313. });
  314. });
  315. EOT
  316. );
  317. }
  318. }