File: Group.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 (711 lines) | stat: -rw-r--r-- 20,828 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
<?php

require_once 'Horde/DataTree.php';
require_once 'Horde/History.php';

/**
 * The Group:: class provides the Horde groups system.
 *
 * $Horde: framework/Group/Group.php,v 1.67.2.15 2006/07/17 14:40:19 jan Exp $
 *
 * Copyright 1999-2006 Stephane Huther <shuther@bigfoot.com>
 * Copyright 2001-2006 Chuck Hagenbuch <chuck@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  Stephane Huther <shuther@bigfoot.com>
 * @author  Chuck Hagenbuch <chuck@horde.org>
 * @since   Horde 2.1
 * @package Horde_Group
 */
class Group {

    /**
     * Pointer to a DataTree instance to manage the different groups.
     *
     * @var DataTree
     */
    var $_datatree;

    /**
     * Constructor
     */
    function Group()
    {
        global $conf;

        if (empty($conf['datatree']['driver'])) {
            Horde::fatal('You must configure a DataTree backend to use Groups.', __FILE__, __LINE__);
        }

        $driver = $conf['datatree']['driver'];
        $this->_datatree = &DataTree::singleton($driver,
                                                array_merge(Horde::getDriverConfig('datatree', $driver),
                                                            array('group' => 'horde.groups')));
    }

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

        if ($parent != DATATREE_ROOT) {
            $name = $this->getGroupName($parent) . ':' . DataTree::encodeName($name);
        }

