<?php if (!defined('PmWiki')) exit();

# Usage:
# (:if authenticated admin :)  Output administrator stuff (:if:)
# Parameters include 'admin', 'read', 'edit', 'attr'.
$Conditions['authenticated'] = 'AuthenticatedAsRole($pagename, $condparm)';

# Use new authentication methods
$AuthFunction = 'BasicAuthUsingAuthenticatedAsRoleMethod';

function isAuthenticated($page, $pagename, $role, $authpw){

  global $DefaultPasswords,$AllowPassword,$GroupAttributesFmt;
  
  foreach($authpw as $pwresp){
    if (@crypt($pwresp,$DefaultPasswords['admin'])==$DefaultPasswords['admin']){
      return $page;  # authenticated:  Matches Administrator password
    }
  }

  SDV($GroupAttributesFmt,'$Group/GroupAttributes');
  SDV($AllowPassword,'nopass');

  $passwd = @$page["passwd$role"];
 
  if ($passwd=="") { 
    $grouppg = ReadPage(FmtPageName($GroupAttributesFmt,$pagename));
    $passwd = @$grouppg["passwd$role"];
    
    if ($passwd=='') $passwd = @$DefaultPasswords[$role];
    if ($passwd=='') $passwd = @$page["passwdread"];
    if ($passwd=='') $passwd = @$grouppg["passwdread"];
    if ($passwd=='') $passwd = @$DefaultPasswords['read'];
  }

  if ($passwd=='') return $page;
  if (crypt($AllowPassword,$passwd)==$passwd){
    return $page;  # authenticated:  no password needed
  }

  foreach($authpw as $pwresp){
    if (@crypt($pwresp,$passwd)==$passwd){
      return $page;  # authenticated:  password needed
    }
  }

  return false;  # not authenticated for page
}

function AuthenticatedAsRole($pagename, $role){

  $page = ReadPage($pagename);
  if (!$page) { return false; }

  @session_start();

  if (@$_POST['authpw']) @$_SESSION['authpw'][$_POST['authpw']]++;
  $authpw = array_keys((array)@$_SESSION['authpw']);

  return isAuthenticated($page, $pagename, $role, $authpw);
}


## Replaces the BasicAuth method in pmwiki.php
function BasicAuthUsingAuthenticatedAsRoleMethod($pagename,$level,$authprompt=true) {
  global $SessionAuthFmt, $HTMLStartFmt,$HTMLEndFmt;
  
  $page = AuthenticatedAsRole($pagename, $level);

  if ($page != false) return $page;

  if (!$authprompt) return false;
  SDV($SessionAuthFmt,array(&$HTMLStartFmt,
    "<p><b>Password required</b></p>
      <form name='authform' action='{$_SERVER['REQUEST_URI']}' method='post'>
        Password: <input tabindex='1' type='password' name='authpw' value='' />
        <input type='submit' value='OK' /></form>", &$HTMLEndFmt));
  PrintFmt($pagename,$SessionAuthFmt);
  exit;
}

?>