TYPO3 CMS  TYPO3_7-6
YouTubeHelper.php
Go to the documentation of this file.
1 <?php
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', rawurlencode($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  $tryNames = ['maxresdefault.jpg', '0.jpg'];
52  foreach ($tryNames as $tryName) {
53  $previewImage = GeneralUtility::getUrl(
54  sprintf('https://img.youtube.com/vi/%s/%s', $videoId, $tryName)
55  );
56  if ($previewImage !== false) {
57  file_put_contents($temporaryFileName, $previewImage);
58  GeneralUtility::fixPermissions($temporaryFileName);
59  break;
60  }
61  }
62  }
63 
64  return $temporaryFileName;
65  }
66 
74  public function transformUrlToFile($url, Folder $targetFolder)
75  {
76  $videoId = null;
77  // Try to get the YouTube code from given url.
78  // These formats are supported with and without http(s)://
79  // - youtu.be/<code> # Share URL
80  // - www.youtube.com/watch?v=<code> # Normal web link
81  // - www.youtube.com/v/<code>
82  // - www.youtube-nocookie.com/v/<code> # youtube-nocookie.com web link
83  // - www.youtube.com/embed/<code> # URL form iframe embed code, can also get code from full iframe snippet
84  if (preg_match('%(?:youtube(?:-nocookie)?\.com/(?:[^/]+/.+/|(?:v|e(?:mbed)?)/|.*[?&]v=)|youtu\.be/)([^"&?/ ]{11})%i', $url, $match)) {
85  $videoId = $match[1];
86  }
87  if (empty($videoId)) {
88  return null;
89  }
90  return $this->transformMediaIdToFile($videoId, $targetFolder, $this->extension);
91  }
92 
100  protected function getOEmbedUrl($mediaId, $format = 'json')
101  {
102  return sprintf(
103  'https://www.youtube.com/oembed?url=%s&format=%s',
104  rawurlencode(sprintf('https://www.youtube.com/watch?v=%s', rawurlencode($mediaId))),
105  rawurlencode($format)
106  );
107  }
108 }
getPublicUrl(File $file, $relativeToCurrentScript=false)
transformMediaIdToFile($mediaId, Folder $targetFolder, $fileExtension)
static fixPermissions($path, $recursive=false)
static getUrl($url, $includeHeader=0, $requestHeaders=false, &$report=null)