TYPO3  7.6
YouTubeHelper.php
Go to the documentation of this file.
1 <?php
2 namespace TYPO3\CMS\Core\Resource\OnlineMedia\Helpers;
3 
4 /*
5  * This file is part of the TYPO3 CMS project.
6  *
7  * It is free software; you can redistribute it and/or modify it under
8  * the terms of the GNU General Public License, either version 2
9  * of the License, or any later version.
10  *
11  * For the full copyright and license information, please read the
12  * LICENSE.txt file that was distributed with this source code.
13  *
14  * The TYPO3 project - inspiring people to share!
15  */
16 
20 
25 {
33  public function getPublicUrl(File $file, $relativeToCurrentScript = false)
34  {
35  $videoId = $this->getOnlineMediaId($file);
36  return sprintf('https://www.youtube.com/watch?v=%s', $videoId);
37  }
38 
45  public function getPreviewImage(File $file)
46  {
47  $videoId = $this->getOnlineMediaId($file);
48  $temporaryFileName = $this->getTempFolderPath() . 'youtube_' . md5($videoId) . '.jpg';
49 
50  if (!file_exists($temporaryFileName)) {
51  $previewImage = GeneralUtility::getUrl(
52  sprintf('https://img.youtube.com/vi/%s/0.jpg', $videoId)
53  );
54  if ($previewImage !== false) {
55  file_put_contents($temporaryFileName, $previewImage);
56  GeneralUtility::fixPermissions($temporaryFileName);
57  }
58  }
59 
60  return $temporaryFileName;
61  }
62 
70  public function transformUrlToFile($url, Folder $targetFolder)
71  {
72  $videoId = null;
73  // Try to get the YouTube code from given url.
74  // These formats are supported with and without http(s)://
75  // - youtu.be/<code> # Share URL
76  // - www.youtube.com/watch?v=<code> # Normal web link
77  // - www.youtube.com/v/<code>
78  // - www.youtube-nocookie.com/v/<code> # youtube-nocookie.com web link
79  // - www.youtube.com/embed/<code> # URL form iframe embed code, can also get code from full iframe snippet
80  if (preg_match('%(?:youtube(?:-nocookie)?\.com/(?:[^/]+/.+/|(?:v|e(?:mbed)?)/|.*[?&]v=)|youtu\.be/)([^"&?/ ]{11})%i', $url, $match)) {
81  $videoId = $match[1];
82  }
83  if (empty($videoId)) {
84  return null;
85  }
86  return $this->transformMediaIdToFile($videoId, $targetFolder, $this->extension);
87  }
88 
96  protected function getOEmbedUrl($mediaId, $format = 'json')
97  {
98  return sprintf('https://www.youtube.com/oembed?url=%s&format=%s',
99  urlencode(sprintf('https://www.youtube.com/watch?v=%s', $mediaId)),
100  rawurlencode($format)
101  );
102  }
103 }