niczak
3/30/2012 - 4:59 PM

gistfile1.aw

<?php

/*
  db_utils.inc
    Collection of database-related function used
    by DRI applications.
    
  Written: 03/30/2012, Nicholas Kreidberg
  Revised: 03/30/2012, Nicholas Kreidberg

*/

function fnDB_Open($sPKG, $sPerm, $sScope)
{
  /*
    Function used to open and return database
    handles.  All parameters are required in
    calls to function and if the function_exists
    encounters any problems it returns NULL
    so it is up the caller to check for return
    values and handle things accordingly.
    
    Call: $hDB = fnDB_Open("PIP", "RO", "Internal");
  */
  
  if(empty($sPKG) || empty($sPerm) || empty($sScope))
    return NULL;
    
  $aConstants = get_defined_constants();
  
  // Convert scope parameter to upper case
  $sScope = strtoupper($sScope);
    
  if($sScope === "INT" && empty($aConstants['sDB_SCOPE_INT'])) {
    // Include internal credentials
    require_once("dbauth_int.inc");
  }  
  else if($sScope === "PUB" && empty($aConstants['sDB_SCOPE_PUB'])) {
    // Include public credentials
    require_once("dbauth_pub.inc"); 
  }
  else {
    // Invalid value passed for this parameter
    if(empty($aConstants['sDB_SCOPE_INT']) && empty($aConstants['sDB_SCOPE_PUB']))
      return NULL; 
  }
  
  $sDB_Prefix = sprintf("sDB_%s_%s", $sPKG, $sPerm);
  
  $sHost = constant($sDB_Prefix."_HOST"."_$sScope");
  $sPort = constant($sDB_Prefix."_PORT"."_$sScope");
  $sUser = constant($sDB_Prefix."_USER"."_$sScope");
  $sPW = constant($sDB_Prefix."_PW"."_$sScope");
  $sPW = base64_decode($sPW);
  $sName = constant($sDB_Prefix."_NAME"."_$sScope");

  ($hDB = pg_connect("host=$sHost port=$sPort user=$sUser password=$sPW dbname=$sName")) or 
    die("Failed to connect to the database $sPKG!");
  
  return $hDB;
}
?>