Translated using Weblate (Portuguese)
[phpmyadmin.git] / src / Sanitize.php
blob06c8f77710ea79264bffc7b5c71388b5e9084b8c
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 in_array;
17 use function is_string;
18 use function json_encode;
19 use function preg_match;
20 use function preg_replace;
21 use function preg_replace_callback;
22 use function str_starts_with;
23 use function strtolower;
24 use function strtr;
26 use const JSON_HEX_TAG;
28 /**
29 * This class includes various sanitization methods that can be called statically
31 class Sanitize
33 /**
34 * Checks whether given link is valid
36 * @param string $url URL to check
37 * @param bool $http Whether to allow http links
38 * @param bool $other Whether to allow ftp and mailto links
40 public static function checkLink(string $url, bool $http = false, bool $other = false): bool
42 $url = strtolower($url);
43 $validStarts = ['https://', 'index.php?route=/url&url=https%3a%2f%2f', './docs/html/', './index.php?'];
44 $isSetup = self::isSetup();
45 // Adjust path to setup script location
46 if ($isSetup) {
47 foreach ($validStarts as $key => $value) {
48 if (! str_starts_with($value, './')) {
49 continue;
52 $validStarts[$key] = '.' . $value;
56 if ($other) {
57 $validStarts[] = 'mailto:';
58 $validStarts[] = 'ftp://';
61 if ($http) {
62 $validStarts[] = 'http://';
65 if ($isSetup) {
66 $validStarts[] = '?page=form&';
67 $validStarts[] = '?page=servers&';
70 foreach ($validStarts as $val) {
71 if (str_starts_with($url, $val)) {
72 return true;
76 return false;
79 /**
80 * Check if we are currently on a setup folder page
82 public static function isSetup(): bool
84 return Config::getInstance()->get('is_setup');
87 /**
88 * Callback function for replacing [a@link@target] links in bb code.
90 * @param string[] $found Array of preg matches
92 * @return string Replaced string
94 private static function replaceBBLink(array $found): string
96 /* Check for valid link */
97 if (! self::checkLink($found[1])) {
98 return $found[0];
101 /* a-z and _ allowed in target */
102 if (! empty($found[3]) && preg_match('/[^a-z_]+/i', $found[3])) {
103 return $found[0];
106 /* Construct target */
107 $target = '';
108 if (! empty($found[3])) {
109 $target = ' target="' . $found[3] . '"';
110 if ($found[3] === '_blank') {
111 $target .= ' rel="noopener noreferrer"';
115 /* Construct url */
116 if (str_starts_with($found[1], 'http')) {
117 $url = Core::linkURL($found[1]);
118 } else {
119 $url = $found[1];
122 return '<a href="' . $url . '"' . $target . '>';
126 * Callback function for replacing [doc@anchor] links in bb code.
128 * @param string[] $found Array of preg matches
130 private static function replaceDocLink(array $found): string
132 if (count($found) >= 4) {
133 /* doc@page@anchor pattern */
134 $page = $found[1];
135 $anchor = $found[3];
136 } else {
137 /* doc@anchor pattern */
138 $anchor = $found[1];
139 if (str_starts_with($anchor, 'faq')) {
140 $page = 'faq';
141 } elseif (str_starts_with($anchor, 'cfg')) {
142 $page = 'config';
143 } else {
144 /* Guess */
145 $page = 'setup';
149 $link = MySQLDocumentation::getDocumentationLink($page, $anchor, self::isSetup() ? '../' : './');
151 return '<a href="' . $link . '" target="documentation">';
155 * Sanitizes $message, taking into account our special codes for formatting.
157 * @param string $message the message
158 * @param bool $safe whether string is safe (can keep < and > chars)
160 public static function convertBBCode(string $message, bool $safe = false): string
162 if (! $safe) {
163 $message = strtr($message, ['<' => '&lt;', '>' => '&gt;', '"' => '&quot;', "'" => '&#039;']);
167 * Interpret bb code
169 * @var array<string, string> $replacePairs
171 static $replacePairs = [];
172 if ($replacePairs === []) {
173 $replacePairs = [
174 '[em]' => '<em>',
175 '[/em]' => '</em>',
176 '[strong]' => '<strong>',
177 '[/strong]' => '</strong>',
178 '[code]' => '<code>',
179 '[/code]' => '</code>',
180 '[kbd]' => '<kbd>',
181 '[/kbd]' => '</kbd>',
182 '[br]' => '<br>',
183 '[/a]' => '</a>',
184 '[/doc]' => '</a>',
185 '[sup]' => '<sup>',
186 '[/sup]' => '</sup>',
187 // used in libraries/Util.php
188 '[dochelpicon]' => Html\Generator::getImage('b_help', __('Documentation')),
192 $message = strtr($message, $replacePairs);
194 /* Match links in bb code ([a@url@target], where @target is options) */
195 $pattern = '/\[a@([^]"@]*)(@([^]"]*))?\]/';
197 /* Find and replace all links */
198 $message = (string) preg_replace_callback(
199 $pattern,
200 static fn (array $match): string => self::replaceBBLink($match),
201 $message,
204 /* Replace documentation links */
205 return (string) preg_replace_callback(
206 '/\[doc@([a-zA-Z0-9_-]+)(@([a-zA-Z0-9_-]*))?\]/',
207 /** @param string[] $match */
208 static fn (array $match): string => self::replaceDocLink($match),
209 $message,
214 * Sanitize a filename by removing anything besides legit characters
216 * Intended usecase:
217 * When using a filename in a Content-Disposition header
218 * the value should not contain ; or "
220 * When exporting, avoiding generation of an unexpected double-extension file
222 * @param string $filename The filename
223 * @param bool $replaceDots Whether to also replace dots
225 * @return string the sanitized filename
227 public static function sanitizeFilename(string $filename, bool $replaceDots = false): string
229 $pattern = '/[^A-Za-z0-9_';
230 // if we don't have to replace dots
231 if (! $replaceDots) {
232 // then add the dot to the list of legit characters
233 $pattern .= '.';
236 $pattern .= '-]/';
238 return preg_replace($pattern, '_', $filename);
242 * Formats an javascript assignment with proper escaping of a value
243 * and support for assigning array of strings.
245 * @param string $key Name of value to set
246 * @param mixed $value Value to set, can be either string or array of strings
248 * @return string Javascript code.
250 public static function getJsValue(string $key, mixed $value): string
252 return $key . ' = ' . json_encode($value, JSON_HEX_TAG) . ";\n";
256 * Removes all variables from request except allowed ones.
258 * @param string[] $allowList list of variables to allow
260 public static function removeRequestVars(array $allowList): void
262 // do not check only $_REQUEST because it could have been overwritten
263 // and use type casting because the variables could have become
264 // strings
265 $keys = array_keys(
266 array_merge($_REQUEST, $_GET, $_POST, $_COOKIE),
269 foreach ($keys as $key) {
270 if (! in_array($key, $allowList)) {
271 unset($_REQUEST[$key], $_GET[$key], $_POST[$key]);
272 continue;
275 // allowed stuff could be compromised so escape it
276 // we require it to be a string
277 if (isset($_REQUEST[$key]) && ! is_string($_REQUEST[$key])) {
278 unset($_REQUEST[$key]);
281 if (isset($_POST[$key]) && ! is_string($_POST[$key])) {
282 unset($_POST[$key]);
285 if (isset($_COOKIE[$key]) && ! is_string($_COOKIE[$key])) {
286 unset($_COOKIE[$key]);
289 if (! isset($_GET[$key]) || is_string($_GET[$key])) {
290 continue;
293 unset($_GET[$key]);