File: ldap.php

package info (click to toggle)
horde3 3.1.3-4etch7
  • links: PTS
  • area: main
  • in suites: etch
  • size: 22,876 kB
  • ctags: 18,071
  • sloc: php: 75,151; xml: 2,979; sql: 1,069; makefile: 79; sh: 64
file content (835 lines) | stat: -rw-r--r-- 26,221 bytes parent folder | download | duplicates (2)
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
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
<?php
/**
 * The Group_ldap class provides an LDAP backend for the Horde groups
 * system.
 *
 * $Horde: framework/Group/Group/ldap.php,v 1.18.2.2 2006/01/01 21:28:19 jan Exp $
 *
 * Copyright 2005-2006 Ben Chavet <ben@horde.org>
 *
 * See the enclosed file COPYING for license information (LGPL). If you
 * did not receive this file, see http://www.fsf.org/copyleft/lgpl.html.
 *
 * @author  Ben Chavet <ben@horde.org>
 * @since   Horde 3.1
 * @package Horde_Group
 */
class Group_ldap extends Group {

    /**
     * LDAP connection handle
     */
    var $_ds;

    /**
     * Local copy of the global $conf['group']['params'] array.  Simply
     * for coding convenience.
     */
    var $_params;

    /**
     * Generated LDAP filter based on the config parameters
     */
    var $_filter;

    /**
     * Constructor.
     */
    function Group_ldap()
    {
        global $conf;
        $this->_params = $conf['group']['params'];

        $this->_params['gid'] = strtolower($this->_params['gid']);
        $this->_params['memberuid'] = strtolower($this->_params['memberuid']);
        foreach ($this->_params['newgroup_objectclass'] as $key => $val) {
            $this->_params['newgroup_objectclass'][$key] = strtolower($val);
        }

        /* Generate LDAP search filter. */
        if (!empty($this->_params['filter'])) {
            $this->_filter = $this->_params['filter'];
        } elseif (!is_array($this->_params['objectclass'])) {
            $this->_filter = 'objectclass=' . $this->_params['objectclass'];
        } else {
            $this->_filter = '';
            foreach ($this->_params['objectclass'] as $objectclass) {
                $this->_filter = '(&' . $this->_filter;
                $this->_filter .= '(objectclass=' . $objectclass . '))';
            }
        }

        $this->_filter = strtolower($this->_filter);
    }

    /**
     * Connects to the LDAP server.
     *
     * @return boolean  True or False based on success of connect and bind.
     */
    function _connect()
    {
        /* Connect to the LDAP server. */
        $this->_ds = @ldap_connect($this->_params['hostspec']);
        if (!$this->_ds) {
            return PEAR::raiseError(_("Failed to connect to LDAP server."));
        }

        if (!ldap_set_option($this->_ds, LDAP_OPT_PROTOCOL_VERSION,
                             $this->_params['version'])) {
            Horde::logMessage(
                sprintf('Set LDAP protocol version to %d failed: [%d] %s',
                        $this->_params['version'],
                        ldap_errno($conn),
                        ldap_error($conn),
                        __FILE__, __LINE__));
        }

        if (isset($this->_params['binddn'])) {
            $bind = @ldap_bind($this->_ds, $this->_params['binddn'],
                               $this->_params['password']);
        } else {
            $bind = @ldap_bind($this->_ds);
        }

        if (!$bind) {
            return PEAR::raiseError(_("Could not bind to LDAP server."));
        }

        return true;
    }

    /**
     * Recursively deletes $dn. $this->_ds MUST already be connected.
     *
     * @return mixed  True if delete was successful, PEAR_Error otherwise.
     */
    function _recursive_delete($dn)
    {
        $search = @ldap_list($this->_ds, $dn, 'objectclass=*', array(''));
        if (!$search) {
            return PEAR::raiseError(_("Could not reach the LDAP server."));
        }

        $children = @ldap_get_entries($this->_ds, $search);
        for ($i = 0; $i < $children['count']; $i++) {
            $result = $this->_recursive_delete($children[$i]['dn']);
            if (!$result) {
                return PEAR::raiseError(sprintf(_("Group_ldap: Unable to delete group %s"), $this->getName($children[$i]['dn'])));
            }
        }

        $result = @ldap_delete($this->_ds, $dn);
        if (!$result) {
            return PEAR::raiseError(sprintf(_("Group_ldap: Unable to delete group %s"), $dn));
        }

        return $result;
    }

