-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTextformatterLiteVideoEmbed.module
More file actions
437 lines (322 loc) · 12.5 KB
/
TextformatterLiteVideoEmbed.module
File metadata and controls
437 lines (322 loc) · 12.5 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
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
<?php namespace ProcessWire;
/**
* ProcessWire Lite Video Embed Module
*
* stephen at millipedia.com
*
* This module licensed under MIT
*
* This textformatter replaces youTube links with Justin Ribeiro's web component
* https://github.com/justinribeiro/lite-youtube/
*
* and Vimeo links with
* https://github.com/slightlyoff/lite-vimeo
*
* * Which I got to via Paul Irish's
* https://github.com/paulirish/lite-youtube-embed
*
* for which jacmaes built a similar thing
* https://github.com/jacmaes/TextformatterLiteYouTubeEmbed)
* some of which is probably still in this version.
*
* There's some discussion of it at this (hijacked) thread.
* https://processwire.com/talk/topic/23528-lite-youtube-embed-module/
*
* ..and now on this non-hijacked thread
* https://processwire.com/talk/topic/28820-textformatterlitevideoembed/
*
* MODULE CONFIGURATION PROPERTIES
* ===============================
* @property string $vimeo_colour Vimeo play button colour
* @property string $youtube_colour Vimeo play button colour
*
*/
class TextformatterLiteVideoEmbed extends Textformatter implements Module, ConfigurableModule
{
public static function getModuleInfo()
{
return array(
'title' => __('Lite Video Embed'),
'version' => 003,
'summary' => __("Replaces plain video links in a text area or text input field with a subdom web component that mimics YouTube or Vimeo but only loads the video when clicked."),
'author' => 'millipedia',
);
}
protected $ytl_added = 0;
/**
* Construct
*
* Set default values for configuration settings
*
*/
public function __construct()
{
$this->set('vimeo_colour', '#62afed');
$this->set('youtube_colour', '#ff0000');
parent::__construct();
}
/**
* Build module configuration inputs
*
* If you prefer configuration can also be specified more declaratively with a PHP
* array in an external configuration file. See the /extras/Helloworld.config.php
* file included in this module’s files for an example.
*
* @param InputfieldWrapper $inputfields
*
*/
public function getModuleConfigInputfields(InputfieldWrapper $inputfields)
{
$modules = $this->wire()->modules;
/** @var InputfieldText $f */
$f = $modules->get('InputfieldText');
$f->attr('name', 'vimeo_colour');
$f->label = $this->_('Vimeo button colour');
$f->description = $this->_('Hex colour for Vimeo play button placeholder');
$f->val($this->vimeo_colour);
$f->required = true;
$f->icon = 'vimeo';
$inputfields->add($f);
$f = $modules->get('InputfieldText');
$f->attr('name', 'youtube_colour');
$f->label = $this->_('Youtube button colour');
$f->description = $this->_('Hex colour for Youtube play button placeholder');
$f->val($this->youtube_colour);
$f->required = true;
$f->icon = 'youtube';
$inputfields->add($f);
}
/**
* Format the input string
*
* @param string $str The block of text to parse
*
* The incoming string is replaced with the formatted version of itself.
**/
public function format(&$str)
{
$this->embedYoutube($str);
$this->embedVimeo($str);
}
public function embedYoutube(&$str)
{
// perform a quick check before moving on to the more expensive regex
if (
strpos($str, '://www.youtube.com/watch') === false
&& strpos($str, '://www.youtube.com/v/') === false
&& strpos($str, '://youtu.be/') === false
) return;
// regex to find YouTube link in a paragraph
// TODO: do I have one for non-cookie domain somewhere? Sure I did... anyway we could use no-cookie in the markup as an option.
// do we know what field type this is? must do surely? If not can we just ass-u-me that if we have a paragraph tag it's
// a text area and if not it's a text input... hmmm.
$regex = '#<p>\s*(https?:\/\/(?:www\.)?youtu(?:.be|be.com)+\/(?:watch\/?\?v=|v\/)?([^\s&<\'"]+))(&[-_,.=&;a-zA-Z0-9]*)?.*?</p>#';
if (preg_match_all($regex, $str, $matches) > 0) {
foreach ($matches[0] as $key => $line) {
// Alternative regex that also allows to find video ID:
// https://gist.github.com/ghalusa/6c7f3a00fd2383e5ef33
// preg_match('%(?:youtube(?:-nocookie)?\.com/(?:[^/]+/.+/|(?:v|e(?:mbed)?)/|.*[?&]v=)|youtu\.be/// )([^"&?/ ]{11})%i', $line, $match);
// $video_id = $match[1];
$lyt_params=$this->get_lyt_parameters($line);
// Find video ID
$video_id = $matches[2][$key];
// get the markup
$lyt_markup = $this->get_lyt_markup($video_id, $lyt_params, $line);
// replace the captured text with the markup.
$str = str_replace($line, $lyt_markup, $str);
}
} else {
// See if we can do the same for a text field with just the URL in.
// Does this string begin with a YouTube URL?
// in either youtube format or watch format
if (preg_match('/^(https?:\/\/(?:www\.)?youtu(?:.be|be.com)+\/(?:watch\/?\?v=|v\/)?([^\s&<\'"]+))(&[-_,.=&;a-zA-Z0-9]*)?.*$/', $str, $matches)) {
$video_id = $matches[2];
$lyt_params = $this->get_lyt_parameters($str);
$lyt_markup = $this->get_lyt_markup($video_id, $lyt_params, $str);
$str = str_replace($str, $lyt_markup, $str);
}
}
// can we add our script to wire->config->scripts?
// .... no. we can't. We can try adding inline but we don't have access to our nonce... hmmm.
// wonder if this needs to be hooked somewhere?
$str = $this->add_you_tube_script($str);
}
/**
* Given a match for a YoutTube url
* lets try and dig out some paramters
*/
public function get_lyt_parameters($yt_url)
{
// We now have an array of parameters we pass to
// lite you tube.
$lyt_params = [];
// TODO: - pull in some of these params from a config field.
// and also the nocookie flag (which we have on by default)
$lyt_params['params'] = '&modestbranding=2&rel=0&enablejsapi=1';
$lyt_params['videoStartAt'] = 0; // lyt uses a separate start value.
$lyt_params['fallback_params'] = '';
$lyt_params['original_params'] = '';
// let's just grab the url to use in parse_string rather than regexing for each parameter.
$yt_url = strip_tags($yt_url);
$yt_url = html_entity_decode($yt_url);
$qparams = [];
parse_str($yt_url, $qparams);
if (array_key_exists('thumbnail', $qparams)) {
$lyt_params['thumbnail'] = $qparams['thumbnail']; // Guess we should saniize this...
} else {
$lyt_params['thumbnail'] = '';
}
if (array_key_exists('start', $qparams)) {
$lyt_params['videoStartAt'] = (int)$qparams['start']; // is this always an int?
} else {
$lyt_params['videoStartAt'] = 0;
}
return $lyt_params;
}
public function embedVimeo(&$str)
{
if (strpos($str, '://vimeo.com/') === false) return;
$lv_params = ''; //TODO : this currently hardcoded into the JS. Need to add parameters and parameters ....
$regex = '#<p>\s*(https?://vimeo.com/(\d+)).*?</p>#';
// get all matches in textarea.
if (preg_match_all($regex, $str, $matches) > 0) {
foreach ($matches[0] as $key => $line) {
// Find video ID
$video_id = $matches[2][$key];
$lv_markup = $this->get_lv_markup($video_id, $lv_params, $line);
$str = str_replace($line, $lv_markup, $str);
$str = $this->add_you_tube_script($str);
}
} else {
// check for match in text field
// this should just be the entire content of the field.
if (preg_match('/(?:http:|https:|)\/\/(?:player.|www.)?vimeo\.com\/(?:video\/|embed\/|watch\?\S*v=|v\/)?(\d*)/', $str, $matches)) {
$line = $matches[0];
$video_id = $matches[1];
$lv_markup = $this->get_lv_markup($video_id, $lv_params, $line);
$str = str_replace($line, $lv_markup, $str);
$str = $this->add_you_tube_script($str);
} else {
// bd("no matches");
}
}
}
/**
* Add the lite youtube script inline, and
* set a flag so we only load it once.
*/
function add_you_tube_script($str)
{
$script = '';
// have we done this before in this content block?
if (strpos($str, 'millco_lite_youtube')) {
return $str;
}
// Was trying to set a global flag so we could see if we needed to add our code
// but it didn't work consistently. So now we check in javascript. Be nice to see if
// we can make it work though just so we're not reloading code.
// $already_added=wire()->page->get('lyt_script_added');
// if(!$already_added){
// // and set a flag so we know we've already added it.
// wire()->page->set('lyt_script_added', 1);
// }
// if not then load the script into a string
// do we have a nonce to add to our scripts?
$nonce = '';
// To use this you need to have a page variable nonce set.
// In my case I use the MillcoUtils module
// which generates a nonce to use by calling $page->nonce
//
// Or you can set a page variable in you _init.php file
// (or wherever is suitable) eg
//
// $nonce = base64_encode(random_bytes(20));
// $page->set('nonce', $nonce);
//
if (wire('page')->nonce) {
$nonce = wire('page')->nonce;
} elseif (wire('page')->get('nonce')) {
$nonce = wire('page')->get('nonce');
}
if ($nonce !== '') {
$nonce = ' nonce="' . $nonce . '" ';
};
$tflve_script_path = wire()->config->urls->siteModules . 'TextformatterLiteVideoEmbed';
$script = '';
// Add custom properties for our button placeholders.
// Handily we can use custom properties to target a shadow dom component.
$script .= '<style ' . $nonce . '> :root{ --millco-lvo-playbtn:' . $this->vimeo_colour . '; --millco-yt: ' . $this->youtube_colour . ' }</style>';
// We explictily write our js here now with full paths
// because import is fussy about dynamic paths.
$script .= '<script class="millco_lite_youtube" ' . $nonce . '>';
//$script .= 'var tflve_script_path="' . $tflve_script_path . '";' . PHP_EOL;
//$script.='console.log(typeof window.text_formatter_lite_video_embed_scripts_loaded);';
$script .= "if (typeof window.text_formatter_lite_video_embed_scripts_loaded === 'undefined') {" . PHP_EOL;
$script .= "async function loadYTLite() {" . PHP_EOL;
$script .= "const LiteYTEmbed = await import('$tflve_script_path/lite-youtube.js?v=1');" . PHP_EOL;
$script .= "const LiteVimeoEmbed = await import('$tflve_script_path/lite-vimeo.js?v=1');" . PHP_EOL;
$script .= "}" . PHP_EOL;
$script .= "loadYTLite();" . PHP_EOL;
$script .= "window.text_formatter_lite_video_embed_scripts_loaded = 1;" . PHP_EOL;
$script .= "}" . PHP_EOL;
$script .= '</script>';
return $str . $script;
}
/**
* Write out the markup for a youtube-lite tag.
* @param String $video_id The YouTube id of the video
* @param Array $lyt_parmas and array of parameters
* @param String $line The url that we're going to replace with our markup.
*
*/
function get_lyt_markup($video_id, $lyt_params, $line)
{
$lyt_markup = '';
$lyt_markup .= '<lite-youtube class="lv_element lv_element_vimeo" videoid="' . $video_id . '" nocookie=1 ';
$lyt_markup .= 'params="' . $lyt_params['params'] . '"';
if ($lyt_params['videoStartAt']) {
$lyt_markup .= ' videoStartAt="' . $lyt_params['videoStartAt'] . '"';
}
// If we pass a thumbnail then add that to our tag as a dataset item.
if ($lyt_params['thumbnail']) {
$lyt_markup .= ' data-thumbnail="' . $lyt_params['thumbnail'] . '"';
}
$lyt_markup .= '>';
// fallback for old browsers.
$fallback_url = $this->url_from_line($line);
$lyt_markup .= '<a class="lite-youtube-fallback" href="' . $fallback_url . $lyt_params['fallback_params'] . '">Watch on YouTube</a>';
$lyt_markup .= '</lite-youtube>';
return $lyt_markup;
}
/**
* Write out the markup for a vimeo-lite tag.
* @param String $video_id The YouTube id of the video
* @param String $lv parmas Params to pass to youtube
* @param String $line The url that we're going to replace with our markup.
*
*/
function get_lv_markup($video_id, $lv_params, $line)
{
$lv_markup = '';
$lv_markup .= '<lite-vimeo class="lv_element lv_element_vimeo" videoid="' . $video_id . '" params="' . $lv_params . '" >';
// TODO: the vimeo script will let use use a background image so we should something similar for thumbnail that we've done
// with YT.
// fallback for old browsers.
$fallback_url = $this->url_from_line($line);
$lv_markup .= '<a class="lite-youtube-fallback" href="' . $fallback_url . $lv_params . '">Watch on Vimeo</a>';
$lv_markup .= '</lite-vimeo>';
return $lv_markup;
}
/**
* Tidy the line we captured (and are replacing) to get the actual URL without tags.
* @param String $line The paragraph of text we're replacing.
*
*/
function url_from_line($line)
{
$url = str_replace('<p>', '', $line);
$url = str_replace('</p>', '', $url);
$url = trim($url);
return $url;
}
}