-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTextformatterVideoMarkup.module
More file actions
389 lines (344 loc) · 9.53 KB
/
TextformatterVideoMarkup.module
File metadata and controls
389 lines (344 loc) · 9.53 KB
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
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
<?php namespace ProcessWire;
/**
* Textformatter Video Markup
*
* #pw-summary Render oEmbed data from YouTube/Vimeo URLs.
* #pw-body Based on TextformatterVideoEmbed by Ryan Cramer and TextformatterVideoEmbedOptions by Steffen Henschel.
*
* @copyright 2026 NB Communication Ltd
* @license Mozilla Public License v2.0 http://mozilla.org/MPL/2.0/
*
* @property Field $field
* @property bool $html
* @property bool $isHtml
* @property Page $page
*
*/
class TextformatterVideoMarkup extends Textformatter implements ConfigurableModule {
/**
* getModuleInfo is a module required by all modules to tell ProcessWire about them
*
* @return array
*
*/
public static function getModuleInfo() {
return [
'title' => 'Video markup for YouTube/Vimeo',
'version' => 105,
'summary' => 'Render oEmbed data from YouTube/Vimeo URLs.',
'author' => 'nbcommunication',
'href' => 'https://github.com/nbcommunication/TextformatterVideoMarkup',
'icon' => 'video-camera',
'requires' => 'ProcessWire>=3.0.148,PHP>=7',
];
}
const noCookie = 'noCookie';
/**
* The field
*
* @var Field
*
*/
public $field = null;
/**
* Is HTML?
*
* @var bool
* @todo should be private?
*
*/
public $html = false;
/**
* Is HTML?
*
* @var bool
*
*/
public $isHtml = false;
/**
* The page
*
* @var Page
*
*/
public $page = null;
/**
* Format the given text string with Page and Field provided.
*
* @param Page $page
* @param Field $field
* @param string|mixed $value Value is provided as a reference, so is modified directly (not returned).
*
*/
public function formatValue(Page $page, Field $field, &$value) {
$this->page = $page;
$this->field = $field;
// Is HTML being parsed?
if($field instanceof Field && $page instanceof Page) {
$of = $page->of();
$page->of(false); // Set output formatting to false before getting the Inputfield
$inputfield = $field->getInputfield($page);
$this->html = $this->isHtml ?: $inputfield instanceof InputfieldTextarea && $inputfield->contentType >= 1;
$page->of($of);
}
$value = str_replace('&', '&', $value);
$this->renderYoutube($value);
$this->renderVimeo($value);
$this->isHtml = false; // reset for next use
}
/**
* Render the data
*
* @param string $tpl
* @param array|null $data
* @param string $line
* @param string|null $emptyValue
* @return string
*
*/
public function ___render($tpl, $data, $line, $emptyValue = null) {
if(!is_array($data)) {
if(is_null($emptyValue)) $emptyValue = $this->emptyValue;
if(strpos($emptyValue, '{link}') !== false) {
$url = $this->html ? strip_tags($line) : $line;
$link = "<a href=$url target=_blank rel=noopener>$url</a>";
$emptyValue = str_replace('{link}', ($this->html ? "<p>$link</p>" : $link), $emptyValue);
}
$emptyValue = str_replace('{url}', $line, $emptyValue);
return $emptyValue;
}
foreach($data as $key => $value) {
if(!is_array($value)) {
$tpl = str_replace('{' . $key .'}', (string) $value, $tpl);
}
}
return $tpl;
}
/**
* Apply options
*
* @param string $prefix
* @param string $url
* @return string
*
*/
protected function applyOptions($prefix, $url) {
$prefix = "{$prefix}_";
$query = [];
$url = explode('?', $url);
if(count($url) > 1) {
parse_str($url[1], $q);
$query = array_merge($query, $q);
}
foreach($this->data as $key => $value) {
if($value === '' || substr($key, 3) === self::noCookie) continue;
if(substr($key, 0, 3) == $prefix) {
$key = str_replace($prefix, '', $key);
if(!isset($query[$key])) {
$query[$key] = $value;
}
}
}
// Apply current language if multi-language enabled
if($this->wire()->languages !== null) {
$lang = $this->wire()->user->language->name;
if($lang) {
foreach([
'yt' => ['cc_lang_pref', 'hl'],
'vm' => ['texttrack'],
] as $provider => $keys) {
if($prefix == "{$provider}_") {
foreach($keys as $key) {
if(!isset($query[$key])) {
$query[$key] = $lang;
}
}
}
}
}
}
foreach($query as $key => $value) {
// Remove # on vm_color
if($key == 'color' && $prefix == 'vm_') $query[$key] = ltrim($value, '#');
}
return $url[0] . (count($query) ? '?' . http_build_query($query) : '');
}
/**
* Apply Vimeo options
*
* Based on TextformatterVideoEmbedOptions::applyVimeo by Steffen Henschel.
*
* @param string $url
* @return string
*
*/
protected function applyVimeoOptions($url) {
return $this->applyOptions('vm', $url);
}
/**
* Apply YouTube options
*
* Based on TextformatterVideoEmbedOptions::applyYoutube by Steffen Henschel.
*
* @param string $url
* @return string
*
*/
protected function applyYoutubeOptions($url) {
return $this->applyOptions('yt', $this->applyYoutubeNoCookie($url));
}
/**
* Apply the YouTube 'No Cookie' URL
*
* @param string $url
* @return string
*
*/
protected function applyYoutubeNoCookie($url) {
return $this->yt_noCookie ? str_replace('youtube.com', 'youtube-nocookie.com', $url) : $url;
}
/**
* Given a service oembed URL and video ID, return its oEmbed data.
*
* A cached version of the data will be used if possible. When not possible,
* it will be retrieved from the service's oembed URL, and then cached.
*
* @param string $provider
* @param string $url
* @param string $originalUrl
* @return array
*
*/
protected function getData($provider, $url, $originalUrl = '') {
$isYoutube = $provider == 'yt';
$query = [
'url' => $url,
'maxwidth' => $this->maxWidth,
'maxheight' => $this->maxHeight,
];
if($isYoutube) {
$query['format'] = 'json';
}
$endpoint = ($isYoutube ?
'https://www.youtube.com/oembed' :
'https://vimeo.com/api/oembed.json'
) . '?' . http_build_query($query);
$data = $this->wire()->cache->getFor($this, md5($endpoint), function() use ($endpoint) {
$response = $this->wire(new WireHttp())->getJSON($endpoint);
if($response && is_array($response) && count($response)) {
return $response;
}
return false;
}, WireCache::expireNever);
if(is_array($data)) {
$query = explode('?', $url);
if(count($query) > 1 && isset($data['html'])) {
$query = $query[1];
if(strlen($query)) {
$query = str_replace('&', '&', $query);
if($isYoutube) {
$query = explode('&', $query, 2);
$query = count($query) > 1 ? trim($query[1], '&') : '';
}
if($query) {
$data['html'] = str_replace('?', "?$query&", $data['html']);
$data['params'] = $query;
}
$data['html'] = $this->applyYoutubeNoCookie($data['html']);
}
}
$data['url'] = $originalUrl ?: $url;
preg_match('/<iframe.*?src="(.*?)"/', $data['html'], $matches);
$data['embedUrl'] = count($matches) ? $matches[1] : '';
$data['width'] = $data['width'] ?? $this->maxWidth;
$data['height'] = $data['height'] ?? $this->maxHeight;
$data['class'] = $provider;
if($data['embedUrl'] && !isset($data['video_id'])) {
$segments = explode('/', explode('?', $data['embedUrl'])[0]);
$data['video_id'] = end($segments);
}
// lite facade
$type = $isYoutube ? 'youtube' : 'vimeo';
$data['lite'] = "<lite-$type videoid=\"{$data['video_id']}\" params=\"{$data['params']}\" playlabel=\"{$this->_('Play')}: {$data['title']}\"></lite-$type>";
if($this->wire()->config->debug) {
$table = $this->wire()->modules->get('MarkupAdminDataTable');
foreach($data as $key => $value) $table->row([$key, $value]);
$data['debug'] = "<h3>$url</h3>" . $table->render();
} else {
$data['debug'] = '';
}
}
return is_array($data) ? $data : [];
}
/**
* Check for Vimeo URLs and render the data if found
*
* Based on TextformatterVideoEmbed::embedVimeo by Ryan Cramer.
*
* @param string $str
*
*/
protected function renderVimeo(&$str) {
if(strpos($str, '://vimeo.com/') === false) return;
if(!preg_match_all(
'#' .
($this->html ? '<p>' : '') .
'\s*(https?://vimeo.com/\S*)' .
($this->html ? '</p>' : '') .
'#',
$str,
$matches
)) return;
foreach($matches[0] as $key => $line) {
$url = $this->applyVimeoOptions($matches[1][$key], 'vm');
$str = $this->replace($str, $this->getData('vm', $url), $line);
}
}
/**
* Check for Youtube URLs and render the data if found
*
* Based on TextformatterVideoEmbed::embedYoutube by Ryan Cramer.
*
* @param string $str
*
*/
protected function renderYoutube(&$str) {
// perform a strpos fast check before performing regex check
if(strpos($str, '://www.youtube.com/watch') === false
&& strpos($str, '://www.youtube.com/v/') === false
&& strpos($str, '://www.youtube.com/shorts/') === false
&& strpos($str, '://youtu.be/') === false) return;
if(!preg_match_all(
'#' .
($this->html ? '<p>' : '') .
'\s*(https?://(?:www\.)?youtu(?:.be|be.com)+/(?:watch/?\?v=|v/|shorts/)?([^\s&<\'"]+)(&[-_,.=&;a-zA-Z0-9]*)?).*?' .
($this->html ? '</p>' : '') .
'#',
$str,
$matches
)) return;
foreach($matches[0] as $key => $line) {
$originalUrl = $matches[1][$key];
$url = $this->applyYoutubeOptions($originalUrl, 'yt');
$str = $this->replace($str, $this->getData('yt', $url, $originalUrl), $line);
}
}
/**
* Replace the URL with the rendered markup
*
* @param string $str
* @param array $data
* @param string $line
* @return string
*
*/
protected function replace($str, $data, $line) {
return str_replace(
$line,
empty($data) ?
'' : // no data, so return empty string
$this->render(($this->markupTpl ?: ($data['debug'] ? '{debug}' : '{html}')), $data, $line),
$str
);
}
}