    /**
     * Searches existing groups for the highest gidnumber, and returns
     * one higher.
     */
    function _nextGid()
    {
        /* Connect to the LDAP server. */
        $success = $this->_connect();
        if (is_a($success, 'PEAR_Error')) {
            return PEAR::raiseError($success->getMessage());
        }

        $search = @ldap_search($this->_ds, $dn, $this->_filter);
        if (!$search) {
            return PEAR::raiseError(_("Could not reach the LDAP server."));
        }

        @ldap_sort($this->_ds, $search, 'gidnumber');
        $result = @ldap_get_entries($this->_ds, $search);
        @ldap_close($this->_ds);

        if (!is_array($result) || (count($result) <= 1)) {
            return 0;
        }

        return $result[$result['count'] - 1]['gidnumber'][0] + 1;
    }

    /**
     * Return a new group object.
     *
     * @param string $name    The group's name.
     * @param string $parent  The group's parent's name.
     *
     * @return LDAP_Group  A new group object.
     */
    function &newGroup($name, $parent = null)
    {
        if (empty($name)) {
            return PEAR::raiseError(_("Group names must be non-empty"));
        }

        global $conf;
        if (!empty($conf['hooks']['groupldap'])) {
            @include HORDE_BASE . '/config/hooks.php';
            if (function_exists('_horde_hook_groupldap')) {
                $entry = call_user_func('_horde_hook_groupldap', $name, $parent);
            }
        } else {
            // Try this simple default and hope it works.
            $entry[$this->_params['gid']] = $name;
            $entry['objectclass'] = $this->_params['newgroup_objectclass'];
            $entry['gidnumber'] = $this->_nextGid();
        }

        $group = &new LDAP_Group($name, $parent);
        $group->_fromAttributes($entry);
        $group->setGroupOb($this);
        return $group;
    }

    /**
     * Return an LDAP_Group object corresponding to the named group, with the
     * users and other data retrieved appropriately.
     *
     * NOTE: getGroupById() should be used where possible instead of
     * getGroup() because group names are potentially non-unique values.
     *
     * @param string $name  The name of the group to retrieve.
     *
     * @return LDAP_Group  The requested group.
     */
    function &getGroup($name)
    {
        $dn = $this->getGroupId($name);
        if (is_a($dn, 'PEAR_Error')) {
            return PEAR::raiseError($dn->getMessage());
        }
        $group = &$this->getGroupById($dn);
        return $group;
    }

    /**
     * Return an LDAP_Object object corresponding to the given dn, with the
     * users and other data retrieved appropriately.
     *
     * @param string $dn  The dn of the group to retrieve.
     *
     * @return LDAP_Object  The requested group.
     */
    function &getGroupById($dn)
    {
        static $cache;

        if (!is_array($cache)) {
            $cache = array();
        }

        if (!isset($cache[$dn])) {
            /* Connect to the LDAP server. */
            $success = $this->_connect();
            if (is_a($success, 'PEAR_Error')) {
                return PEAR::raiseError($success->getMessage());
            }

            $search = @ldap_search($this->_ds, $dn, $this->_filter);
            if (!$search) {
                return PEAR::raiseError(_("Could not reach the LDAP server."));
            }

            $result = @ldap_get_entries($this->_ds, $search);
            @ldap_close($this->_ds);
            if (!is_array($result) || (count($result) <= 1)) {
                return PEAR::raiseError(_("Empty result."));
            }

            $attributes = array();
            for ($i = 0; $i < $result[0]['count']; $i++) {
                if ($result[0][$result[0][$i]]['count'] > 1) {
                    $attributes[$result[0][$i]] = array();
                    for ($j = 0; $j < $result[0][$result[0][$i]]['count']; $j++) {
                        $attributes[$result[0][$i]][] = $result[0][$result[0][$i]][$j];
                    }
                } else {
                    $attributes[$result[0][$i]] = $result[0][$result[0][$i]][0];
                }
            }
            $attributes['dn'] = $result[0]['dn'];

            $group = new LDAP_Group($this->getGroupName($dn));
            $group->_fromAttributes($attributes);
            $group->setGroupOb($this);
            $cache[$dn] = $group;
        }
        return $cache[$dn];
    }

