From b516be1d7e8456984f71ea359efcfdbc8a6e6d89 Mon Sep 17 00:00:00 2001 From: Paul Nicholls Date: Wed, 11 Feb 2015 13:33:11 +1300 Subject: [PATCH] MDL-49059 medialib: Support start time params in Youtube URLs Medialib (and thus the Multimedia Plugins filter) was ignoring start time parameters on YouTube video URLs, meaning that the video would always start at the start, even when the appropriate parameter was present. --- lib/medialib.php | 49 +++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 48 insertions(+), 1 deletion(-) diff --git a/lib/medialib.php b/lib/medialib.php index 9a2ad64e142..f4583c4eb95 100644 --- a/lib/medialib.php +++ b/lib/medialib.php @@ -536,15 +536,62 @@ class core_media_player_youtube extends core_media_player_external { self::pick_video_size($width, $height); + $params = ''; + $start = self::get_start_time($url); + if ($start > 0) { + $params .= "start=$start&"; + } + return << + src="https://www.youtube.com/embed/$videoid?{$params}rel=0&wmode=transparent" frameborder="0" allowfullscreen="1"> OET; } + /** + * Check for start time parameter. Note that it's in hours/mins/secs in the URL, + * but the embedded player takes only a number of seconds as the "start" parameter. + * @param moodle_url $url URL of video to be embedded. + * @return int Number of seconds video should start at. + */ + protected static function get_start_time($url) { + $matches = array(); + $seconds = 0; + + $rawtime = $url->param('t'); + if (empty($rawtime)) { + $rawtime = $url->param('start'); + } + + if (is_numeric($rawtime)) { + // Start time already specified as a number of seconds; ensure it's an integer. + $seconds = $rawtime; + } else if (preg_match('/(\d+?h)?(\d+?m)?(\d+?s)?/i', $rawtime, $matches)) { + // Convert into a raw number of seconds, as that's all embedded players accept. + for ($i = 1; $i < count($matches); $i++) { + if (empty($matches[$i])) { + continue; + } + $part = str_split($matches[$i], strlen($matches[$i]) - 1); + switch ($part[1]) { + case 'h': + $seconds += 3600 * $part[0]; + break; + case 'm': + $seconds += 60 * $part[0]; + break; + default: + $seconds += $part[0]; + } + } + } + + return intval($seconds); + } + protected function get_regex() { // Regex for standard youtube link $link = '(youtube(-nocookie)?\.com/(?:watch\?v=|v/))';