summaryrefslogtreecommitdiff
path: root/library/WT/Filter.php
blob: ebfd63c1785e050d35c6cca8d472494f60ed3102 (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
<?php
// Filter/escape/validate input and output
//
// webtrees: Web based Family History software
// Copyright (c) 2014 webtrees development team
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA

use Michelf\MarkdownExtra;

class WT_Filter {
	// REGEX to match a URL
	// Some versions of RFC3987 have an appendix B which gives the following regex
	// (([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?
	// This matches far too much while a “precise” regex is several pages long.
	// This is a compromise.
	const URL_REGEX='((https?|ftp]):)(//([^\s/?#<>]*))?([^\s?#<>]*)(\?([^\s#<>]*))?(#[^\s?#<>]+)?';


	//////////////////////////////////////////////////////////////////////////////
	// Escape a string for use in HTML
	//////////////////////////////////////////////////////////////////////////////
	public static function escapeHtml($string) {
		if (defined('ENT_SUBSTITUTE')) {
			// PHP5.4 allows us to substitute invalid UTF8 sequences
			return htmlspecialchars($string, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
		} else {
			return htmlspecialchars($string, ENT_QUOTES, 'UTF-8');
		}
	}

	//////////////////////////////////////////////////////////////////////////////
	// Escape a string for use in a URL
	//////////////////////////////////////////////////////////////////////////////
	public static function escapeUrl($string) {
		return rawurlencode($string);
	}

	//////////////////////////////////////////////////////////////////////////////
	// Escape a string for use in Javascript
	//////////////////////////////////////////////////////////////////////////////
	public static function escapeJs($string) {
		return preg_replace_callback('/[^A-Za-z0-9,. _]/Su', function($x) {
			if (strlen($x[0]) == 1) {
				return sprintf('\\x%02X', ord($x[0]));
			} elseif (function_exists('iconv')) {
				return sprintf('\\u%04s', strtoupper(bin2hex(iconv('UTF-8', 'UTF-16BE', $x[0]))));
			} elseif (function_exists('mb_convert_encoding')) {
				return sprintf('\\u%04s', strtoupper(bin2hex(mb_convert_encoding($x[0], 'UTF-16BE', 'UTF-8'))));
			} else {
				return $x[0];
			}
		}, $string);
	}

	//////////////////////////////////////////////////////////////////////////////
	// Unescape an HTML string, giving just the literal text
	//////////////////////////////////////////////////////////////////////////////
	public static function unescapeHtml($string) {
		return html_entity_decode(strip_tags($string), ENT_QUOTES, 'UTF-8');
	}

	//////////////////////////////////////////////////////////////////////////////
	// Format block-level text such as notes or transcripts, etc.
	//////////////////////////////////////////////////////////////////////////////
	public static function formatText($text, WT_Tree $WT_TREE) {
		switch ($WT_TREE->preference('FORMAT_TEXT')) {
		case 'markdown':
			return '<div class="markdown" dir="auto">' . WT_Filter::markdown($text) . '</div>';
			break;
		case '':
		default:
			return '<div style="white-space: pre-wrap;" dir="auto">' . WT_Filter::expandUrls($text) . '</div>';
			break;
		}
	}

	//////////////////////////////////////////////////////////////////////////////
	// Escape a string for use in HTML, and additionally convert URLs to links.
	//////////////////////////////////////////////////////////////////////////////
	public static function expandUrls($text) {
		return preg_replace_callback(
			'/' . addcslashes('(?!>)' . WT_Filter::URL_REGEX . '(?!</a>)', '/') . '/i',
			function ($m) {
				return '<a href="' . $m[0] . '" target="_blank">' . $m[0] . '</a>';
			},
			WT_Filter::escapeHtml($text)
		);
	}

	//////////////////////////////////////////////////////////////////////////////
	// Format a block of text, using "Markdown".
	//////////////////////////////////////////////////////////////////////////////
	public static function markdown($text) {
		$parser = new MarkdownExtra;
		$parser->empty_element_suffix = '>';
		$parser->no_markup            = true;
		$text = $parser->transform($text);

		// HTMLPurifier needs somewhere to write temporary files
		$HTML_PURIFIER_CACHE_DIR = WT_DATA_DIR . 'html_purifier_cache';

		if (!is_dir($HTML_PURIFIER_CACHE_DIR)) {
			mkdir($HTML_PURIFIER_CACHE_DIR);
		}

		$config = HTMLPurifier_Config::createDefault();
		$config->set('Cache.SerializerPath', $HTML_PURIFIER_CACHE_DIR);
		$purifier = new HTMLPurifier($config);
		$text = $purifier->purify($text);

		return $text;
	}

	//////////////////////////////////////////////////////////////////////////////
	// Validate INPUT requests
	//////////////////////////////////////////////////////////////////////////////
	private static function _input($source, $variable, $regexp=null, $default=null) {
		if ($regexp) {
			return filter_input(
				$source,
				$variable,
				FILTER_VALIDATE_REGEXP,
				array(
					'options' => array(
						'regexp'  => '/^(' . $regexp . ')$/u',
						'default' => $default,
					),
				)
			);
		} else {
			$tmp = filter_input(
				$source,
				$variable,
				FILTER_CALLBACK,
				array(
					'options' => function($x) {
						return !function_exists('mb_convert_encoding') || mb_check_encoding($x, 'UTF-8') ? $x : false;
					},
				)
			);
			return ($tmp===null || $tmp===false) ? $default : $tmp;
		}
	}

	private static function _inputArray($source, $variable, $regexp=null, $default=null) {
		if ($regexp) {
			// PHP5.3 requires the $tmp variable
			$tmp = filter_input_array(
				$source,
				array(
					$variable => array(
						'flags'   => FILTER_REQUIRE_ARRAY,
						'filter'  => FILTER_VALIDATE_REGEXP,
						'options' => array(
							'regexp'  => '/^(' . $regexp . ')$/u',
							'default' => $default,
						),
					),
				)
			);
			return $tmp[$variable] ?: array();
		} else {
			// PHP5.3 requires the $tmp variable
			$tmp = filter_input_array(
				$source,
				array(
					$variable => array(
						'flags'   => FILTER_REQUIRE_ARRAY,
						'filter'  => FILTER_CALLBACK,
						'options' => function($x) {
							return !function_exists('mb_convert_encoding') || mb_check_encoding($x, 'UTF-8') ? $x : false;
						}
					),
				)
			);
			return $tmp[$variable] ?: array();
		}
	}

	//////////////////////////////////////////////////////////////////////////////
	// Validate GET requests
	//////////////////////////////////////////////////////////////////////////////
	public static function get($variable, $regexp=null, $default=null) {
		return self::_input(INPUT_GET, $variable, $regexp, $default);
	}

	public static function getArray($variable, $regexp=null, $default=null) {
		return self::_inputArray(INPUT_GET, $variable, $regexp, $default);
	}

	public static function getBool($variable) {
		return (bool)filter_input(INPUT_GET, $variable, FILTER_VALIDATE_BOOLEAN);
	}

	public static function getInteger($variable, $min=0, $max=PHP_INT_MAX, $default=0) {
		return filter_input(INPUT_GET, $variable, FILTER_VALIDATE_INT, array('options'=>array('min_range'=>$min, 'max_range'=>$max, 'default'=>$default)));
	}

	public static function getEmail($variable, $default=null) {
		return filter_input(INPUT_GET, $variable, FILTER_VALIDATE_EMAIL) ?: $default;
	}

	public static function getUrl($variable, $default=null) {
		return filter_input(INPUT_GET, $variable, FILTER_VALIDATE_URL) ?: $default;
	}

	//////////////////////////////////////////////////////////////////////////////
	// Validate POST requests
	//////////////////////////////////////////////////////////////////////////////
	public static function post($variable, $regexp=null, $default=null) {
		return self::_input(INPUT_POST, $variable, $regexp, $default);
	}

	public static function postArray($variable, $regexp=null, $default=null) {
		return self::_inputArray(INPUT_POST, $variable, $regexp, $default);
	}

	public static function postBool($variable) {
		return (bool)filter_input(INPUT_POST, $variable, FILTER_VALIDATE_BOOLEAN);
	}

	public static function postInteger($variable, $min=0, $max=PHP_INT_MAX, $default=0) {
		return filter_input(INPUT_POST, $variable, FILTER_VALIDATE_INT, array('options'=>array('min_range'=>$min, 'max_range'=>$max, 'default'=>$default)));
	}

	public static function postEmail($variable, $default=null) {
		return filter_input(INPUT_POST, $variable, FILTER_VALIDATE_EMAIL) ?: $default;
	}

	public static function postUrl($variable, $default=null) {
		return filter_input(INPUT_POST, $variable, FILTER_VALIDATE_URL) ?: $default;
	}

	//////////////////////////////////////////////////////////////////////////////
	// Cross-Site Request Forgery tokens - ensure that the user is submitting
	// a form that was generated by the current session.
	//////////////////////////////////////////////////////////////////////////////
	public static function getCsrfToken() {
		global $WT_SESSION;

		if ($WT_SESSION->CSRF_TOKEN === null) {
			$charset = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcedfghijklmnopqrstuvwxyz0123456789';
			for ($n=0; $n<32; ++$n) {
				$WT_SESSION->CSRF_TOKEN .= substr($charset, mt_rand(0, 61), 1);
			}
		}

		return $WT_SESSION->CSRF_TOKEN;
	}

	// Generate an <input> element - to protect the current form from CSRF attacks.
	public static function getCsrf() {
		return '<input type="hidden" name="csrf" value="' . WT_Filter::getCsrfToken() . '">';
	}

	// Check that the POST request contains the CSRF token generated above.
	public static function checkCsrf() {
		if (WT_Filter::post('csrf') !== WT_Filter::getCsrfToken()) {
			// Oops.  Something is not quite right
			AddToLog('CSRF mismatch - session expired or malicious attack', 'auth');
			WT_FlashMessages::addMessage(WT_I18N::translate('This form has expired.  Try again.'));
			return false;
		}
		return true;
	}
}