forked from ryancramerdesign/TextformatterVideoEmbed
/
TextformatterVideoEmbed.module
410 lines (340 loc) · 11.5 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
<?php
/**
* ProcessWire Video Embedding Textformatter
*
* Looks for Youtube or Vimeo 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
* @property float $defaultAspectRatio
*
*/
class TextformatterVideoEmbed extends Textformatter implements ConfigurableModule {
public static function getModuleInfo() {
return array(
'title' => __('Video embed for YouTube/Vimeo', __FILE__),
'version' => 112,
'summary' => __('Enter a full YouTube or Vimeo 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. 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/'
);
}
/**
* Name and latest schema version for database table used by this module
*
*/
const dbTableName = 'textformatter_video_embed';
const dbSchemaVersion = 2;
/**
* Default configuration values
*
* @var array
*
*/
protected static $configDefaults = array(
'maxWidth' => 640,
'maxHeight' => 480,
'responsive' => 0,
'defaultAspectRatio' => 16/9,
'dbSchemaVersion' => 1,
);
/**
* 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';
}
/**
* Initialization function
*
* This function updates the database schema, if necessary.
*
*/
public function init() {
// update database schema (if not the latest one yet)
if ($this->dbSchemaVersion < self::dbSchemaVersion) {
$this->updateDatabaseSchema();
}
}
/**
* 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, aspect_ratio FROM $table WHERE video_id=:video_id");
$query->bindValue(":video_id", $videoID);
$query->execute();
$embedCode = '';
$aspectRatio = 0;
if($query->rowCount()) {
list($embedCode, $aspectRatio) = $query->fetch(\PDO::FETCH_NUM);
$query->closeCursor();
} else {
$query->closeCursor();
$http = new WireHttp();
$data = $http->get($oembedURL);
if($data) $data = json_decode($data, true);
if(is_array($data) && isset($data['html'])) {
$embedCode = $data['html'];
if(isset($data['width']) && isset($data['height'])) {
$aspectRatio = $data['width'] / $data['height'];
}
$sql = "INSERT INTO $table SET " .
"video_id=:videoID, " .
"embed_code=:embedCode, " .
"aspect_ratio=:aspectRatio, " .
"created=NOW() ";
$query = $database->prepare($sql);
$query->bindValue(":videoID", $videoID);
$query->bindValue(":embedCode", $embedCode);
$query->bindValue(":aspectRatio", $aspectRatio);
$query->execute();
}
}
// responsive embed codes
if($this->responsive) $embedCode = $this->makeResponsive($embedCode, $aspectRatio);
// 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
* @param float $aspectRatio
* @return string
*
*/
protected function makeResponsive($out, $aspectRatio = 0) {
$aspectRatio = floatval($aspectRatio);
if(!$aspectRatio) $aspectRatio = $this->defaultAspectRatio;
// Calculate padding percentage from aspect ratio
$padding = (1 / $aspectRatio) * 100;
$padding = number_format($padding, 2, '.', '');
$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:0 0 $padding% 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);
}
/**
* 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);
}
$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) {
$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($embedCode) $str = str_replace($line, $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);
$f = $this->wire('modules')->get('InputfieldFloat');
$f->attr('name', 'defaultAspectRatio');
$f->attr('value', $data['defaultAspectRatio']);
$f->label = __('Default Aspect Ratio');
$f->description = __('This will be used as a fallback if the video\'s aspect ratio can\'t be properly determined from the oEmbed request.');
$f->notes = __('A sensible default is 1.78 (equals 16:9)');
$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;
}
/**
* Update database schema
*
* This method applies incremental updates until latest schema version is
* reached, while also keeping schema_version config setting up to date.
*
*/
private function updateDatabaseSchema() {
while ($this->dbSchemaVersion < self::dbSchemaVersion) {
++$this->dbSchemaVersion;
switch ($this->dbSchemaVersion) {
case 2:
$sql = "ALTER TABLE " . self::dbTableName . " ADD aspect_ratio FLOAT(6,2) NOT NULL AFTER embed_code";
break;
default:
throw new WireException("Unrecognized database schema version: $this->dbSchemaVersion");
}
if ($sql && $this->wire('database')->exec($sql) !== false) {
$configData = $this->wire('modules')->getModuleConfigData($this);
$configData['dbSchemaVersion'] = $this->dbSchemaVersion;
$this->wire('modules')->saveModuleConfigData($this, $configData);
} else {
throw new WireException("Couldn't update database schema to version $this->dbSchemaVersion");
}
}
}
/**
* Installation routine
*
*/
public function ___install() {
$sql = "CREATE TABLE " . self::dbTableName . " (" .
"video_id VARCHAR(128) NOT NULL PRIMARY KEY, " .
"embed_code VARCHAR(1024) 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);
}
}