<?php

/*
   File: lib/db/mysql.lib.php3
   $Author: zerodiv $
   $Revision: 1.19 $
   $Date: 1998/12/23 07:39:24 $

   IMP : Copyright 1998 Charles J. Hagenbuch chuck@osmos.ml.org

   This code is under the GNU Public License
   See the file COPYING in this directory

File Purpose:
This file contains the database support for mysql.

*/
/*      EOF - mysql/includes/HordeCopyright.inc       */



/*
Mysql HordeLibrary Version      : mysql/defines/HordeLibVersion.def
*/
/* Horde Library Loaded Define */
define( "MYSQL_HORDE_LIB",             1 );
/* Library Version */
define( "MYSQL_HORDE_LIB_VERSION",     '1.0' );
/*      EOF - mysql/defines/HordeLibVersion.def       */



/*
User_ImapServer Object      : mysql/objects/User_ImapServer.obj
*/
class HordeMysqlDb_User_ImapServer {
   var $db_connection_handle;

   /*
   Function       : HordeMysqlDb_User_ImapServer
   Parameters     : NONE
   Return Values  : NONE
   Purpose        : To instanciate a instance of the HordeMysqlDb_User_ImapServer object.
   */
   Function HordeMysqlDb_User_ImapServer() {
   $db_connection_handle = false;
   } /* END HordeMysqlDb_User_ImapServer() */


   /* CascadeConnection() -   Cascades the connection handle down to 
                              the subobjects */
   Function CascadeConnection() {
   } /* END CascadeConnection */

   /*
   Function       : ListAll
   Parameters     : (HordeUser)
   Return Values  :
      TRUE, (Array - ImapServer)
      FALSE, ERROR_ID
   Purpose        : To return an array of imap servers that the user has available to them.
   */
   Function ListAll( $ThisUser ) {

   /* Make sure the database handle is available */
   if ( $this->db_connection_handle == false ) {
      return array( false, DB_NOT_CONNECTED, 'No connection available to object.' );
   }
 
   } /* END ListAll() */

}
/*      EOF - mysql/objects/User_ImapServer.obj       */



/*
User Object      : mysql/objects/User.obj
*/
class HordeMysqlDb_User {
   var $db_connection_handle;
   var $autocreate_user;
   var $ImapServer;
	var $HordeModules;
	var $debug;

   /*
   Function       : HordeMysqlDbUser
   Parameters     : NONE
   Return Values  : NONE
   Purpose        : To instanciate a instance of the HordeMysqlDb object.
   */
   Function HordeMysqlDb_User() {
      $this->db_connection_handle   = false;
      $this->autocreate_user        = false;
      $this->ImapServer             = new HordeMysqlDb_User_ImapServer;
      $this->HordeModules           = new HordeMysqlDb_User_HordeModules;
		$this->debug						= false;

      $this->CascadeConnection();
      } /* END HordeMysqlDb_User() */

   /* CascadeConnection() -   Cascades the connection handle down to 
                              the subobjects */
   Function CascadeConnection() {
      $this->ImapServer->db_connection_handle     = $this->db_connection_handle;
      $this->HordeModules->db_connection_handle   = $this->db_connection_handle;
      } /* END CascadeConnection() */


