<?php if (! defined ('PmWiki')) exit;
# 
# MySQL Authentication with Auth User.
#
# Copyright
# =========
#
# Copyright 2006 Ben Wilson <ameen@dausha.net>. This software is released under
# the same terms as PmWiki, which is under GPL. Permission to use, modify and
# redistribute are granted provided this copyright statement remains intact.
#
# Release
# =======
# 
# v.0.2 - May 31, 2006. Ben Wilson. Re-released for better integration with
#         AuthUser.

$AuthForm      =<<<AUTHFORM
<form name='authform' action='{$_SERVER['REQUEST_URI']}' method='post'>
<table border='0'>
<tr>
<td class='name'>Name:</td><td><input tabindex='1' type='text' name='authid' value=''></td>
</tr><tr>
<td class='name'>Password:</td><td><input tabindex='2' type='password' name='authpw' value=''></td>
</tr><tr>
<td colspan='2'>
<input type='submit' value='OK'>
</td>
<input type='hidden' name='authaction' value='1'>
</table>
<script language='javascript'<!-- document.authform.authid.focus() //--></script>
</form>

AUTHFORM;
$AuthPromptFmt = array(&$PageStartFmt, $AuthForm, &$PageEndFmt);

if ($_POST['authaction']) {
  $dbauth = array(
	  'host'      => 'localhost',
	  'db'        => 'dbase',
	  'user'      => 'dbase_user',
	  'password'  => 'dbase_password',
	  'table'     => 'table',
	  'userfield' => 'username',
	  'pwfield'   => 'password',
	  #'where'     => "and not(specialcriteria) "
  );
}
$AuthUserFunctions['mysql'] = 'AuthUserMySQL';
function AuthUserMySQL($pagename, $id, $pw, $pwlist) {
  global $dbauth;
  $link = mysql_connect($dbauth['host'],$dbauth['user'],$dbauth['password']);
  if (!$link)  die('Could not connect: '.mysql_error());
  @mysql_select_db($dbauth['db']) or die("Unable to select database $dbauth[db]: ".mysql_error());

  $user = $dbauth['userfield'];
  $pass = $dbauth['pwfield'];
  $table = $dbauth['table'];
  $where = $dbauth['where'];
  $ask = "SELECT * from $table WHERE $user='$id' and $pass=sha('$pw') $where;";
  # Probably should be $ask = "SELECT count(*) from $table WHERE $user='$id' and $pass=sha('$pw') $where;";

  $result = mysql_query($ask);
  if (!$result) die("Could not successfully run query ($query) from DB: ".mysql_error());
  return (mysql_num_rows($result) > 0) ? true : false;
  # With above: return ($result['count'] > 0) ? true : false;
  return false;
}