    /**
     * Get a globally unique ID for a group.  This really just returns the dn
     * for the group, but is included for compatibility with the Group class.
     *
     * @param LDAP_Object $group  The group.
     *
     * @return string  a GUID referring to $group.
     */
    function getGUID($group)
    {
        return $group->get('dn');
    }

    /**
     * Add a group to the groups system.  The group must first be created with
     * Group_ldap::newGroup(), and have any initial users added to it, before
     * this function is called.
     *
     * @param LDAP_Group $group  The new group object.
     *
     * @return mixed  True if successful, PEAR_Error otherwise.
     */
    function addGroup($group)
    {
        if (!is_a($group, 'DataTreeObject_Group')) {
            return PEAR::raiseError('Groups must be DataTreeObject_Group objects or extend that class.');
        }

        /* Connect to the LDAP server. */
        $success = $this->_connect();
        if (is_a($success, 'PEAR_Error')) {
            return PEAR::raiseError($success->getMessage());
        }

        $dn = $group->get('dn');

        $entry = $group->_toAttributes();
        $success = @ldap_add($this->_ds, $dn, $entry);

        if (!$success) {
            return PEAR::raiseError(sprintf(_("Group_ldap: Unable to add group %s. This is what the server said: "), $group->getName()) . @ldap_error($this->_ds));
        }

        @ldap_close($this->_ds);

        return true;
    }

    /**
     * Store updated data - users, etc. - of a group to the backend system.
     *
     * @param LDAP_Object $group  The group to update
     *
     * @return mixed  True on success, PEAR_Error otherwise.
     */
    function updateGroup($group)
    {
        if (!is_a($group, 'DataTreeObject_Group')) {
            return PEAR::raiseError('Groups must be DataTreeObject_Group objects or extend that class.');
        }

        $entry = $group->_toAttributes();

        /* Connect to the LDAP server. */
        $success = $this->_connect();
        if (is_a($success, 'PEAR_Error')) {
            return PEAR::raiseError($success->getMessage());
        }

        $result = @ldap_modify($this->_ds, $group->getId(), $entry);
        if (!$result) {
            return PEAR::raiseError(sprintf(_("Group_ldap: Unable to update group %s"), $group->getName()));
        }

        @ldap_close($this->_ds);

        /* Log the update of the group users on the history log. */
        $history = &Horde_History::singleton();
        $guid = $this->getGUID($group);
        foreach ($group->getAuditLog() as $userId => $action) {
            $history->log($guid, array('action' => $action, 'user' => $userId), true);
        }
        $group->clearAuditLog();

        /* Log the group modification. */
        $history->log($guid, array('action' => 'modify'), true);
        return $result;
    }

    /**
     * Change the name of a group.
     *
     * @param DataTreeObject_Group $group  The group to rename.
     * @param string $newName              The group's new name.
     */
    function renameGroup($group, $newName)
    {
        if (!is_a($group, 'DataTreeObject_Group')) {
            return PEAR::raiseError('Groups must be DataTreeObject_Group objects or extend that class.');
        }

        $group->set($this->_params['gid'], $newName);
        $entry = $group->_toAttributes();

        /* Connect to the LDAP server. */
        $success = $this->_connect();
        if (is_a($success, 'PEAR_Error')) {
            return PEAR::raiseError($success->getMessage());
        }

        $result = @ldap_modify($this->_ds, $group->getId(), $entry);
        if (!$result) {
            return PEAR::raiseError(sprintf(_("Group_ldap: Unable to update group %s"), $group->getName()));
        }

        @ldap_close($this->_ds);

        /* History Log the name change of the group. */
        $history = &Horde_History::singleton();
        $history->log($group->get('dn'), array('action' => 'rename'), true);
        return $result;

    }