        $group = &new DataTreeObject_Group($name);
        $group->setGroupOb($this);
        return $group;
    }

    /**
     * Return a DataTreeObject_Group object corresponding to the named
     * group, with the users and other data retrieved appropriately.
     *
     * @param string $name The name of the group to retrieve.
     */
    function &getGroup($name)
    {
        /* cache of previous retrieved groups */
        static $groupCache;

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

        if (!isset($groupCache[$name])) {
            $groupCache[$name] = $this->_datatree->getObject($name, 'DataTreeObject_Group');
            if (!is_a($groupCache[$name], 'PEAR_Error')) {
                $groupCache[$name]->setGroupOb($this);
            }
        }

        return $groupCache[$name];
    }

    /**
     * Return a DataTreeObject_Group object corresponding to the given
     * unique ID, with the users and other data retrieved
     * appropriately.
     *
     * @param integer $cid  The unique ID of the group to retrieve.
     */
    function &getGroupById($cid)
    {
        $group = $this->_datatree->getObjectById($cid, 'DataTreeObject_Group');
        if (!is_a($group, 'PEAR_Error')) {
            $group->setGroupOb($this);
        }
        return $group;
    }

    /**
     * Get a globally unique ID for a group.
     *
     * @param DataTreeObject_Group $group  The group.
     *
     * @return string  A GUID referring to $group.
     */
    function getGUID($group)
    {
        return 'horde:group:' . $this->getGroupId($group);
    }

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

        /* Log the addition of the group in the history log. */
        $history = &Horde_History::singleton();
        $log = $history->log($this->getGUID($group), array('action' => 'add'), true);
        if (is_a($log, 'PEAR_Error')) {
            return $log;
        }

        return $result;
    }

    /**
     * Store updated data - users, etc. - of a group to the backend system.
     *
     * @param DataTreeObject_Group $group  The group to update.
     */
    function updateGroup($group)
    {
        if (!is_a($group, 'DataTreeObject_Group')) {
            return PEAR::raiseError('Groups must be DataTreeObject_Group objects or extend that class.');
        }
        $result = $this->_datatree->updateData($group);
        if (is_a($result, 'PEAR_Error')) {
            return $result;
        }

        /* 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 without changing its contents or
     * where it is in the groups hierarchy.
     *
     * @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.');
        }
        $result = $this->_datatree->rename($group, $newName);
        if (is_a($result, 'PEAR_Error')) {
            return $result;
        }

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

    /**
     * Remove a group from the groups system permanently.
     *
     * @param DataTreeObject_Group $group  The group to remove.
     * @param boolean $force               Force to remove every child.
     */
    function removeGroup($group, $force = false)
    {
        if (!is_a($group, 'DataTreeObject_Group')) {
            return PEAR::raiseError('Groups must be DataTreeObject_Group objects or extend that class.');
        }

        $history = &Horde_History::singleton();
        $history->log($this->getGUID($group), array('action' => 'delete'), true);

        return $this->_datatree->remove($group, $force);
    }

    /**
     * Retrieve the name of a group.
     *
     * @param integer $gid  The id of the group to retrieve the name for.
     *
     * @return string  The group's name.
     */
    function getGroupName($gid)
    {
        if (is_a($gid, 'DataTreeObject_Group')) {
            return $this->_datatree->getName($gid->getId());
        } else {
            return $this->_datatree->getName($gid);
        }
    }

    /**
     * Strips all parent references off of the given group name.
     *
     * @param string $group  Name of the group.
     *
     * @return The name of the group without parents.
     */
    function getGroupShortName($group)
    {
        return $this->_datatree->getShortName($group);
    }

    /**
     * Retrieve the ID of a group.
     *
     * @param string $group  The group to retrieve the ID for.
     *
     * @return integer  The group's ID.
     */
    function getGroupId($group)
    {
        if (is_a($group, 'DataTreeObject_Group')) {
            return $this->_datatree->getId($group->getName());
        } else {
            return $this->_datatree->getId($group);
        }
    }

    /**
     * Check if a group exists in the system.
     *
     * @param string $group  The group to check.
     *
     * @return boolean  True if the group exists, false otherwise.
     */
    function exists($group)
    {
        return $this->_datatree->exists($group);
    }

    /**
     * Get a list of the parents of a child group.
     *
     * @param integer $gid The id of the child group.
     *
     * @return array
     */
    function getGroupParents($gid)
    {
        $name = $this->getGroupName($gid);
        return $this->_datatree->getParents($name);
    }

    /**
     * Return the single parent of the given group.
     *
     * @param integer $gid  The DataTree ID of the child group.
     *
     * @return the parent of the given group.
     */
    function getGroupParent($gid)
    {
        return $this->_datatree->getParentById($gid);
    }

    /**
     * Get a list of parents all the way up to the root object for $group.
     *
     * @param integer $gid  The id of the group.
     *
     * @return array  A flat list of all of the parents of $group,
     *                hashed in $id => $name format.
     */
    function getGroupParentList($gid)
    {
        return $this->_datatree->getParentList($gid);
    }

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

        if ($refresh || is_null($groups)) {
            $groups = $this->_datatree->get(DATATREE_FORMAT_FLAT, DATATREE_ROOT, true);
            unset($groups[DATATREE_ROOT]);
        }

        return $groups;
    }

    /**
     * Get a list of every user that is a part of this group ONLY.
     *
     * @param integer $gid  The ID of the group.
     *
     * @return array  The user list.
     */
    function listUsers($gid)
    {
        $groupOb = &$this->getGroupById($gid);
        if (is_a($groupOb, 'PEAR_Error')) {
            return $groupOb;
        }

        if (!isset($groupOb->data['users']) ||
            !is_array($groupOb->data['users'])) {
            return array();
        }

        return array_keys($groupOb->data['users']);
    }

    /**
     * Get a list of every user that is part of the specified group
     * and any of its subgroups.
     *
     * @param integer $group  The ID of the parent group.
     *
     * @return array  The complete user list.
     */
    function listAllUsers($gid)
    {
        // Get a list of every group that is a sub-group of $group.
        $groups = $this->_datatree->get(DATATREE_FORMAT_FLAT, $this->getGroupName($gid), true);
        if (is_a($groups, 'PEAR_Error')) {
            return $groups;
        }

        $groups = array_keys($groups);
        $users = array();
        foreach ($groups as $groupId) {
            $users = array_merge($users, $this->listUsers($groupId));
        }
        return array_values(array_flip(array_flip($users)));
    }

    /**
     * Get a list of every group that $user is in.
     *
     * @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])) {
            $criteria = array(
                'AND' => array(
                    array('field' => 'name', 'op' => '=', 'test' => 'user'),
                    array('field' => 'key', 'op' => '=', 'test' => $user)));
            $groups = $this->_datatree->getByAttributes($criteria);

            if (is_a($groups, 'PEAR_Error')) {
                Horde::logMessage($groups, __FILE__, __LINE__, PEAR_LOG_ERROR);
                return false;
            }

            if ($parentGroups) {
                foreach ($groups as $id => $g) {
                    $parents = $this->_datatree->getParentList($id);
                    if (is_a($parents, 'PEAR_Error')) {
                        return $parents;
                    }
                    $groups += $parents;
                }
            }

            $cache[$user] = $groups;
        }

        return $cache[$user];
    }

    /**
     * Say if a user is a member of a group or not.
     *
     * @param string $user        The name of the user.
     * @param integer $gid        The ID of the group.
     * @param boolean $subgroups  Return true if the user is in any subgroups
     *                            of group with ID $gid, also.
     *
     * @return boolean
     */
    function userIsInGroup($user, $gid, $subgroups = true)
    {
        if (!$this->exists($this->getGroupName($gid))) {
            return false;
        } elseif ($subgroups) {
            $groups = $this->getGroupMemberships($user, true);
            if (is_a($groups, 'PEAR_Error')) {
                Horde::logMessage($groups, __FILE__, __LINE__, PEAR_LOG_ERR);
                return false;
            }

            return !empty($groups[$gid]);
        } else {
            $users = $this->listUsers($gid);
            if (is_a($users, 'PEAR_Error')) {
                Horde::logMessage($users, __FILE__, __LINE__, PEAR_LOG_ERR);
                return false;
            }
            return in_array($user, $users);
        }
    }

    /**
     * Returns the DataTree level of the given group. 0 is returned for
     * and object directly below DATATREE_ROOT.
     *
     * @param integer $gid  The DataTree ID of the group.
     *
     * @return The DataTree level of the group.
     */
    function getLevel($gid)
    {
        $name = $this->_datatree->getName($gid);
        return substr_count($name, ':');
    }

    /**
     * Attempts to return a concrete Group instance based on $driver.
     *
     * @param mixed $driver  The type of concrete Group subclass to return.
     * @param array $params  A hash containing any additional configuration or
     *                       connection parameters a subclass might need.
     *
     * @return Group  The newly created concrete Group instance, or a
     *                PEAR_Error object on an error.
     */
    function &factory($driver = '', $params = null)
    {
        $driver = basename($driver);

        if (@file_exists(dirname(__FILE__) . '/Group/' . $driver . '.php')) {
            require_once dirname(__FILE__) . '/Group/' . $driver . '.php';
        } else {
            @include_once 'Horde/Group/' . $driver . '.php';
        }
        $class = 'Group_' . $driver;
        if (class_exists($class)) {
            $group = &new $class($params);
        } else {
            $group = PEAR::raiseError('Class definition of ' . $class . ' not found.');
        }

        return $group;
    }

    /**
     * Attempts to return a reference to a concrete Group instance.
     * It will only create a new instance if no Group instance
     * currently exists.
     *
     * This method must be invoked as: $var = &Group::singleton()
     *
     * @return Group  The concrete Group reference, or false on an error.
     */
    function &singleton()
    {
        static $group;

        if (!isset($group)) {
            global $conf;

            require_once 'Horde/Auth.php';
            $auth = &Auth::singleton($conf['auth']['driver']);
            if ($auth->hasCapability('groups')) {
                $group = &Group::factory($auth->getDriver(), $auth);
            } elseif (!empty($conf['group']['driver']) && $conf['group']['driver'] != 'datatree') {
                $group = &Group::factory($conf['group']['driver']);
            } else {
                $group = new Group();
            }
        }

        return $group;
    }

}

