forked from ryancramerdesign/TextformatterVideoEmbed
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTextformatterVideoEmbed.module
472 lines (378 loc) · 13.6 KB
/
TextformatterVideoEmbed.module
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
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
<?php
/**
* ProcessWire Video Embedding Textformatter
*
* Looks for Youtube, Vimeo, Instagram, Facebook, Twitter or Issuu URLs and automatically converts them to embeds
*
* Copyright (C) 2016 by Ryan Cramer
* Licensed under MPL 2.0
* https://processwire.com
*
* @property int $maxWidth
* @property int $maxHeight
* @property int $responsive
*
*/
class TextformatterVideoEmbed extends Textformatter implements ConfigurableModule {
public static function getModuleInfo() {
return array(
'title' => __('Video or Social Post Embed', __FILE__),
'version' => 121,
'summary' => __('Enter a full YouTube, Vimeo, Instagram, Facebook, Twitter or Issuu URL by itself in any paragraph (example: http://www.youtube.com/watch?v=Wl4XiYadV_k) and this will automatically convert it to an embedded video or social post. This formatter is intended to be run on trusted input. Recommended for use with TinyMCE textarea fields.', __FILE__),
'author' => 'Ryan Cramer',
'href' => 'http://modules.processwire.com/modules/textformatter-video-embed/'
);
}
const dbTableName = 'textformatter_video_embed';
/**
* Default configuration values
*
* @var array
*
*/
protected static $configDefaults = array(
'maxWidth' => 640,
'maxHeight' => 480,
'responsive' => 0,
);
/**
* Data as used by the get/set functions
*
*/
protected $data = array();
/**
* Either http or https, depending on $config->https
*
*/
protected $http = '';
/**
* Set our configuration defaults
*
*/
public function __construct() {
foreach(self::$configDefaults as $key => $value) {
$this->set($key, $value);
}
$this->http = $this->config->https ? 'https' : 'http';
}
/**
* Given a service oembed URL and video ID, return the corresponding embed code.
*
* A cached version of the embed code will be used if possible. When not possible,
* it will be retrieved from the service's oembed URL, and then cached.
*
* @param string $oembedURL
* @param string $videoID
* @return string
*
*/
protected function getEmbedCode($oembedURL, $videoID) {
$database = $this->wire('database');
$table = self::dbTableName;
$query = $database->prepare("SELECT embed_code FROM $table WHERE video_id=:video_id");
$query->bindValue(":video_id", $videoID);
$query->execute();
$embedCode = '';
if($query->rowCount()) {
list($embedCode) = $query->fetch(\PDO::FETCH_NUM);
$query->closeCursor();
} else {
$query->closeCursor();
$http = new WireHttp();
$http->setHeader('User-Agent', 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.13) Gecko/20080311 Firefox/2.0.0.13');
$data = $http->get($oembedURL);
if($data) $data = json_decode($data, true);
if(is_array($data) && isset($data['html'])) {
$embedCode = $data['html'];
$sql = "INSERT INTO $table SET " .
"video_id=:videoID, " .
"embed_code=:embedCode, " .
"created=NOW() ";
$query = $database->prepare($sql);
$query->bindValue(":videoID", $videoID);
$query->bindValue(":embedCode", $embedCode);
$query->execute();
}
}
// account for possibility that stored embed code contains http version while requested on https
if($this->http == 'https') $embedCode = str_replace('http://', 'https://', $embedCode);
return $embedCode;
}
/**
* Make an iframe-based embed code responsive
*
* @param string $out
* @return string
*
*/
protected function makeResponsive($out) {
$out = str_ireplace('<iframe ', "<iframe style='position:absolute;top:0;left:0;width:100%;height:100%;' ", $out);
$out = "<div class='TextformatterVideoEmbed' style='position:relative;padding:30px 0 56.25% 0;height:0;overflow:hidden;'>$out</div>";
return $out;
}
/**
* Text formatting function as used by the Textformatter interface
*
* Here we look for video codes on first pass using a fast strpos() function.
* When found, we do our second pass with preg_match_all and replace the video URLs
* with the proper embed codes obtained from each service's oembed web service.
*
* @var string $str
*
*/
public function format(&$str) {
$this->embedYoutube($str);
$this->embedVimeo($str);
$this->embedIssuu($str);
$this->embedTwitter($str);
$this->embedFacebook($str);
$this->embedInstagram($str);
}
/**
* Check for Youtube URLS and embed when found
*
* @var string $str
*
*/
protected function embedYoutube(&$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, '://youtu.be/') === false) return;
// 1: full URL | 2:video id | 3: query string (optional)
$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)) return;
foreach($matches[0] as $key => $line) {
$oembedURL =
"$this->http://www.youtube.com/oembed?url=" . urlencode($matches[1][$key]) .
"&format=json&maxwidth={$this->maxWidth}&maxheight={$this->maxHeight}";
$videoID = $matches[2][$key];
$queryString = isset($matches[3][$key]) ? $matches[3][$key] : '';
$embedCode = $this->getEmbedCode($oembedURL, $videoID);
if($embedCode) {
if(strlen($queryString)) {
$queryString = str_replace('&', '&', $queryString);
$queryString = trim($queryString, '&');
$embedCode = str_replace("?", "?$queryString&", $embedCode);
}
if($this->responsive) $embedCode = $this->makeResponsive($embedCode);
$str = str_replace($line, $embedCode, $str);
}
}
}
/**
* Check for Vimeo URLS and embed when found
*
* @var string $str
*
*/
protected function embedVimeo(&$str) {
if(strpos($str, '://vimeo.com/') === false) return;
if(!preg_match_all('#<p[^>]*>\s*(https?://vimeo.com/(\d+)).*?</p>#', $str, $matches)) return;
foreach($matches[0] as $key => $line) {
$replaceLine = $line;
$oembedURL =
"$this->http://vimeo.com/api/oembed.json?url=" . urlencode($matches[1][$key]) .
"&maxwidth={$this->maxWidth}&maxheight={$this->maxHeight}";
$videoID = $matches[2][$key];
$embedCode = $this->getEmbedCode($oembedURL, $videoID);
if($this->responsive) $embedCode = $this->makeResponsive($embedCode);
else $replaceLine = $matches[1][$key]; //Only replace the URL and keep the attributes assigned to the <p> tag (eg, align, style)
if($embedCode) $str = str_replace($replaceLine, $embedCode, $str);
}
}
/**
* Check for Twitter URLS and embed when found
*
* @var string $str
*
*/
protected function embedTwitter(&$str) {
if(strpos($str, '://twitter.com/') === false) return;
if(!preg_match_all('#<p[^>]*>\s*(https?://twitter.com/(.*)/(.*)).*?</p>#', $str, $matches)) return;
foreach($matches[0] as $key => $line) {
$replaceLine = $line;
$oembedURL =
"$this->https://publish.twitter.com/oembed?url=" . urlencode($matches[1][$key]) .
"&maxwidth={$this->maxWidth}&maxheight={$this->maxHeight}";
$videoID = 'tw-'.$matches[3][$key];
$embedCode = $this->getEmbedCode($oembedURL, $videoID);
if($this->responsive) $embedCode = $this->makeResponsive($embedCode);
else $replaceLine = $matches[1][$key]; //Only replace the URL and keep the attributes assigned to the <p> tag (eg, align, style)
if($embedCode) $str = str_replace($replaceLine, $embedCode, $str);
}
}
/**
* Check for Facebook URLS and embed when found
*
* @var string $str
*
*/
protected function embedFacebook(&$str) {
$pType = '';
if(strpos($str, '://www.facebook.com/') === false) return;
if(!preg_match_all('#<p[^>]*>\s*((https?:\/\/)?(www\.)?facebook.com\/(.*)/(videos|posts)?/(.*)).*?</p>#', $str, $matches)) return;
foreach($matches[0] as $key => $line) {
$pType = ($matches[5][$key]=='videos' ? 'video':($matches[5][$key]=='posts' ? 'post':''));
$oembedURL =
"$this->https://www.facebook.com/plugins/{$pType}/oembed.json/?url=" . urlencode($matches[1][$key]) .
"&maxwidth={$this->maxWidth}" ;
$videoID = 'fb-'.$this->wire('sanitizer')->name($matches[6][$key]);
$embedCode = $this->getEmbedCode($oembedURL, $videoID);
//if($this->responsive) $embedCode = $this->makeResponsive($embedCode);
if($embedCode) $str = str_replace($line, $embedCode, $str);
}
}
/**
* Check for Instagram URLS and embed when found
*
* @var string $str
*
*/
protected function embedInstagram(&$str) {
/****
* Instagram URLs
* URL scheme: http://instagram.com/p/*
URL scheme: http://instagr.am/p/*
URL scheme: http://www.instagram.com/p/*
URL scheme: http://www.instagr.am/p/*
URL scheme: https://instagram.com/p/*
URL scheme: https://instagr.am/p/*
URL scheme: https://www.instagram.com/p/*
URL scheme: https://www.instagr.am/p/*
*/
if(strpos($str, 'instagram.com/') === false
&& strpos($str, 'instagr.am/') === false) return;
if(!preg_match_all('#<p[^>]*>\s*((https?:\/\/)?([\w\.]*)instagr(?:.am|am.com)+/p/(.*)/).*?</p>#', $str, $matches)) return;
foreach($matches[0] as $key => $line) {
$replaceLine = $line;
$oembedURL =
"$this->https://api.instagram.com/oembed?url=" . urlencode($matches[1][$key]) .
"&maxwidth={$this->maxWidth}&maxheight={$this->maxHeight}";
$videoID = 'ig-'.$matches[4][$key];
$embedCode = $this->getEmbedCode($oembedURL, $videoID);
if($this->responsive) $embedCode = $this->makeResponsive($embedCode);
else $replaceLine = $matches[1][$key]; //Only replace the URL and keep the attributes assigned to the <p> tag (eg, align, style)
if($embedCode) $str = str_replace($replaceLine, $embedCode, $str);
}
}
/**
* Check for Issuu URLS and embed when found
*
* @var string $str
*
*/
protected function embedIssuu(&$str) {
if(strpos($str, '://issuu.com/') === false) return;
if(!preg_match_all('#<p[^>]*>\s*(https?://issuu.com/(.*)/(.*)).*?</p>#', $str, $matches)) return;
foreach($matches[0] as $key => $line) {
$replaceLine = $line;
$oembedURL =
"$this->https://issuu.com/oembed?url=" . urlencode($matches[1][$key]) .
"&maxwidth={$this->maxWidth}&maxheight={$this->maxHeight}&format=json";
$videoID = $matches[3][$key];
$embedCode = $this->getEmbedCode($oembedURL, $videoID);
if($this->responsive) $embedCode = $this->makeResponsive($embedCode);
else $replaceLine = $matches[1][$key]; //Only replace the URL and keep the attributes assigned to the <p> tag (eg, align, style)
if($embedCode) $str = str_replace($replaceLine, $embedCode, $str);
}
}
/**
* Module configuration screen
*
* @param array $data
* @return InputfieldWrapper
*
*/
public function getModuleConfigInputfields(array $data) {
foreach(self::$configDefaults as $key => $value) {
if(!isset($data[$key])) $data[$key] = $value;
}
unset($data['cacheClear']);
$inputfields = new InputfieldWrapper();
$f = $this->wire('modules')->get('InputfieldInteger');
$f->attr('name', 'maxWidth');
$f->attr('value', $data['maxWidth']);
$f->label = __('Max Video Width');
$inputfields->add($f);
$f = $this->wire('modules')->get('InputfieldInteger');
$f->attr('name', 'maxHeight');
$f->attr('value', $data['maxHeight']);
$f->label = __('Max Video Height');
$inputfields->add($f);
$f = $this->wire('modules')->get('InputfieldCheckbox');
$f->attr('name', 'responsive');
$f->attr('value', 1);
if($data['responsive']) $f->attr('checked', 'checked');
$f->label = __('Use Responsive Embed Method?');
$f->description = __('When checked, videos will be embedded in a manner that allows them to be presented in a width-flexible format.');
$inputfields->add($f);
if($this->wire('input')->post('clearCache')) {
$this->wire('database')->query("DELETE FROM " . self::dbTableName);
$this->wire('modules')->message(__('Cleared video embed cache'));
} else {
$query = $this->wire('database')->prepare("SELECT COUNT(*) FROM " . self::dbTableName);
$query->execute();
list($n) = $query->fetch(\PDO::FETCH_NUM);
$query->closeCursor();
$f = $this->wire('modules')->get('InputfieldCheckbox');
$f->attr('name', 'clearCache');
$f->attr('value', 1);
$f->label = __('Clear video cache?');
$f->description = __('This will clear out cached embed codes. There is no harm in doing this, other than that it will force them to be re-pulled from YouTube/Vimeo as needed.');
$f->notes = sprintf(__('There are currently %d video(s) cached'), $n);
$inputfields->add($f);
}
return $inputfields;
}
/**
* Installation routine
*
*/
public function ___install() {
$sql = "CREATE TABLE " . self::dbTableName . " (" .
"video_id VARCHAR(128) NOT NULL PRIMARY KEY, " .
"embed_code text NOT NULL DEFAULT '', " .
"created TIMESTAMP NOT NULL " .
")";
$this->wire('database')->exec($sql);
}
/**
* Uninstallation routine
*
*/
public function ___uninstall() {
try { $this->wire('database')->exec("DROP TABLE " . self::dbTableName); } catch(Exception $e) { }
}
/**
* The following functions are to support the ConfigurableModule interface
* since Textformatter does not originate from WireData
*
* @param string $key
* @param mixed $value
* @return $this
*
*/
public function set($key, $value) {
$this->data[$key] = $value;
return $this;
}
/**
* Get configuration item
*
* @param string $key
* @return mixed
*
*/
public function get($key) {
$value = $this->wire($key);
if($value) return $value;
return isset($this->data[$key]) ? $this->data[$key] : null;
}
public function __set($key, $value) {
$this->set($key, $value);
}
public function __get($key) {
return $this->get($key);
}
}