<?php
/*****
functions.php:
This file contains main stock of functions.
Note this should be included in all pages that require db access
since db connection is made in this file.

author: jez hancock
email: munk@munk.me.uk
date: 15/10/2002
*****/

/******************************************************\
 * Function Name : connectToDB()
 *
 * Task : create connection to db
 *
 * Arguments : none
 *
 * Globals: all defined in config.php
 *
 * Returns : none, sets $link
 *
 \******************************************************/
function connectToDB() {
    global 
$link$dbhost$dbuser$dbpass$dbname;
    
    
// use pconnect - can be changed to just connect:
    
($link mysql_pconnect("$dbhost""$dbuser""$dbpass")) || die("Couldn't connect to MySQL");

    
// select db:
    
mysql_select_db("$dbname"$link) || die("Couldn't open db: $dbname. Error if any was: ".mysql_error() );
// end func dbConnect();



/******************************************************\
 * Function Name : getRow($table, $key, $val)
 *
 * Task : get a single row of info from db based on 
            args passed
 *
 * Arguments : string ($table, $key, $val)
 *
 * Returns : array $row
 *
 \******************************************************/
function getRow($table$key$val) {
    global 
$link;

    
// build query:
    
$query="SELECT * FROM $table WHERE $key='$val'";
    
    
// Run query:
    
$result=mysql_query($query$link) or die("getRow fatal error: ".mysql_error());
    
    
// Retrieve info:
    
$row=mysql_fetch_array($result);

    return 
$row;
// end func getRow($table, $key, $val)


/******************************************************\
 * Function Name : newUser($login, $pass)
 *
 * Task : Create a new user entry in the users table
            based on args passed
 *
 * Arguments : string($login, $pass)
 *
 * Returns : int($id), $id of new user
 *
 \******************************************************/
function newUser($login$pass) {
    global 
$link;

    
$query="INSERT INTO users (login, password) VALUES('$login', '$pass')";
    
$result=mysql_query($query$link) or die("Died inserting login info into db.  Error returned if any: ".mysql_error());
    
    
// last auto increment id:
    
$id=mysql_insert_id($link);
    return 
$id;
// end func newUser($login, $pass)


/******************************************************\
 * Function Name : displayErrors($messages)
 *
 * Task : display a list of errors
 *
 * Arguments : array $messages
 *
 * Returns : none
 *
 \******************************************************/
function displayErrors($messages) {
    print(
"<b>There were problems with the previous action.  Following is a list of the error messages generated:</b>\n<ul>\n");

    foreach(
$messages as $msg){
        print(
"<li>$msg</li>\n");
    }
    print(
"</ul>\n");
// end func displayErrors($messages)


/******************************************************\
 * Function Name : checkLoggedIn($status)
 *
 * Task : check if a user is (isn't) logged in depending on $status
 *
 * Arguments : quasi(!) boolean $status - "yes" or "no"
 *
 * Returns :
 *
 \******************************************************/
function checkLoggedIn($status){
    switch(
$status){
        
// if yes, check user is logged in:
        // ie for actions where, yes, user must be logged in(!)
        
case "yes":
            if(!
$_SESSION["session"]["loggedIn"]){
                
header("Location: login.php");
                exit;
            }
            break;
            
        
// if no, check NOT logged in:
        // ie for actions where user can't already be logged in (ie for joining up or logging in)
        
case "no":
            if(
$_SESSION["session"]["loggedIn"]){
                
header("Location: members.php?".session_name()."=".session_id());
            }
            break;            
    }    
    
// if got here, all ok, return true:
    
return true;
// end func checkLoggedIn($status)


/******************************************************\
 * Function Name : checkPass($login, $password) 
 *
 * Task : check login/passwd match that stored in db 
 *
 * Arguments : string($login, $password);
 *
 * Returns : array $row  - array of member details on success
 *                false on failure
 \******************************************************/
function checkPass($login$password) {
    global 
$link;
    
    
$query="SELECT id, login, password FROM users WHERE login='$login' and password='$password'";
    
$result=mysql_query($query$link)
        or die(
"checkPass fatal error: ".mysql_error());
    
    if(
mysql_num_rows($result)) {
        
$row=mysql_fetch_array($result);
        return 
$row;
    }
    
//Bad Login:
    
return false;
// end func checkPass($login, $password) 


/******************************************************\
 * Function Name : cleanMemberSession($id, $login, $pass)
 *
 * Task : populate a session variable
 *
 * Arguments : string $login, string $pass
                taken from users table in db.
 *
 * Returns : none
 *
 \******************************************************/
function cleanMemberSession($login$pass) {
    
$_SESSION["session"]["login"]=$login;
    
$_SESSION["session"]["password"]=$pass;
    
$_SESSION["session"]["loggedIn"]=true;
// end func cleanMemberSession($id, $login, $pass)


/******************************************************\
 * Function Name : flushMemberSession($session)
 *
 * Task : unset session variables and destroy session
 *
 * Arguments : array $session
 *
 * Returns : true
 *
 \******************************************************/
function flushMemberSession() {
    
// use unset to destroy the $session variable
    // (which is an array stored in the super variable $_SESSION):
    
unset($_SESSION["session"]);

    
// and use session_destroy to destroy all data associated with current session:
    
session_destroy();

    return 
true;



/******************************************************\
 * Function Name : doCSS()
 *
 * Task : output the CSS for the screens
 *
 * Arguments :
 *
 * Returns :
 *
 \******************************************************/
function doCSS() {
    
?>
<style type="text/css">
body{font-family: Arial, Helvetica; font-size: 10pt}
h1{font-size: 12pt}
</style>
    <?php
// end func doCSS()

# function validates HTML form field data passed to it:
function field_validator($field_descr$field_data$field_type$min_length=""$max_length=""$field_required=1) {
    
# array for storing error messages
    
global $messages;
    
    
# first, if no data and field is not required, just return now:
    
if(!$field_data && !$field_required){ return; }

    
# initialize a flag variable - used to flag whether data is valid or not
    
$field_ok=false;

    
# this is the regexp for email validation:
    
$email_regexp="^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|";
    
$email_regexp.="(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$";

    
# a hash array of "types of data" pointing to "regexps" used to validate the data:
    
$data_types=array(
        
"email"=>$email_regexp,
        
"digit"=>"^[0-9]$",
        
"number"=>"^[0-9]+$",
        
"alpha"=>"^[a-zA-Z]+$",
        
"alpha_space"=>"^[a-zA-Z ]+$",
        
"alphanumeric"=>"^[a-zA-Z0-9]+$",
        
"alphanumeric_space"=>"^[a-zA-Z0-9 ]+$",
        
"string"=>""
    
);
    
    
# check for required fields
    
if ($field_required && empty($field_data)) {
        
$messages[] = "$field_descr is a required field.";
        return;
    }
    
    
# if field type is a string, no need to check regexp:
    
if ($field_type == "string") {
        
$field_ok true;
    } else {
        
# Check the field data against the regexp pattern:
        
$field_ok ereg($data_types[$field_type], $field_data);        
    }
    
    
# if field data is bad, add message:
    
if (!$field_ok) {
        
$messages[] = "Please enter a valid $field_descr.";
        return;
    }
    
    
# field data min length checking:
    
if ($field_ok && $min_length) {
        if (
strlen($field_data) < $min_length) {
            
$messages[] = "$field_descr is invalid, it should be at least $min_length character(s).";
            return;
        }
    }
    
    
# field data max length checking:
    
if ($field_ok && $max_length) {
        if (
strlen($field_data) > $max_length) {
            
$messages[] = "$field_descr is invalid, it should be less than $max_length characters.";
            return;
        }
    }
}
?>