/**
 * Extension of the DataTreeObject class for storing Group information
 * in the Categories driver. If you want to store specialized Group
 * information, you should extend this class instead of extending
 * DataTreeObject directly.
 *
 * @author  Chuck Hagenbuch <chuck@horde.org>
 * @since   Horde 2.1
 * @package Horde_Group
 */
class DataTreeObject_Group extends DataTreeObject {

    /**
     * The Group object which this group is associated with - needed
     * for updating data in the backend to make changes stick, etc.
     *
     * @var Group
     */
    var $_groupOb;

    /**
     * This variable caches the users added or removed from the group
     * for History logging of user-groups relationship.
     *
     * @var array
     */
    var $_auditLog = array();

    /**
     * The DataTreeObject_Group constructor. Just makes sure to call
     * the parent constructor so that the group's name is set
     * properly.
     *
     * @param string $name  The name of the group.
     */
    function DataTreeObject_Group($name)
    {
        parent::DataTreeObject($name);
    }

    /**
     * Associates a Group object with this group.
     *
     * @param Group $groupOb  The Group object.
     */
    function setGroupOb(&$groupOb)
    {
        $this->_groupOb = &$groupOb;
    }

    /**
     * Fetch the ID of this group
     *
     * @return string The group's ID
     */
    function getId()
    {
        return $this->_groupOb->getGroupId($this);
    }

