-
Notifications
You must be signed in to change notification settings - Fork 80
/
Copy pathRemoteFileFormFactory.php
388 lines (349 loc) · 12.4 KB
/
RemoteFileFormFactory.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
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
<?php
namespace SilverStripe\AssetAdmin\Forms;
use InvalidArgumentException;
use SilverStripe\AssetAdmin\Exceptions\InvalidRemoteUrlException;
use SilverStripe\Control\Director;
use SilverStripe\Control\RequestHandler;
use SilverStripe\Core\Config\Configurable;
use SilverStripe\Core\Extensible;
use SilverStripe\Core\Injector\Injector;
use SilverStripe\Forms\CompositeField;
use SilverStripe\Forms\FieldGroup;
use SilverStripe\Forms\FieldList;
use SilverStripe\Forms\Form;
use SilverStripe\Forms\FormAction;
use SilverStripe\Forms\FormFactory;
use SilverStripe\Forms\HiddenField;
use SilverStripe\Forms\LiteralField;
use SilverStripe\Forms\OptionsetField;
use SilverStripe\Forms\RequiredFields;
use SilverStripe\Forms\TextField;
use SilverStripe\View\Embed\Embeddable;
class RemoteFileFormFactory implements FormFactory
{
use Extensible;
use Configurable;
/**
* Force whitelist for resource protocols to the given list.
*
* @config
* @var array
*/
private static $fileurl_scheme_whitelist = ['http', 'https'];
/**
* Blacklist of resources. Takes priority over whitelists if both are provided.
*
* @config
* @var array
*/
private static $fileurl_scheme_blacklist = [];
/**
* Force whitelist for resource domains to the given list
*
* @config
* @var array
*/
private static $fileurl_domain_whitelist = [];
/**
* Blacklist of domains. For example, live sites should probably
* include 'localhost' and other protected urls.
* Takes priority over whitelists if both are provided.
*
* @config
* @var array
*/
private static $fileurl_domain_blacklist = [];
/**
* Whitelist of ports allowed.
*
* @config
* @var array
*/
private static $fileurl_port_whitelist = [80, 443];
/**
* Blacklist of ports allowed.
* Takes priority over whitelists if both are provided.
*
* @config
* @var array
*/
private static $fileurl_port_blacklist = [];
/**
* Allow oembed to be disabled
*
* @config
* @var bool
*/
private static $enabled = true;
/**
* @param RequestHandler $controller
* @param string $name
* @param array $context
* @return Form
*/
public function getForm(RequestHandler $controller = null, $name = self::DEFAULT_NAME, $context = [])
{
// Allow form to be disabled
if (!static::config()->get('enabled')) {
return null;
}
// Validate context
foreach ($this->getRequiredContext() as $required) {
if (!isset($context[$required])) {
throw new InvalidArgumentException("Missing required context $required");
}
}
$fields = $this->getFormFields($controller, $name, $context);
$actions = $this->getFormActions($controller, $name, $context);
$validator = new RequiredFields();
$form = Form::create($controller, $name, $fields, $actions, $validator);
$form->addExtraClass('form--fill-height');
$form->addExtraClass('form--no-dividers');
$form->addExtraClass('insert-embed-modal--'. strtolower($context['type'] ?? ''));
// Extend form
$this->invokeWithExtensions('updateForm', $form, $controller, $name, $context);
return $form;
}
public function getRequiredContext()
{
return ['type'];
}
protected function getFormFields($controller, $name, $context)
{
$formType = $context['type'];
switch ($formType) {
case 'create':
return $this->getCreateFormFields();
case 'edit':
return $this->getEditFormFields($context);
default:
throw new InvalidArgumentException("Unknown media form type: {$formType}");
}
}
protected function getFormActions($controller, $name, $context)
{
$actions = [];
if ($context['type'] === 'create') {
$actions = [
FormAction::create('addmedia', _t(__CLASS__.'.AddMedia', 'Add media'))
->setSchemaData(['data' => ['buttonStyle' => 'primary']]),
];
}
if ($context['type'] === 'edit') {
$actions = [
FormAction::create('insertmedia', _t(__CLASS__.'.InsertMedia', 'Insert media'))
->setSchemaData(['data' => ['buttonStyle' => 'primary']]),
FormAction::create('cancel', _t(__CLASS__.'.Cancel', 'Cancel')),
];
}
return FieldList::create($actions);
}
/**
* @param string $url
* @return bool
* @throws InvalidRemoteUrlException
*/
protected function validateUrl($url)
{
$this->validateURLAbsolute($url);
$this->validateURLScheme($url);
$this->validateURLHost($url);
$this->validateURLPort($url);
return true;
}
/**
* Checks if the embed generated is not just a link
*
* @param Embeddable $embed
* @return bool
* @throws InvalidRemoteUrlException
*/
protected function validateEmbed(Embeddable $embed)
{
if (!$embed->validate()) {
throw new InvalidRemoteUrlException(_t(
__CLASS__.'.ERROR_EMBED',
'There is currently no embeddable media available from this URL'
));
}
return true;
}
/**
* Get form fields for create new embed
*
* @return FieldList
*/
protected function getCreateFormFields()
{
return FieldList::create([
TextField::create(
'Url',
'Embed URL'
)
->setInputType('url')
->addExtraClass('insert-embed-modal__url-create')
->setDescription(_t(
__CLASS__.'.UrlDescription',
'Embed Youtube and Vimeo videos, images and other media directly from the web.'
)),
]);
}
/**
* Get form fields for edit form
*
* @param array $context
* @return FieldList
* @throws InvalidRemoteUrlException
*/
protected function getEditFormFields($context)
{
// Check if the url is valid
$url = (isset($context['url'])) ? $context['url'] : null;
if (empty($url)) {
return $this->getCreateFormFields();
}
$url = trim($url ?? '');
// Get embed
$this->validateUrl($url);
/** @var Embeddable $embed */
$embed = Injector::inst()->create(Embeddable::class, $url);
$this->validateEmbed($embed);
// Build form
$alignments = array(
'leftAlone' => _t('SilverStripe\\AssetAdmin\\Controller\\AssetAdmin.AlignmentLeftAlone', 'Left'),
'center' => _t('SilverStripe\\AssetAdmin\\Controller\\AssetAdmin.AlignmentCenter', 'Center'),
'rightAlone' => _t('SilverStripe\\AssetAdmin\\Controller\\AssetAdmin.AlignmentRightAlone', 'Right'),
'left' => _t('SilverStripe\\AssetAdmin\\Controller\\AssetAdmin.AlignmentLeft', 'Left wrap'),
'right' => _t('SilverStripe\\AssetAdmin\\Controller\\AssetAdmin.AlignmentRight', 'Right wrap'),
);
$width = $embed->getWidth();
$height = $embed->getHeight();
$fields = CompositeField::create([
LiteralField::create(
'Preview',
sprintf(
'<img src="%s" class="%s" />',
$embed->getPreviewURL(),
'insert-embed-modal__preview'
)
)->addExtraClass('insert-embed-modal__preview-container'),
HiddenField::create('PreviewUrl', 'PreviewUrl', $embed->getPreviewURL()),
CompositeField::create([
TextField::create('UrlPreview', $embed->getName(), $url)
->setReadonly(true),
HiddenField::create('Url', false, $url),
TextField::create(
'CaptionText',
_t('SilverStripe\\AssetAdmin\\Controller\\AssetAdmin.Caption', 'Caption')
),
OptionsetField::create(
'Placement',
_t('SilverStripe\\AssetAdmin\\Controller\\AssetAdmin.Placement', 'Placement'),
$alignments
)
->addExtraClass('insert-embed-modal__placement'),
$dimensions = FieldGroup::create(
_t('SilverStripe\\AssetAdmin\\Controller\\AssetAdmin.ImageSpecs', 'Dimensions'),
TextField::create('Width', '', $width)
->setRightTitle(_t(
'SilverStripe\\AssetAdmin\\Controller\\AssetAdmin.ImageWidth',
'Width'
))
->setMaxLength(5)
->addExtraClass('flexbox-area-grow'),
TextField::create('Height', '', $height)
->setRightTitle(_t(
'SilverStripe\\AssetAdmin\\Controller\\AssetAdmin.ImageHeight',
'Height'
))
->setMaxLength(5)
->addExtraClass('flexbox-area-grow')
)->addExtraClass('fieldgroup--fill-width')
->setName('Dimensions')
])->addExtraClass('flexbox-area-grow'),
])->addExtraClass('insert-embed-modal__fields--fill-width');
if ($dimensions && $width && $height) {
$ratio = $width / $height;
$dimensions->setSchemaComponent('ProportionConstraintField');
$dimensions->setSchemaState([
'data' => [
'ratio' => $ratio,
'isRemoteFile' => true
]
]);
}
return FieldList::create($fields);
}
/**
* @param string $url
* @throws InvalidRemoteUrlException
*/
protected function validateURLScheme($url)
{
$scheme = strtolower(parse_url($url ?? '', PHP_URL_SCHEME) ?? '');
$allowedSchemes = self::config()->get('fileurl_scheme_whitelist');
$disallowedSchemes = self::config()->get('fileurl_scheme_blacklist');
if (!$scheme
|| ($allowedSchemes && !in_array($scheme, $allowedSchemes ?? []))
|| ($disallowedSchemes && in_array($scheme, $disallowedSchemes ?? []))
) {
throw new InvalidRemoteUrlException(_t(
__CLASS__ . '.ERROR_SCHEME',
'This file scheme is not allowed'
));
}
}
/**
* @param string $url
* @throws InvalidRemoteUrlException
*/
protected function validateURLHost($url)
{
$domain = strtolower(parse_url($url ?? '', PHP_URL_HOST) ?? '');
$allowedDomains = self::config()->get('fileurl_domain_whitelist');
$disallowedDomains = self::config()->get('fileurl_domain_blacklist');
if (!$domain
|| ($allowedDomains && !in_array($domain, $allowedDomains ?? []))
|| ($disallowedDomains && in_array($domain, $disallowedDomains ?? []))
) {
throw new InvalidRemoteUrlException(_t(
__CLASS__ . '.ERROR_HOSTNAME',
'This file hostname is not allowed'
));
}
}
/**
* @param string $url
* @throws InvalidRemoteUrlException
*/
protected function validateURLPort($url)
{
$port = (int)parse_url($url ?? '', PHP_URL_PORT);
if (!$port) {
return;
}
$allowedPorts = self::config()->get('fileurl_port_whitelist');
$disallowedPorts = self::config()->get('fileurl_port_blacklist');
if (($allowedPorts && !in_array($port, $allowedPorts ?? []))
|| ($disallowedPorts && in_array($port, $disallowedPorts ?? []))
) {
throw new InvalidRemoteUrlException(_t(
__CLASS__ . '.ERROR_PORT',
'This file port is not allowed'
));
}
}
/**
* @param string $url
* @throws InvalidRemoteUrlException
*/
protected function validateURLAbsolute($url)
{
if (!Director::is_absolute_url($url)) {
throw new InvalidRemoteUrlException(_t(
__CLASS__ . '.ERROR_ABSOLUTE',
'Only absolute urls can be embedded'
));
}
}
}