   /*
   Function       : Verify
   Parameters     : (HordeUser)
   Return Values  :                    
      TRUE, HordeUser
      FALSE, Error Id
   Purpose        : To verify a users access to the horde system.
   */
   Function Verify( $ThisUser ) {

      /* Make sure the database handle is available */
      if ( $this->db_connection_handle == false ) {
         return array( false, DB_NOT_CONNECTED, 'No connection available to object.' );
         }

		echo( '<!-- Call get -->' );
      list( $return_val, $TempUser ) = $this->Get( $ThisUser );

      if ( $return_val == false ) {
         /* User not found and or another error */
			echo( '<!-- Call get -->' );
         list( $return_val, $error_code, $reason ) = $this->Get( $ThisUser );
			echo( '<!-- REturn code : ' . $error_code . " -->\n" );
			echo( '<!-- Re : ' . $reason . " -->\n" );
         if ( $error_code == DB_NO_MATCH_FOUND && $this->autocreate_user == true ) {
            /* Auto create the user */
            $this->Add( $ThisUser );
            return array( true, $ThisUser );
            }
         } /* End if NOT found and other error */

      if ( $TempUser->login_deny == true ) {
         return array( false, DENY_LOGIN, 'Your account has been locked out.' );
         }
      if ( $TempUser->password == $ThisUser->password ) {
         return array( true, $TempUser );
      } else {
         return array( false, DENY_LOGIN, 'Invalid user name and or password please try again.' );
      }

      return array( false, DENY_LOGIN, 'UNKOWN LOGIN ERROR' );

      } /* END Verify() */

   /*
   Function       : Get
   Parameters     : (HordeUser)
   Return Values  :                       
      (HordeUser) $ThisUser               
      FALSE, ERROR_ID
   Purpose        : Finds a user with the attributes that are passed in.
   */
   Function Get( $ThisUser ) {

      /* Make sure the database handle is available */
      if ( $this->db_connection_handle == false ) {
         return array( false, DB_NOT_CONNECTED, 'No connection available to object.' );
         }

      /* Build up the query string */
      $query_string = '';
      $query_string .= 'SELECT
                        	user_id, user_name, user_password, login_deny
								FROM
									horde_user_table
								WHERE
';

      $more_than_one = false;
      if ( $ThisUser->user_id && $ThisUser->user_id != -1 ) {
         $query_string .= 'user_id = ' . $ThisUser->user_id;
         $more_than_one = true;
         }


      if ( $ThisUser->user_name ) {
      	if ( $more_than_one == true ) { $query_string .= ' AND '; }
         $query_string .= 'user_name = "' . $user_name . '"';
         $more_than_one = true;
         }


      if ( $ThisUser->password ) {
      	if ( $more_than_one == true ) { $query_string .= ' AND '; }
         $query_string .= 'password = "' . $password . '"';
         $more_than_one = true;
         }

      $query_string .= ';';

      if ( ! $result_handle = mysql_db_query( $this->db_connection_handle, $query_string ) ) {
         return array( false, DB_QUERY_FAILED, 'Database query of : ' . $query_string . ' failed.' );
         }

      $ResultObject = new HordeUser;
      if ( ! ( list( $user_id, $user_name, $password, $login_deny ) = mysql_fetch_row( $result_handle )) ){
         return array( false, DB_NO_MATCH_FOUND, 'NO Match found.' );
      }

      $ResultObject->user_id     = $user_id;
      $ResultObject->user_name   = $user_name;
      $ResultObject->password    = $password;
      $ResultObject->login_deny  = $login_deny;

		echo( '<!-- User Id : ' . $user_id . " -->\n" );
		echo( '<!-- User N  : ' . $user_name . " -->\n" );
		echo( '<!-- User P : ' . $password . " -->\n" );
		echo( '<!-- User D : ' . $login_deny . " -->\n" );
      return array( true, $ResultObject );

      } /* END Get() */

