<?php
  /*
      authentication.php
       
      Contains the authentication functions.

      Changelog:
        2006-01-14 dave: Cleaned up code for v1.0 release
        2005-07-02 arne_sf: Failed login attempts are now logged on userid 0, not "-1" as before (which caused a constraint violation)
        2005-07-02 arne_sf: Replaced all instances of column name 'user' for table tbl_Users with 'username'
        2005-05-07 arne_sf: Changed the logging of successful/failed login attempts,
                            instead of logging complete SQL query (with password hash),
                            it now only logs supplied username and password when failed.
                             
      ## PAGE CONTAINS HANDYANDY MYSQL MODS ##
      ## Copyright (C) 2005 Andy Deakin (handyandy.org.uk) ##

      modified by Mark Harrison
        
      ----

      Created by:
        Copyright (C) 2005  Jason L Ellison <infotek@da...>

      This program is free software; you can redistribute it and/or
      modify it under the terms of the GNU General Public License
      as published by the Free Software Foundation version 2.

      This program is distributed in the hope that it will be useful,
      but WITHOUT ANY WARRANTY; without even the implied warranty of
      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
      GNU General Public License for more details.

      You should have received a copy of the GNU General Public License
      along with this program; if not, write to the Free Software
      Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.

   */

  //this script may only be included or required- so its better to die if called directly.
  if (strpos($_SERVER["SCRIPT_NAME"],basename(__FILE__, '.php')) !== false) {
    header("location: index.php");
  }

  function auth($user, $password) {
    // Try to find the submitted username and password combination in the
    // tbl_Users database table.
    $sql = "SELECT id,username,name,email,root,restricted FROM tbl_Users
      WHERE active=1 AND username='" . strtolower($user) . "' AND pass='" .
      md5($password) . "'";
    $result = db_recordset($sql);
  
    if (count($result) == 0) {
      //Attempt unsucessful
      makelog(0,0,"ATTEMPTED LOGIN - FAILURE","User: $user, with password: $password");
      return 0;
    } elseif (count($result) != 1) {
      // If the user / password cannot be reconciled, then return 0
      return 0;
    } else {
      return array(
        $result[0][username],
        $result[0][name],
        $result[0][email],
        $result[0][id],
        $result[0][root],
        $result[0][restricted]
      );
    }
  }

?>