Debian Codegraph @

vendor/oojs/oojs-ui/php/Tag.php

raw
1 <?php
2
3 namespace OOUI;
4
5 class Tag {
6
7 /* Properties */
8
9 /**
10 * Tag name for this instance.
11 *
12 * @var string HTML tag name
13 */
14 protected $tag = '';
15
16 /**
17 * Attributes.
18 *
19 * @var array HTML attributes
20 */
21 protected $attributes = [];
22
23 /**
24 * Classes.
25 *
26 * @var array CSS classes
27 */
28 protected $classes = [];
29
30 /**
31 * Content.
32 *
33 * @var array Content text and elements
34 */
35 protected $content = [];
36
37 /**
38 * Group.
39 *
40 * @var GroupElement|null Group element is in
41 */
42 protected $elementGroup = null;
43
44 /**
45 * Infusion support.
46 *
47 * @var bool Whether to serialize tag/element/widget state for client-side use.
48 */
49 protected $infusable = false;
50
51 /* Methods */
52
53 /**
54 * Create element.
55 *
56 * @param string $tag HTML tag name
57 */
58 public function __construct( $tag = 'div' ) {
59 $this->tag = $tag;
60 }
61
62 /**
63 * Check for CSS class.
64 *
65 * @param string $class CSS class name
66 * @return bool
67 */
68 public function hasClass( $class ) {
69 return in_array( $class, $this->classes );
70 }
71
72 /**
73 * Add CSS classes.
74 *
75 * @param array $classes List of classes to add
76 * @return $this
77 */
78 public function addClasses( array $classes ) {
79 $this->classes = array_unique( array_merge( $this->classes, $classes ) );
80 return $this;
81 }
82
83 /**
84 * Remove CSS classes.
85 *
86 * @param array $classes List of classes to remove
87 * @return $this
88 */
89 public function removeClasses( array $classes ) {
90 $this->classes = array_diff( $this->classes, $classes );
91 return $this;
92 }
93
94 /**
95 * Toggle CSS classes.
96 *
97 * @param array $classes List of classes to add
98 * @param bool|null $toggle Add classes
99 * @return $this
100 */
101 public function toggleClasses( array $classes, $toggle = null ) {
102 if ( $toggle === null ) {
103 $this->classes = array_diff(
104 array_merge( $this->classes, $classes ),
105 array_intersect( $this->classes, $classes )
106 );
107 } elseif ( $toggle ) {
108 $this->classes = array_merge( $this->classes, $classes );
109 } else {
110 $this->classes = array_diff( $this->classes, $classes );
111 }
112 return $this;
113 }
114
115 /**
116 * @return string
117 */
118 public function getTag() {
119 return $this->tag;
120 }
121
122 /**
123 * Get HTML attribute value.
124 *
125 * @param string $key HTML attribute name
126 * @return string|null
127 */
128 public function getAttribute( $key ) {
129 return $this->attributes[$key] ?? null;
130 }
131
132 /**
133 * Add HTML attributes.
134 *
135 * @param array $attributes List of attribute key/value pairs to add
136 * @return $this
137 */
138 public function setAttributes( array $attributes ) {
139 foreach ( $attributes as $key => $value ) {
140 $this->attributes[$key] = $value;
141 }
142 return $this;
143 }
144
145 /**
146 * Set value of input element ('value' attribute for most, element content for textarea).
147 *
148 * @param mixed $value New value should usually be a string
149 * @return $this
150 */
151 public function setValue( $value ) {
152 if ( strtolower( $this->tag ) === 'textarea' ) {
153 $this->clearContent();
154 $this->appendContent( $value );
155 } else {
156 $this->setAttributes( [ 'value' => $value ] );
157 }
158 return $this;
159 }
160
161 /**
162 * Remove HTML attributes.
163 *
164 * @param array $keys List of attribute keys to remove
165 * @return $this
166 */
167 public function removeAttributes( array $keys ) {
168 foreach ( $keys as $key ) {
169 unset( $this->attributes[$key] );
170 }
171 return $this;
172 }
173
174 /**
175 * Remove any items that match by reference
176 *
177 * String items should never match by reference
178 * so will not be removed.
179 *
180 * @param string|Tag|HtmlSnippet|array ...$content Content to remove.
181 * @return $this
182 */
183 public function removeContent( ...$content ) {
184 if ( isset( $content[0] ) && is_array( $content[0] ) ) {
185 return $this->removeContent( ...$content[0] );
186 }
187 foreach ( $content as $i => $item ) {
188 if ( !is_int( $i ) ) {
189 throw new \AssertionError( '$content cannot have string keys' );
190 }
191 if ( !is_string( $item ) ) {
192 // Use strict type comparions so we don't
193 // compare objects with existing strings
194 $index = array_search( $item, $this->content, true );
195 if ( $index !== false ) {
196 array_splice( $this->content, $index, 1 );
197 }
198 }
199 }
200 return $this;
201 }
202
203 /**
204 * Add content to the end. Strings will be HTML-escaped, use HtmlSnippet to prevent that.
205 *
206 * Accepts either variadic arguments (the $content argument can be repeated any number of times)
207 * or an array of arguments.
208 *
209 * For example, these uses are valid:
210 * * $tag->appendContent( [ $element1, $element2 ] );
211 * * $tag->appendContent( $element1, $element2 );
212 * This, however, is not acceptable
213 * * $tag->appendContent( [ $element1, $element2 ], $element3 );
214 *
215 * Objects that are already in $this->content will be moved
216 * to the end of the list, not duplicated.
217 *
218 * @param string|Tag|HtmlSnippet|array ...$content Content to append
219 * @return $this
220 */
221 public function appendContent( ...$content ) {
222 if ( isset( $content[0] ) && is_array( $content[0] ) ) {
223 return $this->appendContent( ...$content[0] );
224 }
225 $this->removeContent( ...$content );
226 $this->content = array_merge( $this->content, $content );
227 return $this;
228 }
229
230 /**
231 * Add content to the beginning.
232 *
233 * Accepts either variadic arguments (the $content argument can be repeated any number of times)
234 * or an array of arguments.
235 *
236 * Objects that are already in $this->content will be moved
237 * to the end of the list, not duplicated.
238 *
239 * For example, these uses are valid:
240 * * $tag->prependContent( [ $element1, $element2 ] );
241 * * $tag->prependContent( $element1, $element2 );
242 * This, however, is not acceptable
243 * * $tag->prependContent( [ $element1, $element2 ], $element3 );
244 *
245 * @param string|Tag|HtmlSnippet|array ...$content Content to prepend. Strings will be HTML-escaped
246 * for output, use a HtmlSnippet instance to prevent that.
247 * @return $this
248 */
249 public function prependContent( ...$content ) {
250 if ( isset( $content[0] ) && is_array( $content[0] ) ) {
251 return $this->prependContent( ...$content[0] );
252 }
253 $this->removeContent( ...$content );
254 array_splice( $this->content, 0, 0, $content );
255 return $this;
256 }
257
258 /**
259 * Remove all content.
260 *
261 * @return $this
262 */
263 public function clearContent() {
264 $this->content = [];
265 return $this;
266 }
267
268 /**
269 * Get group element is in.
270 *
271 * @return GroupElement|null Group element, null if none
272 */
273 public function getElementGroup() {
274 return $this->elementGroup;
275 }
276
277 /**
278 * Set group element is in.
279 *
280 * @param GroupElement|null $group Group element, null if none
281 * @return $this
282 */
283 public function setElementGroup( $group ) {
284 $this->elementGroup = $group;
285 return $this;
286 }
287
288 /**
289 * Enable widget for client-side infusion.
290 *
291 * @param bool $infusable True to allow tag/element/widget to be referenced client-side.
292 * @return $this
293 */
294 public function setInfusable( $infusable ) {
295 $this->infusable = $infusable;
296 return $this;
297 }
298
299 /**
300 * Get client-side infusability.
301 *
302 * @return bool If this tag/element/widget can be referenced client-side.
303 */
304 public function isInfusable() {
305 return $this->infusable;
306 }
307
308 /** @var int */
309 private static $elementId = 0;
310
311 /**
312 * Generate a unique ID for element
313 *
314 * @return string ID
315 */
316 public static function generateElementId() {
317 self::$elementId++;
318 return 'ooui-php-' . self::$elementId;
319 }
320
321 /**
322 * Reset the unique ID, for consistent test output.
323 * Warning: Do not use this function outside of tests!
324 *
325 * @see https://phabricator.wikimedia.org/T345515
326 */
327 public static function resetElementId() {
328 self::$elementId = 0;
329 }
330
331 /**
332 * Ensure that this given Tag is infusable and has a unique `id`
333 * attribute.
334 * @return $this
335 */
336 public function ensureInfusableId() {
337 $this->setInfusable( true );
338 if ( $this->getAttribute( 'id' ) === null ) {
339 $this->setAttributes( [ 'id' => self::generateElementId() ] );
340 }
341 return $this;
342 }
343
344 /**
345 * Return an augmented `attributes` array, including synthetic attributes
346 * which are created from other properties (like the `classes` array)
347 * but which shouldn't be retained in the user-visible `attributes`.
348 * @return string[]
349 */
350 protected function getGeneratedAttributes() {
351 // Copy attributes, add `class` attribute from `$this->classes` array.
352 $attributesArray = $this->attributes;
353 if ( $this->classes ) {
354 $attributesArray['class'] = implode( ' ', array_unique( $this->classes ) );
355 }
356 if ( $this->infusable ) {
357 // Indicate that this is "just" a tag (not a widget)
358 $attributesArray['data-ooui'] = json_encode( [ '_' => 'Tag' ] );
359 }
360 return $attributesArray;
361 }
362
363 /**
364 * Check whether the string $haystack begins with the string $needle.
365 *
366 * @param string $haystack
367 * @param string $needle
368 * @return bool True if $haystack begins with $needle, false otherwise.
369 */
370 private static function stringStartsWith( $haystack, $needle ) {
371 return strncmp( $haystack, $needle, strlen( $needle ) ) === 0;
372 }
373
374 /**
375 * Check whether user-supplied URL is safe, that is, whether outputting it will not result in XSS
376 * vulnerability. (Note that URLs must be HTML-escaped regardless of this check.)
377 *
378 * The point is to disallow 'javascript:' URLs (there are no good reasons to ever use them
379 * anyway), but there's no good way to prohibit them because of very lax parsing in browsers.
380 *
381 * An URL is safe if:
382 *
383 * - it is empty, or
384 * - it starts with an allowed protocol, followed by a colon (absolute URL), or
385 * - it starts with two slashes `//` (protocol-relative URL), or
386 * - it starts with a single slash `/`, or dot and slash `./` (relative URL), or
387 * - it starts with a question mark `?` (replace query part in current URL), or
388 * - it starts with a pound sign `#` (replace fragment part in current URL)
389 *
390 * Plain relative URLs (like `index.php`) are not allowed, since it's pretty much impossible to
391 * distinguish them from malformed absolute ones (again, very lax rules for parsing protocols).
392 *
393 * @param string $url URL
394 * @return bool [description]
395 */
396 public static function isSafeUrl( $url ) {
397 // Keep this function in sync with OO.ui.isSafeUrl
398 $protocolAllowList = [
399 // Sourced from MediaWiki's $wgUrlProtocols
400 'bitcoin', 'ftp', 'ftps', 'geo', 'git', 'gopher', 'http', 'https', 'irc', 'ircs',
401 'magnet', 'mailto', 'mms', 'news', 'nntp', 'redis', 'sftp', 'sip', 'sips', 'sms', 'ssh',
402 'svn', 'tel', 'telnet', 'urn', 'worldwind', 'xmpp',
403 ];
404
405 if ( $url === '' ) {
406 return true;
407 }
408
409 foreach ( $protocolAllowList as $protocol ) {
410 if ( self::stringStartsWith( $url, $protocol . ':' ) ) {
411 return true;
412 }
413 }
414
415 // This matches '//' too
416 if ( self::stringStartsWith( $url, '/' ) || self::stringStartsWith( $url, './' ) ) {
417 return true;
418 }
419 if ( self::stringStartsWith( $url, '?' ) || self::stringStartsWith( $url, '#' ) ) {
420 return true;
421 }
422
423 return false;
424 }
425
426 /**
427 * Render element into HTML.
428 * @return string HTML serialization
429 */
430 public function toString() {
431 // List of void elements from HTML5, section 8.1.2 as of 2016-09-19
432 static $voidElements = [
433 'area',
434 'base',
435 'br',
436 'col',
437 'embed',
438 'hr',
439 'img',
440 'input',
441 'keygen',
442 'link',
443 'meta',
444 'param',
445 'source',
446 'track',
447 'wbr',
448 ];
449
450 $attributes = '';
451 foreach ( $this->getGeneratedAttributes() as $key => $value ) {
452 if ( !preg_match( '/^[0-9a-zA-Z-]+$/', $key ) ) {
453 throw new Exception( 'Attribute name must consist of only ASCII letters, numbers and dash' );
454 }
455
456 // Note that this is not a complete list of HTML attributes that need this validation.
457 // We only check for the ones that are generated by built-in OOUI PHP elements.
458 if ( $key === 'href' || $key === 'action' ) {
459 if ( !self::isSafeUrl( $value ) ) {
460 // We can't tell for sure whether this URL is safe (although it might be). The only safe
461 // URLs that we can't check for is relative ones, so just prefix with './'. This should
462 // change nothing for relative URLs, and it will neutralize sneaky 'javascript:' URLs.
463 $value = './' . $value;
464 }
465 }
466
467 // Use single-quotes around the attribute value in HTML, because
468 // some of the values might be JSON strings
469 // 1. Encode both single and double quotes (and other special chars)
470 $value = htmlspecialchars( $value ?? '', ENT_QUOTES );
471 // 2. Decode double quotes, for readability.
472 $value = str_replace( '&quot;', '"', $value );
473 // 3. Wrap attribute value in single quotes in the HTML.
474 $attributes .= ' ' . $key . "='" . $value . "'";
475 }
476
477 // Content
478 $content = '';
479 foreach ( $this->content as $part ) {
480 if ( $part instanceof Tag || $part instanceof HtmlSnippet ) {
481 $content .= (string)$part;
482 } else {
483 $content .= htmlspecialchars( (string)$part );
484 }
485 }
486
487 if ( !preg_match( '/^[0-9a-zA-Z]+$/', $this->tag ) ) {
488 throw new Exception( 'Tag name must consist of only ASCII letters and numbers' );
489 }
490
491 // Tag
492 if ( !$content && in_array( $this->tag, $voidElements ) ) {
493 return '<' . $this->tag . $attributes . ' />';
494 } else {
495 return '<' . $this->tag . $attributes . '>' . $content . '</' . $this->tag . '>';
496 }
497 }
498
499 /**
500 * Magic method implementation.
501 *
502 * It was not possible to throw an exception from within a __toString() method prior to PHP 7.4.0.
503 * Doing so will result in a fatal error.
504 * This is a wrapper around the real toString() to convert them to errors instead.
505 *
506 * @return string
507 */
508 public function __toString() {
509 try {
510 return $this->toString();
511 } catch ( Exception $ex ) {
512 trigger_error( (string)$ex, E_USER_ERROR );
513 }
514 }
515 }