-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathHtmlField.php
539 lines (458 loc) · 17.6 KB
/
HtmlField.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
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
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
<?php
/**
* @link https://craftcms.com/
* @copyright Copyright (c) Pixel & Tonic, Inc.
* @license MIT
*/
namespace craft\htmlfield;
use Craft;
use craft\base\ElementInterface;
use craft\base\Field;
use craft\base\PreviewableFieldInterface;
use craft\base\Volume;
use craft\elements\Asset;
use craft\helpers\FileHelper;
use craft\helpers\Html;
use craft\helpers\HtmlPurifier;
use craft\helpers\Json;
use craft\helpers\StringHelper;
use craft\helpers\UrlHelper;
use craft\validators\HandleValidator;
use HTMLPurifier_Config;
use yii\db\Schema;
/**
* Base HTML Field
*
* @author Pixel & Tonic, Inc. <[email protected]>
* @since 1.0.0
*/
abstract class HtmlField extends Field implements PreviewableFieldInterface
{
/**
* @inheritdoc
*/
public static function valueType(): string
{
return 'string';
}
/**
* @var string|null The HTML Purifier config file to use
*/
public ?string $purifierConfig = null;
/**
* @var bool Whether the HTML should be purified on save
*/
public bool $purifyHtml = true;
/**
* @var bool Whether `<font>` tags and disallowed inline styles should be removed on save
*/
public bool $removeInlineStyles = false;
/**
* @var bool Whether empty tags should be removed on save
*/
public bool $removeEmptyTags = false;
/**
* @var bool Whether non-breaking spaces should be replaced by regular spaces on save
*/
public bool $removeNbsp = false;
/**
* @var string The type of database column the field should have in the content table
*/
public string $columnType = Schema::TYPE_TEXT;
/**
* @inheritdoc
*/
public function getTableAttributeHtml(mixed $value, ElementInterface $element): string
{
return strip_tags((string)$value);
}
/**
* @inheritdoc
*/
public function getContentColumnType(): array|string
{
return $this->columnType;
}
/**
* @inheritdoc
*/
public function settingsAttributes(): array
{
$attributes = parent::settingsAttributes();
$attributes[] = 'purifierConfig';
$attributes[] = 'removeInlineStyles';
$attributes[] = 'removeEmptyTags';
$attributes[] = 'removeNbsp';
$attributes[] = 'purifyHtml';
$attributes[] = 'columnType';
return $attributes;
}
/**
* @inheritdoc
*/
public function normalizeValue(mixed $value, ?\craft\base\ElementInterface $element = null): mixed
{
if ($value === null || $value instanceof HtmlFieldData) {
return $value;
}
$value = trim($value);
if (in_array($value, ['<p><br></p>', '<p> </p>', '<p></p>', ''], true)) {
return null;
}
return $this->createFieldData($value, $element->siteId ?? null);
}
/**
* Creates the field data object with the given value and site ID.
*
* @param string $content
* @param int|null $siteId
* @return HtmlFieldData
*/
protected function createFieldData(string $content, ?int $siteId): HtmlFieldData
{
return new HtmlFieldData($content, $siteId);
}
/**
* Returns the value prepped for the input.
*
* @param HtmlFieldData|string|null $value
* @param ElementInterface|null $element
* @return string
*/
protected function prepValueForInput($value, ?ElementInterface $element): string
{
if ($value instanceof HtmlFieldData) {
$value = $value->getRawContent();
}
if ($value !== null) {
$value = $this->_parseRefs($value, $element);
}
return $value ?? '';
}
/**
* @inheritdoc
*/
public function isValueEmpty(mixed $value, ElementInterface $element): bool
{
/** @var HtmlFieldData|null $value */
if ($value === null) {
return true;
}
return parent::isValueEmpty($value->getRawContent(), $element);
}
/**
* @inheritdoc
*/
protected function searchKeywords(mixed $value, ElementInterface $element): string
{
$keywords = parent::searchKeywords($value, $element);
if (!Craft::$app->getDb()->getSupportsMb4()) {
$keywords = StringHelper::encodeMb4($keywords);
}
return $keywords;
}
/**
* @inheritdoc
*/
public function serializeValue(mixed $value, ?\craft\base\ElementInterface $element = null): mixed
{
/** @var HtmlFieldData|string|null $value */
if (!$value) {
return null;
}
if ($value instanceof HtmlFieldData) {
$value = $value->getRawContent();
}
if ($value === '') {
return null;
}
if ($this->purifyHtml) {
// Parse reference tags so HTMLPurifier doesn't encode the curly braces
$value = $this->_parseRefs($value, $element);
// Sanitize & tokenize any SVGs
$svgTokens = [];
$svgContent = [];
$value = preg_replace_callback('/<svg\b.*>.*<\/svg>/Uis', function(array $match) use (&$svgTokens, &$svgContent): string {
$svgContent[] = Html::sanitizeSvg($match[0]);
return $svgTokens[] = 'svg:' . StringHelper::randomString(10);
}, $value);
$value = HtmlPurifier::process($value, $this->purifierConfig());
// Put the sanitized SVGs back
$value = str_replace($svgTokens, $svgContent, $value);
}
if ($this->removeInlineStyles) {
// Remove <font> tags
$value = preg_replace('/<(?:\/)?font\b[^>]*>/', '', $value);
// Remove disallowed inline styles
$allowedStyles = $this->allowedStyles();
$value = preg_replace_callback(
'/(<(?:h1|h2|h3|h4|h5|h6|p|div|blockquote|pre|strong|em|b|i|u|a|span|img|table|thead|tbody|tr|td|th)\b[^>]*)\s+style="([^"]*)"/',
function(array $matches) use ($allowedStyles) {
// Only allow certain styles through
$allowed = [];
$styles = explode(';', $matches[2]);
foreach ($styles as $style) {
[$name, $value] = array_map('trim', array_pad(explode(':', $style, 2), 2, ''));
if (isset($allowedStyles[$name])) {
$allowed[] = "$name: $value";
}
}
return $matches[1] . ($allowed ? sprintf(' style="%s"', implode('; ', $allowed)) : '');
},
$value
);
}
if ($this->removeEmptyTags) {
// Remove empty tags
$value = preg_replace('/<(h1|h2|h3|h4|h5|h6|p|div|blockquote|pre|strong|em|a|b|i|u|span)\s*><\/\1>/', '', $value);
}
if ($this->removeNbsp) {
// Replace non-breaking spaces with regular spaces
$value = preg_replace('/( | |\x{00A0})/u', ' ', $value);
$value = preg_replace('/ +/', ' ', $value);
}
// Find any element URLs and swap them with ref tags
$value = preg_replace_callback(
sprintf('/(href=|src=)([\'"])([^\'"\?#]*)(\?[^\'"\?#]+)?(#[^\'"\?#]+)?(?:#|%%23)([\w\\\\]+)\:(\d+)(?:@(\d+))?(\:(?:transform\:)?%s)?\2/', HandleValidator::$handlePattern),
function($matches) {
[, $attr, $q, $url, $query, $hash, $elementType, $ref, $siteId, $transform] = array_pad($matches, 10, null);
// Create the ref tag, and make sure :url is in there
$ref = "$elementType:$ref" . ($siteId ? "@$siteId" : '') . ($transform ?: ':url');
if ($query || $hash) {
// Make sure that the query/hash isn't actually part of the parsed URL
// - someone's Entry URL Format could include "?slug={slug}" or "#{slug}", etc.
// - assets could include ?mtime=X&focal=none, etc.
$parsed = Craft::$app->getElements()->parseRefs("{{$ref}}");
if ($query) {
// Decode any HTML entities, e.g. &
$query = Html::decode($query);
if (mb_strpos($parsed, $query) !== false) {
$url .= $query;
$query = '';
}
}
if ($hash && mb_strpos($parsed, $hash) !== false) {
$url .= $hash;
$hash = '';
}
}
return sprintf('%s%s%s', "$attr$q{", "$ref||$url", "}$query$hash$q");
},
$value
);
// Swap any regular URLS with element refs, too
// Get all base URLs, sorted by longest first
$baseUrls = [];
$baseUrlLengths = [];
$siteIds = [];
$volumeIds = [];
foreach (Craft::$app->getSites()->getAllSites(false) as $site) {
if ($site->hasUrls && ($baseUrl = $site->getBaseUrl())) {
$baseUrls[] = $baseUrl;
$siteIds[] = $site->id;
$volumeIds[] = null;
}
}
foreach (Craft::$app->getVolumes()->getAllVolumes() as $volume) {
$fs = $volume->getFs();
if ($fs->hasUrls && ($baseUrl = $fs->getRootUrl())) {
$baseUrls[] = $baseUrl;
$siteIds[] = null;
$volumeIds[] = $volume->id;
}
}
foreach ($baseUrls as &$baseUrl) {
// just to be safe
$baseUrl = StringHelper::ensureRight($baseUrl, '/');
$baseUrlLengths[] = strlen($baseUrl);
}
array_multisort($baseUrlLengths, SORT_DESC, SORT_NUMERIC, $baseUrls, $siteIds, $volumeIds);
$value = preg_replace_callback(
'/(href=|src=)([\'"])((?:\/|http).*?)\2/',
function($matches) use ($baseUrls, $siteIds, $volumeIds) {
$url = $matches[3] ?? null;
if (!$url) {
return '';
}
foreach ($baseUrls as $key => $baseUrl) {
if (StringHelper::startsWith($url, $baseUrl)) {
// Drop query
$query = parse_url($url, PHP_URL_QUERY);
if (!empty($query)) {
break;
}
$uri = preg_replace('/\?.*/', '', $url);
// Drop page trigger
$pageTrigger = Craft::$app->getConfig()->getGeneral()->getPageTrigger();
if (strpos($pageTrigger, '?') !== 0) {
$pageTrigger = preg_quote($pageTrigger, '/');
$uri = preg_replace("/^(?:(.*)\/)?$pageTrigger(\d+)$/", '', $uri);
}
// Drop the base URL
$uri = StringHelper::removeLeft($uri, $baseUrl);
if ($siteIds[$key] !== null) {
// site URL
if ($element = Craft::$app->getElements()->getElementByUri($uri, $siteIds[$key], true)) {
$refHandle = $element::refHandle();
if ($refHandle) {
$url = sprintf('{%s:%s@%s:url||%s}', $refHandle, $element->id, $siteIds[$key], $url);
}
break;
}
} else {
// volume URL
$filename = basename($uri);
$folderPath = dirname($uri);
$assetId = Asset::find()
->volumeId($volumeIds[$key])
->filename($filename)
->folderPath($folderPath !== '.' ? $folderPath : '')
->select(['elements.id'])
->scalar();
if ($assetId) {
$url = sprintf('{asset:%s:url||%s}', $assetId, $url);
break;
}
}
}
}
return $matches[1] . $matches[2] . $url . $matches[2];
},
$value
);
if (!Craft::$app->getDb()->getSupportsMb4()) {
// Encode any 4-byte UTF-8 characters.
$value = StringHelper::encodeMb4($value);
}
return $value;
}
/**
* Parse ref tags in URLs, while preserving the original tag values in the URL fragments
* (e.g. `href="{entry:id:url}"` => `href="[entry-url]#entry:id:url"`)
*
* @param string $value
* @param ElementInterface|null $element
* @return string
*/
private function _parseRefs(string $value, ?ElementInterface $element = null): string
{
if (!StringHelper::contains($value, '{')) {
return $value;
}
$elementsService = Craft::$app->getElements();
return preg_replace_callback(
sprintf('/(href=|src=)([\'"])(\{([\w\\\\]+)(\:\d+(?:@\d+)?\:(?:transform\:)?%s)(?:\|\|[^\}]+)?\})(?:\?([^\'"#]*))?(#[^\'"#]+)?\2/', HandleValidator::$handlePattern),
function($matches) use ($element, $elementsService) {
[$fullMatch, $attr, $q, $refTag, $refHandle, $refRemainder, $query, $fragment] = array_pad($matches, 8, null);
$parsed = Craft::$app->getElements()->parseRefs($refTag, $element->siteId ?? null);
// If the ref tag couldn't be parsed, leave it alone
if ($parsed === $refTag) {
return $fullMatch;
}
if ($query) {
// Decode any HTML entities, e.g. &
$query = Html::decode($query);
if (mb_strpos($parsed, $query) !== false) {
$parsed = UrlHelper::urlWithParams($parsed, $query);
}
}
// Make sure the ref handle matches the real ref handle from the resolved element type
/** @var string|ElementInterface|null $class */
$class = $elementsService->getElementTypeByRefHandle($refHandle);
if ($class) {
$realRefHandle = $class::refHandle();
if ($realRefHandle) {
$refHandle = $realRefHandle;
}
}
return $attr . $q . $parsed . ($fragment ?? '') . '#' . $refHandle . $refRemainder . $q;
},
$value
);
}
/**
* Returns the HTML Purifier config used by this field.
*
* @return HTMLPurifier_Config
*/
protected function purifierConfig(): HTMLPurifier_Config
{
$purifierConfig = HTMLPurifier_Config::createDefault();
$purifierConfig->autoFinalize = false;
$config = $this->config('htmlpurifier', $this->purifierConfig) ?: $this->defaultPurifierOptions();
foreach ($config as $option => $value) {
$purifierConfig->set($option, $value);
}
return $purifierConfig;
}
/**
* Returns the default HTML Purifier config options, if no config is specified/exists.
*
* @return array
*/
protected function defaultPurifierOptions(): array
{
return [
'Attr.AllowedFrameTargets' => ['_blank'],
'Attr.EnableID' => true,
'HTML.SafeIframe' => true,
'URI.SafeIframeRegexp' => '%^(https?:)?//(www\.youtube(-nocookie)?\.com/embed/|player\.vimeo\.com/video/)%',
];
}
/**
* Returns the available config options in a given directory.
*
* @param string $dir The directory name within the config/ folder to look for config files
* @return array
*/
protected function configOptions(string $dir): array
{
$options = ['' => Craft::t('app', 'Default')];
$path = Craft::$app->getPath()->getConfigPath() . DIRECTORY_SEPARATOR . $dir;
if (is_dir($path)) {
$files = FileHelper::findFiles($path, [
'only' => ['*.json'],
'recursive' => false,
]);
foreach ($files as $file) {
$filename = basename($file);
if ($filename !== 'Default.json') {
$options[$filename] = pathinfo($file, PATHINFO_FILENAME);
}
}
}
ksort($options);
return $options;
}
/**
* Returns a JSON-decoded config, if it exists.
*
* @param string $dir The directory name within the config/ folder to look for the config file
* @param string|null $file The filename to load.
* @return array|false The config, or false if the file doesn't exist
*/
protected function config(string $dir, string $file = null)
{
if (!$file) {
$file = 'Default.json';
}
$path = Craft::$app->getPath()->getConfigPath() . DIRECTORY_SEPARATOR . $dir . DIRECTORY_SEPARATOR . $file;
if (!is_file($path)) {
if ($file !== 'Default.json') {
// Try again with Default
return $this->config($dir);
}
return false;
}
return Json::decode(file_get_contents($path));
}
/**
* Returns the allowed inline CSS styles, based on the plugins that are enabled.
*
* @return array<string,bool>
*/
protected function allowedStyles(): array
{
return [];
}
}