fix calendar css, take 2. (#213)
[openemr.git] / interface / modules / zend_modules / library / Zend / Ldap / Dn.php
blob1b10e5a8aac47aa903085024fd3454fe3d2d35ca
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-2015 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 default:
449 return $default;
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
474 $val = str_replace(
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)) {
482 $val = $matches[2];
483 for ($i = 0, $len = strlen($matches[1]); $i < $len; $i++) {
484 $val = '\20' . $val;
486 for ($i = 0, $len = strlen($matches[3]); $i < $len; $i++) {
487 $val = $val . '\20';
490 if (null === $val) {
491 $val = '\0';
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
517 $val = str_replace(
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
530 * array(
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.
538 * @param string $dn
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
542 * @return array
543 * @throws Exception\LdapException
545 public static function explodeDn(
546 $dn, array &$keys = null, array &$vals = null,
547 $caseFold = self::ATTR_CASEFOLD_NONE
549 $k = array();
550 $v = array();
551 if (!self::checkDn($dn, $k, $v, $caseFold)) {
552 throw new Exception\LdapException(null, 'DN is malformed');
554 $ret = array();
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]))) {
557 $multi = array();
558 for ($j = 0; $j < $keyCount; $j++) {
559 $key = $k[$i][$j];
560 $val = $v[$i][$j];
561 $multi[$key] = $val;
563 $ret[] = $multi;
564 } elseif (is_string($k[$i]) && is_string($v[$i])) {
565 $ret[] = array($k[$i] => $v[$i]);
568 if ($keys !== null) {
569 $keys = $k;
571 if ($vals !== null) {
572 $vals = $v;
574 return $ret;
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.
595 $slen = strlen($dn);
596 $state = 1;
597 $ko = $vo = 0;
598 $multi = false;
599 $ka = array();
600 $va = array();
601 for ($di = 0; $di <= $slen; $di++) {
602 $ch = ($di == $slen) ? 0 : $dn[$di];
603 switch ($state) {
604 case 1: // collect key
605 if ($ch === '=') {
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)) {
615 return false;
617 $ka[count($ka) - 1][] = $key;
618 $multi[] = $keyId;
619 } else {
620 $ka[] = $key;
622 $state = 2;
623 $vo = $di + 1;
624 } elseif ($ch === ',' || $ch === ';' || $ch === '+') {
625 return false;
627 break;
628 case 2: // collect value
629 if ($ch === '\\') {
630 $state = 3;
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;
635 } else {
636 $va[] = $value;
638 $state = 1;
639 $ko = $di + 1;
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) {
647 $multi = false;
649 } elseif ($ch === '=') {
650 return false;
652 break;
653 case 3: // escaped
654 $state = 2;
655 break;
659 if ($keys !== null) {
660 $keys = $ka;
662 if ($vals !== null) {
663 $vals = $va;
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.
675 * @param array $part
676 * @param string $caseFold
677 * @return string
678 * @throws Exception\LdapException
680 public static function implodeRdn(array $part, $caseFold = null)
682 static::assertRdn($part);
683 $part = static::caseFoldRdn($part, $caseFold);
684 $rdnParts = array();
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()}
697 * to a DN string.
699 * $dnArray must be of type
700 * array(
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
710 * @return string
711 * @throws Exception\LdapException
713 public static function implodeDn(array $dnArray, $caseFold = null, $separator = ',')
715 $parts = array();
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
728 * @return bool
730 public static function isChildOf($childDn, $parentDn)
732 try {
733 $keys = array();
734 $vals = array();
735 if ($childDn instanceof Dn) {
736 $cdn = $childDn->toArray(DN::ATTR_CASEFOLD_LOWER);
737 } else {
738 $cdn = static::explodeDn($childDn, $keys, $vals, DN::ATTR_CASEFOLD_LOWER);
740 if ($parentDn instanceof Dn) {
741 $pdn = $parentDn->toArray(DN::ATTR_CASEFOLD_LOWER);
742 } else {
743 $pdn = static::explodeDn($parentDn, $keys, $vals, DN::ATTR_CASEFOLD_LOWER);
745 } catch (Exception\LdapException $e) {
746 return false;
749 $startIndex = count($cdn) - count($pdn);
750 if ($startIndex < 0) {
751 return false;
753 for ($i = 0, $count = count($pdn); $i < $count; $i++) {
754 if ($cdn[$i + $startIndex] != $pdn[$i]) {
755 return false;
758 return true;