    /**
     * Remove a group from the groups system permanently.
     *
     * @param LDAP_Group $group  The group to remove.
     * @param boolean $force     Recursively delete children groups if true.
     *
     * @return mixed  True on success, PEAR_Error otherwise.
     */
    function removeGroup($group, $force = false)
    {
        if (!is_a($group, 'DataTreeObject_Group')) {
            return PEAR::raiseError('Groups must be DataTreeObject_Group objects or extend that class.');
        }

        $dn = $group->getId();

        /* Connect to the LDAP server. */
        $success = $this->_connect();
        if (is_a($success, 'PEAR_Error')) {
            return PEAR::raiseError($success->getMessage());
        }

        if ($force) {
            return $this->_recursive_delete($dn);
        } else {
            $result = @ldap_delete($this->_ds, $dn);
            if (!$result) {
                return PEAR::raiseError(sprintf(_("Group_ldap: Unable to delete group %s"), $dn));
            }
        }
    }

    /**
     * Retrieve the name of a group.
     *
     * @param string $dn  The dn of the group to retrieve the name for.
     *
     * @return string  The group's name.
     */
    function getGroupName($dn)
    {
        $result = ldap_explode_dn($dn, 1);
        return $result[0];
    }

    /**
     * DataTreeObject full names include references to parents, but LDAP does
     * not have this concept.  This function simply returns the $group
     * parameter and is included for compatibility with the Group class.
     *
     * @param string $group  Group name.
     *
     * @return string  $group.
     */
    function getGroupShortName($group)
    {
        return $group;
    }

    /**
     * Retrieve the ID of the given group.
     *
     * NOTE: If given a group name, this function can be unreliable if more
     * than one group exists with the same name.
     *
     * @param mixed $group   LDAP_Group object, or a group name (string)
     *
     * @return string  The group's ID.
     */
    function getGroupId($group)
    {
        if (is_a($group, 'LDAP_Group')) {
            return $group->get('dn');
        }

        static $cache;

        if (!is_array($cache)) {
            $cache = array();
        }

        if (!isset($cache[$group])) {
            $this->_connect();
            $search = @ldap_search($this->_ds, $this->_params['basedn'],
                                   $this->_params['gid'] . '=' . $group,
                                   array($this->_params['gid']));
            if (!$search) {
                return PEAR::raiseError(_("Could not reach the LDAP server."));
            }

            $result = @ldap_get_entries($this->_ds, $search);
            @ldap_close($this->_ds);
            if (!is_array($result) || (count($result) <= 1)) {
                return PEAR::raiseError(_("Empty result."));
            }
            $cache[$group] = $result[0]['dn'];
        }

        return $cache[$group];
    }

    /**
     * Check if a group exists in the system.
     *
     * @param string $group  The group name to check for.
     *
     * @return boolean  True if the group exists, False otherwise.
     */
    function exists($group)
    {
        static $cache;

        if (!is_array($cache)) {
            $cache = array();
        }

        if (!isset($cache[$group])) {
            /* Connect to the LDAP server. */
            $success = $this->_connect();
            if (is_a($success, 'PEAR_Error')) {
                return PEAR::raiseError($success->getMessage());
            }

            $search = @ldap_search($this->_ds, $dn, '(&' . $this->_filter . '(' . $this->_params['gid'] . '=' . $group . '))');
            if (!$search) {
                return PEAR::raiseError(_("Could not reach the LDAP server."));
            }

            $result = @ldap_get_entries($this->_ds, $search);
            @ldap_close($this->_ds);
            $cache[$group] = (is_array($result) && (count($result > 1)));
        }

        return $cache[$group];
    }

    /**
     * Get a list of the parents of a child group.
     *
     * @param string $dn  The dn of the child group.
     *
     * @return array  The dn and name of the parent group.
     */
    function getGroupParents($dn)
    {
        $parent = $this->getGroupParent($dn);
        return array($parent => $this->getGroupName($parent));
    }

