forked from zendframework/zendframework
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Dn.php
762 lines (715 loc) · 22.5 KB
/
Dn.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
<?php
/**
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2013 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
namespace Zend\Ldap;
/**
* Zend\Ldap\Dn provides an API for DN manipulation
*/
class Dn implements \ArrayAccess
{
const ATTR_CASEFOLD_NONE = 'none';
const ATTR_CASEFOLD_UPPER = 'upper';
const ATTR_CASEFOLD_LOWER = 'lower';
/**
* The default case fold to use
*
* @var string
*/
protected static $defaultCaseFold = self::ATTR_CASEFOLD_NONE;
/**
* The case fold used for this instance
*
* @var string
*/
protected $caseFold;
/**
* The DN data
*
* @var array
*/
protected $dn;
/**
* Creates a DN from an array or a string
*
* @param string|array $dn
* @param string|null $caseFold
* @return Dn
* @throws Exception\LdapException
*/
public static function factory($dn, $caseFold = null)
{
if (is_array($dn)) {
return static::fromArray($dn, $caseFold);
} elseif (is_string($dn)) {
return static::fromString($dn, $caseFold);
}
throw new Exception\LdapException(null, 'Invalid argument type for $dn');
}
/**
* Creates a DN from a string
*
* @param string $dn
* @param string|null $caseFold
* @return Dn
* @throws Exception\LdapException
*/
public static function fromString($dn, $caseFold = null)
{
$dn = trim($dn);
if (empty($dn)) {
$dnArray = array();
} else {
$dnArray = static::explodeDn((string) $dn);
}
return new static($dnArray, $caseFold);
}
/**
* Creates a DN from an array
*
* @param array $dn
* @param string|null $caseFold
* @return Dn
* @throws Exception\LdapException
*/
public static function fromArray(array $dn, $caseFold = null)
{
return new static($dn, $caseFold);
}
/**
* Constructor
*
* @param array $dn
* @param string|null $caseFold
*/
protected function __construct(array $dn, $caseFold)
{
$this->dn = $dn;
$this->setCaseFold($caseFold);
}
/**
* Gets the RDN of the current DN
*
* @param string $caseFold
* @return array
* @throws Exception\LdapException if DN has no RDN (empty array)
*/
public function getRdn($caseFold = null)
{
$caseFold = static::sanitizeCaseFold($caseFold, $this->caseFold);
return static::caseFoldRdn($this->get(0, 1, $caseFold), null);
}
/**
* Gets the RDN of the current DN as a string
*
* @param string $caseFold
* @return string
* @throws Exception\LdapException if DN has no RDN (empty array)
*/
public function getRdnString($caseFold = null)
{
$caseFold = static::sanitizeCaseFold($caseFold, $this->caseFold);
return static::implodeRdn($this->getRdn(), $caseFold);
}
/**
* Get the parent DN $levelUp levels up the tree
*
* @param int $levelUp
* @throws Exception\LdapException
* @return Dn
*/
public function getParentDn($levelUp = 1)
{
$levelUp = (int) $levelUp;
if ($levelUp < 1 || $levelUp >= count($this->dn)) {
throw new Exception\LdapException(null, 'Cannot retrieve parent DN with given $levelUp');
}
$newDn = array_slice($this->dn, $levelUp);
return new static($newDn, $this->caseFold);
}
/**
* Get a DN part
*
* @param int $index
* @param int $length
* @param string $caseFold
* @return array
* @throws Exception\LdapException if index is illegal
*/
public function get($index, $length = 1, $caseFold = null)
{
$caseFold = static::sanitizeCaseFold($caseFold, $this->caseFold);
$this->assertIndex($index);
$length = (int) $length;
if ($length <= 0) {
$length = 1;
}
if ($length === 1) {
return static::caseFoldRdn($this->dn[$index], $caseFold);
}
return static::caseFoldDn(array_slice($this->dn, $index, $length, false), $caseFold);
}
/**
* Set a DN part
*
* @param int $index
* @param array $value
* @return Dn Provides a fluent interface
* @throws Exception\LdapException if index is illegal
*/
public function set($index, array $value)
{
$this->assertIndex($index);
static::assertRdn($value);
$this->dn[$index] = $value;
return $this;
}
/**
* Remove a DN part
*
* @param int $index
* @param int $length
* @return Dn Provides a fluent interface
* @throws Exception\LdapException if index is illegal
*/
public function remove($index, $length = 1)
{
$this->assertIndex($index);
$length = (int) $length;
if ($length <= 0) {
$length = 1;
}
array_splice($this->dn, $index, $length, null);
return $this;
}
/**
* Append a DN part
*
* @param array $value
* @return Dn Provides a fluent interface
*/
public function append(array $value)
{
static::assertRdn($value);
$this->dn[] = $value;
return $this;
}
/**
* Prepend a DN part
*
* @param array $value
* @return Dn Provides a fluent interface
*/
public function prepend(array $value)
{
static::assertRdn($value);
array_unshift($this->dn, $value);
return $this;
}
/**
* Insert a DN part
*
* @param int $index
* @param array $value
* @return Dn Provides a fluent interface
* @throws Exception\LdapException if index is illegal
*/
public function insert($index, array $value)
{
$this->assertIndex($index);
static::assertRdn($value);
$first = array_slice($this->dn, 0, $index + 1);
$second = array_slice($this->dn, $index + 1);
$this->dn = array_merge($first, array($value), $second);
return $this;
}
/**
* Assert index is correct and usable
*
* @param mixed $index
* @return bool
* @throws Exception\LdapException
*/
protected function assertIndex($index)
{
if (!is_int($index)) {
throw new Exception\LdapException(null, 'Parameter $index must be an integer');
}
if ($index < 0 || $index >= count($this->dn)) {
throw new Exception\LdapException(null, 'Parameter $index out of bounds');
}
return true;
}
/**
* Assert if value is in a correct RDN format
*
* @param array $value
* @return bool
* @throws Exception\LdapException
*/
protected static function assertRdn(array $value)
{
if (count($value) < 1) {
throw new Exception\LdapException(null, 'RDN Array is malformed: it must have at least one item');
}
foreach (array_keys($value) as $key) {
if (!is_string($key)) {
throw new Exception\LdapException(null, 'RDN Array is malformed: it must use string keys');
}
}
}
/**
* Sets the case fold
*
* @param string|null $caseFold
*/
public function setCaseFold($caseFold)
{
$this->caseFold = static::sanitizeCaseFold($caseFold, static::$defaultCaseFold);
}
/**
* Return DN as a string
*
* @param string $caseFold
* @return string
* @throws Exception\LdapException
*/
public function toString($caseFold = null)
{
$caseFold = static::sanitizeCaseFold($caseFold, $this->caseFold);
return static::implodeDn($this->dn, $caseFold);
}
/**
* Return DN as an array
*
* @param string $caseFold
* @return array
*/
public function toArray($caseFold = null)
{
$caseFold = static::sanitizeCaseFold($caseFold, $this->caseFold);
if ($caseFold === self::ATTR_CASEFOLD_NONE) {
return $this->dn;
}
return static::caseFoldDn($this->dn, $caseFold);
}
/**
* Do a case folding on a RDN
*
* @param array $part
* @param string $caseFold
* @return array
*/
protected static function caseFoldRdn(array $part, $caseFold)
{
switch ($caseFold) {
case self::ATTR_CASEFOLD_UPPER:
return array_change_key_case($part, CASE_UPPER);
case self::ATTR_CASEFOLD_LOWER:
return array_change_key_case($part, CASE_LOWER);
case self::ATTR_CASEFOLD_NONE:
default:
return $part;
}
}
/**
* Do a case folding on a DN ort part of it
*
* @param array $dn
* @param string $caseFold
* @return array
*/
protected static function caseFoldDn(array $dn, $caseFold)
{
$return = array();
foreach ($dn as $part) {
$return[] = static::caseFoldRdn($part, $caseFold);
}
return $return;
}
/**
* Cast to string representation {@see toString()}
*
* @return string
*/
public function __toString()
{
return $this->toString();
}
/**
* Required by the ArrayAccess implementation
*
* @param int $offset
* @return bool
*/
public function offsetExists($offset)
{
$offset = (int) $offset;
if ($offset < 0 || $offset >= count($this->dn)) {
return false;
}
return true;
}
/**
* Proxy to {@see get()}
* Required by the ArrayAccess implementation
*
* @param int $offset
* @return array
*/
public function offsetGet($offset)
{
return $this->get($offset, 1, null);
}
/**
* Proxy to {@see set()}
* Required by the ArrayAccess implementation
*
* @param int $offset
* @param array $value
*/
public function offsetSet($offset, $value)
{
$this->set($offset, $value);
}
/**
* Proxy to {@see remove()}
* Required by the ArrayAccess implementation
*
* @param int $offset
*/
public function offsetUnset($offset)
{
$this->remove($offset, 1);
}
/**
* Sets the default case fold
*
* @param string $caseFold
*/
public static function setDefaultCaseFold($caseFold)
{
static::$defaultCaseFold = static::sanitizeCaseFold($caseFold, self::ATTR_CASEFOLD_NONE);
}
/**
* Sanitizes the case fold
*
* @param string $caseFold
* @param string $default
* @return string
*/
protected static function sanitizeCaseFold($caseFold, $default)
{
switch ($caseFold) {
case self::ATTR_CASEFOLD_NONE:
case self::ATTR_CASEFOLD_UPPER:
case self::ATTR_CASEFOLD_LOWER:
return $caseFold;
break;
default:
return $default;
break;
}
}
/**
* Escapes a DN value according to RFC 2253
*
* Escapes the given VALUES according to RFC 2253 so that they can be safely used in LDAP DNs.
* The characters ",", "+", """, "\", "<", ">", ";", "#", " = " with a special meaning in RFC 2252
* are preceeded by ba backslash. Control characters with an ASCII code < 32 are represented as \hexpair.
* Finally all leading and trailing spaces are converted to sequences of \20.
* @see Net_LDAP2_Util::escape_dn_value() from Benedikt Hallinger <[email protected]>
* @link http://pear.php.net/package/Net_LDAP2
* @author Benedikt Hallinger <[email protected]>
*
* @param string|array $values An array containing the DN values that should be escaped
* @return array The array $values, but escaped
*/
public static function escapeValue($values = array())
{
if (!is_array($values)) {
$values = array($values);
}
foreach ($values as $key => $val) {
// Escaping of filter meta characters
$val = str_replace(
array('\\', ',', '+', '"', '<', '>', ';', '#', '=',),
array('\\\\', '\,', '\+', '\"', '\<', '\>', '\;', '\#', '\='), $val
);
$val = Converter\Converter::ascToHex32($val);
// Convert all leading and trailing spaces to sequences of \20.
if (preg_match('/^(\s*)(.+?)(\s*)$/', $val, $matches)) {
$val = $matches[2];
for ($i = 0, $len = strlen($matches[1]); $i < $len; $i++) {
$val = '\20' . $val;
}
for ($i = 0, $len = strlen($matches[3]); $i < $len; $i++) {
$val = $val . '\20';
}
}
if (null === $val) {
$val = '\0';
} // apply escaped "null" if string is empty
$values[$key] = $val;
}
return (count($values) == 1) ? $values[0] : $values;
}
/**
* Undoes the conversion done by {@link escapeValue()}.
*
* Any escape sequence starting with a baskslash - hexpair or special character -
* will be transformed back to the corresponding character.
* @see Net_LDAP2_Util::escape_dn_value() from Benedikt Hallinger <[email protected]>
* @link http://pear.php.net/package/Net_LDAP2
* @author Benedikt Hallinger <[email protected]>
*
* @param string|array $values Array of DN Values
* @return array Same as $values, but unescaped
*/
public static function unescapeValue($values = array())
{
if (!is_array($values)) {
$values = array($values);
}
foreach ($values as $key => $val) {
// strip slashes from special chars
$val = str_replace(
array('\\\\', '\,', '\+', '\"', '\<', '\>', '\;', '\#', '\='),
array('\\', ',', '+', '"', '<', '>', ';', '#', '=',), $val
);
$values[$key] = Converter\Converter::hex32ToAsc($val);
}
return (count($values) == 1) ? $values[0] : $values;
}
/**
* Creates an array containing all parts of the given DN.
*
* Array will be of type
* array(
* array("cn" => "name1", "uid" => "user"),
* array("cn" => "name2"),
* array("dc" => "example"),
* array("dc" => "org")
* )
* for a DN of cn=name1+uid=user,cn=name2,dc=example,dc=org.
*
* @param string $dn
* @param array $keys An optional array to receive DN keys (e.g. CN, OU, DC, ...)
* @param array $vals An optional array to receive DN values
* @param string $caseFold
* @return array
* @throws Exception\LdapException
*/
public static function explodeDn(
$dn, array &$keys = null, array &$vals = null,
$caseFold = self::ATTR_CASEFOLD_NONE
) {
$k = array();
$v = array();
if (!self::checkDn($dn, $k, $v, $caseFold)) {
throw new Exception\LdapException(null, 'DN is malformed');
}
$ret = array();
for ($i = 0, $count = count($k); $i < $count; $i++) {
if (is_array($k[$i]) && is_array($v[$i]) && (count($k[$i]) === count($v[$i]))) {
$multi = array();
for ($j = 0; $j < count($k[$i]); $j++) {
$key = $k[$i][$j];
$val = $v[$i][$j];
$multi[$key] = $val;
}
$ret[] = $multi;
} elseif (is_string($k[$i]) && is_string($v[$i])) {
$ret[] = array($k[$i] => $v[$i]);
}
}
if ($keys !== null) {
$keys = $k;
}
if ($vals !== null) {
$vals = $v;
}
return $ret;
}
/**
* @param string $dn The DN to parse
* @param array $keys An optional array to receive DN keys (e.g. CN, OU, DC, ...)
* @param array $vals An optional array to receive DN values
* @param string $caseFold
* @return bool True if the DN was successfully parsed or false if the string is not a valid DN.
*/
public static function checkDn(
$dn, array &$keys = null, array &$vals = null,
$caseFold = self::ATTR_CASEFOLD_NONE
) {
/* This is a classic state machine parser. Each iteration of the
* loop processes one character. State 1 collects the key. When equals ( = )
* is encountered the state changes to 2 where the value is collected
* until a comma (,) or semicolon (;) is encountered after which we switch back
* to state 1. If a backslash (\) is encountered, state 3 is used to collect the
* following character without engaging the logic of other states.
*/
$key = null;
$value = null;
$slen = strlen($dn);
$state = 1;
$ko = $vo = 0;
$multi = false;
$ka = array();
$va = array();
for ($di = 0; $di <= $slen; $di++) {
$ch = ($di == $slen) ? 0 : $dn[$di];
switch ($state) {
case 1: // collect key
if ($ch === '=') {
$key = trim(substr($dn, $ko, $di - $ko));
if ($caseFold == self::ATTR_CASEFOLD_LOWER) {
$key = strtolower($key);
} elseif ($caseFold == self::ATTR_CASEFOLD_UPPER) {
$key = strtoupper($key);
}
if (is_array($multi)) {
$keyId = strtolower($key);
if (in_array($keyId, $multi)) {
return false;
}
$ka[count($ka) - 1][] = $key;
$multi[] = $keyId;
} else {
$ka[] = $key;
}
$state = 2;
$vo = $di + 1;
} elseif ($ch === ',' || $ch === ';' || $ch === '+') {
return false;
}
break;
case 2: // collect value
if ($ch === '\\') {
$state = 3;
} elseif ($ch === ',' || $ch === ';' || $ch === 0 || $ch === '+') {
$value = static::unescapeValue(trim(substr($dn, $vo, $di - $vo)));
if (is_array($multi)) {
$va[count($va) - 1][] = $value;
} else {
$va[] = $value;
}
$state = 1;
$ko = $di + 1;
if ($ch === '+' && $multi === false) {
$lastKey = array_pop($ka);
$lastVal = array_pop($va);
$ka[] = array($lastKey);
$va[] = array($lastVal);
$multi = array(strtolower($lastKey));
} elseif ($ch === ',' || $ch === ';' || $ch === 0) {
$multi = false;
}
} elseif ($ch === '=') {
return false;
}
break;
case 3: // escaped
$state = 2;
break;
}
}
if ($keys !== null) {
$keys = $ka;
}
if ($vals !== null) {
$vals = $va;
}
return ($state === 1 && $ko > 0);
}
/**
* Returns a DN part in the form $attribute = $value
*
* This method supports the creation of multi-valued RDNs
* $part must contain an even number of elements.
*
* @param array $part
* @param string $caseFold
* @return string
* @throws Exception\LdapException
*/
public static function implodeRdn(array $part, $caseFold = null)
{
static::assertRdn($part);
$part = static::caseFoldRdn($part, $caseFold);
$rdnParts = array();
foreach ($part as $key => $value) {
$value = static::escapeValue($value);
$keyId = strtolower($key);
$rdnParts[$keyId] = implode('=', array($key, $value));
}
ksort($rdnParts, SORT_STRING);
return implode('+', $rdnParts);
}
/**
* Implodes an array in the form delivered by {@link explodeDn()}
* to a DN string.
*
* $dnArray must be of type
* array(
* array("cn" => "name1", "uid" => "user"),
* array("cn" => "name2"),
* array("dc" => "example"),
* array("dc" => "org")
* )
*
* @param array $dnArray
* @param string $caseFold
* @param string $separator
* @return string
* @throws Exception\LdapException
*/
public static function implodeDn(array $dnArray, $caseFold = null, $separator = ',')
{
$parts = array();
foreach ($dnArray as $p) {
$parts[] = static::implodeRdn($p, $caseFold);
}
return implode($separator, $parts);
}
/**
* Checks if given $childDn is beneath $parentDn subtree.
*
* @param string|Dn $childDn
* @param string|Dn $parentDn
* @return bool
*/
public static function isChildOf($childDn, $parentDn)
{
try {
$keys = array();
$vals = array();
if ($childDn instanceof Dn) {
$cdn = $childDn->toArray(DN::ATTR_CASEFOLD_LOWER);
} else {
$cdn = static::explodeDn($childDn, $keys, $vals, DN::ATTR_CASEFOLD_LOWER);
}
if ($parentDn instanceof Dn) {
$pdn = $parentDn->toArray(DN::ATTR_CASEFOLD_LOWER);
} else {
$pdn = static::explodeDn($parentDn, $keys, $vals, DN::ATTR_CASEFOLD_LOWER);
}
} catch (Exception\LdapException $e) {
return false;
}
$startIndex = count($cdn) - count($pdn);
if ($startIndex < 0) {
return false;
}
for ($i = 0, $count = count($pdn); $i < $count; $i++) {
if ($cdn[$i + $startIndex] != $pdn[$i]) {
return false;
}
}
return true;
}
}