]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/WikiGroup.php
Disable default options in config-dist.ini
[SourceForge/phpwiki.git] / lib / WikiGroup.php
1 <?php
2 rcs_id('$Id: WikiGroup.php,v 1.44 2004-11-11 10:31:26 rurban Exp $');
3 /*
4  Copyright (C) 2003, 2004 $ThePhpWikiProgrammingTeam
5
6  This file is part of PhpWiki.
7
8  PhpWiki is free software; you can redistribute it and/or modify
9  it under the terms of the GNU General Public License as published by
10  the Free Software Foundation; either version 2 of the License, or
11  (at your option) any later version.
12
13  PhpWiki is distributed in the hope that it will be useful,
14  but WITHOUT ANY WARRANTY; without even the implied warranty of
15  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  GNU General Public License for more details.
17
18  You should have received a copy of the GNU General Public License
19  along with PhpWiki; if not, write to the Free Software
20  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
21  */
22
23 if (!defined('GROUP_METHOD') or 
24     !in_array(GROUP_METHOD,
25               array('NONE','WIKIPAGE','DB','FILE','LDAP')))
26     trigger_error(_("No or unsupported GROUP_METHOD defined"), E_USER_WARNING);
27     
28 /* Special group names for ACL */    
29 define('GROUP_EVERY',           _("Every"));
30 define('GROUP_ANONYMOUS',       _("Anonymous Users"));
31 define('GROUP_BOGOUSER',        _("Bogo Users"));
32 define('GROUP_HASHOMEPAGE',     _("HasHomePage"));
33 define('GROUP_SIGNED',          _("Signed Users"));
34 define('GROUP_AUTHENTICATED',   _("Authenticated Users"));
35 define('GROUP_ADMIN',           _("Administrators"));
36 define('GROUP_OWNER',           _("Owner"));
37 define('GROUP_CREATOR',         _("Creator"));
38
39 /**
40  * WikiGroup is an abstract class to provide the base functions for determining
41  * group membership for a specific user. Some functions are user independent.
42  *
43  * Limitation: For the current user only. This must be fixed to be able to query 
44  * for membership of any user.
45  * 
46  * WikiGroup is an abstract class with three functions:
47  * <ol><li />Provide the static method getGroup with will return the proper
48  *         subclass.
49  *     <li />Provide an interface for subclasses to implement.
50  *     <li />Provide fallover methods (with error msgs) if not impemented in subclass.
51  * </ol>
52  * Do not ever instantiate this class. Use: $group = &WikiGroup::getGroup();
53  * This will instantiate the proper subclass.
54  *
55  * @author Joby Walker <zorloc@imperium.org>
56  * @author Reini Urban
57  */ 
58 class WikiGroup{
59     /** User name */
60     var $username = '';
61     /** User object if different from current user */
62     var $user;
63     /** The global WikiRequest object */
64     //var $request;
65     /** Array of groups $username is confirmed to belong to */
66     var $membership;
67     /** boolean if not the current user */
68     var $not_current = false;
69     
70     /**
71      * Initializes a WikiGroup object which should never happen.  Use:
72      * $group = &WikiGroup::getGroup();
73      * @param object $request The global WikiRequest object -- ignored.
74      */ 
75     function WikiGroup($not_current = false) {
76         $this->not_current = $not_current;
77         //$this->request =& $GLOBALS['request'];
78     }
79
80     /**
81      * Gets the current username from the internal user object
82      * and erases $this->membership if is different than
83      * the stored $this->username
84      * @return string Current username.
85      */ 
86     function _getUserName(){
87         global $request;
88         $user = (!empty($this->user)) ? $this->user : $request->getUser();
89         $username = $user->getID();
90         if ($username != $this->username) {
91             $this->membership = array();
92             $this->username = $username;
93         }
94         if (!$this->not_current)
95            $this->user = $user;
96         return $username;
97     }
98     
99     /**
100      * Static method to return the WikiGroup subclass used in this wiki.  Controlled
101      * by the constant GROUP_METHOD.
102      * @param object $request The global WikiRequest object.
103      * @return object Subclass of WikiGroup selected via GROUP_METHOD.
104      */ 
105     function getGroup($not_current = false){
106         switch (GROUP_METHOD){
107             case "NONE": 
108                 return new GroupNone($not_current);
109                 break;
110             case "WIKIPAGE":
111                 return new GroupWikiPage($not_current);
112                 break;
113             case "DB":
114                 if ($GLOBALS['DBParams']['dbtype'] == 'ADODB') {
115                     return new GroupDB_ADODB($not_current);
116                 } elseif ($GLOBALS['DBParams']['dbtype'] == 'SQL') {
117                     return new GroupDb_PearDB($not_current);
118                 } else {
119                     trigger_error("GROUP_METHOD = DB: Unsupported dbtype " 
120                                   . $GLOBALS['DBParams']['dbtype'],
121                                   E_USER_ERROR);
122                 }
123                 break;
124             case "FILE": 
125                 return new GroupFile($not_current);
126                 break;
127             case "LDAP": 
128                 return new GroupLDAP($not_current);
129                 break;
130             default:
131                 trigger_error(_("No or unsupported GROUP_METHOD defined"), E_USER_WARNING);
132                 return new WikiGroup($not_current);
133         }
134     }
135
136     /** ACL PagePermissions will need those special groups based on the User status only.
137      *  translated 
138      */
139     function specialGroup($group){
140         return in_array($group,$this->specialGroups());
141     }
142     /** untranslated */
143     function _specialGroup($group){
144         return in_array($group,$this->_specialGroups());
145     }
146     /** translated */
147     function specialGroups(){
148         return array(
149                      GROUP_EVERY,
150                      GROUP_ANONYMOUS,
151                      GROUP_BOGOUSER,
152                      GROUP_SIGNED,
153                      GROUP_AUTHENTICATED,
154                      GROUP_ADMIN);
155     }
156     /** untranslated */
157     function _specialGroups(){
158         return array(
159                      "_EVERY",
160                      "_ANONYMOUS",
161                      "_BOGOUSER",
162                      "_SIGNED",
163                      "_AUTHENTICATED",
164                      "_ADMIN");
165     }
166
167     /**
168      * Determines if the current user is a member of a group.
169      * 
170      * This method is an abstraction.  The group is ignored, an error is sent, and
171      * false (not a member of the group) is returned.
172      * @param string $group Name of the group to check for membership (ignored).
173      * @return boolean True if user is a member, else false (always false).
174      */ 
175     function isMember($group){
176         if (isset($this->membership[$group]))
177             return $this->membership[$group];
178         if ($this->specialGroup($group)) {
179             return $this->isSpecialMember($group);
180         } else {
181             trigger_error(__sprintf("Method '%s' not implemented in this GROUP_METHOD %s",
182                                     'isMember', GROUP_METHOD),
183                           E_USER_WARNING);
184         }
185         return false;
186     }
187
188     function isSpecialMember($group){
189         global $request;
190
191         if (isset($this->membership[$group]))
192             return $this->membership[$group];
193         $user = (!empty($this->user)) ? $this->user : $request->getUser();
194         switch ($group) {
195             case GROUP_EVERY:           
196                 return $this->membership[$group] = true;
197             case GROUP_ANONYMOUS:       
198                 return $this->membership[$group] = ! $user->isSignedIn();
199             case GROUP_BOGOUSER:        
200                 return $this->membership[$group] = (isa($user,'_BogoUser') 
201                                                     and $user->_level >= WIKIAUTH_BOGO);
202             case GROUP_SIGNED:          
203                 return $this->membership[$group] = $user->isSignedIn();
204             case GROUP_AUTHENTICATED:   
205                 return $this->membership[$group] = $user->isAuthenticated();
206             case GROUP_ADMIN:           
207                 return $this->membership[$group] = (isset($user->_level) 
208                                                     and $user->_level == WIKIAUTH_ADMIN);
209             default:
210                 trigger_error(__sprintf("Undefined method %s for special group %s",
211                                         'isMember',$group),
212                               E_USER_WARNING);
213         }
214         return false;
215     }
216     
217     /**
218      * Determines all of the groups of which the current user is a member.
219      * 
220      * This method is an abstraction.  An error is sent and an empty 
221      * array is returned.
222      * @return array Array of groups to which the user belongs (always empty).
223      */ 
224     function getAllGroupsIn(){
225         trigger_error(__sprintf("Method '%s' not implemented in this GROUP_METHOD %s",
226                                 'getAllGroupsIn', GROUP_METHOD),
227                       E_USER_WARNING);
228         return array();
229     }
230
231     function _allUsers() {
232         static $result = array();
233         if (!empty($result))
234                 return $result;
235
236         global $request;
237         /* WikiPage users: */
238         $dbh =& $request->_dbi;
239         $page_iter = $dbh->getAllPages();
240         $users = array();
241         while ($page = $page_iter->next()) {
242             if ($page->isUserPage())
243                 $users[] = $page->_pagename;
244         }
245
246         /* WikiDB users from prefs (not from users): */
247         if (ENABLE_USER_NEW)
248             $dbi = _PassUser::getAuthDbh();
249         else 
250             $dbi = false;
251
252         if ($dbi and $dbh->getAuthParam('pref_select')) {
253             //get prefs table
254             $sql = preg_replace('/SELECT .+ FROM/i','SELECT userid FROM',
255                                 $dbh->getAuthParam('pref_select'));
256             //don't strip WHERE, only the userid stuff.
257             $sql = preg_replace('/(WHERE.*?)\s+\w+\s*=\s*["\']\$userid[\'"]/i','\\1 AND 1', $sql);
258             $sql = str_replace('WHERE AND 1','',$sql);
259             if (isa($dbi, 'WikiDB_backend_ADODB')) {
260                 $db_result = $dbi->Execute($sql);
261                 foreach ($db_result->GetArray() as $u) {
262                     $users = array_merge($users,array_values($u));
263                 }
264             } elseif (isa($dbi, 'WikiDB_backend_PearDB')) {
265                 $users = array_merge($users,$dbi->getCol($sql));
266             }
267         }
268
269         /* WikiDB users from users: */
270         // Fixme: don't strip WHERE, only the userid stuff.
271         if ($dbi and $dbh->getAuthParam('auth_user_exists')) {
272             //don't strip WHERE, only the userid stuff.
273             $sql = preg_replace('/(WHERE.*?)\s+\w+\s*=\s*["\']\$userid[\'"]/i','\\1 AND 1',
274                                 $dbh->getAuthParam('auth_user_exists'));
275             $sql = str_replace('WHERE AND 1','', $sql);
276             if (isa($dbi, 'WikiDB_backend_ADODB')) {
277                 $db_result = $dbi->Execute($sql);
278                 foreach ($db_result->GetArray() as $u) {
279                    $users = array_merge($users, array_values($u));
280                 }
281             } elseif (isa($dbi, 'WikiDB_backend_PearDB')) {
282                 $users = array_merge($users, $dbi->getCol($sql));
283             }
284         }
285
286         // remove empty and duplicate users
287         $result = array();
288         foreach ($users as $u) {
289             if (empty($u) or in_array($u,$result)) continue;
290             $result[] = $u;
291         }
292         return $result;
293     }
294
295     /**
296      * Determines all of the members of a particular group.
297      * 
298      * This method is an abstraction.  The group is ignored, an error is sent, 
299      * and an empty array is returned
300      * @param string $group Name of the group to get the full membership list of.
301      * @return array Array of usernames that have joined the group (always empty).
302      */ 
303     function getMembersOf($group){
304         if ($this->specialGroup($group)) {
305             return getSpecialMembersOf($group);
306         }
307         trigger_error(__sprintf("Method '%s' not implemented in this GROUP_METHOD %s",
308                                 'getMembersOf', GROUP_METHOD),
309                       E_USER_WARNING);
310         return array();
311     }
312                 
313     function getSpecialMembersOf($group) {
314         //$request = &$this->request;
315         $all = $this->_allUsers();
316         $users = array();
317         switch ($group) {
318         case GROUP_EVERY:
319             return $all;
320         case GROUP_ANONYMOUS:   
321             return $users;
322         case GROUP_BOGOUSER:
323             foreach ($all as $u) {
324                 if (isWikiWord($user)) $users[] = $u;
325             }
326             return $users;
327         case GROUP_SIGNED:      
328             foreach ($all as $u) {
329                 $user = WikiUser($u);
330                 if ($user->isSignedIn()) $users[] = $u;
331             }
332             return $users;
333         case GROUP_AUTHENTICATED:
334             foreach ($all as $u) {
335                 $user = WikiUser($u);
336                 if ($user->isAuthenticated()) $users[] = $u;
337             }
338             return $users;
339         case GROUP_ADMIN:               
340             foreach ($all as $u) {
341                 $user = WikiUser($u);
342                 if (isset($user->_level) and $user->_level == WIKIAUTH_ADMIN) 
343                     $users[] = $u;
344             }
345             return $users;
346         default:
347             trigger_error(__sprintf("Unknown special group '%s'", $group),
348                           E_USER_WARNING);
349         }
350     }
351
352     /**
353      * Add the current or specified user to a group.
354      * 
355      * This method is an abstraction.  The group and user are ignored, an error 
356      * is sent, and false (not added) is always returned.
357      * @param string $group User added to this group.
358      * @param string $user Username to add to the group (default = current user).
359      * @return bool On true user was added, false if not.
360      */ 
361     function setMemberOf($group, $user = false){
362         trigger_error(__sprintf("Method '%s' not implemented in this GROUP_METHOD %s",
363                                 'setMemberOf', GROUP_METHOD),
364                       E_USER_WARNING);
365         return false;
366     }
367     
368     /**
369      * Remove the current or specified user to a group.
370      * 
371      * This method is an abstraction.  The group and user are ignored, and error
372      * is sent, and false (not removed) is always returned.
373      * @param string $group User removed from this group.
374      * @param string $user Username to remove from the group (default = current user).
375      * @return bool On true user was removed, false if not.
376      */ 
377     function removeMemberOf($group, $user = false){
378         trigger_error(__sprintf("Method '%s' not implemented in this GROUP_METHOD %s",
379                                 'removeMemberOf', GROUP_METHOD),
380                       E_USER_WARNING);
381         return false;
382     }
383 }
384
385 /**
386  * GroupNone disables all Group funtionality
387  * 
388  * All of the GroupNone functions return false or empty values to indicate failure or 
389  * no results.  Use GroupNone if group controls are not desired.
390  * @author Joby Walker <zorloc@imperium.org>
391  */ 
392 class GroupNone extends WikiGroup{
393
394     /**
395      * Constructor
396      * 
397      * Ignores the parameter provided.
398      * @param object $request The global WikiRequest object - ignored.
399      */ 
400     function GroupNone() {
401         //$this->request = &$GLOBALS['request'];
402         return;
403     }    
404
405     /**
406      * Determines if the current user is a member of a group.
407      * 
408      * The group is ignored and false (not a member of the group) is returned.
409      * @param string $group Name of the group to check for membership (ignored).
410      * @return boolean True if user is a member, else false (always false).
411      */ 
412     function isMember($group){
413         if ($this->specialGroup($group)) {
414             return $this->isSpecialMember($group);
415         } else {
416             return false;
417         }
418     }
419     
420     /**
421      * Determines all of the groups of which the current user is a member.
422      * 
423      * The group is ignored and an empty array (a member of no groups) is returned.
424      * @param string $group Name of the group to check for membership (ignored).
425      * @return array Array of groups to which the user belongs (always empty).
426      */ 
427     function getAllGroupsIn(){
428         return array();
429     }
430
431     /**
432      * Determines all of the members of a particular group.
433      * 
434      * The group is ignored and an empty array (a member of no groups) is returned.
435      * @param string $group Name of the group to check for membership (ignored).
436      * @return array Array of groups user belongs to (always empty).
437      */ 
438     function getMembersOf($group){
439         return array();
440     }
441
442 }
443
444 /**
445  * GroupWikiPage provides group functionality via pages within the Wiki.
446  * 
447  * GroupWikiPage is the Wiki way of managing a group.  Every group will have 
448  * a page. To modify the membership of the group, one only needs to edit the 
449  * membership list on the page.
450  * @author Joby Walker <zorloc@imperium.org>
451  */ 
452 class GroupWikiPage extends WikiGroup{
453     
454     /**
455      * Constructor
456      * 
457      * Initializes the three superclass instance variables
458      * @param object $request The global WikiRequest object.
459      */ 
460     function GroupWikiPage() {
461         //$this->request = &$GLOBALS['request'];
462         $this->username = $this->_getUserName();
463         //$this->username = null;
464         $this->membership = array();
465     }
466
467     /**
468      * Determines if the current user is a member of a group.
469      * 
470      * To determine membership in a particular group, this method checks the 
471      * superclass instance variable $membership to see if membership has 
472      * already been determined.  If not, then the group page is parsed to 
473      * determine membership.
474      * @param string $group Name of the group to check for membership.
475      * @return boolean True if user is a member, else false.
476      */ 
477     function isMember($group){
478         if (isset($this->membership[$group])) {
479             return $this->membership[$group];
480         }
481         global $request;
482         $group_page = $request->getPage($group);
483         if ($this->_inGroupPage($group_page)) {
484             $this->membership[$group] = true;
485             return true;
486         }
487         $this->membership[$group] = false;
488         // Let grouppages override certain defaults, such as members of admin
489         if ($this->specialGroup($group)) {
490             return $this->isSpecialMember($group);
491         }
492         return false;
493     }
494     
495     /**
496     * Private method to take a WikiDB_Page and parse to determine if the
497     * current_user is a member of the group.
498     * @param object $group_page WikiDB_Page object for the group's page
499     * @return boolean True if user is a member, else false.
500     * @access private
501     */
502     function _inGroupPage($group_page, $strict=false){
503         $group_revision = $group_page->getCurrentRevision();
504         if ($group_revision->hasDefaultContents()) {
505             $group = $group_page->getName();
506             if ($strict) trigger_error(sprintf(_("Group page '%s' does not exist"), $group), 
507                                        E_USER_WARNING);
508             return false;
509         }
510         $contents = $group_revision->getContent();
511         $match = '/^\s*[\*\#]+\s*' . $this->username . '\s*$/';
512         foreach ($contents as $line){
513             if (preg_match($match, $line)) {
514                 return true;
515             }
516         }
517         return false;
518     }
519     
520     /**
521      * Determines all of the groups of which the current user is a member.
522      * 
523      * Checks the root Group page ('CategoryGroup') for the list of all groups, 
524      * then checks each group to see if the current user is a member.
525      * @param string $group Name of the group to check for membership.
526      * @return array Array of groups to which the user belongs.
527      */ 
528     function getAllGroupsIn(){
529         $membership = array();
530
531         $specialgroups = $this->specialGroups();
532         foreach ($specialgroups as $group) {
533             $this->membership[$group] = $this->isSpecialMember($group);
534         }
535
536         global $request;
537         $dbh = &$request->_dbi;
538         $master_page = $request->getPage(CATEGORY_GROUP_PAGE);
539         $master_list = $master_page->getLinks(true);
540         while ($group_page = $master_list->next()){
541             $group = $group_page->getName();
542             $this->membership[$group] = $this->_inGroupPage($group_page);
543         }
544         foreach ($this->membership as $g => $bool) {
545             if ($bool) $membership[] = $g;
546         }
547         return $membership;
548     }
549
550     /**
551      * Determines all of the members of a particular group.
552      * 
553      * Checks a group's page to return all the current members.  Currently this
554      * method is disabled and triggers an error and returns an empty array.
555      * @param string $group Name of the group to get the full membership list of.
556      * @return array Array of usernames that have joined the group (always empty).
557      */ 
558     function getMembersOf($group){
559         if ($this->specialGroup($group))
560             return $this->getSpecialMembersOf($group);
561
562         trigger_error("GroupWikiPage::getMembersOf is not yet implimented",
563                       E_USER_WARNING);
564         return array();
565         /*
566         * Waiting for a reliable way to check if a string is a username.
567         $request = $this->request;
568         $user = $this->user;
569         $group_page = $request->getPage($group);
570         $group_revision = $group_page->getCurrentRevision();
571         if ($group_revision->hasDefaultContents()) {
572             trigger_error("Group $group does not exist", E_USER_WARNING);
573             return false;
574         }
575         $contents = $group_revision->getContent();
576         $match = '/^(\s*[\*\#]+\s*)(\w+)(\s*)$/';
577         $members = array();
578         foreach($contents as $line){
579             $matches = array();
580             if(preg_match($match, $line, $matches)){
581                 $members[] = $matches[2];
582             }
583         }
584         return $members;
585         */
586     }
587 }
588
589 /**
590  * GroupDb is configured by $DbAuthParams[] statements
591  * 
592  * Fixme: adodb
593  * @author ReiniUrban
594  */ 
595 class GroupDb extends WikiGroup {
596     
597     var $_is_member, $_group_members, $_user_groups;
598
599     /**
600      * Constructor
601      * 
602      * @param object $request The global WikiRequest object. ignored
603      */ 
604     function GroupDb() {
605         global $DBAuthParams, $DBParams;
606         //$this->request = &$GLOBALS['request'];
607         $this->username = $this->_getUserName();
608         $this->membership = array();
609
610         if (empty($DBAuthParams['group_members']) or 
611             empty($DBAuthParams['user_groups']) or
612             empty($DBAuthParams['is_member'])) {
613             trigger_error(_("No or not enough GROUP_DB SQL statements defined"), 
614                           E_USER_WARNING);
615             return new GroupNone();
616         }
617         if (empty($this->user)) {
618             // use _PassUser::prepare instead
619             if (isa($request->getUser(),'_PassUser'))
620                 $user =& $request->getUser();
621             else
622                 $user = new _PassUser($this->username);
623         } else { 
624             $user =& $this->user;
625         }
626         $this->_is_member = $user->prepare($DBAuthParams['is_member'],
627                                            array('userid','groupname'));
628         $this->_group_members = $user->prepare($DBAuthParams['group_members'],'groupname');
629         $this->_user_groups = $user->prepare($DBAuthParams['user_groups'],'userid');
630         $this->dbh = $user->_auth_dbi;
631     }
632 }
633
634 /**
635  * PearDB methods
636  * 
637  * @author ReiniUrban
638  */ 
639 class GroupDb_PearDB extends GroupDb {
640     
641     /**
642      * Determines if the current user is a member of a database group.
643      * 
644      * @param string $group Name of the group to check for membership.
645      * @return boolean True if user is a member, else false.
646      */ 
647     function isMember($group) {
648         if (isset($this->membership[$group])) {
649             return $this->membership[$group];
650         }
651         $dbh = & $this->dbh;
652         $db_result = $dbh->query(sprintf($this->_is_member,$dbh->quote($this->username),
653                                          $dbh->quote($group)));
654         if ($db_result->numRows() > 0) {
655             $this->membership[$group] = true;
656             return true;
657         }
658         $this->membership[$group] = false;
659         // Let override certain defaults, such as members of admin
660         if ($this->specialGroup($group))
661             return $this->isSpecialMember($group);
662         return false;
663     }
664     
665     /**
666      * Determines all of the groups of which the current user is a member.
667      * 
668      * then checks each group to see if the current user is a member.
669      * @param string $group Name of the group to check for membership.
670      * @return array Array of groups to which the user belongs.
671      */ 
672     function getAllGroupsIn(){
673         $membership = array();
674
675         $dbh = & $this->dbh;
676         $db_result = $dbh->query(sprintf($this->_user_groups,$dbh->quote($this->username)));
677         if ($db_result->numRows() > 0) {
678             while (list($group) = $db_result->fetchRow(DB_FETCHMODE_ORDERED)) {
679                 $membership[] = $group;
680                 $this->membership[$group] = true;
681             }
682         }
683
684         $specialgroups = $this->specialGroups();
685         foreach ($specialgroups as $group) {
686             if ($this->isMember($group)) {
687                 $membership[] = $group;
688             }
689         }
690         return $membership;
691     }
692
693     /**
694      * Determines all of the members of a particular group.
695      * 
696      * Checks a group's page to return all the current members.  Currently this
697      * method is disabled and triggers an error and returns an empty array.
698      * @param string $group Name of the group to get the full membership list of.
699      * @return array Array of usernames that have joined the group.
700      */ 
701     function getMembersOf($group){
702
703         $members = array();
704         $dbh = & $this->dbh;
705         $db_result = $dbh->query(sprintf($this->_group_members,$dbh->quote($group)));
706         if ($db_result->numRows() > 0) {
707             while (list($userid) = $db_result->fetchRow(DB_FETCHMODE_ORDERED)) {
708                 $members[] = $userid;
709             }
710         }
711         // add certain defaults, such as members of admin
712         if ($this->specialGroup($group))
713             $members = array_merge($members, $this->getSpecialMembersOf($group));
714         return $members;
715     }
716 }
717
718 /**
719  * ADODB methods
720  * 
721  * @author ReiniUrban
722  */ 
723 class GroupDb_ADODB extends GroupDb {
724
725     /**
726      * Determines if the current user is a member of a database group.
727      * 
728      * @param string $group Name of the group to check for membership.
729      * @return boolean True if user is a member, else false.
730      */ 
731     function isMember($group) {
732         if (isset($this->membership[$group])) {
733             return $this->membership[$group];
734         }
735         $dbh = & $this->dbh;
736         $rs = $dbh->Execute(sprintf($this->_is_member,$dbh->qstr($this->username),
737                                     $dbh->qstr($group)));
738         if ($rs->EOF) {
739             $rs->Close();
740         } else {
741             if ($rs->numRows() > 0) {
742                 $this->membership[$group] = true;
743                 $rs->Close();
744                 return true;
745             }
746         }
747         $this->membership[$group] = false;
748         if ($this->specialGroup($group))
749             return $this->isSpecialMember($group);
750
751         return false;
752     }
753     
754     /**
755      * Determines all of the groups of which the current user is a member.
756      * then checks each group to see if the current user is a member.
757      *
758      * @param string $group Name of the group to check for membership.
759      * @return array Array of groups to which the user belongs.
760      */ 
761     function getAllGroupsIn(){
762         $membership = array();
763
764         $dbh = & $this->dbh;
765         $rs = $dbh->Execute(sprintf($this->_user_groups, $dbh->qstr($this->username)));
766         if (!$rs->EOF and $rs->numRows() > 0) {
767             while (!$rs->EOF) {
768                 $group = reset($rs->fields);
769                 $membership[] = $group;
770                 $this->membership[$group] = true;
771                 $rs->MoveNext();
772             }
773         }
774         $rs->Close();
775
776         $specialgroups = $this->specialGroups();
777         foreach ($specialgroups as $group) {
778             if ($this->isMember($group)) {
779                 $membership[] = $group;
780             }
781         }
782         return $membership;
783     }
784
785     /**
786      * Determines all of the members of a particular group.
787      * 
788      * @param string $group Name of the group to get the full membership list of.
789      * @return array Array of usernames that have joined the group.
790      */ 
791     function getMembersOf($group){
792         $members = array();
793         $dbh = & $this->dbh;
794         $rs = $dbh->Execute(sprintf($this->_group_members,$dbh->qstr($group)));
795         if (!$rs->EOF and $rs->numRows() > 0) {
796             while (!$rs->EOF) {
797                 $members[] = reset($rs->fields);
798                 $rs->MoveNext();
799             }
800         }
801         $rs->Close();
802         // add certain defaults, such as members of admin
803         if ($this->specialGroup($group))
804             $members = array_merge($members, $this->getSpecialMembersOf($group));
805         return $members;
806     }
807 }
808
809 /**
810  * GroupFile is configured by AUTH_GROUP_FILE
811  * groupname: user1 user2 ...
812  * 
813  * @author ReiniUrban
814  */ 
815 class GroupFile extends WikiGroup {
816     
817     /**
818      * Constructor
819      * 
820      * @param object $request The global WikiRequest object.
821      */ 
822     function GroupFile(){
823         //$this->request = &$GLOBALS['request'];
824         $this->username = $this->_getUserName();
825         //$this->username = null;
826         $this->membership = array();
827
828         if (!defined('AUTH_GROUP_FILE')) {
829             trigger_error(_("AUTH_GROUP_FILE not defined"), E_USER_WARNING);
830             return false;
831         }
832         if (!file_exists(AUTH_GROUP_FILE)) {
833             trigger_error(sprintf(_("Cannot open AUTH_GROUP_FILE %s"), AUTH_GROUP_FILE), 
834                           E_USER_WARNING);
835             return false;
836         }
837         require_once('lib/pear/File_Passwd.php');
838         $this->_file = new File_Passwd(AUTH_GROUP_FILE,false,AUTH_GROUP_FILE.".lock");
839     }
840
841     /**
842      * Determines if the current user is a member of a group.
843      * 
844      * To determine membership in a particular group, this method checks the 
845      * superclass instance variable $membership to see if membership has 
846      * already been determined.  If not, then the group file is parsed to 
847      * determine membership.
848      * @param string $group Name of the group to check for membership.
849      * @return boolean True if user is a member, else false.
850      */ 
851     function isMember($group) {
852         //$request = $this->request;
853         //$username = $this->username;
854         if (isset($this->membership[$group])) {
855             return $this->membership[$group];
856         }
857
858         if (is_array($this->_file->users)) {
859           foreach ($this->_file->users as $g => $u) {
860             $users = explode(' ',$u);
861             if (in_array($this->username,$users)) {
862                 $this->membership[$group] = true;
863                 return true;
864             }
865           }
866         }
867         $this->membership[$group] = false;
868         if ($this->specialGroup($group))
869             return $this->isSpecialMember($group);
870         return false;
871     }
872     
873     /**
874      * Determines all of the groups of which the current user is a member.
875      * 
876      * then checks each group to see if the current user is a member.
877      * @param string $group Name of the group to check for membership.
878      * @return array Array of groups to which the user belongs.
879      */ 
880     function getAllGroupsIn(){
881         //$username = $this->_getUserName();
882         $membership = array();
883
884         if (is_array($this->_file->users)) {
885           foreach ($this->_file->users as $group => $u) {
886             $users = explode(' ',$u);
887             if (in_array($this->username,$users)) {
888                 $this->membership[$group] = true;
889                 $membership[] = $group;
890             }
891           }
892         }
893
894         $specialgroups = $this->specialGroups();
895         foreach ($specialgroups as $group) {
896             if ($this->isMember($group)) {
897                 $this->membership[$group] = true;
898                 $membership[] = $group;
899             }
900         }
901         return $membership;
902     }
903
904     /**
905      * Determines all of the members of a particular group.
906      * 
907      * Return all the current members.
908      * @param string $group Name of the group to get the full membership list of.
909      * @return array Array of usernames that have joined the group.
910      */ 
911     function getMembersOf($group){
912         $members = array();
913         if (!empty($this->_file->users[$group])) {
914             $members = explode(' ',$this->_file->users[$group]);
915         }
916         if ($this->specialGroup($group)) {
917             $members = array_merge($members, $this->getSpecialMembersOf($group));
918         }
919         return $members;
920     }
921 }
922
923 /**
924  * Ldap is configured in index.php
925  * 
926  * @author ReiniUrban
927  */ 
928 class GroupLdap extends WikiGroup {
929     
930     /**
931      * Constructor
932      * 
933      * @param object $request The global WikiRequest object.
934      */ 
935     function GroupLdap(){
936         //$this->request = &$GLOBALS['request'];
937         $this->username = $this->_getUserName();
938         $this->membership = array();
939
940         if (!defined("LDAP_AUTH_HOST")) {
941             trigger_error(_("LDAP_AUTH_HOST not defined"), E_USER_WARNING);
942             return false;
943         }
944         // We should ignore multithreaded environments, not generally windows.
945         // CGI does work.
946         if (! function_exists('ldap_connect') and (!isWindows() or isCGI())) {
947             // on MacOSX >= 4.3 you'll need PHP_SHLIB_SUFFIX instead.
948             dl("ldap".defined('PHP_SHLIB_SUFFIX') ? PHP_SHLIB_SUFFIX : DLL_EXT); 
949             if (! function_exists('ldap_connect')) {
950                 trigger_error(_("No LDAP in this PHP version"), E_USER_WARNING);
951                 return false;
952             }
953         }
954         if (!defined("LDAP_BASE_DN"))
955             define("LDAP_BASE_DN",'');
956         $this->base_dn = LDAP_BASE_DN;
957         // if no users ou (organizational unit) is defined,
958         // then take out the ou= from the base_dn (if exists) and append a default
959         // from users and group
960         if (!LDAP_OU_USERS)
961             if (strstr(LDAP_BASE_DN, "ou="))
962                 $this->base_dn = preg_replace("/(ou=\w+,)?()/","\$2", LDAP_BASE_DN);
963
964         if (!isset($this->user) or !isa($this->user, '_LDAPPassUser'))
965             $this->_user = new _LDAPPassUser('LdapGroupTest'); // to have a valid username
966         else 
967             $this->_user =& $this->user;
968     }
969
970     /**
971      * Determines if the current user is a member of a group.
972      * Not ready yet!
973      * 
974      * @param string $group Name of the group to check for membership.
975      * @return boolean True if user is a member, else false.
976      */ 
977     function isMember($group) {
978         if (isset($this->membership[$group])) {
979             return $this->membership[$group];
980         }
981         //$request = $this->request;
982         //$username = $this->_getUserName();
983         $this->membership[$group] = in_array($this->username,$this->getMembersOf($group));
984         if ($this->membership[$group])
985             return true;
986         if ($this->specialGroup($group))
987             return $this->isSpecialMember($group);
988     }
989     
990     /**
991      * Determines all of the groups of which the current user is a member.
992      *
993      * @param string $group Name of the group to check for membership.
994      * @return array Array of groups to which the user belongs.
995      */ 
996     function getAllGroupsIn(){
997         //$request = &$this->request;
998         //$username = $this->_getUserName();
999         $membership = array();
1000
1001         $specialgroups = $this->specialGroups();
1002         foreach ($specialgroups as $group) {
1003             if ($this->isMember($group)) {
1004                 $this->membership[$group] = true;
1005                 $membership[] = $group;
1006             }
1007         }
1008         
1009         // must be a valid LDAP server, and username must not contain a wildcard
1010         if ($ldap = $this->_user->_init()) {
1011             $st_search = LDAP_SEARCH_FIELD ? LDAP_SEARCH_FIELD."=".$this->username
1012                                            : "uid=".$this->username;
1013             $sr = ldap_search($ldap, (LDAP_OU_USERS ? LDAP_OU_USERS : "ou=Users")
1014                               .($this->base_dn ? ",".$this->base_dn : ''), 
1015                               $st_search);
1016             if (!$sr) {
1017                 $this->_user->_free();
1018                 return $this->membership;
1019             }
1020             $info = ldap_get_entries($ldap, $sr);
1021             if (empty($info["count"])) {
1022                 $this->_user->_free();
1023                 return $this->membership;
1024             }
1025             for ($i = 0; $i < $info["count"]; $i++) {
1026                 if ($info[$i]["gidNumber"]["count"]) {
1027                     $gid = $info[$i]["gidnumber"][0];
1028                     $sr2 = ldap_search($ldap, (LDAP_OU_GROUP ? LDAP_OU_GROUP : "ou=Groups")
1029                                        .($this->base_dn ? ",".$this->base_dn : ''),
1030                                        "gidNumber=$gid");
1031                     if ($sr2) {
1032                         $info2 = ldap_get_entries($ldap, $sr2);
1033                         if (!empty($info2["count"]))
1034                             $membership[] =  $info2[0]["cn"][0];
1035                     }
1036                 }
1037             }
1038         } else {
1039             trigger_error(fmt("Unable to connect to LDAP server %s", LDAP_AUTH_HOST), 
1040                           E_USER_WARNING);
1041         }
1042         $this->_user->_free();
1043         //ldap_close($ldap);
1044         $this->membership = $membership;
1045         return $membership;
1046     }
1047
1048     /**
1049      * Determines all of the members of a particular group.
1050      * 
1051      * Return all the members of the given group. LDAP just returns the gid of each user
1052      * @param string $group Name of the group to get the full membership list of.
1053      * @return array Array of usernames that have joined the group.
1054      */ 
1055     function getMembersOf($group){
1056         $members = array();
1057         if ($ldap = $this->_user->_init()) {
1058             $base_dn = (LDAP_OU_GROUP ? LDAP_OU_GROUP : "ou=Groups")
1059                 .($this->base_dn ? ",".$this->base_dn : '');
1060             $sr2 = ldap_search($ldap, $base_dn, "cn=$group");
1061             if ($sr)
1062                 $info = ldap_get_entries($ldap, $sr);
1063             else {
1064                 $info = array('count' => 0);
1065                 trigger_error("LDAP_SEARCH: base=\"$base_dn\" \"(cn=$group)\" failed", E_USER_NOTICE);
1066             }
1067             $base_dn = (LDAP_OU_USERS ? LDAP_OU_USERS : "ou=Users")
1068                 .($this->base_dn ? ",".$this->base_dn : '');
1069             for ($i = 0; $i < $info["count"]; $i++) {
1070                 $gid = $info[$i]["gidNumber"][0];
1071                 //uid=* would be better probably
1072                 $sr2 = ldap_search($ldap, $base_dn, "gidNumber=$gid");
1073                 if ($sr2) {
1074                     $info2 = ldap_get_entries($ldap, $sr2);
1075                     for ($j = 0; $j < $info2["count"]; $j++) {
1076                         $members[] = $info2[$j]["cn"][0];
1077                     }
1078                 } else {
1079                     trigger_error("LDAP_SEARCH: base=\"$base_dn\" \"(gidNumber=$gid)\" failed", E_USER_NOTICE);
1080                 }
1081             }
1082         }
1083         $this->_user->_free();
1084         //ldap_close($ldap);
1085
1086         if ($this->specialGroup($group)) {
1087             $members = array_merge($members, $this->getSpecialMembersOf($group));
1088         }
1089         return $members;
1090     }
1091 }
1092
1093 // $Log: not supported by cvs2svn $
1094 // Revision 1.43  2004/11/10 15:29:21  rurban
1095 // * requires newer Pear_DB (as the internal one): quote() uses now escapeSimple for strings
1096 // * ACCESS_LOG_SQL: fix cause request not yet initialized
1097 // * WikiDB: moved SQL specific methods upwards
1098 // * new Pear_DB quoting: same as ADODB and as newer Pear_DB.
1099 //   fixes all around: WikiGroup, WikiUserNew SQL methods, SQL logging
1100 //
1101 // Revision 1.42  2004/11/01 10:43:56  rurban
1102 // seperate PassUser methods into seperate dir (memory usage)
1103 // fix WikiUser (old) overlarge data session
1104 // remove wikidb arg from various page class methods, use global ->_dbi instead
1105 // ...
1106 //
1107 // Revision 1.41  2004/09/17 14:21:28  rurban
1108 // fix LDAP ou= issue, wrong strstr arg order
1109 //
1110 // Revision 1.40  2004/06/29 06:48:02  rurban
1111 // Improve LDAP auth and GROUP_LDAP membership:
1112 //   no error message on false password,
1113 //   added two new config vars: LDAP_OU_USERS and LDAP_OU_GROUP with GROUP_METHOD=LDAP
1114 //   fixed two group queries (this -> user)
1115 // stdlib: ConvertOldMarkup still flawed
1116 //
1117 // Revision 1.39  2004/06/28 15:39:28  rurban
1118 // fixed endless recursion in WikiGroup: isAdmin()
1119 //
1120 // Revision 1.38  2004/06/27 10:24:19  rurban
1121 // suggestion by Paul Henry
1122 //
1123 // Revision 1.37  2004/06/25 14:29:18  rurban
1124 // WikiGroup refactoring:
1125 //   global group attached to user, code for not_current user.
1126 //   improved helpers for special groups (avoid double invocations)
1127 // new experimental config option ENABLE_XHTML_XML (fails with IE, and document.write())
1128 // fixed a XHTML validation error on userprefs.tmpl
1129 //
1130 // Revision 1.36  2004/06/16 13:21:05  rurban
1131 // stabilize on failing ldap queries or bind
1132 //
1133 // Revision 1.35  2004/06/16 12:08:25  rurban
1134 // better desc
1135 //
1136 // Revision 1.34  2004/06/16 11:51:35  rurban
1137 // catch dl error on Windows
1138 //
1139 // Revision 1.33  2004/06/15 10:40:35  rurban
1140 // minor WikiGroup cleanup: no request param, start of current user independency
1141 //
1142 // Revision 1.32  2004/06/15 09:15:52  rurban
1143 // IMPORTANT: fixed passwd handling for passwords stored in prefs:
1144 //   fix encrypted usage, actually store and retrieve them from db
1145 //   fix bogologin with passwd set.
1146 // fix php crashes with call-time pass-by-reference (references wrongly used
1147 //   in declaration AND call). This affected mainly Apache2 and IIS.
1148 //   (Thanks to John Cole to detect this!)
1149 //
1150 // Revision 1.31  2004/06/03 18:06:29  rurban
1151 // fix file locking issues (only needed on write)
1152 // fixed immediate LANG and THEME in-session updates if not stored in prefs
1153 // advanced editpage toolbars (search & replace broken)
1154 //
1155 // Revision 1.30  2004/06/03 09:39:51  rurban
1156 // fix LDAP injection (wildcard in username) detected by Steve Christey, MITRE
1157 //
1158 // Revision 1.29  2004/05/16 22:07:35  rurban
1159 // check more config-default and predefined constants
1160 // various PagePerm fixes:
1161 //   fix default PagePerms, esp. edit and view for Bogo and Password users
1162 //   implemented Creator and Owner
1163 //   BOGOUSERS renamed to BOGOUSER
1164 // fixed syntax errors in signin.tmpl
1165 //
1166 // Revision 1.28  2004/05/15 22:54:49  rurban
1167 // fixed important WikiDB bug with DEBUG > 0: wrong assertion
1168 // improved SetAcl (works) and PagePerms, some WikiGroup helpers.
1169 //
1170 // Revision 1.27  2004/05/06 13:56:40  rurban
1171 // Enable the Administrators group, and add the WIKIPAGE group default root page.
1172 //
1173 // Revision 1.26  2004/04/07 23:13:18  rurban
1174 // fixed pear/File_Passwd for Windows
1175 // fixed FilePassUser sessions (filehandle revive) and password update
1176 //
1177 // Revision 1.25  2004/03/29 10:40:36  rurban
1178 // GroupDb_PearDB fetchmode fix
1179 //
1180 // Revision 1.24  2004/03/14 16:26:22  rurban
1181 // copyright line
1182 //
1183 // Revision 1.23  2004/03/12 23:20:58  rurban
1184 // pref fixes (base64)
1185 //
1186 // Revision 1.22  2004/03/12 15:48:07  rurban
1187 // fixed explodePageList: wrong sortby argument order in UnfoldSubpages
1188 // simplified lib/stdlib.php:explodePageList
1189 //
1190 // Revision 1.21  2004/03/12 11:18:24  rurban
1191 // fixed ->membership chache
1192 //
1193 // Revision 1.20  2004/03/12 10:47:30  rurban
1194 // fixed GroupDB for ADODB
1195 //
1196 // Revision 1.19  2004/03/11 16:27:30  rurban
1197 // fixed GroupFile::getMembersOf for special groups
1198 // added authenticated bind for GroupLdap (Windows AD) as in WikiUserNew
1199 //
1200 // Revision 1.18  2004/03/11 13:30:47  rurban
1201 // fixed File Auth for user and group
1202 // missing only getMembersOf(Authenticated Users),getMembersOf(Every),getMembersOf(Signed Users)
1203 //
1204 // Revision 1.17  2004/03/10 15:38:48  rurban
1205 // store current user->page and ->action in session for WhoIsOnline
1206 // better WhoIsOnline icon
1207 // fixed WhoIsOnline warnings
1208 //
1209 // Revision 1.15  2004/03/09 12:11:57  rurban
1210 // prevent from undefined DBAuthParams warning
1211 //
1212 // Revision 1.14  2004/03/08 19:30:01  rurban
1213 // fixed Theme->getButtonURL
1214 // AllUsers uses now WikiGroup (also DB User and DB Pref users)
1215 // PageList fix for empty pagenames
1216 //
1217 // Revision 1.13  2004/03/08 18:17:09  rurban
1218 // added more WikiGroup::getMembersOf methods, esp. for special groups
1219 // fixed $LDAP_SET_OPTIONS
1220 // fixed _AuthInfo group methods
1221 //
1222 // Revision 1.12  2004/02/23 21:30:25  rurban
1223 // more PagePerm stuff: (working against 1.4.0)
1224 //   ACL editing and simplification of ACL's to simple rwx------ string
1225 //   not yet working.
1226 //
1227 // Revision 1.11  2004/02/07 10:41:25  rurban
1228 // fixed auth from session (still double code but works)
1229 // fixed GroupDB
1230 // fixed DbPassUser upgrade and policy=old
1231 // added GroupLdap
1232 //
1233 // Revision 1.10  2004/02/03 09:45:39  rurban
1234 // LDAP cleanup, start of new Pref classes
1235 //
1236 // Revision 1.9  2004/02/01 09:14:11  rurban
1237 // Started with Group_Ldap (not yet ready)
1238 // added new _AuthInfo plugin to help in auth problems (warning: may display passwords)
1239 // fixed some configurator vars
1240 // renamed LDAP_AUTH_SEARCH to LDAP_BASE_DN
1241 // changed PHPWIKI_VERSION from 1.3.8a to 1.3.8pre
1242 // USE_DB_SESSION defaults to true on SQL
1243 // changed GROUP_METHOD definition to string, not constants
1244 // changed sample user DBAuthParams from UPDATE to REPLACE to be able to
1245 //   create users. (Not to be used with external databases generally, but
1246 //   with the default internal user table)
1247 //
1248 // fixed the IndexAsConfigProblem logic. this was flawed:
1249 //   scripts which are the same virtual path defined their own lib/main call
1250 //   (hmm, have to test this better, phpwiki.sf.net/demo works again)
1251 //
1252 // Revision 1.8  2004/01/27 23:23:39  rurban
1253 // renamed ->Username => _userid for consistency
1254 // renamed mayCheckPassword => mayCheckPass
1255 // fixed recursion problem in WikiUserNew
1256 // fixed bogo login (but not quite 100% ready yet, password storage)
1257 //
1258 // Revision 1.7  2004/01/26 16:52:40  rurban
1259 // added GroupDB and GroupFile classes
1260 //
1261 // Revision 1.6  2003/12/07 19:29:11  carstenklapp
1262 // Code Housecleaning: fixed syntax errors. (php -l *.php)
1263 //
1264 // Revision 1.5  2003/02/22 20:49:55  dairiki
1265 // Fixes for "Call-time pass by reference has been deprecated" errors.
1266 //
1267 // Revision 1.4  2003/01/21 04:02:39  zorloc
1268 // Added Log entry and page footer.
1269 //
1270
1271 // Local Variables:
1272 // mode: php
1273 // tab-width: 8
1274 // c-basic-offset: 4
1275 // c-hanging-comment-ender-p: nil
1276 // indent-tabs-mode: nil
1277 // End:
1278 ?>