3 * Zend Framework (http://framework.zend.com/)
5 * @link http://github.com/zendframework/zf2 for the canonical source repository
6 * @copyright Copyright (c) 2005-2013 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
:
456 * Escapes a DN value according to RFC 2253
458 * Escapes the given VALUES according to RFC 2253 so that they can be safely used in LDAP DNs.
459 * The characters ",", "+", """, "\", "<", ">", ";", "#", " = " with a special meaning in RFC 2252
460 * are preceded by ba backslash. Control characters with an ASCII code < 32 are represented as \hexpair.
461 * Finally all leading and trailing spaces are converted to sequences of \20.
462 * @see Net_LDAP2_Util::escape_dn_value() from Benedikt Hallinger <beni@php.net>
463 * @link http://pear.php.net/package/Net_LDAP2
464 * @author Benedikt Hallinger <beni@php.net>
466 * @param string|array $values An array containing the DN values that should be escaped
467 * @return array The array $values, but escaped
469 public static function escapeValue($values = array())
471 if (!is_array($values)) {
472 $values = array($values);
474 foreach ($values as $key => $val) {
475 // Escaping of filter meta characters
477 array('\\', ',', '+', '"', '<', '>', ';', '#', '=',),
478 array('\\\\', '\,', '\+', '\"', '\<', '\>', '\;', '\#', '\='), $val
480 $val = Converter\Converter
::ascToHex32($val);
482 // Convert all leading and trailing spaces to sequences of \20.
483 if (preg_match('/^(\s*)(.+?)(\s*)$/', $val, $matches)) {
485 for ($i = 0, $len = strlen($matches[1]); $i < $len; $i++
) {
488 for ($i = 0, $len = strlen($matches[3]); $i < $len; $i++
) {
494 } // apply escaped "null" if string is empty
495 $values[$key] = $val;
497 return (count($values) == 1) ?
$values[0] : $values;
501 * Undoes the conversion done by {@link escapeValue()}.
503 * Any escape sequence starting with a baskslash - hexpair or special character -
504 * will be transformed back to the corresponding character.
505 * @see Net_LDAP2_Util::escape_dn_value() from Benedikt Hallinger <beni@php.net>
506 * @link http://pear.php.net/package/Net_LDAP2
507 * @author Benedikt Hallinger <beni@php.net>
509 * @param string|array $values Array of DN Values
510 * @return array Same as $values, but unescaped
512 public static function unescapeValue($values = array())
514 if (!is_array($values)) {
515 $values = array($values);
517 foreach ($values as $key => $val) {
518 // strip slashes from special chars
520 array('\\\\', '\,', '\+', '\"', '\<', '\>', '\;', '\#', '\='),
521 array('\\', ',', '+', '"', '<', '>', ';', '#', '=',), $val
523 $values[$key] = Converter\Converter
::hex32ToAsc($val);
525 return (count($values) == 1) ?
$values[0] : $values;
529 * Creates an array containing all parts of the given DN.
531 * Array will be of type
533 * array("cn" => "name1", "uid" => "user"),
534 * array("cn" => "name2"),
535 * array("dc" => "example"),
536 * array("dc" => "org")
538 * for a DN of cn=name1+uid=user,cn=name2,dc=example,dc=org.
541 * @param array $keys An optional array to receive DN keys (e.g. CN, OU, DC, ...)
542 * @param array $vals An optional array to receive DN values
543 * @param string $caseFold
545 * @throws Exception\LdapException
547 public static function explodeDn(
548 $dn, array &$keys = null, array &$vals = null,
549 $caseFold = self
::ATTR_CASEFOLD_NONE
553 if (!self
::checkDn($dn, $k, $v, $caseFold)) {
554 throw new Exception\
LdapException(null, 'DN is malformed');
557 for ($i = 0, $count = count($k); $i < $count; $i++
) {
558 if (is_array($k[$i]) && is_array($v[$i]) && (count($k[$i]) === count($v[$i]))) {
560 for ($j = 0; $j < count($k[$i]); $j++
) {
566 } elseif (is_string($k[$i]) && is_string($v[$i])) {
567 $ret[] = array($k[$i] => $v[$i]);
570 if ($keys !== null) {
573 if ($vals !== null) {
580 * @param string $dn The DN to parse
581 * @param array $keys An optional array to receive DN keys (e.g. CN, OU, DC, ...)
582 * @param array $vals An optional array to receive DN values
583 * @param string $caseFold
584 * @return bool True if the DN was successfully parsed or false if the string is not a valid DN.
586 public static function checkDn(
587 $dn, array &$keys = null, array &$vals = null,
588 $caseFold = self
::ATTR_CASEFOLD_NONE
590 /* This is a classic state machine parser. Each iteration of the
591 * loop processes one character. State 1 collects the key. When equals ( = )
592 * is encountered the state changes to 2 where the value is collected
593 * until a comma (,) or semicolon (;) is encountered after which we switch back
594 * to state 1. If a backslash (\) is encountered, state 3 is used to collect the
595 * following character without engaging the logic of other states.
605 for ($di = 0; $di <= $slen; $di++
) {
606 $ch = ($di == $slen) ?
0 : $dn[$di];
608 case 1: // collect key
610 $key = trim(substr($dn, $ko, $di - $ko));
611 if ($caseFold == self
::ATTR_CASEFOLD_LOWER
) {
612 $key = strtolower($key);
613 } elseif ($caseFold == self
::ATTR_CASEFOLD_UPPER
) {
614 $key = strtoupper($key);
616 if (is_array($multi)) {
617 $keyId = strtolower($key);
618 if (in_array($keyId, $multi)) {
621 $ka[count($ka) - 1][] = $key;
628 } elseif ($ch === ',' ||
$ch === ';' ||
$ch === '+') {
632 case 2: // collect value
635 } elseif ($ch === ',' ||
$ch === ';' ||
$ch === 0 ||
$ch === '+') {
636 $value = static::unescapeValue(trim(substr($dn, $vo, $di - $vo)));
637 if (is_array($multi)) {
638 $va[count($va) - 1][] = $value;
644 if ($ch === '+' && $multi === false) {
645 $lastKey = array_pop($ka);
646 $lastVal = array_pop($va);
647 $ka[] = array($lastKey);
648 $va[] = array($lastVal);
649 $multi = array(strtolower($lastKey));
650 } elseif ($ch === ',' ||
$ch === ';' ||
$ch === 0) {
653 } elseif ($ch === '=') {
663 if ($keys !== null) {
666 if ($vals !== null) {
670 return ($state === 1 && $ko > 0);
674 * Returns a DN part in the form $attribute = $value
676 * This method supports the creation of multi-valued RDNs
677 * $part must contain an even number of elements.
680 * @param string $caseFold
682 * @throws Exception\LdapException
684 public static function implodeRdn(array $part, $caseFold = null)
686 static::assertRdn($part);
687 $part = static::caseFoldRdn($part, $caseFold);
689 foreach ($part as $key => $value) {
690 $value = static::escapeValue($value);
691 $keyId = strtolower($key);
692 $rdnParts[$keyId] = implode('=', array($key, $value));
694 ksort($rdnParts, SORT_STRING
);
696 return implode('+', $rdnParts);
700 * Implodes an array in the form delivered by {@link explodeDn()}
703 * $dnArray must be of type
705 * array("cn" => "name1", "uid" => "user"),
706 * array("cn" => "name2"),
707 * array("dc" => "example"),
708 * array("dc" => "org")
711 * @param array $dnArray
712 * @param string $caseFold
713 * @param string $separator
715 * @throws Exception\LdapException
717 public static function implodeDn(array $dnArray, $caseFold = null, $separator = ',')
720 foreach ($dnArray as $p) {
721 $parts[] = static::implodeRdn($p, $caseFold);
724 return implode($separator, $parts);
728 * Checks if given $childDn is beneath $parentDn subtree.
730 * @param string|Dn $childDn
731 * @param string|Dn $parentDn
734 public static function isChildOf($childDn, $parentDn)
739 if ($childDn instanceof Dn
) {
740 $cdn = $childDn->toArray(DN
::ATTR_CASEFOLD_LOWER
);
742 $cdn = static::explodeDn($childDn, $keys, $vals, DN
::ATTR_CASEFOLD_LOWER
);
744 if ($parentDn instanceof Dn
) {
745 $pdn = $parentDn->toArray(DN
::ATTR_CASEFOLD_LOWER
);
747 $pdn = static::explodeDn($parentDn, $keys, $vals, DN
::ATTR_CASEFOLD_LOWER
);
749 } catch (Exception\LdapException
$e) {
753 $startIndex = count($cdn) - count($pdn);
754 if ($startIndex < 0) {
757 for ($i = 0, $count = count($pdn); $i < $count; $i++
) {
758 if ($cdn[$i +
$startIndex] != $pdn[$i]) {