Translated using Weblate (Portuguese (Brazil))
[phpmyadmin.git] / src / Sanitize.php
blobd3a58b5bada570b7b6dd7b2e5c89bdcb463af431
1 <?php
2 /**
3 * This class includes various sanitization methods that can be called statically
4 */
6 declare(strict_types=1);
8 namespace PhpMyAdmin;
10 use PhpMyAdmin\Html\MySQLDocumentation;
12 use function __;
13 use function array_keys;
14 use function array_merge;
15 use function count;
16 use function htmlspecialchars;
17 use function in_array;
18 use function is_string;
19 use function json_encode;
20 use function preg_match;
21 use function preg_replace;
22 use function preg_replace_callback;
23 use function str_starts_with;
24 use function strtolower;
25 use function strtr;
27 use const JSON_HEX_TAG;
29 /**
30 * This class includes various sanitization methods that can be called statically
32 class Sanitize
34 /**
35 * Checks whether given link is valid
37 * @param string $url URL to check
38 * @param bool $http Whether to allow http links
39 * @param bool $other Whether to allow ftp and mailto links
41 public static function checkLink(string $url, bool $http = false, bool $other = false): bool
43 $url = strtolower($url);
44 $validStarts = ['https://', 'index.php?route=/url&url=https%3a%2f%2f', './doc/html/', './index.php?'];
45 $isSetup = self::isSetup();
46 // Adjust path to setup script location
47 if ($isSetup) {
48 foreach ($validStarts as $key => $value) {
49 if (! str_starts_with($value, './')) {
50 continue;
53 $validStarts[$key] = '.' . $value;
57 if ($other) {
58 $validStarts[] = 'mailto:';
59 $validStarts[] = 'ftp://';
62 if ($http) {
63 $validStarts[] = 'http://';
66 if ($isSetup) {
67 $validStarts[] = '?page=form&';
68 $validStarts[] = '?page=servers&';
71 foreach ($validStarts as $val) {
72 if (str_starts_with($url, $val)) {
73 return true;
77 return false;
80 /**
81 * Check if we are currently on a setup folder page
83 public static function isSetup(): bool
85 return Config::getInstance()->get('is_setup');
88 /**
89 * Callback function for replacing [a@link@target] links in bb code.
91 * @param mixed[] $found Array of preg matches
93 * @return string Replaced string
95 public static function replaceBBLink(array $found): string
97 /* Check for valid link */
98 if (! self::checkLink($found[1])) {
99 return $found[0];
102 /* a-z and _ allowed in target */
103 if (! empty($found[3]) && preg_match('/[^a-z_]+/i', $found[3])) {
104 return $found[0];
107 /* Construct target */
108 $target = '';
109 if (! empty($found[3])) {
110 $target = ' target="' . $found[3] . '"';
111 if ($found[3] === '_blank') {
112 $target .= ' rel="noopener noreferrer"';
116 /* Construct url */
117 if (str_starts_with($found[1], 'http')) {
118 $url = Core::linkURL($found[1]);
119 } else {
120 $url = $found[1];
123 return '<a href="' . $url . '"' . $target . '>';
127 * Callback function for replacing [doc@anchor] links in bb code.
129 * @param string[] $found Array of preg matches
131 public static function replaceDocLink(array $found): string
133 if (count($found) >= 4) {
134 /* doc@page@anchor pattern */
135 $page = $found[1];
136 $anchor = $found[3];
137 } else {
138 /* doc@anchor pattern */
139 $anchor = $found[1];
140 if (str_starts_with($anchor, 'faq')) {
141 $page = 'faq';
142 } elseif (str_starts_with($anchor, 'cfg')) {
143 $page = 'config';
144 } else {
145 /* Guess */
146 $page = 'setup';
150 $link = MySQLDocumentation::getDocumentationLink($page, $anchor, self::isSetup() ? '../' : './');
152 return '<a href="' . $link . '" target="documentation">';
156 * Sanitizes $message, taking into account our special codes
157 * for formatting.
159 * If you want to include result in element attribute, you should escape it.
161 * Examples:
163 * <p><?php echo Sanitize::sanitizeMessage($foo); ?></p>
165 * <a title="<?php echo Sanitize::sanitizeMessage($foo, true); ?>">bar</a>
167 * @param string $message the message
168 * @param bool $escape whether to escape html in result
169 * @param bool $safe whether string is safe (can keep < and > chars)
171 public static function sanitizeMessage(string $message, bool $escape = false, bool $safe = false): string
173 if (! $safe) {
174 $message = strtr($message, ['<' => '&lt;', '>' => '&gt;']);
177 /* Interpret bb code */
178 $replacePairs = [
179 '[em]' => '<em>',
180 '[/em]' => '</em>',
181 '[strong]' => '<strong>',
182 '[/strong]' => '</strong>',
183 '[code]' => '<code>',
184 '[/code]' => '</code>',
185 '[kbd]' => '<kbd>',
186 '[/kbd]' => '</kbd>',
187 '[br]' => '<br>',
188 '[/a]' => '</a>',
189 '[/doc]' => '</a>',
190 '[sup]' => '<sup>',
191 '[/sup]' => '</sup>',
192 // used in libraries/Util.php
193 '[dochelpicon]' => Html\Generator::getImage('b_help', __('Documentation')),
196 $message = strtr($message, $replacePairs);
198 /* Match links in bb code ([a@url@target], where @target is options) */
199 $pattern = '/\[a@([^]"@]*)(@([^]"]*))?\]/';
201 /* Find and replace all links */
202 $message = (string) preg_replace_callback(
203 $pattern,
204 static fn (array $match): string => self::replaceBBLink($match),
205 $message,
208 /* Replace documentation links */
209 $message = (string) preg_replace_callback(
210 '/\[doc@([a-zA-Z0-9_-]+)(@([a-zA-Z0-9_-]*))?\]/',
211 /** @param string[] $match */
212 static fn (array $match): string => self::replaceDocLink($match),
213 $message,
216 /* Possibly escape result */
217 if ($escape) {
218 return htmlspecialchars($message);
221 return $message;
225 * Sanitize a filename by removing anything besides legit characters
227 * Intended usecase:
228 * When using a filename in a Content-Disposition header
229 * the value should not contain ; or "
231 * When exporting, avoiding generation of an unexpected double-extension file
233 * @param string $filename The filename
234 * @param bool $replaceDots Whether to also replace dots
236 * @return string the sanitized filename
238 public static function sanitizeFilename(string $filename, bool $replaceDots = false): string
240 $pattern = '/[^A-Za-z0-9_';
241 // if we don't have to replace dots
242 if (! $replaceDots) {
243 // then add the dot to the list of legit characters
244 $pattern .= '.';
247 $pattern .= '-]/';
249 return preg_replace($pattern, '_', $filename);
253 * Formats an javascript assignment with proper escaping of a value
254 * and support for assigning array of strings.
256 * @param string $key Name of value to set
257 * @param mixed $value Value to set, can be either string or array of strings
259 * @return string Javascript code.
261 public static function getJsValue(string $key, mixed $value): string
263 return $key . ' = ' . json_encode($value, JSON_HEX_TAG) . ";\n";
267 * Removes all variables from request except allowed ones.
269 * @param string[] $allowList list of variables to allow
271 public static function removeRequestVars(array $allowList): void
273 // do not check only $_REQUEST because it could have been overwritten
274 // and use type casting because the variables could have become
275 // strings
276 $keys = array_keys(
277 array_merge($_REQUEST, $_GET, $_POST, $_COOKIE),
280 foreach ($keys as $key) {
281 if (! in_array($key, $allowList)) {
282 unset($_REQUEST[$key], $_GET[$key], $_POST[$key]);
283 continue;
286 // allowed stuff could be compromised so escape it
287 // we require it to be a string
288 if (isset($_REQUEST[$key]) && ! is_string($_REQUEST[$key])) {
289 unset($_REQUEST[$key]);
292 if (isset($_POST[$key]) && ! is_string($_POST[$key])) {
293 unset($_POST[$key]);
296 if (isset($_COOKIE[$key]) && ! is_string($_COOKIE[$key])) {
297 unset($_COOKIE[$key]);
300 if (! isset($_GET[$key]) || is_string($_GET[$key])) {
301 continue;
304 unset($_GET[$key]);