    /**
     * Get the parent of the given group.
     *
     * @param string $dn  The dn of the child group.
     *
     * @return string  The dn of the parent group.
     */
    function getGroupParent($dn)
    {
        $result = ldap_explode_dn($dn, 0);
        unset($result['count']);
        unset($result[0]);
        $parent_dn = implode(',', $result);

        if ($parent_dn == $GLOBALS['conf']['group']['params']['basedn']) {
            return DATATREE_ROOT;
        } else {
            return $parent_dn;
        }
    }

    /**
     * Get a list of parents all the way up to the root object for the given
     * group.
     *
     * @param string $dn  The dn of the group.
     *
     * @return array  A flat list of all of the parents of the given group,
     *                hashed in $dn => $name format.
     */
    function getGroupParentList($dn)
    {
        $result = ldap_explode_dn($dn, 0);
        $num = $result['count'];

        unset($result['count']);
        unset($result[0]);

        $count = 0;
        $parents = array();
        $parent_dn = implode(',', $result);
        while ($parent_dn != $this->_params['basedn'] && $count++ != $num) {
            $parents[$parent_dn] = $this->getGroupName($parent_dn);
            unset($result[$count]);
            $parent_dn = implode(',', $result);
        }
        $parents[DATATREE_ROOT] = DATATREE_ROOT;

        return $parents;
    }

    /**
     * Get a list of every group, in the format dn => groupname.
     *
     * @param boolean $refresh  If true, the cached value is ignored and the
     *                          group list is refreshed from the group backend.
     *
     * @return array  dn => groupname hash.
     */
    function listGroups($refresh = false)
    {
        static $groups;

        if ($refresh || is_null($groups)) {
            /* Connect to the LDAP server. */
            $success = $this->_connect();
            if (is_a($success, 'PEAR_Error')) {
                return PEAR::raiseError($success->getMessage());
            }

            $search = @ldap_search($this->_ds, $this->_params['basedn'], $this->_filter, array($this->_params['gid']));
            if (!$search) {
                return PEAR::raiseError(_("Could not reach the LDAP server."));
            }

            @ldap_sort($this->_ds, $search, $this->_params['gid']);

            $result = @ldap_get_entries($this->_ds, $search);
            @ldap_close($this->_ds);
            if (!is_array($result) || (count($result) <= 1)) {
                return array();
            }

            $groups = array();
            for ($i = 0; $i < $result['count']; $i++) {
                $groups[$result[$i]['dn']] = $result[$i][$this->_params['gid']][0];
            }
        }

        return $groups;
    }

    /**
     * Get a list of every user that is part of the specified group and any
     * of its subgroups.
     *
     * @param string $dn  The dn of the parent group.
     *
     * @return array  The complete user list.
     */
    function listAllUsers($dn)
    {
        static $cache;

        if (!is_array($cache)) {
            $cache = array();
        }

        if (!isset($cache[$dn])) {
            $success = $this->_connect();
            if (is_a($success, 'PEAR_Error')) {
                return PEAR::raiseError($success->getMessage());
            }

            $search = @ldap_search($this->_ds, $this->getGroupParent($dn), $this->_filer);
            if (!$search) {
                return PEAR::raiseError(_("Could not reach the LDAP server."));
            }

            $result = @ldap_get_entries($this->_ds, $search);
            @ldap_close($this->_ds);
            if (!is_array($result) || (count($result) <= 1)) {
                return PEAR::raiseError(_("Empty result."));
            }

            $users = array();
            for ($i = 0; $i < $result['count']; $i++) {
                for ($j = 0; $j < $result[$i][$this->_params['memberuid']]['count']; $j++) {
                    $users[] = $result[$i][$this->_params['memberuid']][$j];
                }
            }

            $cache[$dn] = array_unique($users);
        }

        return $cache[$dn];
    }

