Added the zend framework 2 library, the path is specified in line no.26 in zend_modul...
[openemr.git] / interface / modules / zend_modules / library / Zend / Ldap / Dn.php
blob988e9ee8758961cee7328f0d82fad8d887fae3ec
1 <?php
2 /**
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
8 */
10 namespace Zend\Ldap;
12 use ArrayAccess;
14 /**
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';
23 /**
24 * The default case fold to use
26 * @var string
28 protected static $defaultCaseFold = self::ATTR_CASEFOLD_NONE;
30 /**
31 * The case fold used for this instance
33 * @var string
35 protected $caseFold;
37 /**
38 * The DN data
40 * @var array
42 protected $dn;
44 /**
45 * Creates a DN from an array or a string
47 * @param string|array $dn
48 * @param string|null $caseFold
49 * @return Dn
50 * @throws Exception\LdapException
52 public static function factory($dn, $caseFold = null)
54 if (is_array($dn)) {
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');
62 /**
63 * Creates a DN from a string
65 * @param string $dn
66 * @param string|null $caseFold
67 * @return Dn
68 * @throws Exception\LdapException
70 public static function fromString($dn, $caseFold = null)
72 $dn = trim($dn);
73 if (empty($dn)) {
74 $dnArray = array();
75 } else {
76 $dnArray = static::explodeDn((string) $dn);
78 return new static($dnArray, $caseFold);
81 /**
82 * Creates a DN from an array
84 * @param array $dn
85 * @param string|null $caseFold
86 * @return Dn
87 * @throws Exception\LdapException
89 public static function fromArray(array $dn, $caseFold = null)
91 return new static($dn, $caseFold);
94 /**
95 * Constructor
97 * @param array $dn
98 * @param string|null $caseFold
100 protected function __construct(array $dn, $caseFold)
102 $this->dn = $dn;
103 $this->setCaseFold($caseFold);
107 * Gets the RDN of the current DN
109 * @param string $caseFold
110 * @return array
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
123 * @return string
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
137 * @return Dn
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);
150 * Get a DN part
152 * @param int $index
153 * @param int $length
154 * @param string $caseFold
155 * @return array
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;
163 if ($length <= 0) {
164 $length = 1;
166 if ($length === 1) {
167 return static::caseFoldRdn($this->dn[$index], $caseFold);
169 return static::caseFoldDn(array_slice($this->dn, $index, $length, false), $caseFold);
173 * Set a DN part
175 * @param int $index
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;
185 return $this;
189 * Remove a DN part
191 * @param int $index
192 * @param int $length
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;
200 if ($length <= 0) {
201 $length = 1;
203 array_splice($this->dn, $index, $length, null);
204 return $this;
208 * Append a DN part
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;
217 return $this;
221 * Prepend a DN part
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);
230 return $this;
234 * Insert a DN part
236 * @param int $index
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);
248 return $this;
252 * Assert index is correct and usable
254 * @param mixed $index
255 * @return bool
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');
266 return true;
270 * Assert if value is in a correct RDN format
272 * @param array $value
273 * @return bool
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');
290 * Sets the case fold
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
303 * @return string
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
316 * @return array
318 public function toArray($caseFold = null)
320 $caseFold = static::sanitizeCaseFold($caseFold, $this->caseFold);
322 if ($caseFold === self::ATTR_CASEFOLD_NONE) {
323 return $this->dn;
325 return static::caseFoldDn($this->dn, $caseFold);
329 * Do a case folding on a RDN
331 * @param array $part
332 * @param string $caseFold
333 * @return array
335 protected static function caseFoldRdn(array $part, $caseFold)
337 switch ($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:
343 default:
344 return $part;
349 * Do a case folding on a DN ort part of it
351 * @param array $dn
352 * @param string $caseFold
353 * @return array
355 protected static function caseFoldDn(array $dn, $caseFold)
357 $return = array();
358 foreach ($dn as $part) {
359 $return[] = static::caseFoldRdn($part, $caseFold);
361 return $return;
365 * Cast to string representation {@see toString()}
367 * @return string
369 public function __toString()
371 return $this->toString();
375 * Required by the ArrayAccess implementation
377 * @param int $offset
378 * @return bool
380 public function offsetExists($offset)
382 $offset = (int) $offset;
383 if ($offset < 0 || $offset >= count($this->dn)) {
384 return false;
386 return true;
390 * Proxy to {@see get()}
391 * Required by the ArrayAccess implementation
393 * @param int $offset
394 * @return array
396 public function offsetGet($offset)
398 return $this->get($offset, 1, null);
402 * Proxy to {@see set()}
403 * Required by the ArrayAccess implementation
405 * @param int $offset
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
417 * @param int $offset
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
439 * @return string
441 protected static function sanitizeCaseFold($caseFold, $default)
443 switch ($caseFold) {
444 case self::ATTR_CASEFOLD_NONE:
445 case self::ATTR_CASEFOLD_UPPER:
446 case self::ATTR_CASEFOLD_LOWER:
447 return $caseFold;
448 break;
449 default:
450 return $default;
451 break;
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
476 $val = str_replace(
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)) {
484 $val = $matches[2];
485 for ($i = 0, $len = strlen($matches[1]); $i < $len; $i++) {
486 $val = '\20' . $val;
488 for ($i = 0, $len = strlen($matches[3]); $i < $len; $i++) {
489 $val = $val . '\20';
492 if (null === $val) {
493 $val = '\0';
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
519 $val = str_replace(
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
532 * array(
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.
540 * @param string $dn
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
544 * @return array
545 * @throws Exception\LdapException
547 public static function explodeDn(
548 $dn, array &$keys = null, array &$vals = null,
549 $caseFold = self::ATTR_CASEFOLD_NONE
551 $k = array();
552 $v = array();
553 if (!self::checkDn($dn, $k, $v, $caseFold)) {
554 throw new Exception\LdapException(null, 'DN is malformed');
556 $ret = array();
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]))) {
559 $multi = array();
560 for ($j = 0; $j < count($k[$i]); $j++) {
561 $key = $k[$i][$j];
562 $val = $v[$i][$j];
563 $multi[$key] = $val;
565 $ret[] = $multi;
566 } elseif (is_string($k[$i]) && is_string($v[$i])) {
567 $ret[] = array($k[$i] => $v[$i]);
570 if ($keys !== null) {
571 $keys = $k;
573 if ($vals !== null) {
574 $vals = $v;
576 return $ret;
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.
597 $key = null;
598 $value = null;
599 $slen = strlen($dn);
600 $state = 1;
601 $ko = $vo = 0;
602 $multi = false;
603 $ka = array();
604 $va = array();
605 for ($di = 0; $di <= $slen; $di++) {
606 $ch = ($di == $slen) ? 0 : $dn[$di];
607 switch ($state) {
608 case 1: // collect key
609 if ($ch === '=') {
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)) {
619 return false;
621 $ka[count($ka) - 1][] = $key;
622 $multi[] = $keyId;
623 } else {
624 $ka[] = $key;
626 $state = 2;
627 $vo = $di + 1;
628 } elseif ($ch === ',' || $ch === ';' || $ch === '+') {
629 return false;
631 break;
632 case 2: // collect value
633 if ($ch === '\\') {
634 $state = 3;
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;
639 } else {
640 $va[] = $value;
642 $state = 1;
643 $ko = $di + 1;
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) {
651 $multi = false;
653 } elseif ($ch === '=') {
654 return false;
656 break;
657 case 3: // escaped
658 $state = 2;
659 break;
663 if ($keys !== null) {
664 $keys = $ka;
666 if ($vals !== null) {
667 $vals = $va;
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.
679 * @param array $part
680 * @param string $caseFold
681 * @return string
682 * @throws Exception\LdapException
684 public static function implodeRdn(array $part, $caseFold = null)
686 static::assertRdn($part);
687 $part = static::caseFoldRdn($part, $caseFold);
688 $rdnParts = array();
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()}
701 * to a DN string.
703 * $dnArray must be of type
704 * array(
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
714 * @return string
715 * @throws Exception\LdapException
717 public static function implodeDn(array $dnArray, $caseFold = null, $separator = ',')
719 $parts = array();
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
732 * @return bool
734 public static function isChildOf($childDn, $parentDn)
736 try {
737 $keys = array();
738 $vals = array();
739 if ($childDn instanceof Dn) {
740 $cdn = $childDn->toArray(DN::ATTR_CASEFOLD_LOWER);
741 } else {
742 $cdn = static::explodeDn($childDn, $keys, $vals, DN::ATTR_CASEFOLD_LOWER);
744 if ($parentDn instanceof Dn) {
745 $pdn = $parentDn->toArray(DN::ATTR_CASEFOLD_LOWER);
746 } else {
747 $pdn = static::explodeDn($parentDn, $keys, $vals, DN::ATTR_CASEFOLD_LOWER);
749 } catch (Exception\LdapException $e) {
750 return false;
753 $startIndex = count($cdn) - count($pdn);
754 if ($startIndex < 0) {
755 return false;
757 for ($i = 0, $count = count($pdn); $i < $count; $i++) {
758 if ($cdn[$i + $startIndex] != $pdn[$i]) {
759 return false;
762 return true;