summaryrefslogtreecommitdiff
path: root/vendor/oojs/oojs-ui/php/Tag.php
blob: e5fa9df6640655b2cc6f2b8b9fbf84c3c05eb472 (plain)
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
<?php

namespace OOUI;

class Tag {

	/* Properties */

	/**
	 * Tag name for this instance.
	 *
	 * @var string HTML tag name
	 */
	protected $tag = '';

	/**
	 * Attributes.
	 *
	 * @var array HTML attributes
	 */
	protected $attributes = array();

	/**
	 * Classes.
	 *
	 * @var array CSS classes
	 */
	protected $classes = array();

	/**
	 * Content.
	 *
	 * @var array Content text and elements
	 */
	protected $content = array();

	/**
	 * Group.
	 *
	 * @var GroupElement|null Group element is in
	 */
	protected $elementGroup = null;

	/**
	 * Infusion support.
	 *
	 * @var boolean Whether to serialize tag/element/widget state for client-side use.
	 */
	protected $infusable = false;

	/* Methods */

	/**
	 * Create element.
	 *
	 * @param string $tag HTML tag name
	 */
	public function __construct( $tag = 'div' ) {
		$this->tag = $tag;
	}

	/**
	 * Check for CSS class.
	 *
	 * @param string $name CSS class name
	 * @return boolean
	 */
	public function hasClass( $class ) {
		return in_array( $class, $this->classes );
	}

	/**
	 * Add CSS classes.
	 *
	 * @param array $classes List of classes to add
	 * @chainable
	 */
	public function addClasses( array $classes ) {
		$this->classes = array_merge( $this->classes, $classes );
		return $this;
	}

	/**
	 * Remove CSS classes.
	 *
	 * @param array $classes List of classes to remove
	 * @chainable
	 */
	public function removeClasses( array $classes ) {
		$this->classes = array_diff( $this->classes, $classes );
		return $this;
	}

	/**
	 * Toggle CSS classes.
	 *
	 * @param array $classes List of classes to add
	 * @param boolean $toggle Add classes
	 * @chainable
	 */
	public function toggleClasses( array $classes, $toggle = null ) {
		if ( $toggle === null ) {
			$this->classes = array_diff(
				array_merge( $this->classes, $classes ),
				array_intersect( $this->classes, $classes )
			);
		} elseif ( $toggle ) {
			$this->classes = array_merge( $this->classes, $classes );
		} else {
			$this->classes = array_diff( $this->classes, $classes );
		}
		return $this;
	}

	/**
	 * Get HTML attribute value.
	 *
	 * @param string $key HTML attribute name
	 * @return string|null
	 */
	public function getAttribute( $key ) {
		return isset( $this->attributes[$key] ) ? $this->attributes[$key] : null;
	}

	/**
	 * Add HTML attributes.
	 *
	 * @param array $attributes List of attribute key/value pairs to add
	 * @chainable
	 */
	public function setAttributes( array $attributes ) {
		foreach ( $attributes as $key => $value ) {
			$this->attributes[$key] = $value;
		}
		return $this;
	}

	/**
	 * Set value of input element ('value' attribute for most, element content for textarea).
	 *
	 * @param string $value Value to set
	 * @chainable
	 */
	public function setValue( $value ) {
		if ( strtolower( $this->tag ) === 'textarea' ) {
			$this->clearContent();
			$this->appendContent( $value );
		} else {
			$this->setAttributes( array( 'value' => $value ) );
		}
		return $this;
	}

	/**
	 * Remove HTML attributes.
	 *
	 * @param array $keys List of attribute keys to remove
	 * @chainable
	 */
	public function removeAttributes( array $keys ) {
		foreach ( $keys as $key ) {
			unset( $this->attributes[$key] );
		}
		return $this;
	}

	/**
	 * Add content to the end.
	 *
	 * Accepts variadic arguments (the $content argument can be repeated any number of times).
	 *
	 * @param string|Tag|HtmlSnippet $content Content to append. Strings will be HTML-escaped
	 *   for output, use a HtmlSnippet instance to prevent that.
	 * @chainable
	 */
	public function appendContent( /* $content... */ ) {
		$contents = func_get_args();
		$this->content = array_merge( $this->content, $contents );
		return $this;
	}

	/**
	 * Add content to the beginning.
	 *
	 * Accepts variadic arguments (the $content argument can be repeated any number of times).
	 *
	 * @param string|Tag|HtmlSnippet $content Content to prepend. Strings will be HTML-escaped
	 *   for output, use a HtmlSnippet instance to prevent that.
	 * @chainable
	 */
	public function prependContent( /* $content... */ ) {
		$contents = func_get_args();
		array_splice( $this->content, 0, 0, $contents );
		return $this;
	}

	/**
	 * Remove all content.
	 *
	 * @chainable
	 */
	public function clearContent() {
		$this->content = array();
		return $this;
	}

	/**
	 * Get group element is in.
	 *
	 * @return GroupElement|null Group element, null if none
	 */
	public function getElementGroup() {
		return $this->elementGroup;
	}

	/**
	 * Set group element is in.
	 *
	 * @param GroupElement|null $group Group element, null if none
	 * @chainable
	 */
	public function setElementGroup( $group ) {
		$this->elementGroup = $group;
		return $this;
	}

