3 * Zend Framework (http://framework.zend.com/)
5 * @link http://github.com/zendframework/zf2 for the canonical source repository
6 * @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
7 * @license http://framework.zend.com/license/new-bsd New BSD License
15 * Zend\Ldap\Dn provides an API for DN manipulation
17 class Dn
implements ArrayAccess
19 const ATTR_CASEFOLD_NONE
= 'none';
20 const ATTR_CASEFOLD_UPPER
= 'upper';
21 const ATTR_CASEFOLD_LOWER
= 'lower';
24 * The default case fold to use
28 protected static $defaultCaseFold = self
::ATTR_CASEFOLD_NONE
;
31 * The case fold used for this instance
45 * Creates a DN from an array or a string
47 * @param string|array $dn
48 * @param string|null $caseFold
50 * @throws Exception\LdapException
52 public static function factory($dn, $caseFold = null)
55 return static::fromArray($dn, $caseFold);
56 } elseif (is_string($dn)) {
57 return static::fromString($dn, $caseFold);
59 throw new Exception\
LdapException(null, 'Invalid argument type for $dn');
63 * Creates a DN from a string
66 * @param string|null $caseFold
68 * @throws Exception\LdapException
70 public static function fromString($dn, $caseFold = null)
76 $dnArray = static::explodeDn((string) $dn);
78 return new static($dnArray, $caseFold);
82 * Creates a DN from an array
85 * @param string|null $caseFold
87 * @throws Exception\LdapException
89 public static function fromArray(array $dn, $caseFold = null)
91 return new static($dn, $caseFold);
98 * @param string|null $caseFold
100 protected function __construct(array $dn, $caseFold)
103 $this->setCaseFold($caseFold);
107 * Gets the RDN of the current DN
109 * @param string $caseFold
111 * @throws Exception\LdapException if DN has no RDN (empty array)
113 public function getRdn($caseFold = null)
115 $caseFold = static::sanitizeCaseFold($caseFold, $this->caseFold
);
116 return static::caseFoldRdn($this->get(0, 1, $caseFold), null);
120 * Gets the RDN of the current DN as a string
122 * @param string $caseFold
124 * @throws Exception\LdapException if DN has no RDN (empty array)
126 public function getRdnString($caseFold = null)
128 $caseFold = static::sanitizeCaseFold($caseFold, $this->caseFold
);
129 return static::implodeRdn($this->getRdn(), $caseFold);
133 * Get the parent DN $levelUp levels up the tree
135 * @param int $levelUp
136 * @throws Exception\LdapException
139 public function getParentDn($levelUp = 1)
141 $levelUp = (int) $levelUp;
142 if ($levelUp < 1 ||
$levelUp >= count($this->dn
)) {
143 throw new Exception\
LdapException(null, 'Cannot retrieve parent DN with given $levelUp');
145 $newDn = array_slice($this->dn
, $levelUp);
146 return new static($newDn, $this->caseFold
);
154 * @param string $caseFold
156 * @throws Exception\LdapException if index is illegal
158 public function get($index, $length = 1, $caseFold = null)
160 $caseFold = static::sanitizeCaseFold($caseFold, $this->caseFold
);
161 $this->assertIndex($index);
162 $length = (int) $length;
167 return static::caseFoldRdn($this->dn
[$index], $caseFold);
169 return static::caseFoldDn(array_slice($this->dn
, $index, $length, false), $caseFold);
176 * @param array $value
177 * @return Dn Provides a fluent interface
178 * @throws Exception\LdapException if index is illegal
180 public function set($index, array $value)
182 $this->assertIndex($index);
183 static::assertRdn($value);
184 $this->dn
[$index] = $value;
193 * @return Dn Provides a fluent interface
194 * @throws Exception\LdapException if index is illegal
196 public function remove($index, $length = 1)
198 $this->assertIndex($index);
199 $length = (int) $length;
203 array_splice($this->dn
, $index, $length, null);
210 * @param array $value
211 * @return Dn Provides a fluent interface
213 public function append(array $value)
215 static::assertRdn($value);
216 $this->dn
[] = $value;
223 * @param array $value
224 * @return Dn Provides a fluent interface
226 public function prepend(array $value)
228 static::assertRdn($value);
229 array_unshift($this->dn
, $value);
237 * @param array $value
238 * @return Dn Provides a fluent interface
239 * @throws Exception\LdapException if index is illegal
241 public function insert($index, array $value)
243 $this->assertIndex($index);
244 static::assertRdn($value);
245 $first = array_slice($this->dn
, 0, $index +
1);
246 $second = array_slice($this->dn
, $index +
1);
247 $this->dn
= array_merge($first, array($value), $second);
252 * Assert index is correct and usable
254 * @param mixed $index
256 * @throws Exception\LdapException
258 protected function assertIndex($index)
260 if (!is_int($index)) {
261 throw new Exception\
LdapException(null, 'Parameter $index must be an integer');
263 if ($index < 0 ||
$index >= count($this->dn
)) {
264 throw new Exception\
LdapException(null, 'Parameter $index out of bounds');
270 * Assert if value is in a correct RDN format
272 * @param array $value
274 * @throws Exception\LdapException
276 protected static function assertRdn(array $value)
278 if (count($value) < 1) {
279 throw new Exception\
LdapException(null, 'RDN Array is malformed: it must have at least one item');
282 foreach (array_keys($value) as $key) {
283 if (!is_string($key)) {
284 throw new Exception\
LdapException(null, 'RDN Array is malformed: it must use string keys');
292 * @param string|null $caseFold
294 public function setCaseFold($caseFold)
296 $this->caseFold
= static::sanitizeCaseFold($caseFold, static::$defaultCaseFold);
300 * Return DN as a string
302 * @param string $caseFold
304 * @throws Exception\LdapException
306 public function toString($caseFold = null)
308 $caseFold = static::sanitizeCaseFold($caseFold, $this->caseFold
);
309 return static::implodeDn($this->dn
, $caseFold);
313 * Return DN as an array
315 * @param string $caseFold
318 public function toArray($caseFold = null)
320 $caseFold = static::sanitizeCaseFold($caseFold, $this->caseFold
);
322 if ($caseFold === self
::ATTR_CASEFOLD_NONE
) {
325 return static::caseFoldDn($this->dn
, $caseFold);
329 * Do a case folding on a RDN
332 * @param string $caseFold
335 protected static function caseFoldRdn(array $part, $caseFold)
338 case self
::ATTR_CASEFOLD_UPPER
:
339 return array_change_key_case($part, CASE_UPPER
);
340 case self
::ATTR_CASEFOLD_LOWER
:
341 return array_change_key_case($part, CASE_LOWER
);
342 case self
::ATTR_CASEFOLD_NONE
:
349 * Do a case folding on a DN ort part of it
352 * @param string $caseFold
355 protected static function caseFoldDn(array $dn, $caseFold)
358 foreach ($dn as $part) {
359 $return[] = static::caseFoldRdn($part, $caseFold);
365 * Cast to string representation {@see toString()}
369 public function __toString()
371 return $this->toString();
375 * Required by the ArrayAccess implementation
380 public function offsetExists($offset)
382 $offset = (int) $offset;
383 if ($offset < 0 ||
$offset >= count($this->dn
)) {
390 * Proxy to {@see get()}
391 * Required by the ArrayAccess implementation
396 public function offsetGet($offset)
398 return $this->get($offset, 1, null);
402 * Proxy to {@see set()}
403 * Required by the ArrayAccess implementation
406 * @param array $value
408 public function offsetSet($offset, $value)
410 $this->set($offset, $value);
414 * Proxy to {@see remove()}
415 * Required by the ArrayAccess implementation
419 public function offsetUnset($offset)
421 $this->remove($offset, 1);
425 * Sets the default case fold
427 * @param string $caseFold
429 public static function setDefaultCaseFold($caseFold)
431 static::$defaultCaseFold = static::sanitizeCaseFold($caseFold, self
::ATTR_CASEFOLD_NONE
);
435 * Sanitizes the case fold
437 * @param string $caseFold
438 * @param string $default
441 protected static function sanitizeCaseFold($caseFold, $default)
444 case self
::ATTR_CASEFOLD_NONE
:
445 case self
::ATTR_CASEFOLD_UPPER
:
446 case self
::ATTR_CASEFOLD_LOWER
:
454 * Escapes a DN value according to RFC 2253
456 * Escapes the given VALUES according to RFC 2253 so that they can be safely used in LDAP DNs.
457 * The characters ",", "+", """, "\", "<", ">", ";", "#", " = " with a special meaning in RFC 2252
458 * are preceded by ba backslash. Control characters with an ASCII code < 32 are represented as \hexpair.
459 * Finally all leading and trailing spaces are converted to sequences of \20.
460 * @see Net_LDAP2_Util::escape_dn_value() from Benedikt Hallinger <beni@php.net>
461 * @link http://pear.php.net/package/Net_LDAP2
462 * @author Benedikt Hallinger <beni@php.net>
464 * @param string|array $values An array containing the DN values that should be escaped
465 * @return array The array $values, but escaped
467 public static function escapeValue($values = array())
469 if (!is_array($values)) {
470 $values = array($values);
472 foreach ($values as $key => $val) {
473 // Escaping of filter meta characters
475 array('\\', ',', '+', '"', '<', '>', ';', '#', '='),
476 array('\\\\', '\,', '\+', '\"', '\<', '\>', '\;', '\#', '\='), $val
478 $val = Converter\Converter
::ascToHex32($val);
480 // Convert all leading and trailing spaces to sequences of \20.
481 if (preg_match('/^(\s*)(.+?)(\s*)$/', $val, $matches)) {
483 for ($i = 0, $len = strlen($matches[1]); $i < $len; $i++
) {
486 for ($i = 0, $len = strlen($matches[3]); $i < $len; $i++
) {
492 } // apply escaped "null" if string is empty
493 $values[$key] = $val;
495 return (count($values) == 1) ?
$values[0] : $values;
499 * Undoes the conversion done by {@link escapeValue()}.
501 * Any escape sequence starting with a baskslash - hexpair or special character -
502 * will be transformed back to the corresponding character.
503 * @see Net_LDAP2_Util::escape_dn_value() from Benedikt Hallinger <beni@php.net>
504 * @link http://pear.php.net/package/Net_LDAP2
505 * @author Benedikt Hallinger <beni@php.net>
507 * @param string|array $values Array of DN Values
508 * @return array Same as $values, but unescaped
510 public static function unescapeValue($values = array())
512 if (!is_array($values)) {
513 $values = array($values);
515 foreach ($values as $key => $val) {
516 // strip slashes from special chars
518 array('\\\\', '\,', '\+', '\"', '\<', '\>', '\;', '\#', '\='),
519 array('\\', ',', '+', '"', '<', '>', ';', '#', '=', ), $val
521 $values[$key] = Converter\Converter
::hex32ToAsc($val);
523 return (count($values) == 1) ?
$values[0] : $values;
527 * Creates an array containing all parts of the given DN.
529 * Array will be of type
531 * array("cn" => "name1", "uid" => "user"),
532 * array("cn" => "name2"),
533 * array("dc" => "example"),
534 * array("dc" => "org")
536 * for a DN of cn=name1+uid=user,cn=name2,dc=example,dc=org.
539 * @param array $keys An optional array to receive DN keys (e.g. CN, OU, DC, ...)
540 * @param array $vals An optional array to receive DN values
541 * @param string $caseFold
543 * @throws Exception\LdapException
545 public static function explodeDn(
546 $dn, array &$keys = null, array &$vals = null,
547 $caseFold = self
::ATTR_CASEFOLD_NONE
551 if (!self
::checkDn($dn, $k, $v, $caseFold)) {
552 throw new Exception\
LdapException(null, 'DN is malformed');
555 for ($i = 0, $count = count($k); $i < $count; $i++
) {
556 if (is_array($k[$i]) && is_array($v[$i]) && (($keyCount = count($k[$i])) === count($v[$i]))) {
558 for ($j = 0; $j < $keyCount; $j++
) {
564 } elseif (is_string($k[$i]) && is_string($v[$i])) {
565 $ret[] = array($k[$i] => $v[$i]);
568 if ($keys !== null) {
571 if ($vals !== null) {
578 * @param string $dn The DN to parse
579 * @param array $keys An optional array to receive DN keys (e.g. CN, OU, DC, ...)
580 * @param array $vals An optional array to receive DN values
581 * @param string $caseFold
582 * @return bool True if the DN was successfully parsed or false if the string is not a valid DN.
584 public static function checkDn(
585 $dn, array &$keys = null, array &$vals = null,
586 $caseFold = self
::ATTR_CASEFOLD_NONE
588 /* This is a classic state machine parser. Each iteration of the
589 * loop processes one character. State 1 collects the key. When equals ( = )
590 * is encountered the state changes to 2 where the value is collected
591 * until a comma (,) or semicolon (;) is encountered after which we switch back
592 * to state 1. If a backslash (\) is encountered, state 3 is used to collect the
593 * following character without engaging the logic of other states.
601 for ($di = 0; $di <= $slen; $di++
) {
602 $ch = ($di == $slen) ?
0 : $dn[$di];
604 case 1: // collect key
606 $key = trim(substr($dn, $ko, $di - $ko));
607 if ($caseFold == self
::ATTR_CASEFOLD_LOWER
) {
608 $key = strtolower($key);
609 } elseif ($caseFold == self
::ATTR_CASEFOLD_UPPER
) {
610 $key = strtoupper($key);
612 if (is_array($multi)) {
613 $keyId = strtolower($key);
614 if (in_array($keyId, $multi)) {
617 $ka[count($ka) - 1][] = $key;
624 } elseif ($ch === ',' ||
$ch === ';' ||
$ch === '+') {
628 case 2: // collect value
631 } elseif ($ch === ',' ||
$ch === ';' ||
$ch === 0 ||
$ch === '+') {
632 $value = static::unescapeValue(trim(substr($dn, $vo, $di - $vo)));
633 if (is_array($multi)) {
634 $va[count($va) - 1][] = $value;
640 if ($ch === '+' && $multi === false) {
641 $lastKey = array_pop($ka);
642 $lastVal = array_pop($va);
643 $ka[] = array($lastKey);
644 $va[] = array($lastVal);
645 $multi = array(strtolower($lastKey));
646 } elseif ($ch === ',' ||
$ch === ';' ||
$ch === 0) {
649 } elseif ($ch === '=') {
659 if ($keys !== null) {
662 if ($vals !== null) {
666 return ($state === 1 && $ko > 0);
670 * Returns a DN part in the form $attribute = $value
672 * This method supports the creation of multi-valued RDNs
673 * $part must contain an even number of elements.
676 * @param string $caseFold
678 * @throws Exception\LdapException
680 public static function implodeRdn(array $part, $caseFold = null)
682 static::assertRdn($part);
683 $part = static::caseFoldRdn($part, $caseFold);
685 foreach ($part as $key => $value) {
686 $value = static::escapeValue($value);
687 $keyId = strtolower($key);
688 $rdnParts[$keyId] = implode('=', array($key, $value));
690 ksort($rdnParts, SORT_STRING
);
692 return implode('+', $rdnParts);
696 * Implodes an array in the form delivered by {@link explodeDn()}
699 * $dnArray must be of type
701 * array("cn" => "name1", "uid" => "user"),
702 * array("cn" => "name2"),
703 * array("dc" => "example"),
704 * array("dc" => "org")
707 * @param array $dnArray
708 * @param string $caseFold
709 * @param string $separator
711 * @throws Exception\LdapException
713 public static function implodeDn(array $dnArray, $caseFold = null, $separator = ',')
716 foreach ($dnArray as $p) {
717 $parts[] = static::implodeRdn($p, $caseFold);
720 return implode($separator, $parts);
724 * Checks if given $childDn is beneath $parentDn subtree.
726 * @param string|Dn $childDn
727 * @param string|Dn $parentDn
730 public static function isChildOf($childDn, $parentDn)
735 if ($childDn instanceof Dn
) {
736 $cdn = $childDn->toArray(DN
::ATTR_CASEFOLD_LOWER
);
738 $cdn = static::explodeDn($childDn, $keys, $vals, DN
::ATTR_CASEFOLD_LOWER
);
740 if ($parentDn instanceof Dn
) {
741 $pdn = $parentDn->toArray(DN
::ATTR_CASEFOLD_LOWER
);
743 $pdn = static::explodeDn($parentDn, $keys, $vals, DN
::ATTR_CASEFOLD_LOWER
);
745 } catch (Exception\LdapException
$e) {
749 $startIndex = count($cdn) - count($pdn);
750 if ($startIndex < 0) {
753 for ($i = 0, $count = count($pdn); $i < $count; $i++
) {
754 if ($cdn[$i +
$startIndex] != $pdn[$i]) {