Below is a differential between the unpatched vulnerable code and the patched update, for reference.
--- a/google-maps-easy/classes/errors.php
+++ b/google-maps-easy/classes/errors.php
@@ -7,9 +7,6 @@
private static $errors = [];
private static $haveErrors = false;
- public static $current = [];
- public static $displayed = false;
-
public static function push($error, $type = 'common')
{
if (!isset(self::$errors[$type])) {
@@ -39,41 +36,13 @@
}
reqGmp::setVar('sesErrors', $sesErrors, 'session');
}
+ /**
+ * Error texts are never taken from the request: the old "gmpErrors" parameter let any visitor put text (and shortcodes)
+ * into the page content and into admin notices, and nothing in the plugin used it.
+ * Kept empty for files of an older version that may still call it while the plugin is being updated.
+ */
public static function init()
{
- $gmpErrors = reqGmp::getVar('gmpErrors');
- if (!empty($gmpErrors)) {
- if (!is_array($gmpErrors)) {
- $gmpErrors = [$gmpErrors];
- }
- $gmpErrors = array_map('htmlspecialchars', array_map('stripslashes', array_map('trim', $gmpErrors)));
- if (!empty($gmpErrors)) {
- self::$current = $gmpErrors;
- if (is_admin()) {
- add_action('admin_notices', ['errorsGmp', 'showAdminErrors']);
- } else {
- add_filter('the_content', ['errorsGmp', 'appendErrorsContent'], 99999);
- }
- }
- }
- }
- public static function showAdminErrors()
- {
- if (self::$current) {
- $html = '';
- foreach (self::$current as $error) {
- $html .= '<div class="error"><p><strong style="font-size: 15px;">' . $error . '</strong></p></div>';
- }
- echo $html;
- }
- }
- public static function appendErrorsContent($content)
- {
- if (!self::$displayed && !empty(self::$current)) {
- $content = '<div class="toeErrorMsg">' . implode('<br />', self::$current) . '</div>' . $content;
- self::$displayed = true;
- }
- return $content;
}
public static function getSession()
{
--- a/google-maps-easy/classes/req.php
+++ b/google-maps-easy/classes/req.php
@@ -40,6 +40,10 @@
} else {
if (!is_array($value)) {
$value = wp_kses_post(sanitize_text_field($value));
+ // Roles that may manage maps without the right to publish any HTML, and visitors
+ if ('marker_link_src' === $key && utilsGmp::isScriptUrl($value) && (!function_exists('wp_get_current_user') || !current_user_can('unfiltered_html'))) {
+ $value = '';
+ }
} else {
self::sanitize_array($value);
}
--- a/google-maps-easy/classes/utils.php
+++ b/google-maps-easy/classes/utils.php
@@ -38,6 +38,22 @@
return serialize($data);
}
/**
+ * A link that runs a script, however it is written.
+ */
+ public static function isScriptUrl($url)
+ {
+ $url = preg_replace('/[x00-x20x7F\\]+|xC2xA0|xE2x80[x8B-x8FxA8xA9]/', '', html_entity_decode((string) $url, ENT_QUOTES, 'UTF-8'));
+ return (bool) preg_match('/^(javascript|vbscript|data):/i', $url);
+ }
+ /**
+ * A text that must stay a text: an invisible character after "[" keeps it from being a shortcode, now or later
+ * (after the marker is edited in wp-admin, too).
+ */
+ public static function disableShortcodes($text)
+ {
+ return is_string($text) ? preg_replace('/(?:[|�*91;|�*5b;|[|[)(?!s|xE2x80x8B)/i', "[xE2x80x8B", $text) : $text;
+ }
+ /**
* The plugin tables are utf8 (3 bytes per character), and wpdb refuses a whole row that has a 4-byte character
* (most emoji): the save failed without a word. Such characters are stored as HTML entities, as WordPress does
* for posts on utf8 tables. Columns that already are utf8mb4 keep the characters as they are.
--- a/google-maps-easy/config.php
+++ b/google-maps-easy/config.php
@@ -53,7 +53,7 @@
define('GMP_PLUGIN_INSTALLED', true);
-define('GMP_VERSION_PLUGIN', '1.18.0');
+define('GMP_VERSION_PLUGIN', '1.18.1');
define('GMP_USER', 'user');
define('GMP_CLASS_PREFIX', 'gmpc');
--- a/google-maps-easy/gmp.php
+++ b/google-maps-easy/gmp.php
@@ -4,7 +4,7 @@
* Plugin Name: Easy Google Maps
* Plugin URI: https://supsystic.com/plugins/google-maps-plugin/
* Description: Google Maps with unlimited markers, custom icons, marker categories, clustering and map themes. Gutenberg block, Elementor widget, no coding.
- * Version: 1.18.0
+ * Version: 1.18.1
* Author: supsystic.com
* Author URI: https://supsystic.com
* Text Domain: google-maps-easy
@@ -47,10 +47,9 @@
importClassGmp('installerDbUpdaterGmp');
importClassGmp('dateGmp');
/**
- * Check plugin version - maybe we need to update database, and check global errors in request
+ * Check plugin version - maybe we need to update database
*/
installerGmp::update();
-errorsGmp::init();
/**
* Start application
*/
--- a/google-maps-easy/modules/csv/controller.php
+++ b/google-maps-easy/modules/csv/controller.php
@@ -260,7 +260,7 @@
foreach ($fileArray as $i => $row) {
$map = [];
foreach ($keys as $j => $key) {
- $value = $this->_prepareValueToImport(isset($row[$j]) ? $row[$j] : '');
+ $value = $this->_prepareValueToImport(isset($row[$j]) ? $row[$j] : '', $key);
if ($value === '') {
$value = null;
}
@@ -304,7 +304,7 @@
foreach ($fileArray as $i => $row) {
$marker = [];
foreach ($keys as $j => $key) {
- $this->_setKeyVal($marker, $key, $this->_prepareValueToImport(isset($row[$j]) ? $row[$j] : ''));
+ $this->_setKeyVal($marker, $key, $this->_prepareValueToImport(isset($row[$j]) ? $row[$j] : '', $key));
}
if (isset($marker['id']) && !$markerModel->existsId($marker['id'])) {
unset($marker['id']);
@@ -343,7 +343,7 @@
$figures = [];
foreach ($keys as $j => $key) {
if (!empty($row[$j])) {
- $this->_setKeyVal($figures, $key, $this->_prepareValueToImport($row[$j]));
+ $this->_setKeyVal($figures, $key, $this->_prepareValueToImport($row[$j], $key));
}
}
if (isset($figures['id']) && !$figuresModel->existsId($figures['id'])) {
@@ -365,7 +365,7 @@
$heatmap = [];
foreach ($keys as $j => $key) {
if (!empty($row[$j])) {
- $this->_setKeyVal($heatmap, $key, $this->_prepareValueToImport($row[$j]));
+ $this->_setKeyVal($heatmap, $key, $this->_prepareValueToImport($row[$j], $key));
}
}
if (isset($heatmap['id']) && !$heatmapModel->existsId($heatmap['id'])) {
@@ -554,11 +554,19 @@
$sitePath = $this->_getSitePath();
return htmlspecialchars(str_replace($sitePath, '[GMP_SITE_PATH]', $val));
}
- private function _prepareValueToImport($val)
+ private function _prepareValueToImport($val, $key = '')
{
$sitePath = $this->_getSitePath();
// No addslashes(): values from the file are saved through $wpdb, "O'Brien" was saved as "O'Brien"
- return str_replace('[GMP_SITE_PATH]', $sitePath, htmlspecialchars_decode($val));
+ $val = str_replace('[GMP_SITE_PATH]', $sitePath, htmlspecialchars_decode($val));
+ // Without the unfiltered_html right a file goes through the same cleaning as the forms
+ if ($val !== '' && !current_user_can('unfiltered_html')) {
+ $keys = explode('.', (string) $key);
+ $cell = [trim(end($keys)) => $val];
+ reqGmp::sanitize_array($cell);
+ $val = reset($cell);
+ }
+ return $val;
}
private function _toYesNo($val)
{
--- a/google-maps-easy/modules/gmap/views/gmap.php
+++ b/google-maps-easy/modules/gmap/views/gmap.php
@@ -181,8 +181,8 @@
}
if (isset($params['display_as_img']) && $params['display_as_img']) {
$mapObj['params']['map_display_mode'] = 'popup';
- $mapObj['params']['img_width'] = isset($params['img_width']) ? $params['img_width'] : 175;
- $mapObj['params']['img_height'] = isset($params['img_height']) ? $params['img_height'] : 175;
+ $mapObj['params']['img_width'] = isset($params['img_width']) ? $this->_cleanShortcodeValue('img_width', $params['img_width']) : 175;
+ $mapObj['params']['img_height'] = isset($params['img_height']) ? $this->_cleanShortcodeValue('img_height', $params['img_height']) : 175;
}
if (isset($params['display_as_img']) && $params['display_as_img']) {
$mapObj['params']['map_display_mode'] = 'popup';
@@ -200,7 +200,7 @@
$mapObj['marker_groups'] = frameGmp::_()->getModule('marker_groups')->getModel()->getMarkerGroupsByIds($mapMarkersGroupsList);
}
$mapVarTemp = isset($mapObj['params']['markers_list_type']) && !empty($mapObj['params']['markers_list_type']) ? $mapObj['params']['markers_list_type'] : '';
- $mapObj['params']['markers_list_type'] = isset($params['markers_list_type']) ? $params['markers_list_type'] : $mapVarTemp;
+ $mapObj['params']['markers_list_type'] = isset($params['markers_list_type']) ? $this->_cleanShortcodeValue('markers_list_type', $params['markers_list_type']) : $mapVarTemp;
$mapObj = dispatcherGmp::applyFilters('mapDataRender', $mapObj);
// for Social Share integration
@@ -283,6 +283,22 @@
return $mapObj;
}
+ /**
+ * Attributes are set by whoever writes the post, also by users who may not publish HTML. They are numbers, words, colors
+ * and plain texts, and some of them get into HTML and styles as they are: no tags and quotes, and only the characters of
+ * a color, a size or a word where a style is made of them.
+ */
+ private function _cleanShortcodeValue($code, $value)
+ {
+ if (!is_string($value)) {
+ return $value;
+ }
+ $value = str_replace(['<', '>', '`', '"'], ['', '', '', '"'], wp_strip_all_tags($value));
+ if (preg_match('/color|size|width|height|units|align|type|mode/', $code)) {
+ $value = (string) preg_replace('/"|[^ws.,%#()+/-]/', '', $value);
+ }
+ return $value;
+ }
public function applyShortcodeHtmlParams($mapObj, $params)
{
// width="400px" / width="50%" (shortcode, block, widget): the unit was dropped and the map's own one used,
@@ -296,7 +312,7 @@
if (in_array($code, $this->_paramsCanNotBeEmpty) && empty($params[$code])) {
continue;
}
- $mapObj['html_options'][$code] = $params[$code];
+ $mapObj['html_options'][$code] = $this->_cleanShortcodeValue($code, $params[$code]);
}
}
return $mapObj;
@@ -339,11 +355,15 @@
}
}
foreach ($shortCodeMapParams as $code) {
+ // The list of the KML files comes only from the map: a text instead of the list broke the page
+ if ($code === 'kml_file_url' && isset($params[$code]) && !is_array($params[$code])) {
+ continue;
+ }
if (isset($params[$code])) {
if (in_array($code, $this->_paramsCanNotBeEmpty) && empty($params[$code])) {
continue;
}
- $mapObj['params'][$code] = $params[$code];
+ $mapObj['params'][$code] = $this->_cleanShortcodeValue($code, $params[$code]);
}
}
return $mapObj;
@@ -551,7 +571,8 @@
$coreGmapFile = $this->getModule()->getModDir() . 'js' . DS . 'core.gmap.js';
$coreMarkerPath = frameGmp::_()->getModule('marker')->getModPath() . 'js/core.marker.js';
$coreMarkerFile = frameGmp::_()->getModule('marker')->getModDir() . 'js' . DS . 'core.marker.js';
- frameGmp::_()->addScript('google_maps_api', $this->getApiUrl() . '&language=' . $params['language']);
+ // A language code only: the value may come from a shortcode and is a part of the URL
+ frameGmp::_()->addScript('google_maps_api', $this->getApiUrl() . '&language=' . preg_replace('/[^A-Za-z0-9_-]/', '', (string) $params['language']));
frameGmp::_()->addScript('core.gmap', $coreGmapPath, [], filemtime($coreGmapFile));
frameGmp::_()->addScript('core.marker', $coreMarkerPath, [], filemtime($coreMarkerFile));
if ((isset($params['marker_clasterer']) && $params['marker_clasterer'] != 'none') || $forAdminArea) {
--- a/google-maps-easy/modules/icons/mod.php
+++ b/google-maps-easy/modules/icons/mod.php
@@ -1,11 +1,270 @@
<?php
class iconsGmp extends moduleGmp
{
+ // Elements kept in an uploaded SVG: shapes, text, references inside the file, gradients and filters.
+ private $_svgElements = [
+ 'svg',
+ 'g',
+ 'path',
+ 'rect',
+ 'circle',
+ 'ellipse',
+ 'line',
+ 'polyline',
+ 'polygon',
+ 'text',
+ 'tspan',
+ 'tref',
+ 'textPath',
+ 'altGlyph',
+ 'glyphRef',
+ 'altGlyphDef',
+ 'altGlyphItem',
+ 'glyph',
+ 'missing-glyph',
+ 'desc',
+ 'title',
+ 'use',
+ 'symbol',
+ 'defs',
+ 'clipPath',
+ 'filter',
+ 'pattern',
+ 'mask',
+ 'marker',
+ 'image',
+ 'switch',
+ 'style',
+ 'view',
+ 'linearGradient',
+ 'radialGradient',
+ 'stop',
+ 'feBlend',
+ 'feColorMatrix',
+ 'feComponentTransfer',
+ 'feComposite',
+ 'feConvolveMatrix',
+ 'feDiffuseLighting',
+ 'feDisplacementMap',
+ 'feDistantLight',
+ 'feDropShadow',
+ 'feFlood',
+ 'feFuncA',
+ 'feFuncB',
+ 'feFuncG',
+ 'feFuncR',
+ 'feGaussianBlur',
+ 'feMerge',
+ 'feMergeNode',
+ 'feMorphology',
+ 'feOffset',
+ 'fePointLight',
+ 'feSpecularLighting',
+ 'feSpotLight',
+ 'feTile',
+ 'feTurbulence',
+ ];
+ // Attributes kept in an uploaded SVG (and aria-*). Links and url() are limited further in _cleanSvgAttributes().
+ private $_svgAttributes = [
+ 'id',
+ 'xml:lang',
+ 'xml:space',
+ 'height',
+ 'width',
+ 'x',
+ 'y',
+ 'z',
+ 'x1',
+ 'x2',
+ 'y1',
+ 'y2',
+ 'cx',
+ 'cy',
+ 'r',
+ 'rx',
+ 'ry',
+ 'fx',
+ 'fy',
+ 'fr',
+ 'dx',
+ 'dy',
+ 'd',
+ 'points',
+ 'rotate',
+ 'version',
+ 'baseProfile',
+ 'preserveAspectRatio',
+ 'viewBox',
+ 'transform',
+ 'transform-origin',
+ 'style',
+ 'class',
+ 'type',
+ 'media',
+ 'lang',
+ 'role',
+ 'focusable',
+ 'pathLength',
+ 'textLength',
+ 'lengthAdjust',
+ 'startOffset',
+ 'method',
+ 'spacing',
+ 'side',
+ 'href',
+ 'xlink:href',
+ 'xlink:title',
+ 'xlink:show',
+ 'xlink:actuate',
+ 'xlink:type',
+ 'xlink:role',
+ 'xlink:arcrole',
+ 'xlink:label',
+ 'xlink:from',
+ 'xlink:to',
+ 'requiredFeatures',
+ 'systemLanguage',
+ 'fill',
+ 'fill-opacity',
+ 'fill-rule',
+ 'stroke',
+ 'stroke-width',
+ 'stroke-linecap',
+ 'stroke-linejoin',
+ 'stroke-miterlimit',
+ 'stroke-dasharray',
+ 'stroke-dashoffset',
+ 'stroke-opacity',
+ 'opacity',
+ 'display',
+ 'visibility',
+ 'cursor',
+ 'paint-order',
+ 'isolation',
+ 'mix-blend-mode',
+ 'shape-rendering',
+ 'text-rendering',
+ 'image-rendering',
+ 'font',
+ 'font-family',
+ 'font-size',
+ 'font-size-adjust',
+ 'font-stretch',
+ 'font-style',
+ 'font-variant',
+ 'font-weight',
+ 'text-anchor',
+ 'pointer-events',
+ 'clip',
+ 'clip-path',
+ 'clip-rule',
+ 'clipPathUnits',
+ 'marker',
+ 'marker-start',
+ 'marker-mid',
+ 'marker-end',
+ 'marker-height',
+ 'marker-units',
+ 'marker-width',
+ 'markerHeight',
+ 'markerUnits',
+ 'markerWidth',
+ 'refX',
+ 'refY',
+ 'orient',
+ 'mask',
+ 'mask-type',
+ 'maskContentUnits',
+ 'maskUnits',
+ 'pattern',
+ 'patternContentUnits',
+ 'patternTransform',
+ 'patternUnits',
+ 'filter',
+ 'filterUnits',
+ 'filterRes',
+ 'primitiveUnits',
+ 'gradientTransform',
+ 'gradientUnits',
+ 'spreadMethod',
+ 'stop-color',
+ 'stop-opacity',
+ 'offset',
+ 'result',
+ 'in',
+ 'in2',
+ 'mode',
+ 'values',
+ 'operator',
+ 'k1',
+ 'k2',
+ 'k3',
+ 'k4',
+ 'order',
+ 'kernelMatrix',
+ 'kernelUnitLength',
+ 'divisor',
+ 'bias',
+ 'targetX',
+ 'targetY',
+ 'edgeMode',
+ 'preserveAlpha',
+ 'surfaceScale',
+ 'diffuseConstant',
+ 'specularConstant',
+ 'specularExponent',
+ 'limitingConeAngle',
+ 'pointsAtX',
+ 'pointsAtY',
+ 'pointsAtZ',
+ 'azimuth',
+ 'elevation',
+ 'scale',
+ 'xChannelSelector',
+ 'yChannelSelector',
+ 'tableValues',
+ 'slope',
+ 'intercept',
+ 'amplitude',
+ 'exponent',
+ 'stdDeviation',
+ 'radius',
+ 'baseFrequency',
+ 'numOctaves',
+ 'seed',
+ 'stitchTiles',
+ 'color',
+ 'direction',
+ 'overflow',
+ 'enable-background',
+ 'writing-mode',
+ 'word-spacing',
+ 'glyph-orientation-horizontal',
+ 'glyph-orientation-vertical',
+ 'kerning',
+ 'letter-spacing',
+ 'alignment-baseline',
+ 'baseline-shift',
+ 'dominant-baseline',
+ 'text-decoration',
+ 'unicode-bidi',
+ 'color-interpolation',
+ 'color-interpolation-filters',
+ 'color-profile',
+ 'color-rendering',
+ 'flood-color',
+ 'flood-opacity',
+ 'lighting-color',
+ 'vector-effect',
+ ];
public function init()
{
parent::init();
add_filter('upload_mimes', [$this, 'addMimeTypes']);
add_filter('wp_handle_upload_prefilter', [$this, 'simple_svg_sanitize_file']);
+ add_filter('wp_handle_sideload_prefilter', [$this, 'sanitizeSideloadedSvg']);
+ // The stored file, whatever way it came: wp_upload_bits() (XML-RPC) has no prefilter
+ add_filter('wp_handle_upload', [$this, 'sanitizeStoredSvg'], 1, 2);
//$this->getModel()->checkDefIcons();
/*if(frameGmp::_()->isAdminPlugPage()){
$gmpExistsIcons = $this->getModel()->getIcons();
@@ -21,180 +280,225 @@
// Sanitize SVG files upon upload.
public function simple_svg_sanitize_file($file)
{
- if ($file['type'] === 'image/svg+xml') {
- $svg = file_get_contents($file['tmp_name']);
- $clean_svg = $this->simple_svg_sanitize($svg);
-
- if ($clean_svg) {
- file_put_contents($file['tmp_name'], $clean_svg);
- } else {
- $file['error'] = 'Unable to sanitize SVG file.';
- }
+ // A failed upload has no file: WordPress reports its error itself
+ if (!is_array($file) || empty($file['tmp_name']) || !empty($file['error'])) {
+ return $file;
+ }
+ $name = isset($file['name']) ? $file['name'] : '';
+ $type = isset($file['type']) ? $file['type'] : '';
+ if ($this->_isSvg($name, $type) && !$this->_sanitizeSvgOnDisk($file['tmp_name'])) {
+ $file['error'] = 'Unable to sanitize SVG file.';
}
return $file;
}
- // Basic SVG sanitization function.
+ // Files that come not as a form upload: the body of a REST request, remote images.
+ public function sanitizeSideloadedSvg($file)
+ {
+ return $this->_isTrustedSideload() ? $file : $this->simple_svg_sanitize_file($file);
+ }
+ // The last check: the file that has been stored in the uploads folder.
+ public function sanitizeStoredSvg($upload, $context = 'upload')
+ {
+ if (!is_array($upload) || empty($upload['file']) || !empty($upload['error'])) {
+ return $upload;
+ }
+ if (!$this->_isSvg($upload['file'], isset($upload['type']) ? $upload['type'] : '') || !is_file($upload['file'])) {
+ return $upload;
+ }
+ if ('sideload' === $context && $this->_isTrustedSideload()) {
+ return $upload;
+ }
+ if (!$this->_sanitizeSvgOnDisk($upload['file'])) {
+ wp_delete_file($upload['file']);
+ return ['error' => 'Unable to sanitize SVG file.'];
+ }
+ return $upload;
+ }
+ // Importers: users who may publish any HTML, background jobs and WP-CLI work with their files as before.
+ private function _isTrustedSideload()
+ {
+ return current_user_can('unfiltered_html') || wp_doing_cron() || (defined('WP_CLI') && WP_CLI);
+ }
+ // The type comes from the client, so the extension decides; the type only adds files.
+ private function _isSvg($name, $type)
+ {
+ return 'svg' === strtolower(trim(pathinfo((string) $name, PATHINFO_EXTENSION))) || 0 === stripos((string) $type, 'image/svg+xml');
+ }
+ private function _sanitizeSvgOnDisk($path)
+ {
+ $svg = @file_get_contents($path);
+ if (false === $svg) {
+ return false;
+ }
+ // Importers reserve a name with an empty file first
+ if ('' === trim($svg)) {
+ return true;
+ }
+ $isGzip = 0 === strpos($svg, "x1fx8b");
+ if ($isGzip) {
+ $svg = function_exists('gzdecode') ? @gzdecode($svg, 10485760) : false;
+ if (empty($svg)) {
+ return false;
+ }
+ }
+ $clean = $this->simple_svg_sanitize($svg);
+ if (!$clean) {
+ return false;
+ }
+ return $clean === $svg || false !== file_put_contents($path, $isGzip ? gzencode($clean) : $clean);
+ }
+ /**
+ * SVG sanitization function: only the listed elements and attributes are left, links and url() lead only inside the
+ * file, no DOCTYPE, processing instructions and comments.
+ * @param string $svg
+ * @return string|bool False if it is not an SVG document
+ */
public function simple_svg_sanitize($svg)
{
- // List of allowed elements.
- $allowed_elements = [
- 'svg',
- 'g',
- 'path',
- 'rect',
- 'circle',
- 'ellipse',
- 'line',
- 'polyline',
- 'polygon',
- 'text',
- 'tspan',
- 'tref',
- 'textPath',
- 'altGlyph',
- 'glyphRef',
- 'altGlyphDef',
- 'altGlyphItem',
- 'glyph',
- 'missing-glyph',
- 'desc',
- 'title',
- 'use',
- 'symbol',
- 'defs',
- 'clipPath',
- 'filter',
- 'pattern',
- 'mask',
- 'image',
- 'switch',
- 'style',
- 'view',
- ];
-
- // List of allowed attributes.
- $allowed_attributes = [
- 'id',
- 'xml:base',
- 'xml:lang',
- 'xml:space',
- 'height',
- 'width',
- 'x',
- 'y',
- 'version',
- 'preserveAspectRatio',
- 'viewBox',
- 'transform',
- 'style',
- 'class',
- 'd',
- 'pathLength',
- 'xlink:href',
- 'xlink:title',
- 'xlink:show',
- 'xlink:actuate',
- 'xlink:type',
- 'xlink:role',
- 'xlink:arcrole',
- 'xlink:label',
- 'xlink:from',
- 'xlink:to',
- 'xlink:title',
- 'fill',
- 'stroke',
- 'stroke-width',
- 'stroke-linecap',
- 'stroke-linejoin',
- 'stroke-miterlimit',
- 'stroke-dasharray',
- 'stroke-dashoffset',
- 'opacity',
- 'fill-opacity',
- 'stroke-opacity',
- 'font-family',
- 'font-size',
- 'font-weight',
- 'font-style',
- 'text-anchor',
- 'pointer-events',
- 'clip-rule',
- 'fill-rule',
- 'marker',
- 'marker-start',
- 'marker-mid',
- 'marker-end',
- 'mask',
- 'pattern',
- 'filter',
- 'style',
- 'clip-path',
- 'filter',
- 'stop-color',
- 'stop-opacity',
- 'offset',
- 'result',
- 'color',
- 'direction',
- 'overflow',
- 'enable-background',
- 'writing-mode',
- 'word-spacing',
- 'glyph-orientation-horizontal',
- 'glyph-orientation-vertical',
- 'kerning',
- 'letter-spacing',
- 'alignment-baseline',
- 'baseline-shift',
- 'dominant-baseline',
- 'text-decoration',
- 'unicode-bidi',
- 'color-interpolation',
- 'color-interpolation-filters',
- 'color-profile',
- 'color-rendering',
- 'flood-color',
- 'flood-opacity',
- 'lighting-color',
- 'marker-height',
- 'marker-units',
- 'marker-width',
- 'maskContentUnits',
- 'maskUnits',
- 'patternContentUnits',
- 'patternTransform',
- 'patternUnits',
- 'spreadMethod',
- 'stop-color',
- 'stop-opacity',
- 'transform',
- 'vector-effect',
- 'viewBox',
- 'points',
- ];
+ $dom = $this->_loadSvg($svg);
+ if ($dom && $dom->doctype) {
+ $dom = $this->_loadSvg($this->_replaceSvgEntities($dom));
+ }
+ $root = $dom && !$dom->doctype ? $dom->documentElement : null;
+ if (!$root || 'svg' !== $root->localName || !$this->_isSvgNamespace($root)) {
+ return false;
+ }
+ $this->_cleanSvgAttributes($root);
+ $this->_cleanSvgChildren($root);
- // Load the SVG into a DOMDocument.
+ // A new document: without the DOCTYPE and everything around the root
+ $clean = new DOMDocument('1.0', 'UTF-8');
+ $clean->appendChild($clean->importNode($root, true));
+ return $clean->saveXML();
+ }
+ // Load the SVG into a DOMDocument.
+ private function _loadSvg($svg)
+ {
+ $svg = ltrim((string) $svg, " trn");
+ if ('' === $svg || !class_exists('DOMDocument')) {
+ return false;
+ }
$dom = new DOMDocument();
- libxml_use_internal_errors(true);
+ $errorsMode = libxml_use_internal_errors(true);
$dom->resolveExternals = false;
$dom->substituteEntities = false;
- $dom->loadXML($svg, LIBXML_NONET | LIBXML_NOCDATA | LIBXML_NOWARNING | LIBXML_NOERROR);
+ $loaded = $dom->loadXML($svg, LIBXML_NONET | LIBXML_NOCDATA | LIBXML_NOWARNING | LIBXML_NOERROR);
libxml_clear_errors();
-
- $elements = $dom->getElementsByTagName('*');
- for ($i = $elements->length - 1; $i >= 0; $i--) {
- $element = $elements->item($i);
- if (!in_array($element->nodeName, $allowed_elements)) {
- $element->parentNode->removeChild($element);
- } else {
- foreach (iterator_to_array($element->attributes) as $attribute) {
- if (!in_array($attribute->nodeName, $allowed_attributes)) {
- $element->removeAttribute($attribute->nodeName);
+ libxml_use_internal_errors($errorsMode);
+ return $loaded ? $dom : false;
+ }
+ // The document without its DOCTYPE: its short text entities (Adobe Illustrator keeps the namespaces there) become plain text.
+ private function _replaceSvgEntities($dom)
+ {
+ $entities = ['amp' => '&', 'lt' => '<', 'gt' => '>', 'quot' => '"', 'apos' => '''];
+ preg_match_all('/<!ENTITYs+([a-z_:][w:.-]*)s+(["'])(.{0,255}?)2s*>/is', (string) $dom->doctype->internalSubset, $found, PREG_SET_ORDER);
+ foreach ($found as $entity) {
+ $entities += [$entity[1] => htmlspecialchars($entity[3], ENT_QUOTES, 'UTF-8')];
+ }
+ return preg_replace_callback(
+ '/&([a-z_:][w:.-]*);/i',
+ function ($match) use ($entities) {
+ return isset($entities[$match[1]]) ? $entities[$match[1]] : '';
+ },
+ (string) $dom->saveXML($dom->documentElement)
+ );
+ }
+ private function _isSvgNamespace($element)
+ {
+ return empty($element->namespaceURI) || 'http://www.w3.org/2000/svg' === $element->namespaceURI;
+ }
+ private function _cleanSvgChildren($parent)
+ {
+ $child = $parent->firstChild;
+ while ($child) {
+ $next = $child->nextSibling;
+ switch ($child->nodeType) {
+ case XML_ELEMENT_NODE:
+ if (!in_array($child->localName, $this->_svgElements, true) || !$this->_isSvgNamespace($child)) {
+ $parent->removeChild($child);
+ break;
+ }
+ $this->_cleanSvgAttributes($child);
+ if (in_array($child->localName, ['style', 'title', 'desc'], true)) {
+ $text = $child->textContent;
+ $this->_setSvgText($child, 'style' === $child->localName ? $this->_cleanSvgCss($text) : $text);
+ } else {
+ $this->_cleanSvgChildren($child);
}
+ break;
+ case XML_TEXT_NODE:
+ case XML_CDATA_SECTION_NODE:
+ break;
+ default:
+ $parent->removeChild($child);
+ }
+ $child = $next;
+ }
+ }
+ private function _cleanSvgAttributes($element)
+ {
+ // Not by name: attributes with the same name and another prefix must all be here
+ foreach (iterator_to_array($element->attributes, false) as $attribute) {
+ $name = $attribute->nodeName;
+ if (!in_array($name, $this->_svgAttributes, true) && !preg_match('/^aria-[a-z]+$/', $name)) {
+ $element->removeAttributeNode($attribute);
+ continue;
+ }
+ $value = $attribute->value;
+ if ('href' === $name || 'xlink:href' === $name) {
+ $isImage = 'image' === $element->localName && preg_match('#^s*data:image/(png|jpe?g|gif|webp|avif|bmp|x-icon)s*[;,]#i', $value);
+ if (!$isImage && '#' !== substr(ltrim($value), 0, 1)) {
+ $element->removeAttributeNode($attribute);
+ continue;
}
+ } elseif ('style' === $name || preg_match('/urls*(|\\/i', $value)) {
+ $value = $this->_cleanSvgCss($value);
+ }
+ if ($value !== $attribute->value) {
+ $this->_setSvgText($attribute, $value);
}
}
-
- return $dom->saveXML();
+ }
+ private function _setSvgText($node, $text)
+ {
+ while ($node->firstChild) {
+ $node->removeChild($node->firstChild);
+ }
+ if ('' !== $text) {
+ $node->appendChild($node->ownerDocument->createTextNode($text));
+ }
+ }
+ // Styles stay, but nothing is loaded from outside the file.
+ private function _cleanSvgCss($css)
+ {
+ $css = preg_replace('#/*.*?(*/|$)#s', ' ', (string) $css);
+ $unsafe = '/@import|urls*(|image-sets*(|expressions*(|javascripts*:|behaviou?rs*:|-moz-binding/i';
+ // The same words written with CSS escapes
+ if (false !== strpos($css, '\') && preg_match_all($unsafe, $this->_decodeCssEscapes($css)) !== preg_match_all($unsafe, $css)) {
+ return '';
+ }
+ $css = preg_replace('/@import[^;]*;?/i', '', $css);
+ if (preg_match('/@import|image-sets*(|expressions*(|javascripts*:|behaviou?rs*:|-moz-binding/i', $css)) {
+ return '';
+ }
+ return (string) preg_replace_callback('/urls*(s*("[^"]*"|'[^']*'|[^)"']*)s*)?/i', [$this, '_cleanSvgCssUrl'], $css);
+ }
+ private function _cleanSvgCssUrl($match)
+ {
+ $url = trim($match[1], " trnf"'");
+ $isData = preg_match('#^data:(image/(png|jpe?g|gif|webp|avif|bmp|x-icon)|font/[w.+-]+|application/(x-)?font[w.+-]*|application/vnd.ms-fontobject|application/octet-stream)s*[;,]#i', $url);
+ return '#' === substr($url, 0, 1) || $isData ? $match[0] : 'none';
+ }
+ private function _decodeCssEscapes($css)
+ {
+ $css = preg_replace_callback(
+ '/\\([0-9a-f]{1,6})s?/i',
+ function ($match) {
+ $code = hexdec($match[1]);
+ return $code > 31 && $code < 127 ? chr($code) : ' ';
+ },
+ $css
+ );
+ return preg_replace('/\\(rn|.)/s', '$1', $css);
}
}
--- a/google-maps-easy/modules/icons/models/icons.php
+++ b/google-maps-easy/modules/icons/models/icons.php
@@ -156,15 +156,18 @@
$this->pushError(__('File not found', GMP_LANG_CODE));
return false;
}
- $imageinfo = getimagesize($url, $imgProp);
- if (empty($imageinfo)) {
+ // Only an image of a public web site: no local files, stream wrappers and addresses of the own network
+ $response = preg_match('#^https?://#i', $url) ? wp_safe_remote_get($url, ['timeout' => 15, 'limit_response_size' => 5 * MB_IN_BYTES]) : null;
+ $body = $response && !is_wp_error($response) && (int) wp_remote_retrieve_response_code($response) === 200 ? wp_remote_retrieve_body($response) : '';
+ $imageinfo = $body !== '' ? @getimagesizefromstring($body) : false;
+ if (empty($imageinfo) || !in_array($imageinfo['mime'], ['image/png', 'image/jpeg', 'image/gif', 'image/webp', 'image/bmp', 'image/x-ms-bmp', 'image/vnd.microsoft.icon'], true)) {
$this->pushError(__('Cannot get image', GMP_LANG_CODE));
return false;
}
- $fileExt = str_replace('image/', '', $imageinfo['mime']);
+ $fileExt = preg_replace('/[^a-z0-9]/', '', str_replace('image/', '', $imageinfo['mime']));
$filename = utilsGmp::getRandStr(8) . '.' . $fileExt;
$dest = $this->getIconsFullPath() . $filename;
- file_put_contents($dest, fopen($url, 'r'));
+ file_put_contents($dest, $body);
$newIconId = frameGmp::_()
->getTable('icons')
->store(['path' => $filename], 'insert');
--- a/google-maps-easy/modules/marker/controller.php
+++ b/google-maps-easy/modules/marker/controller.php
@@ -188,7 +188,7 @@
// Marker Icon Image
$path = !empty($data[$i]['icon_data']['path']) ? $data[$i]['icon_data']['path'] : '';
- $icon = '<div class="egm-marker-icon"><img src="' . $path . '" /></div>';
+ $icon = '<div class="egm-marker-icon"><img src="' . esc_attr($path) . '" /></div>';
$data[$i]['icon_img'] = preg_replace('/ss+/', ' ', trim($icon));
// Marker Coordinates
--- a/google-maps-easy/modules/marker/models/marker.php
+++ b/google-maps-easy/modules/marker/models/marker.php
@@ -31,6 +31,18 @@
$update = (bool) $id;
if (!empty($marker['title'])) {
$marker = apply_filters('gmp_before_marker_save', $marker);
+ // Front-end marker form: the texts of visitors are never shortcodes (users who can write posts can use shortcodes there anyway)
+ if ('frontend_actions' === frameGmp::_()->getMod() && !current_user_can('edit_posts')) {
+ foreach (['title', 'description', 'address'] as $field) {
+ if (isset($marker[$field])) {
+ $marker[$field] = utilsGmp::disableShortcodes($marker[$field]);
+ }
+ }
+ }
+ // and their titles get into attributes, too (the markers list of older PRO versions): typographic quotes instead of straight ones
+ if ('frontend_actions' === frameGmp::_()->getMod() && !current_user_can('unfiltered_html')) {
+ $marker['title'] = str_replace(['\"', '"'], "xE2x80x9D", $marker['title']);
+ }
if (isset($marker['description'])) {
//Replace site url in markers descriptions backend. Fixed site migration issue.
$marker['description'] = str_replace(GMP_SITE_URL, 'GMP_SITE_URL', $marker['description']);