   /*
   Function       : Add
   Parameters     : (HordeUser)
   Return Values  :                       
      TRUE,  (hordeuser)                                
      FALSE, ERROR_ID
   Purpose        : Adds a user with the attributes defined in the
                    $ThisUser that is passed in.
   */
   Function Add( $ThisUser ) {

      /* Make sure the database handle is available */
      if ( $this->db_connection_handle == false ) {
         return array( false, DB_NOT_CONNECTED, 'No connection available to the object.' );
         }

      $query_string = '';
      $query_string =
         'INSERT INTO horde_user_table
            ( horde_user_name, horde_password, login_deny ) VALUES (';
      if ( $ThisUser->user_name == '' ) {
         return array( false, DB_INSERT_FAILED, 'NO user name provided' );
         } else {
         $query_string .=  "'" . $ThisUser->user_name . "', ";
         }
      if ( $ThisUser->user_password == '' ) {
         return array( false, DB_INSERT_FAILED, 'NO password provided' );
         } else {
         $query_string .= "'" . $ThisUser->user_password . "', ";
         }
      if ( $ThisUser->login_deny == false
            || $ThisUser->login_deny == true  ) {
         $ThisUser->login_deny = 1;
         } else { 
         $ThisUser->login_deny = 0;
         }
      $query_string .= $ThisUser->login_deny;
      $query_string .= ' )';
      /*
      echo( '<BR><code><pre>' . $query_string . '</pre></code><BR><BR>' );             
      */
      if ( ! ( $result_handle = mysql_query(
            $query_string,
            $this->db_connection_handle
             ) ) ) {
         return array( false, DB_INSERT_FAILED, 'Insert to table failed.' );
         } else {
         return array( true, $ThisUser );
         }
      } /* END Add() */

   /*
   Function       : Modify
   Parameters     : (HordeUser->user_id), (HordeUser) 
   Return Values  :                       
      TRUE                                
      FALSE, ERROR_ID
   Purpose        : Modify the user_id(x)'s member data to contain
                    the new data provided within the
                    passed in object
   */
   Function Modify( $user_id, $ThisUser ) {

      /* Make sure the database handle is available */
      if ( $this->db_connection_handle == false ) {
         return array( false, DB_NOT_CONNECTED, 'NO connection available to the object' );
         }
      if ( $user_id != '' ) { 
         } else {
         return array( false, DB_QUERY_FAILED, 'Please provide a user id.' );
         }
      $query_string = '';
      $more_than_one = false;
      $query_string = 'UPDATE horde_user_table SET ';
      if ( $ThisUser->user_name != '' ) {
         $query_string .= " horde_user_name = '" . $ThisUser->user_name . "'";
      }
      if ( $ThisUser->user_password != '' ) {
         $query_string .= ", horde_password = '" . $ThisUser->user_password . "'";
      }
      if ( $ThisUser->login_deny == false
            || $ThisUser->login_deny == true  ) {
         $query_string .= ", login_deny = 1";
         } else { 
         $query_string .= ", login_deny = 0";
         }
      if ( $ThisUser->user_id != '' ) {
         $query_string .= ', horde_user_id = ' . $ThisUser->user_id;
      }
      $query_string .= " where horde_user_id = $user_id";
      if ( ! ( $result_handle = mysql_query(
            $query_string,
            $this->db_connection_handle
             ) ) ) {
         return array( false, DB_QUERY_FAILED, 'Query Failed : ' . $query_string );
         }
     
      return array( true, $ThisUser );
      } /* END Modify */

   /*
   Function       : Delete
   Parameters     : (HordeUser->user_id)
   Return Values  :
      TRUE
      FALSE, ERROR_ID
   Purpose        : To delete a user_id(x)'s data from the database.
   */
   Function Delete( $user_id ) {

      /* Make sure the database handle is available */
      if ( $this->db_connection_handle == false ) {
         return array( false, DB_NOT_CONNECTED );
         }

      } /* END Delete */

   /*
   Function       : ListAll
   Parameters     : NONE
   Return Values  : Array of HordeUser objects
   Purpose        : To list all of the users within the system.
   */
   Function ListAll() {

      /* Make sure the database handle is available */
      if ( $this->db_connection_handle == false ) {
         return array( false, DB_NOT_CONNECTED );
         }
      $query_string = '';
      $query_string =
         'SELECT horde_user_id, horde_user_name, horde_password, login_deny FROM horde_user_table ORDER BY horde_user_id';
      
      if ( ! ( $result_handle = mysql_query(
            $query_string,
            $this->db_connection_handle
             ) ) ) {
         return array( false, DB_QUERY_FAILED, 'Query Failed' );
         }
     
      $i = 0; 
      $ResultArray   = array();
      $ResultObj     = new HordeUser;

      while( list( $user_id, $user_name, $password, $login_deny ) = mysql_fetch_row( $result_handle ) ) {
         /* Loop through the output and build the array */
         $ResultObj->user_id     = 0;
         $ResultObj->user_name   = '';
         $ResultObj->password    = '';
         $ResultObj->login_deny  = true;
         $ResultObj->user_id     = $user_id;
         $ResultObj->user_name   = $user_name;
         $ResultObj->password    = $password;
         $ResultObj->login_deny  = $login_deny;
         $ResultArray[ $i ] = $ResultObj;
         $i++;
      }
      return array( true, $i, $ResultArray );
      } /* END List All */

   }
/*      EOF - mysql/objects/User.obj       */



class HordeMysqlDb_User_HordeModules {
   var $db_connection_handle;
	var $debug;

