<?php

/**
*  Authenticate against phpBB3 database
*/

include_once ("$FarmD/cookbook/adodb-connect.php"); # what path to adodb-connect.php
include_once ("$FarmD/cookbook/passwordhashing.php"); # path to PasswordHash.php

# let Site.AuthForm know that we're doing user-based authorization
$EnableAuthUser = 1;

if (@$_POST['authid'])
  AuthUserId($pagename, stripmagic(@$_POST['authid']),
             stripmagic(@$_POST['authpw']));
else
  SessionAuth($pagename);

function AuthUserId($pagename, $id, $pw=NULL) {
  global $AuthId;

  if (!AuthUserDatabase($pagename, $id, $pw, $authlist)) {
    $GLOBALS['InvalidLogin'] = 1;
    return;
  }
  else {
    if (!isset($AuthId))
      $AuthId = $id;
    $authlist["id:$id"] = 1;
    $authlist["id:-$id"] = -1;
    SessionAuth($pagename, array('authid' => $id, 'authlist' => $authlist));
  }
}

function AuthUserDatabase($pagename, $id, $pw, &$authlist) {
  global $DB;

  # Connect to the database
  $out = ADOdbConnect('phpbb_db');
  if ($out !== TRUE) die($out);

  $id = addslashes($id);
  $query = "SELECT user_password, user_id FROM phpbb_users WHERE username='$id' AND user_type<>1";
  # Query Database, Get Hash and User Id
  $result = $DB['phpbb_db']->Execute($query);
  $hash = $result->fields[0];
  $UserId = $result->fields[1];

  $pw_hash = crypt_private($pw, $hash);

  if ($pw_hash == $hash) {
    # If successfully authenticated then get the user's groups
    $query = "SELECT g.group_name, ug.group_leader
        FROM phpbb_groups g, phpbb_user_group ug
        WHERE ug.group_id = g.group_id
        AND ug.user_id = $UserId
        AND user_pending = 0";
    $rowset = $DB['phpbb_db']->Execute($query);
    while ( $row = $rowset->FetchRow() ) {
      $GroupName = str_replace(' ', '', $row['group_name']); # remove spaces
      $authlist['@' . $GroupName] = 1;
      if ($row['group_leader'] == 1)
        $authlist['@' . $GroupName . 'Moderator'] = 1;
    }
    return true;
  }
  else
    return false;
}


?>