    /**
     * Save any changes to this object to the backend permanently.
     */
    function save()
    {
        return $this->_groupOb->updateGroup($this);

    }

    /**
     * Adds a user to this group, and makes sure that the backend is
     * updated as well.
     *
     * @param string $username The user to add.
     */
    function addUser($username, $update = true)
    {
        $this->data['users'][$username] = 1;
        $this->_auditLog[$username] = 'addUser';
        if ($update && $this->_groupOb->exists($this->getName())) {
            return $this->save();
        }
    }

    /**
     * Removes a user from this group, and makes sure that the backend
     * is updated as well.
     *
     * @param string $username The user to remove.
     */
    function removeUser($username, $update = true)
    {
        unset($this->data['users'][$username]);
        $this->_auditLog[$username] = 'deleteUser';
        if ($update) {
            return $this->save();
        }
    }

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

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

    /**
     * Get all the users recently added or removed from the group.
     */
    function getAuditLog()
    {
        return $this->_auditLog;
    }

    /**
     * Clears the audit log. To be called after group update.
     */
    function clearAuditLog()
    {
        $this->_auditLog = array();
    }

    /**
     * Map this object's attributes from the data array into a format
     * that we can store in the attributes storage backend.
     *
     * @return array  The attributes array.
     */
    function _toAttributes()
    {
        // Default to no attributes.
        $attributes = array();

        // Loop through all users, if any.
        if (isset($this->data['users']) && is_array($this->data['users']) && count($this->data['users'])) {
            foreach ($this->data['users'] as $user => $active) {
                $attributes[] = array('name' => 'user',
                                      'key' => $user,
                                      'value' => $active);
            }
        }
        $attributes[] = array('name' => 'email',
                              'key' => '',
                              'value' => $this->get('email'));

        return $attributes;
    }

    /**
     * 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 (attribute name, key, and value).
     */
    function _fromAttributes($attributes)
    {
        // Initialize data array.
        $this->data['users'] = array();

        foreach ($attributes as $attr) {
            if ($attr['name'] == 'user') {
                $this->data['users'][$attr['key']] = $attr['value'];
            } else {
                $this->data[$attr['name']] = $attr['value'];
            }
        }
    }

}