   /*
   Function       : HordeMysqlDb_User_HordeModules
   Parameters     : NONE
   Return Values  : NONE
   Purpose        : To instanciate a instance of the HordeMysqlDb_User_HordeModules object.
   */
   Function HordeMysqlDb_User_HordeModules() {
   $db_connection_handle 		= false;
	$debug							= false;
   } /* END HordeMysqlDb_User_HordeModules() */


   /* CascadeConnection() -   Cascades the connection handle down to 
                              the subobjects */
   Function CascadeConnection() {
   } /* END CascadeConnection */

	/*
   Function       : VerifyModuleAccess
   Parameters     : (Horde *UserId must be provided*, Horde Module Name)
   Return Values  :
      TRUE, $ResultObj
      FALSE, ERROR_ID
   Purpose        : To return an array of imap servers that the user has available to them.
	*/
	Function VerifyModuleAccess( $ThisUser, $ModuleName ) {
		$return_vals = $this->ListAll( $ThisUser );
		/* False means we've had a problem so, propigate it up to the calling env */
		if ( $return_vals[ 0 ] == false ) { return $return_vals; }
		$ResultObj         = new HordeModule;
		list( $tf_scrap, $count, $object_arr ) = $return_vals;
	
		$found_module = false;
		for( $i = 0; $i < $count; $i++ ) {
			if ( $object_arr[ $i ]->horde_module_name == $ModuleName ) {
				$ResultObj = $object_arr[ $i ];
				$found_module = true;
			}
		}
		if ( $found_module == false ) {
			return array( false, DB_QUERY_FAILED, 'No match found' );
		}
		return array( true, $ResultObj );
	}
   /*
   Function       : ListAll
   Parameters     : (HordeUser *UserId must be provided*)
   Return Values  :
      TRUE, NumItems, (Array - HordeModule)
      FALSE, ERROR_ID
   Purpose        : To return an array of imap servers that the user has available to them.
   */
   Function ListAll( $ThisUser ) {

   /* Make sure the database handle is available */
   if ( $this->db_connection_handle == false ) {
      return array( false, DB_NOT_CONNECTED, 'No connection available to object.' );
   }

	if ( ! $ThisUser->user_id ) {
		return array( false, DB_QUERY_FAILED, 'No User Id Provided' );
	}

	$query_string = '';

	$query_string = '
		SELECT
			horde_modules_table.horde_module_id,
			horde_modules_table.horde_module_name,
			horde_modules_table.horde_module_full_name
		FROM
			horde_modules_table,
			horde_user_module_grant_table,
			horde_user_table
		WHERE
			horde_modules_table.horde_module_id = horde_user_module_grant_table.horde_module_id
		AND
			horde_user_table.horde_user_id	= horde_user_module_grant_table.horde_user_id
		AND
	';
	
	  
     if ( $ThisUser->user_id ) { $query_string .= 'horde_user_table.user_id = ' . $ThisUser->user_id; }

     $query_string .= ';';

     if ( ! ( $result_handle = mysql_query( $query_string, $this->db_connection_handle) ) ) {
         return array( false, DB_QUERY_FAILED, 'Query Failed' );
     }

	$i = 0;
	$ResultsArray      = Array();
	$ResultObj         = new HordeModule;
	while( list( $horde_module_id, $horde_module_name, $horde_module_full_name ) = mysql_fetch_row( $result_handle ) ) {
		$ResultObj->horde_module_id				= $horde_module_id;
		$ResultObj->horde_module_name				= $horde_module_name;
		$ResultObj->horde_module_full_name		= $horde_module_full_name;
		$ResultsArray[ $i ] = $ResultObj;
		$i++;
	}
	return array( true, $i, $ResultsArray );
	
   } /* END ListAll() */

}
/*      EOF - mysql/objects/User_HordeModules.obj       */



/*
HordeMysqlDb Object      : mysql/objects/HordeMysqlDb.obj
*/
class HordeMysqlDb {
   var $user_name;
   var $password;
   var $server_name;
   var $server_port;
   var $db_name;
   var $db_connect_string;
   var $db_connection_handle;
   var $persistent_mode;
   var $connection_init;
	var $debug;