    /**
     * Get a list of every group that the given user is a member of.
     *
     * @param string  $user          The user to get groups for.
     * @param boolean $parentGroups  Also return the parents of any groups?
     *
     * @return array  An array of all groups the user is in.
     */
    function getGroupMemberships($user, $parentGroups = false)
    {
        static $cache;

        if (empty($cache[$user])) {
            /* Connect to the LDAP server. */
            $success = $this->_connect();
            if (is_a($success, 'PEAR_Error')) {
                return PEAR::raiseError($success->getMessage());
            }

            $search = @ldap_search($this->_ds, $this->_params['basedn'], '(' . $this->_params['memberuid'] . '=' . $user . ')');
            if (!$search) {
                return PEAR::raiseError(_("Could not reach the LDAP server."));
            }

            $result = @ldap_get_entries($this->_ds, $search);
            @ldap_close($this->_ds);
            if (!is_array($result) || (count($result) <= 1)) {
                return PEAR::raiseError(_("Empty result."));
            }

            $groups = array();
            for ($i = 0; $i < $result['count']; $i++) {
                $groups[$result[$i]['dn']] = $result[$i][$this->_params['gid']][0];
            }

            $cache[$user] = $groups;
        }

        return $cache[$user];
    }

    /**
     * Returns the tree depth of the given group, relative to the base dn.
     * 0 is returned for any object directly below the base dn.
     *
     * @param string $dn  The dn of the object.
     *
     * @return intenger  The tre depth of the group.
     */
    function getLevel($dn)
    {
        $base = @ldap_explode_dn($this->_params['basedn'], 0);
        $group = @ldap_explode_dn($dn, 0);
        return $group['count'] - $base['count'] - 1;
    }

}

/**
 * Extension of the DataTreeObject_Group class for storing group information
 * in an LDAP directory.
 *
 * @author  Ben Chavet <ben@horde.org>
 * @since   Horde 3.1
 * @package Horde_Group
 */
class LDAP_Group extends DataTreeObject_Group {

    /**
     * Constructor.
     *
     * @param string $name    The name of this group.
     * @param string $parent  The dn of the parent of this group.
     */
    function LDAP_Group($name, $parent = null)
    {
        parent::DataTreeObject_Group($name);
        if ($parent) {
            $this->data['dn'] = strtolower($GLOBALS['conf']['group']['params']['gid']) . '=' . $name . ',' . $parent;
        } else {
            $this->data['dn'] = strtolower($GLOBALS['conf']['group']['params']['gid']) . '=' . $name .
                ',' . strtolower($GLOBALS['conf']['group']['params']['basedn']);
        }
    }

    /**
     * Get a list of every user that is part of this group (and only
     * this group).
     *
     * @return array  The user list.
     */
    function listUsers()
    {
        return $this->_groupOb->listUsers($this->data['dn']);
    }

    /**
     * Get a list of every user that is a member of this group and any of
     * it's subgroups.
     *
     * @return array  The complete user list.
     */
    function listAllUsers()
    {
        return $this->_groupOb->listAllUsers($this->data['dn']);
    }

    /**
     * Take in a list of attributes from the backend and map it to our
     * internal data array.
     *
     * @param array $attributes  The list of attributes from the backend.
     */
    function _fromAttributes($attributes = array())
    {
        $this->data['users'] = array();
        foreach ($attributes as $key => $value) {
            if ($key == strtolower($GLOBALS['conf']['group']['params']['memberuid'])) {
                if (is_array($value)) {
                    foreach ($value as $user) {
                        $this->data['users'][$user] = '1';
                    }
                } else {
                    $this->data['users'][$value] = '1';
                }
            } elseif ($key == 'mail') {
                $this->data['email'] = $value;
            } else {
                $this->data[$key] = $value;
            }
        }
    }

    /**
     * Map this object's attributes from the data array into a format that
     * can be stored in an LDAP entry.
     *
     * @return array  The entry array.
     */
    function _toAttributes()
    {
        $attributes = array();
        foreach ($this->data as $key => $value) {
            if ($key == 'users') {
                foreach ($value as $user => $membership) {
                    $attributes[strtolower($GLOBALS['conf']['group']['params']['memberuid'])][] = $user;
                }
            } elseif ($key == 'email') {
                $attributes['mail'] = !empty($value) ? $value : ' ';
            } elseif ($key != 'dn' && $key != strtolower($GLOBALS['conf']['group']['params']['memberuid'])) {
                $attributes[$key] = !empty($value) ? $value : ' ';
            }
        }

        return $attributes;
    }

}