2 rcs_id('$Id: PagePerm.php,v 1.8 2004-03-14 16:24:35 rurban Exp $');
4 Copyright 2004 $ThePhpWikiProgrammingTeam
6 This file is part of PhpWiki.
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.
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.
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
24 Permissions per page and action based on current user,
25 ownership and group membership implemented with ACL's (Access Control Lists),
26 opposed to the simplier unix like ugo:rwx system.
27 The previous system was only based on action and current user. (lib/main.php)
29 Permissions maybe inherited its parent pages, and ultimativly the
30 optional master page (".")
31 Pagenames starting with "." have special default permissions.
32 For Authentication see WikiUserNew.php, WikiGroup.php and main.php
33 Page Permssions are in PhpWiki since v1.3.9 and enabled since v1.4.0
35 This file might replace the following functions from main.php:
36 Request::_notAuthorized($require_level)
37 display the denied message and optionally a login form
38 to gain higher privileges
39 Request::getActionDescription($action)
40 helper to localize the _notAuthorized message per action,
42 Request::getDisallowedActionDescription($action)
43 helper to localize the _notAuthorized message per action,
45 Request::requiredAuthority($action)
46 returns the needed user level
47 has a hook for plugins on POST
48 Request::requiredAuthorityForAction($action)
49 just returns the level per action, will be replaced with the
52 The defined main.php actions map to simplier access types:
55 create => edit or create
59 list in PageList => list
62 /* Symbolic special ACL groups. Untranslated to be stored in page metadata*/
63 define('ACL_EVERY', '_EVERY');
64 define('ACL_ANONYMOUS', '_ANONYMOUS');
65 define('ACL_BOGOUSERS', '_BOGOUSERS');
66 define('ACL_HASHOMEPAGE', '_HASHOMEPAGE');
67 define('ACL_SIGNED', '_SIGNED');
68 define('ACL_AUTHENTICATED','_AUTHENTICATED');
69 define('ACL_ADMIN', '_ADMIN');
70 define('ACL_OWNER', '_OWNER');
71 define('ACL_CREATOR', '_CREATOR');
73 // Return an page permissions array for this page.
74 // To provide ui helpers to view and change page permissions:
75 // <tr><th>Group</th><th>Access</th><th>Allow or Forbid</th></tr>
76 // <tr><td>$group</td><td>_($access)</td><td> [ ] </td></tr>
77 function pagePermissions($pagename) {
79 $page = $request->getPage($pagename);
80 // Page not found (new page); returned inherited permissions, to be displayed in gray
81 if (! $page->exists() ) {
82 if ($pagename == '.') // stop recursion
83 return array('default',new PagePermission());
85 return array('inherited',pagePermissions(getParentPage($pagename)));
87 } elseif ($perm = getPagePermissions($page)) {
88 return array('page',$perm);
89 // or no permissions defined; returned inherited permissions, to be displayed in gray
91 return array('inherited',pagePermissions(getParentPage($pagename)));
95 function pagePermissionsSimpleFormat($perm_tree,$owner,$group=false) {
96 list($type,$perm) = pagePermissionsAcl($perm_tree[0], $perm_tree);
98 $type = $perm_tree[0];
99 $perm = pagePermissionsAcl($perm_tree);
100 if (is_object($perm_tree[1]))
101 $perm = $perm_tree[1];
102 elseif (is_array($perm_tree[1])) {
103 $perm_tree = pagePermissionsSimpleFormat($perm_tree[1],$owner,$group);
104 if (isa($perm_tree[1],'pagepermission'))
105 $perm = $perm_tree[1];
106 elseif (isa($perm_tree,'htmlelement'))
111 return HTML::tt(HTML::bold($perm->asRwxString($owner,$group).'+'));
112 elseif ($type == 'default')
113 return HTML::tt($perm->asRwxString($owner,$group));
114 elseif ($type == 'inherited') {
115 return HTML::tt(array('class'=>'inherited','style'=>'color:#aaa;'),
116 $perm->asRwxString($owner,$group));
120 function pagePermissionsAcl($type,$perm_tree) {
121 $perm = $perm_tree[1];
122 while (!is_object($perm)) {
123 $perm_tree = pagePermissionsAcl($type, $perm);
124 $perm = $perm_tree[1];
126 return array($type,$perm);
131 function pagePermissionsAclFormat($perm_tree,$editable=false) {
132 list($type,$perm) = pagePermissionsAcl($perm_tree[0], $perm_tree);
134 return $perm->asEditableTable($type);
136 return $perm->asTable($type);
140 * Check permission per page.
141 * Returns true or false.
143 function mayAccessPage ($access,$pagename) {
144 return _requiredAuthorityForPagename($access,$pagename);
147 /** Check the permissions for the current action.
148 * Walk down the inheritance tree. Collect all permissions until
149 * the minimum required level is gained, which is not
150 * overruled by more specific forbid rules.
151 * Todo: cache result per access and page in session?
153 function requiredAuthorityForPage ($action) {
154 if (_requiredAuthorityForPagename(action2access($action),
155 $GLOBALS['request']->getArg('pagename')))
156 return $GLOBALS['request']->_user->_level;
158 return WIKIAUTH_FORBIDDEN;
161 // Translate action or plugin to the simplier access types:
162 function action2access ($action) {
180 $page = $request->getPage();
181 $current = $page->getCurrentRevision();
182 if ($current->hasDefaultContents())
189 // probably create/edit but we cannot check all page permissions, can we?
195 //Todo: Plugins should be able to override its access type
196 if (isWikiWord($action))
204 // Recursive helper to do the real work
205 function _requiredAuthorityForPagename($access, $pagename) {
207 $page = $request->getPage($pagename);
208 // Page not found; check against default permissions
209 if (! $page->exists() ) {
210 $perm = new PagePermission();
211 return ($perm->isAuthorized($access,$request->_user) === true);
213 // no ACL defined; check for special dotfile or walk down
214 if (! ($perm = getPagePermissions($page))) {
215 if ($pagename[0] == '.') {
216 $perm = new PagePermission(PagePermission::dotPerms());
217 return ($perm->isAuthorized($access,$request->_user) === true);
219 return _requiredAuthorityForPagename($access,getParentPage($pagename));
221 // ACL defined; check if isAuthorized returns true or false or undecided
222 $authorized = $perm->isAuthorized($access,$request->_user);
223 if ($authorized != -1) // -1 for undecided
226 return _requiredAuthorityForPagename($access,getParentPage($pagename));
230 * @param string $pagename page from which the parent page is searched.
231 * @return string parent pagename or the (possibly pseudo) dot-pagename.
233 function getParentPage($pagename) {
234 if (isSubPage($pagename)) {
235 return subPageSlice($pagename,0);
241 // Read the ACL from the page
242 // Done: Not existing pages should NOT be queried.
243 // Check the parent page instead and don't take the default ACL's
244 function getPagePermissions ($page) {
245 if ($hash = $page->get('perm')) // hash => object
246 return new PagePermission(unserialize($hash));
251 // Store the ACL in the page
252 function setPagePermissions ($page,$perm) {
256 function getAccessDescription($access) {
257 static $accessDescriptions;
258 if (! $accessDescriptions) {
259 $accessDescriptions = array(
260 'list' => _("List this page and all subpages"),
261 'view' => _("View this page and all subpages"),
262 'edit' => _("Edit this page and all subpages"),
263 'create' => _("Create a new (sub)page"),
264 'dump' => _("Download the page contents"),
265 'change' => _("Change page attributes"),
266 'remove' => _("Remove this page"),
269 if (in_array($access, array_keys($accessDescriptions)))
270 return $accessDescriptions[$access];
276 * The ACL object per page. It is stored in a page, but can also
277 * be merged with ACL's from other pages or taken from the master (pseudo) dot-file.
279 * A hash of "access" => "requires" pairs.
280 * "access" is a shortcut for common actions, which map to main.php actions
281 * "requires" required username or groupname or any special group => true or false
283 * Define any special rules here, like don't list dot-pages.
285 class PagePermission {
288 function PagePermission($hash = array()) {
289 if (is_array($hash) and !empty($hash)) {
290 $accessTypes = $this->accessTypes();
291 foreach ($hash as $access => $requires) {
292 if (in_array($access,$accessTypes))
293 $this->perm[$access] = $requires;
295 trigger_error(sprintf(_("Unsupported ACL access type %s ignored."),$access),
299 // set default permissions, the so called dot-file acl's
300 $this->perm = $this->defaultPerms();
306 * The workhorse to check the user against the current ACL pairs.
307 * Must translate the various special groups to the actual users settings
308 * (userid, group membership).
310 function isAuthorized($access,$user) {
311 if (!empty($this->perm{$access})) {
312 foreach ($this->perm[$access] as $group => $bool) {
313 if ($this->isMember($user,$group))
317 return -1; // undecided
321 * Translate the various special groups to the actual users settings
322 * (userid, group membership).
324 function isMember($user,$group) {
326 if ($group === ACL_EVERY) return true;
327 $member = &WikiGroup::getGroup($request);
328 //$user = & $request->_user;
329 if ($group === ACL_ADMIN) // WIKI_ADMIN or member of _("Administrators")
330 return $user->isAdmin() or
331 $member->isMember(GROUP_ADMIN);
332 if ($group === ACL_ANONYMOUS)
333 return ! $user->isSignedIn();
334 if ($group === ACL_BOGOUSERS)
335 if (ENABLE_USER_NEW) return isa($user,'_BogoUser');
336 else return isWikiWord($user->UserName());
337 if ($group === ACL_HASHOMEPAGE)
338 return $user->hasHomePage();
339 if ($group === ACL_SIGNED)
340 return $user->isSignedIn();
341 if ($group === ACL_AUTHENTICATED)
342 return $user->isAuthenticated();
343 if ($group === ACL_OWNER) {
344 $page = $request->getPage();
345 return $page->get('author') === $user->UserName();
347 if ($group === ACL_CREATOR) {
348 $page = $request->getPage();
349 $rev = $page->getRevision(1);
350 return $rev->get('author') === $user->UserName();
352 /* Or named groups or usernames.
353 Note: We don't seperate groups and users here.
354 Users overrides groups with the same name. */
355 return $user->UserName() === $group or
356 $member->isMember($group);
360 * returns hash of default permissions.
361 * check if the page '.' exists and returns this instead.
363 function defaultPerms() {
364 //Todo: check for the existance of '.' and take this instead.
365 //Todo: honor more index.php auth settings here
366 $perm = array('view' => array(ACL_EVERY => true),
367 'edit' => array(ACL_EVERY => true),
368 'create' => array(ACL_EVERY => true),
369 'list' => array(ACL_EVERY => true),
370 'remove' => array(ACL_ADMIN => true,
372 'change' => array(ACL_ADMIN => true,
374 if (defined('ZIPDUMP_AUTH') && ZIPDUMP_AUTH)
375 $perm['dump'] = array(ACL_ADMIN => true,
378 $perm['dump'] = array(ACL_EVERY => true);
379 if (defined('REQUIRE_SIGNIN_BEFORE_EDIT') && REQUIRE_SIGNIN_BEFORE_EDIT)
380 $perm['edit'] = array(ACL_SIGNED => true);
381 if (defined('ALLOW_ANON_USER') && ! ALLOW_ANON_USER) {
382 if (defined('ALLOW_BOGO_USER') && ALLOW_BOGO_USER) {
383 $perm['view'] = array(ACL_BOGOUSER => true);
384 $perm['edit'] = array(ACL_BOGOUSER => true);
385 } elseif (defined('ALLOW_USER_PASSWORDS') && ALLOW_USER_PASSWORDS) {
386 $perm['view'] = array(ACL_AUTHENTICATED => true);
387 $perm['edit'] = array(ACL_AUTHENTICATED => true);
389 $perm['view'] = array(ACL_SIGNED => true);
390 $perm['edit'] = array(ACL_SIGNED => true);
397 * returns list of all supported access types.
399 function accessTypes() {
400 return array_keys($this->defaultPerms());
404 * special permissions for dot-files, beginning with '.'
405 * maybe also for '_' files?
407 function dotPerms() {
408 $def = array(ACL_ADMIN => true,
411 foreach ($this->accessTypes() as $access) {
412 $perm[$access] = $def;
418 * dead code. not needed inside the object. see getPagePermissions($page)
420 function retrieve($page) {
421 $hash = $page->get('perm');
422 if ($hash) // hash => object
423 return new PagePermission(unserialize($hash));
425 return new PagePermission();
428 function store($page) {
430 return $page->set('perm',serialize(obj2hash($this->perm)));
433 /* type: page, default, inherited */
434 function asTable($type) {
435 $table = HTML::table();
436 foreach ($this->perm as $access => $perms) {
437 $td = HTML::table(array('class' => 'cal','valign' => 'top'));
438 foreach ($perms as $group => $bool) {
439 $td->pushContent(HTML::tr(HTML::td(array('align'=>'right'),$group),
440 HTML::td($bool ? '[X]' : '[ ]')));
442 $table->pushContent(HTML::tr(array('valign' => 'top'),
443 HTML::td($access),HTML::td($td)));
445 if ($type == 'default')
446 $table->setAttr('style','border: dotted thin black; background-color:#eee;');
447 elseif ($type == 'inherited')
448 $table->setAttr('style','border: dotted thin black; background-color:#ddd;');
449 elseif ($type == 'page')
450 $table->setAttr('style','border: solid thin black; font-weight: bold;');
454 /* type: page, default, inherited */
455 function asEditableTable($type) {
456 $table = HTML::table();
457 $table->pushContent(HTML::tr(array('valign' => 'top'),
458 HTML::th(array('align' => 'left'),'access'),
459 HTML::th(array('align'=>'right'),
462 HTML::th('Description')));
463 foreach ($this->perm as $access => $perms) {
464 //$permlist = HTML::table(array('class' => 'cal','valign' => 'top'));
466 foreach ($perms as $group => $bool) {
467 $checkbox = HTML::input(array('type' => 'checkbox',
468 'name' => "acl[$access][$group]",
470 if ($bool) $checkbox->setAttr('checked','checked');
472 $table->pushContent(HTML::tr(array('valign' => 'top'),
473 HTML::td(HTML::strong($access.":")),
474 HTML::td(array('class' => 'cal-today','align'=>'right'),
475 constant("GROUP".$group)),
477 HTML::td(HTML::em(getAccessDescription($access)))));
480 $table->pushContent(HTML::tr(array('valign' => 'top'),
482 HTML::td(array('class' => 'cal-today','align'=>'right'),
483 constant("GROUP".$group)),
489 $table->pushContent(HTML::tr(array('valign' => 'top'),
490 HTML::td(HTML::strong($access)),
492 HTML::td(HTML::em(getAccessDescription($access)))));
495 if ($type == 'default')
496 $table->setAttr('style','border: dotted thin black; background-color:#eee;');
497 elseif ($type == 'inherited')
498 $table->setAttr('style','border: dotted thin black; background-color:#ddd;');
499 elseif ($type == 'page')
500 $table->setAttr('style','border: solid thin black; font-weight: bold;');
504 // this is just a bad hack for testing
505 // simplify the ACL to a unix-like "rwx------" string
506 function asRwxString($owner,$group=false) {
508 // simplify object => rwxrw---x+ string as in cygwin (+ denotes additional ACLs)
509 $perm =& $this->perm;
510 // get effective user and group
512 if (isset($perm['view'][$owner]) or
513 (isset($perm['view'][ACL_AUTHENTICATED]) and $request->_user->isAuthenticated()))
515 if (isset($perm['edit'][$owner]) or
516 (isset($perm['edit'][ACL_AUTHENTICATED]) and $request->_user->isAuthenticated()))
518 if (isset($perm['change'][$owner]) or
519 (isset($perm['change'][ACL_AUTHENTICATED]) and $request->_user->isAuthenticated()))
521 if (!empty($group)) {
522 if (isset($perm['view'][$group]) or
523 (isset($perm['view'][ACL_AUTHENTICATED]) and $request->_user->isAuthenticated()))
525 if (isset($perm['edit'][$group]) or
526 (isset($perm['edit'][ACL_AUTHENTICATED]) and $request->_user->isAuthenticated()))
528 if (isset($perm['change'][$group]) or
529 (isset($perm['change'][ACL_AUTHENTICATED]) and $request->_user->isAuthenticated()))
532 if (isset($perm['view'][ACL_EVERY]) or
533 (isset($perm['view'][ACL_AUTHENTICATED]) and $request->_user->isAuthenticated()))
535 if (isset($perm['edit'][ACL_EVERY]) or
536 (isset($perm['edit'][ACL_AUTHENTICATED]) and $request->_user->isAuthenticated()))
538 if (isset($perm['change'][ACL_EVERY]) or
539 (isset($perm['change'][ACL_AUTHENTICATED]) and $request->_user->isAuthenticated()))
545 // $Log: not supported by cvs2svn $
546 // Revision 1.7 2004/02/28 22:25:07 rurban
547 // First PagePerm implementation:
549 // $Theme->setAnonEditUnknownLinks(false);
551 // Layout improvement with dangling links for mostly closed wiki's:
552 // If false, only users with edit permissions will be presented the
553 // special wikiunknown class with "?" and Tooltip.
554 // If true (default), any user will see the ?, but will be presented
555 // the PrintLoginForm on a click.
557 // Revision 1.6 2004/02/24 15:20:05 rurban
558 // fixed minor warnings: unchecked args, POST => Get urls for sortby e.g.
560 // Revision 1.5 2004/02/23 21:30:25 rurban
561 // more PagePerm stuff: (working against 1.4.0)
562 // ACL editing and simplification of ACL's to simple rwx------ string
565 // Revision 1.4 2004/02/12 13:05:36 rurban
566 // Rename functional for PearDB backend
567 // some other minor changes
568 // SiteMap comes with a not yet functional feature request: includepages (tbd)
570 // Revision 1.3 2004/02/09 03:58:12 rurban
571 // for now default DB_SESSION to false
573 // * not existing perms will now query the parent, and not
574 // return the default perm
575 // * added pagePermissions func which returns the object per page
576 // * added getAccessDescription
578 // * added global ->prepare (not yet used) with smart user/pref/member table prefixing.
579 // * force init of authdbh in the 2 db classes
581 // * fixed session handling (not triple auth request anymore)
582 // * don't store cookie prefs with sessions
583 // stdlib: global obj2hash helper from _AuthInfo, also needed for PagePerm
585 // Revision 1.2 2004/02/08 13:17:48 rurban
586 // This should be the functionality. Needs testing and some minor todos.
588 // Revision 1.1 2004/02/08 12:29:30 rurban
589 // initial version, not yet hooked into lib/main.php
597 // c-hanging-comment-ender-p: nil
598 // indent-tabs-mode: nil