   /* The following object api MUST be within all database objects */
   var $User;
   var $Grant;
   var $ImapServer;

   Function HordeMysqlDb() {

      $this->user_name              = '';
      $this->password               = '';
      $this->server_name            = 'localhost';
      $this->server_port            = '';
      $this->db_name                = '';
      $this->db_connect_string      = '';
      $this->db_connection_handle   = false;
      $this->persistent_mode        = true;
      $this->connection_init        = false;
		$this->debug						= false;

      /* The following object api MUST be within all database objects */
      $this->User                   = new HordeMysqlDb_User;

      } /* END HordeMysqlDb() */

   /* CascadeConnection() -   Cascades the connection handle down to 
                              the subobjects */
   Function CascadeConnection() {
		$this->DebugMessage( 'Cascade Connection' );
      $this->User->db_connection_handle   = $this->db_connection_handle;
		$this->User->debug						= $this->debug;
      } /* END CascadeConnection() */

	Function DebugMessage( $message ) {
		if ( $this->debug ) {
			/* Debug Messages */
			echo( '<!-- HordeMysqlDb : ' . $message . ' -->' . "\n" );
		}
	}

   Function BuildConnectString() {

		$this->DebugMessage( 'Build ConnectString' );
      $this->db_connect_string = $this->server_name;
		
      if ( $this->server_port != '' ) {
         $this->db_connect_string .= ':' . $this->port_name;
         }

      } /* END BuildConnectionString */

   Function CreateConnection() {

      $this->BuildConnectString();

      if ( $this->persistent_mode == true && $this->connection_init == false ) {

         /* Open the connection to the database */
         if ( !(
               $this->db_connection_handle =
               mysql_pconnect(
                  $this->db_connect_string,
                  $this->user_name,
                  $this->password )
               ) ) {
				$this->DebugMessage( 'Database Invalid Username / Password Combo' );
            return array( false, DB_INVALID_USERNAME_PASSWORD, 'Invalid username / password combonation.' );
            }

         /* Switch to the horde database for that connection */
         if ( !( $db_test = mysql_select_db(
               $this->db_name, $this->db_connection_handle )
               )  ) { 
				$this->DebugMessage( 'Database select failed, check for database existance or misconfiguration.' );
            return array( false, DB_DATABASE_FAILED, 'Select database : ' . $this->db_name . ' failed, check for database existance, or misconfiguration' );
            }

         $this->CascadeConnection();

         return array( true, $this->db_connection_handle );

         }

      if ( 
         $this->persistent_mode == true &&
         $this->connection_init == true ) {
         $this->CascadeConnection();
         return array( $this->db_connection_handle );
         } 

      } /* END CreateConnection() */

      
   } /* END HordeMysqlDb class */
/*      EOF - mysql/objects/HordeMysqlDb.obj       */



?>
