Translated using Weblate (Slovenian)
[phpmyadmin.git] / libraries / Sanitize.php
blob0011705c3d53ef31d0b9c085dcbf0abc8c628abe
1 <?php
2 /* vim: set expandtab sw=4 ts=4 sts=4: */
3 /**
4 * This class includes various sanitization methods that can be called statically
6 * @package PhpMyAdmin
7 */
8 namespace PMA\libraries;
10 use PMA\libraries\Util;
12 /**
13 * This class includes various sanitization methods that can be called statically
15 * @package PhpMyAdmin
17 class Sanitize
19 /**
20 * Checks whether given link is valid
22 * @param string $url URL to check
23 * @param boolean $http Whether to allow http links
24 * @param boolean $other Whether to allow ftp and mailto links
26 * @return boolean True if string can be used as link
28 public static function checkLink($url, $http=false, $other=false)
30 $url = strtolower($url);
31 $valid_starts = array(
32 'https://',
33 './url.php?url=https%3a%2f%2f',
34 './doc/html/',
35 # possible return values from Util::getScriptNameForOption
36 './index.php?',
37 './server_databases.php?',
38 './server_status.php?',
39 './server_variables.php?',
40 './server_privileges.php?',
41 './db_structure.php?',
42 './db_sql.php?',
43 './db_search.php?',
44 './db_operations.php?',
45 './tbl_structure.php?',
46 './tbl_sql.php?',
47 './tbl_select.php?',
48 './tbl_change.php?',
49 './sql.php?',
50 # Hardcoded options in libraries/special_schema_links.lib.php
51 './db_events.php?',
52 './db_routines.php?',
53 './server_privileges.php?',
54 './tbl_structure.php?',
56 // Adjust path to setup script location
57 if (defined('PMA_SETUP')) {
58 foreach ($valid_starts as $key => $value) {
59 if (substr($value, 0, 2) === './') {
60 $valid_starts[$key] = '.' . $value;
64 if ($other) {
65 $valid_starts[] = 'mailto:';
66 $valid_starts[] = 'ftp://';
68 if ($http) {
69 $valid_starts[] = 'http://';
71 if (defined('PMA_SETUP')) {
72 $valid_starts[] = '?page=form&';
73 $valid_starts[] = '?page=servers&';
75 foreach ($valid_starts as $val) {
76 if (substr($url, 0, strlen($val)) == $val) {
77 return true;
80 return false;
83 /**
84 * Callback function for replacing [a@link@target] links in bb code.
86 * @param array $found Array of preg matches
88 * @return string Replaced string
90 public static function replaceBBLink($found)
92 /* Check for valid link */
93 if (! Sanitize::checkLink($found[1])) {
94 return $found[0];
96 /* a-z and _ allowed in target */
97 if (! empty($found[3]) && preg_match('/[^a-z_]+/i', $found[3])) {
98 return $found[0];
101 /* Construct target */
102 $target = '';
103 if (! empty($found[3])) {
104 $target = ' target="' . $found[3] . '"';
105 if ($found[3] == '_blank') {
106 $target .= ' rel="noopener noreferrer"';
110 /* Construct url */
111 if (substr($found[1], 0, 4) == 'http') {
112 $url = PMA_linkURL($found[1]);
113 } else {
114 $url = $found[1];
117 return '<a href="' . $url . '"' . $target . '>';
121 * Callback function for replacing [doc@anchor] links in bb code.
123 * @param array $found Array of preg matches
125 * @return string Replaced string
127 public static function replaceDocLink($found)
129 if (count($found) >= 4) {
130 $page = $found[1];
131 $anchor = $found[3];
132 } else {
133 $anchor = $found[1];
134 if (strncmp('faq', $anchor, 3) == 0) {
135 $page = 'faq';
136 } else if (strncmp('cfg', $anchor, 3) == 0) {
137 $page = 'config';
138 } else {
139 /* Guess */
140 $page = 'setup';
143 $link = Util::getDocuLink($page, $anchor);
144 return '<a href="' . $link . '" target="documentation">';
148 * Sanitizes $message, taking into account our special codes
149 * for formatting.
151 * If you want to include result in element attribute, you should escape it.
153 * Examples:
155 * <p><?php echo Sanitize::sanitize($foo); ?></p>
157 * <a title="<?php echo Sanitize::sanitize($foo, true); ?>">bar</a>
159 * @param string $message the message
160 * @param boolean $escape whether to escape html in result
161 * @param boolean $safe whether string is safe (can keep < and > chars)
163 * @return string the sanitized message
165 public static function sanitize($message, $escape = false, $safe = false)
167 if (!$safe) {
168 $message = strtr($message, array('<' => '&lt;', '>' => '&gt;'));
171 /* Interpret bb code */
172 $replace_pairs = array(
173 '[em]' => '<em>',
174 '[/em]' => '</em>',
175 '[strong]' => '<strong>',
176 '[/strong]' => '</strong>',
177 '[code]' => '<code>',
178 '[/code]' => '</code>',
179 '[kbd]' => '<kbd>',
180 '[/kbd]' => '</kbd>',
181 '[br]' => '<br />',
182 '[/a]' => '</a>',
183 '[/doc]' => '</a>',
184 '[sup]' => '<sup>',
185 '[/sup]' => '</sup>',
186 // used in common.inc.php:
187 '[conferr]' => '<iframe src="show_config_errors.php"><a href="show_config_errors.php">show_config_errors.php</a></iframe>',
188 // used in libraries/Util.php
189 '[dochelpicon]' => Util::getImage('b_help.png', __('Documentation')),
192 $message = strtr($message, $replace_pairs);
194 /* Match links in bb code ([a@url@target], where @target is options) */
195 $pattern = '/\[a@([^]"@]*)(@([^]"]*))?\]/';
197 /* Find and replace all links */
198 $message = preg_replace_callback($pattern, function($match){
199 return Sanitize::replaceBBLink($match);
200 }, $message);
202 /* Replace documentation links */
203 $message = preg_replace_callback(
204 '/\[doc@([a-zA-Z0-9_-]+)(@([a-zA-Z0-9_-]*))?\]/',
205 function($match){
206 return Sanitize::replaceDocLink($match);
208 $message
211 /* Possibly escape result */
212 if ($escape) {
213 $message = htmlspecialchars($message);
216 return $message;
221 * Sanitize a filename by removing anything besides legit characters
223 * Intended usecase:
224 * When using a filename in a Content-Disposition header
225 * the value should not contain ; or "
227 * When exporting, avoiding generation of an unexpected double-extension file
229 * @param string $filename The filename
230 * @param boolean $replaceDots Whether to also replace dots
232 * @return string the sanitized filename
235 public static function sanitizeFilename($filename, $replaceDots = false)
237 $pattern = '/[^A-Za-z0-9_';
238 // if we don't have to replace dots
239 if (! $replaceDots) {
240 // then add the dot to the list of legit characters
241 $pattern .= '.';
243 $pattern .= '-]/';
244 $filename = preg_replace($pattern, '_', $filename);
245 return $filename;
249 * Format a string so it can be a string inside JavaScript code inside an
250 * eventhandler (onclick, onchange, on..., ).
251 * This function is used to displays a javascript confirmation box for
252 * "DROP/DELETE/ALTER" queries.
254 * @param string $a_string the string to format
255 * @param boolean $add_backquotes whether to add backquotes to the string or not
257 * @return string the formatted string
259 * @access public
261 public static function jsFormat($a_string = '', $add_backquotes = true)
263 $a_string = htmlspecialchars($a_string);
264 $a_string = Sanitize::escapeJsString($a_string);
265 // Needed for inline javascript to prevent some browsers
266 // treating it as a anchor
267 $a_string = str_replace('#', '\\#', $a_string);
269 return $add_backquotes
270 ? Util::backquote($a_string)
271 : $a_string;
272 } // end of the 'Sanitize::jsFormat()' function
275 * escapes a string to be inserted as string a JavaScript block
276 * enclosed by <![CDATA[ ... ]]>
277 * this requires only to escape ' with \' and end of script block
279 * We also remove NUL byte as some browsers (namely MSIE) ignore it and
280 * inserting it anywhere inside </script would allow to bypass this check.
282 * @param string $string the string to be escaped
284 * @return string the escaped string
286 public static function escapeJsString($string)
288 return preg_replace(
289 '@</script@i', '</\' + \'script',
290 strtr(
291 $string,
292 array(
293 "\000" => '',
294 '\\' => '\\\\',
295 '\'' => '\\\'',
296 '"' => '\"',
297 "\n" => '\n',
298 "\r" => '\r'
305 * Formats a value for javascript code.
307 * @param string $value String to be formatted.
309 * @return string formatted value.
311 public static function formatJsVal($value)
313 if (is_bool($value)) {
314 if ($value) {
315 return 'true';
318 return 'false';
321 if (is_int($value)) {
322 return (int)$value;
325 return '"' . Sanitize::escapeJsString($value) . '"';
329 * Formats an javascript assignment with proper escaping of a value
330 * and support for assigning array of strings.
332 * @param string $key Name of value to set
333 * @param mixed $value Value to set, can be either string or array of strings
334 * @param bool $escape Whether to escape value or keep it as it is
335 * (for inclusion of js code)
337 * @return string Javascript code.
339 public static function getJsValue($key, $value, $escape = true)
341 $result = $key . ' = ';
342 if (!$escape) {
343 $result .= $value;
344 } elseif (is_array($value)) {
345 $result .= '[';
346 foreach ($value as $val) {
347 $result .= Sanitize::formatJsVal($val) . ",";
349 $result .= "];\n";
350 } else {
351 $result .= Sanitize::formatJsVal($value) . ";\n";
353 return $result;
357 * Prints an javascript assignment with proper escaping of a value
358 * and support for assigning array of strings.
360 * @param string $key Name of value to set
361 * @param mixed $value Value to set, can be either string or array of strings
363 * @return void
365 public static function printJsValue($key, $value)
367 echo Sanitize::getJsValue($key, $value);
371 * Formats javascript assignment for form validation api
372 * with proper escaping of a value.
374 * @param string $key Name of value to set
375 * @param string $value Value to set
376 * @param boolean $addOn Check if $.validator.format is required or not
377 * @param boolean $comma Check if comma is required
379 * @return string Javascript code.
381 public static function getJsValueForFormValidation($key, $value, $addOn, $comma)
383 $result = $key . ': ';
384 if ($addOn) {
385 $result .= '$.validator.format(';
387 $result .= Sanitize::formatJsVal($value);
388 if ($addOn) {
389 $result .= ')';
391 if ($comma) {
392 $result .= ', ';
394 return $result;
398 * Prints javascript assignment for form validation api
399 * with proper escaping of a value.
401 * @param string $key Name of value to set
402 * @param string $value Value to set
403 * @param boolean $addOn Check if $.validator.format is required or not
404 * @param boolean $comma Check if comma is required
406 * @return void
408 public static function printJsValueForFormValidation($key, $value, $addOn=false, $comma=true)
410 echo Sanitize::getJsValueForFormValidation($key, $value, $addOn, $comma);
414 * Removes all variables from request except whitelisted ones.
416 * @param string &$whitelist list of variables to allow
418 * @return void
419 * @access public
421 public static function removeRequestVars(&$whitelist)
423 // do not check only $_REQUEST because it could have been overwritten
424 // and use type casting because the variables could have become
425 // strings
426 if (! isset($_REQUEST)) {
427 $_REQUEST = array();
429 if (! isset($_GET)) {
430 $_GET = array();
432 if (! isset($_POST)) {
433 $_POST = array();
435 if (! isset($_COOKIE)) {
436 $_COOKIE = array();
438 $keys = array_keys(
439 array_merge((array)$_REQUEST, (array)$_GET, (array)$_POST, (array)$_COOKIE)
442 foreach ($keys as $key) {
443 if (! in_array($key, $whitelist)) {
444 unset($_REQUEST[$key], $_GET[$key], $_POST[$key]);
445 continue;
448 // allowed stuff could be compromised so escape it
449 // we require it to be a string
450 if (isset($_REQUEST[$key]) && ! is_string($_REQUEST[$key])) {
451 unset($_REQUEST[$key]);
453 if (isset($_POST[$key]) && ! is_string($_POST[$key])) {
454 unset($_POST[$key]);
456 if (isset($_COOKIE[$key]) && ! is_string($_COOKIE[$key])) {
457 unset($_COOKIE[$key]);
459 if (isset($_GET[$key]) && ! is_string($_GET[$key])) {
460 unset($_GET[$key]);