<?php if (!defined('PmWiki')) exit();
/*  Copyright 2005 Patrick R. Michaud (pmichaud@pobox.com)
    This file is part of PmWiki; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published
    by the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.  See pmwiki.php for full details.
*/

SDV($AuthFunction,'BasicAuth');

## BasicAuth provides password-protection of pages using PHP sessions.
## It is normally called from RetrieveAuthPage.
function BasicAuth($pagename,$level,$authprompt=true) {
  global $DefaultPasswords,$AllowPassword,$GroupAttributesFmt,$SessionAuthFmt,
    $HTMLStartFmt,$HTMLEndFmt;
  SDV($GroupAttributesFmt,'$Group/GroupAttributes');
  SDV($AllowPassword,'nopass');
  $page = ReadPage($pagename);
  if (!$page) { return false; }
  $passwd = @$page["passwd$level"];
  if ($passwd=="") { 
    $grouppg = ReadPage(FmtPageName($GroupAttributesFmt,$pagename));
    $passwd = @$grouppg["passwd$level"];
    if ($passwd=='') $passwd = @$DefaultPasswords[$level];
    if ($passwd=='') $passwd = @$page["passwdread"];
    if ($passwd=='') $passwd = @$grouppg["passwdread"];
    if ($passwd=='') $passwd = @$DefaultPasswords['read'];
  }
  if ($passwd=='') return $page;
  foreach((array)$passwd as $p)
    if (crypt($AllowPassword, $p) == $p) return $page;
  @session_start();
  if (@$_POST['authpw']) @$_SESSION['authpw'][$_POST['authpw']]++;
  $authpw = array_keys((array)@$_SESSION['authpw']);
  foreach (array_merge((array)$DefaultPasswords['admin'],(array)$passwd) 
      as $pwchal)
    foreach($authpw as $pwresp)
      if (@crypt($pwresp,$pwchal)==$pwchal) return $page;
  if (!$authprompt) return false;
  $postvars = '';
  foreach($_POST as $k=>$v) {
    if ($k == 'authpw') continue;
    $v = str_replace('$', '&#036;', 
      htmlspecialchars(stripmagic($v), ENT_COMPAT));
    $postvars .= "<input type='hidden' name='$k' value=\"$v\" />\n";
  }
  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' />$postvars</form>
        <script language='javascript'><!--
          document.authform.authpw.focus() //--></script>", &$HTMLEndFmt));
  PrintFmt($pagename,$SessionAuthFmt);
  exit;
}

?>