	/**
	 * Enable widget for client-side infusion.
	 *
	 * @param boolean $infusable True to allow tag/element/widget to be referenced client-side.
	 * @chainable
	 */
	public function setInfusable( $infusable ) {
		$this->infusable = $infusable;
		return $this;
	}

	/**
	 * Get client-side infusability.
	 *
	 * @return boolean If this tag/element/widget can be referenced client-side.
	 */
	public function isInfusable() {
		return $this->infusable;
	}

	private static $id_cnt = 0;
	/**
	 * Ensure that this given Tag is infusable and has a unique `id`
	 * attribute.
	 * @chainable
	 */
	public function ensureInfusableId() {
		$this->setInfusable( true );
		if ( $this->getAttribute( 'id' ) === null ) {
			$this->setAttributes( array( 'id' => "ooui-" . ( self::$id_cnt++ ) ) );
		}
		return $this;
	}

	/**
	 * Return an augmented `attributes` array, including synthetic attributes
	 * which are created from other properties (like the `classes` array)
	 * but which shouldn't be retained in the user-visible `attributes`.
	 * @return array An attributes array.
	 */
	protected function getGeneratedAttributes() {
		// Copy attributes, add `class` attribute from `$this->classes` array.
		$attributesArray = $this->attributes;
		if ( $this->classes ) {
			$attributesArray['class'] = implode( ' ', array_unique( $this->classes ) );
		}
		if ( $this->infusable ) {
			// Indicate that this is "just" a tag (not a widget)
			$attributesArray['data-ooui'] = json_encode( array( '_' => 'Tag' ) );
		}
		return $attributesArray;
	}

	/**
	 * Render element into HTML.
	 *
	 * @return string HTML serialization
	 */
	public function toString() {
		$attributes = '';
		foreach ( $this->getGeneratedAttributes() as $key => $value ) {
			if ( !preg_match( '/^[0-9a-zA-Z-]+$/', $key ) ) {
				throw new Exception( 'Attribute name must consist of only ASCII letters, numbers and dash' );
			}

			if ( $key === 'href' || $key === 'action' ) {
				// Make it impossible to point a link or a form to a 'javascript:' URL. There's no good way
				// to blacklist them because of very lax parsing, so instead we whitelist known-good
				// protocols (and also accept protocol-less and protocol-relative links). There are no good
				// reasons to ever use 'javascript:' URLs anyway.
				$protocolWhitelist = array(
					// Sourced from MediaWiki's $wgUrlProtocols
					// Keep in sync with OO.ui.isSafeUrl
					'bitcoin', 'ftp', 'ftps', 'geo', 'git', 'gopher', 'http', 'https', 'irc', 'ircs',
					'magnet', 'mailto', 'mms', 'news', 'nntp', 'redis', 'sftp', 'sip', 'sips', 'sms', 'ssh',
					'svn', 'tel', 'telnet', 'urn', 'worldwind', 'xmpp',
					'(protocol-relative)', '(relative)',
				);

				// Protocol-relative URLs are handled really badly by parse_url()
				if ( substr( $value, 0, 2 ) === '//' ) {
					$scheme = '(protocol-relative)';
				} else {
					// Must suppress warnings when the value is not a valid URL. parse_url() returns false then.
					\MediaWiki\suppressWarnings();
					$scheme = parse_url( $value, PHP_URL_SCHEME );
					\MediaWiki\restoreWarnings();
					if ( $scheme === null || ( !$scheme && substr( $value, 0, 1 ) === '/' ) ) {
						$scheme = '(relative)';
					}
				}

				if ( !in_array( strtolower( $scheme ), $protocolWhitelist ) ) {
					throw new Exception( "Potentially unsafe '$key' attribute value. " .
						"Scheme: '$scheme'; value: '$value'." );
				}
			}

			// Use single-quotes around the attribute value in HTML, because
			// some of the values might be JSON strings
			// 1. Encode both single and double quotes (and other special chars)
			$value = htmlspecialchars( $value, ENT_QUOTES );
			// 2. Decode double quotes, for readability.
			$value = str_replace( '&quot;', '"', $value );
			// 3. Wrap attribute value in single quotes in the HTML.
			$attributes .= ' ' . $key . "='" . $value . "'";
		}

		// Content
		$content = '';
		foreach ( $this->content as $part ) {
			if ( is_string( $part ) ) {
				$content .= htmlspecialchars( $part );
			} elseif ( $part instanceof Tag || $part instanceof HtmlSnippet ) {
				$content .= (string)$part;
			}
		}

		if ( !preg_match( '/^[0-9a-zA-Z]+$/', $this->tag ) ) {
			throw new Exception( 'Tag name must consist of only ASCII letters and numbers' );
		}

		// Tag
		return '<' . $this->tag . $attributes . '>' . $content . '</' . $this->tag . '>';
	}

	/**
	 * Magic method implementation.
	 *
	 * PHP doesn't allow __toString to throw exceptions and will trigger a fatal error if it does.
	 * This is a wrapper around the real toString() to convert them to errors instead.
	 *
	 * @return string
	 */
	public function __toString() {
		try {
			return $this->toString();
		} catch ( Exception $ex ) {
			trigger_error( (string)$ex, E_USER_ERROR );
			return '';
		}
	}
}