10b3fd2d3SAndreas Gohr<?php 2*dad993c5SAndreas Gohr 30b3fd2d3SAndreas Gohr/** 40b3fd2d3SAndreas Gohr * This file is part of the FreeDSx LDAP package. 50b3fd2d3SAndreas Gohr * 60b3fd2d3SAndreas Gohr * (c) Chad Sikorra <Chad.Sikorra@gmail.com> 70b3fd2d3SAndreas Gohr * 80b3fd2d3SAndreas Gohr * For the full copyright and license information, please view the LICENSE 90b3fd2d3SAndreas Gohr * file that was distributed with this source code. 100b3fd2d3SAndreas Gohr */ 110b3fd2d3SAndreas Gohr 120b3fd2d3SAndreas Gohrnamespace FreeDSx\Ldap\Entry; 130b3fd2d3SAndreas Gohr 14*dad993c5SAndreas Gohruse function bin2hex; 15*dad993c5SAndreas Gohruse function implode; 16*dad993c5SAndreas Gohruse function preg_match; 17*dad993c5SAndreas Gohruse function preg_replace_callback; 18*dad993c5SAndreas Gohruse function str_split; 19*dad993c5SAndreas Gohr 200b3fd2d3SAndreas Gohr/** 210b3fd2d3SAndreas Gohr * Some common methods around escaping attribute values and RDN values. 220b3fd2d3SAndreas Gohr * 230b3fd2d3SAndreas Gohr * @author Chad Sikorra <Chad.Sikorra@gmail.com> 240b3fd2d3SAndreas Gohr */ 250b3fd2d3SAndreas Gohrtrait EscapeTrait 260b3fd2d3SAndreas Gohr{ 270b3fd2d3SAndreas Gohr /** 280b3fd2d3SAndreas Gohr * Escape all characters in a value. 290b3fd2d3SAndreas Gohr * 300b3fd2d3SAndreas Gohr * @param string $value 310b3fd2d3SAndreas Gohr * @return string 320b3fd2d3SAndreas Gohr */ 330b3fd2d3SAndreas Gohr public static function escapeAll(string $value): string 340b3fd2d3SAndreas Gohr { 350b3fd2d3SAndreas Gohr if (self::shouldNotEscape($value)) { 360b3fd2d3SAndreas Gohr return $value; 370b3fd2d3SAndreas Gohr } 380b3fd2d3SAndreas Gohr 39*dad993c5SAndreas Gohr return '\\' . implode('\\', str_split(bin2hex($value), 2)); 400b3fd2d3SAndreas Gohr } 410b3fd2d3SAndreas Gohr 420b3fd2d3SAndreas Gohr /** 430b3fd2d3SAndreas Gohr * Replace non-printable ASCII with escaped hex. 440b3fd2d3SAndreas Gohr */ 450b3fd2d3SAndreas Gohr protected static function escapeNonPrintable(string $value): string 460b3fd2d3SAndreas Gohr { 47*dad993c5SAndreas Gohr return (string) preg_replace_callback('/([\x00-\x1F\x7F])/', function ($matches) { 48*dad993c5SAndreas Gohr return '\\' . bin2hex($matches[1]); 490b3fd2d3SAndreas Gohr }, $value); 500b3fd2d3SAndreas Gohr } 510b3fd2d3SAndreas Gohr 520b3fd2d3SAndreas Gohr protected static function shouldNotEscape(string $value): bool 530b3fd2d3SAndreas Gohr { 54*dad993c5SAndreas Gohr return (preg_match('/^(\\\\[0-9A-Fa-f]{2})+$/', $value) === 1 || $value === ''); 550b3fd2d3SAndreas Gohr } 560b3fd2d3SAndreas Gohr} 57