-
Notifications
You must be signed in to change notification settings - Fork 37
/
Copy pathOembedService.php
executable file
·333 lines (278 loc) · 11.5 KB
/
OembedService.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
<?php
/**
* oEmbed plugin for Craft CMS 3.x
*
* A simple plugin to extract media information from websites, like youtube videos, twitter statuses or blog articles.
*
* @link https://github.com/wrav
* @copyright Copyright (c) 2017 reganlawton
*/
namespace wrav\oembed\services;
use craft;
use craft\base\Component;
use craft\helpers\Template;
use DOMDocument;
use Embed\Embed;
use Exception;
use wrav\oembed\adapters\EmbedAdapter;
use wrav\oembed\adapters\FallbackAdapter;
use wrav\oembed\events\BrokenUrlEvent;
use wrav\oembed\Oembed;
/**
* OembedService Service
*
* @author reganlawton
* @package Oembed
* @since 1.0.0
*/
class OembedService extends Component
{
private $youtubePattern = '/(?:http|https)*?:*\/\/(?:www\.|)(?:youtube\.com|m\.youtube\.com|youtu\.be|youtube-nocookie\.com)/i';
/**
* @param $url
* @param array $options
* @return string
*/
public function render($url, array $options = [], array $cacheProps = [])
{
/** @var Media $media */
$media = $this->embed($url, $options, $cacheProps);
if (!empty($media)) {
// If code is empty, we have a fallback to HTML prop
if(empty($media->code)) {
return Template::raw($media->html ?? '');
}
return Template::raw($media->code ?? '');
} else {
return null;
}
}
/**
* @param string $input
* @param array $options
* @return string
*/
public function parseTags(string $input, array $options = [], array $cacheProps = [])
{
if (empty($input)) {
return '';
}
$output = preg_replace_callback('/\<oembed\s(?:.*?)url="(.*?)"(?:.*?)>(?:.*?)<\/oembed>/i', function($matches) use ($options, $cacheProps) {
$url = $matches[1];
return $this->render($url, $options, $cacheProps);
}, $input);
return $output;
}
/**
* @param $url
* @param array $options
* @return Media|string
*/
public function embed($url, array $options = [], array $cacheProps = [], $factories = [])
{
$plugin = Craft::$app->plugins->getPlugin('oembed');
try {
$hash = md5(json_encode($options)).md5(json_encode($cacheProps));
} catch (\Exception $exception) {
$hash = '';
}
$cacheKey = $url . '_' . $plugin->getVersion() . '_' . $hash;
$data = [];
if (Oembed::getInstance()->getSettings()->enableCache && Craft::$app->cache->exists($cacheKey)) {
return \Craft::$app->cache->get($cacheKey);
}
if (Oembed::getInstance()->getSettings()->facebookKey) {
$options['facebook']['key'] = Oembed::getInstance()->getSettings()->facebookKey;
}
try {
array_multisort($options);
$embed = new Embed();
// Add custom factories
if (count($factories) > 0) {
foreach ($factories as $factory) {
$embed->getExtractorFactory()->addAdapter($factory['domain'], $factory['extractor']::class);
}
}
$infos = $embed
->get($url ?: "")
;
$infos->setSettings($options);
$data = $infos->getOEmbed()->all();
$media = new EmbedAdapter($data, $infos);
} catch (Exception $e) {
Craft::info($e->getMessage(), 'oembed');
// Trigger notification event
if (Oembed::getInstance()->getSettings()->enableNotifications) {
Oembed::getInstance()->trigger(Oembed::EVENT_BROKEN_URL_DETECTED, new BrokenUrlEvent([
'url' => $url,
]));
}
// Create fallback
$media = new FallbackAdapter([
'html' => $url ? '<iframe src="'.$url.'"></iframe>' : null
]);
} finally {
// Fallback to iframex
if (empty($data)) {
$data = [
'html' => $url ? '<iframe src="'.$url.'"></iframe>' : null
];
}
// Wrapping to be safe :)
try {
$dom = new DOMDocument;
$html = $media->getCode() ?: null;
if (empty($html) || empty((string)$url) ) {
$html = empty((string)$url) ? '' : '<iframe src="'.$url.'"></iframe>';
$dom->loadHTML($html);
} else {
$dom->loadHTML($data['html']);
}
$iframe = $dom->getElementsByTagName('iframe')->item(0);
$src = $iframe->getAttribute('src');
$src = $this->manageGDPR($src);
// Adds additional attributes for GDPR compliance
if (Oembed::getInstance()->getSettings()->enableGdprCookieBot) {
$iframe->setAttribute('data-cookieblock-src', $src);
$iframe->setAttribute('data-cookieconsent', 'marketing');
}
// Solved issue with "params" options not applying
if (!preg_match('/\?(.*)$/i', $src)) {
$src .= "?";
}
if (!empty($options['params'])) {
foreach ((array)$options['params'] as $key => $value) {
// If value is an array, skip
if (is_array($value)) {
continue;
}
$src = preg_replace('/\?(.*)$/i', '?' . $key . '=' . $value . '&${1}', $src);
}
}
// Autoplay
if (!empty($options['autoplay']) && strpos($src, 'autoplay=') === false && $src) {
$src = preg_replace('/\?(.*)$/i', '?autoplay=' . (!!$options['autoplay'] ? '1' : '0') . '&${1}', $src);
}
// Width - Override
if (!empty($options['width']) && is_int($options['width'])) {
$iframe->setAttribute('width', $options['width']);
}
// Height - Override
if (!empty($options['height']) && is_int($options['height'])) {
$iframe->setAttribute('height', $options['height']);
}
// Looping
if (!empty($options['loop']) && strpos($src, 'loop=') === false && $src) {
$src = preg_replace('/\?(.*)$/i', '?loop=' . (!!$options['loop'] ? '1' : '0') . '&${1}', $src);
}
// Autopause
if (!empty($options['autopause']) && strpos($src, 'autopause=') === false && $src) {
$src = preg_replace('/\?(.*)$/i', '?autopause=' . (!!$options['autopause'] ? '1' : '0') . '&${1}', $src);
}
// Rel
if (!empty($options['rel']) && strpos($src, 'rel=') === false && $src) {
$src = preg_replace('/\?(.*)$/i', '?rel=' . (!!$options['rel'] ? '1' : '0') . '&${1}', $src);
}
// Apply attributes to the iframe
if (!empty($options['attributes'])) {
foreach ((array)$options['attributes'] as $key => $value) {
$iframe->setAttribute($key, $value);
// If key in array, add to the media object
if (in_array($key, ['width', 'height'])) {
$media->$key = $value;
}
}
}
// Resolve YT loop issues
preg_match($this->youtubePattern, $url, $ytMatch, PREG_OFFSET_CAPTURE);
// If youtube video and loop=1 is found
if (count($ytMatch) && strpos($src, 'loop=1') !== false) {
// Get playlist param from the URL code
preg_match('/\/embed\/([^?]+)/', $src, $ytCode);
// If playlist param is found
if (count($ytCode)) {
// Add playlist param to the URL
$src = preg_replace('/\?(.*)$/i', '?playlist=' . $ytCode[1] . '&${1}', $src);
}
}
// Set the SRC
$iframe->setAttribute('src', $src);
// Set the code
$code = $dom->saveXML($iframe, LIBXML_NOEMPTYTAG);
// Apply the code to the media object
$media->code = $code;
// Set the URL if not set
$media->url = $media->url ?: $url;
} catch (\Exception $exception) {
Craft::info($exception->getMessage(), 'oembed');
} finally {
if (Oembed::getInstance()->getSettings()->enableCache) {
// Cache failed requests only for 15 minutes
$duration = $media instanceof FallbackAdapter ? 15 * 60 : 60 * 60;
$defaultCacheKeys = [
'title',
'description',
'url',
'type',
'tags',
'images',
'image',
'imageWidth',
'imageHeight',
'code',
'width',
'height',
'aspectRatio',
'authorName',
'authorUrl',
'providerName',
'providerUrl',
'providerIcons',
'providerIcon',
'publishedDate',
'license',
'linkedData',
'feeds',
];
$cacheKeys = array_unique(array_merge($defaultCacheKeys, $cacheProps));
// Make sure all keys are set to avoid errors
foreach ($cacheKeys as $key) {
try {
$media->{$key} = $media->{$key};
} catch (\Exception $e) {
$media->{$key} = null;
}
}
Craft::$app->cache->set($cacheKey, json_decode(json_encode($media)), $duration);
}
return $media ?? [];
}
}
}
private function manageGDPR($url)
{
if (Oembed::getInstance()->getSettings()->enableGdpr) {
$skip = false;
$youtubePattern = '/(?:http|https)*?:*\/\/(?:www\.|)(?:youtube\.com|m\.youtube\.com|youtu\.be|youtube-nocookie\.com)/i';
preg_match($youtubePattern, $url, $matches, PREG_OFFSET_CAPTURE);
if (count($matches)) {
$url = preg_replace($youtubePattern, 'https://www.youtube-nocookie.com', $url);
$skip = true;
}
if (!$skip) {
if (strpos($url, 'vimeo.com') !== false) {
if (strpos($url, 'dnt=') === false) {
preg_match('/\?.*$/', $url, $matches, PREG_OFFSET_CAPTURE);
if (count($matches)) {
$url = preg_replace('/(\?(.*))$/i', '?dnt=1&${2}', $url);
} else {
$url = $url . '?dnt=1';
}
}
$url = preg_replace('/(dnt=(1|0))/i', 'dnt=1', $url);
}
}
}
return $url;
}
}