1: <?php
2:
3: class LdapUtils {
4:
5: public static function normalizeDn($dn) {
6: $rdns = self::explodeDn($dn, true);
7: $newRdns = array();
8: foreach ($rdns as $rdn) {
9: $newRdns[] = array(
10: 'attribute' => strtolower($rdn['attribute']),
11: 'value' => trim($rdn['value'])
12: );
13: }
14:
15: return self::implodeDn($newRdns, true);
16: }
17:
18: public static function explodeDn($dn, $explodeRdns = false) {
19: $rdns = explode(',', $dn);
20: unset($rdns['count']);
21:
22: if ($explodeRdns) {
23: $explodedRdns = array();
24: foreach ($rdns as $rdn) {
25: $explodedRdns[] = self::explodeRdn($rdn);
26: }
27: return $explodedRdns;
28: } else {
29: return $rdns;
30: }
31: }
32:
33: public static function explodeRdn($rdn) {
34: $equalsSymbolPosition = strpos($rdn, '=');
35:
36: if ($equalsSymbolPosition === false) {
37: throw new Exception("RDN \"$rdn\" has no equals symbol");
38: }
39:
40: return array(
41: 'attribute' => substr($rdn, 0, $equalsSymbolPosition),
42: 'value' => substr($rdn, $equalsSymbolPosition + 1)
43: );
44: }
45:
46: public static function implodeDn($rdns, $isExplodedRdns) {
47: if ($isExplodedRdns) {
48: $implodedRdns = array();
49: foreach ($rdns as $rdn) {
50: $implodedRdns[] = "{$rdn['attribute']}={$rdn['value']}";
51: }
52: $rdns = $implodedRdns;
53: }
54:
55: return implode(',', $rdns);
56: }
57:
58: public static function firstRdn($dn, $field = null) {
59: $explodedDn = self::explodeDn($dn);
60:
61: switch ($field) {
62: case 'attribute':
63: case 'value':
64: $rdn = self::explodeRdn($explodedDn[0]);
65: return $rdn[$field];
66:
67: default:
68: return $explodedDn[0];
69: }
70: }
71:
72: public static function joinDns($dn1, $dn2) {
73: $dn1 = trim($dn1);
74: $dn2 = trim($dn2);
75: if ($dn1 != '' && $dn2 != '') {
76: return $dn1 . ',' . $dn2;
77: } else {
78: return $dn1 . $dn2;
79: }
80: }
81:
82: public static function parentDn($dn) {
83: $rdns = self::explodeDn($dn, true);
84: array_shift($rdns);
85: if (empty($rdns)) {
86: return false;
87: } else {
88: return self::implodeDn($rdns, true);
89: }
90: }
91:
92: public static function isDnParent($parentDn, $childDn) {
93: $parentRdns = array_reverse(self::explodeDn($parentDn));
94: $childRdns = array_reverse(self::explodeDn($childDn));
95: if (count($childRdns) <= count($parentRdns)) {
96: return false;
97: }
98: for ($i = 0; $i < count($parentRdns); $i++) {
99: if (strtolower($parentRdns[$i]) != strtolower($childRdns[$i])) {
100: return false;
101: }
102: }
103: return true;
104: }
105:
106: }