<?php
/* Engsoc Registry (http://clarkhall.ca/)
 * Copyright (C) 2001 Philip Steinke and Kevin Everets
 *
 * 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; either version 2 of the License, or
 * (at your option) any later version.
 *
 * 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
 *
 * The author may be reached at:
 *                                        Philip Steinke
 *                                        88B Wellington St.
 *   lintec@clarkhall.ca         or       Kingston, Ont.
 *                                        K7L 3C4
 *                                        CANADA
 */

/*****
 * Global Includes
 *
 * Other files that the registry depends on.
 *****/

// PHP4 Database-independent routines
// Note that the PEAR repository must be in the PHP include path.
require_once ('DB.php');

// registry configuration
// Sets database connection information and the list of administrators.
// Kept in a separate file to keep its contents private.
require_once (dirname(__FILE__).'/config.inc.php');

// Authentication/User class
require_once (dirname(__FILE__).'/auth.class.php');

/*****
 * Registry-wide global variables and initialization.
 *****/

// The mail domain for the registry.
$reg_domain 'clarkhall.ca';

// Check for NS4, set flag to do some kludges if it's being used.
if (strstr($HTTP_USER_AGENT'Mozilla/4'
    && !
strstr($HTTP_USER_AGENT'compatible')) {
    
$using_ns4 true;
}

// session must be started BEFORE we connect to the database!  otherwise we
// lose our connection index.
session_name("RegistryID");        
session_start();

// Set up the user object if it wasn't restored as part of the session.
//if (!session_is_registered("webuser")) { // this is the old way, and broken
if (!isset($_SESSION['webuser'])){
// AuthUser is the authentication/user class from auth.class.php
    
$webuser = new AuthUser();        
    
// track the user in the started the session
    
$_SESSION['webuser']= $webuser ;
    
//make $webuser and alias of that in the session
    
$webuser = &$_SESSION['webuser'];
} else {
     
$webuser = &$_SESSION['webuser'];
}    
    
// Debuging code
    /*
    print('<pre>');
    print_r($_SESSION);
    print('</pre>');
    */

// Initialize the database object.
$regdb = new DB;

// Define the database connection.  See the PEAR DB class docs for the
// syntax of this DSN.
$regdsn "pgsql://$db_user:$db_pwd@unix+localhost/$db_name";

// connect to the database
// parameters are (dsn, persistent).
$regdb $regdb->connect($regdsntrue);

// If the user agent is the W3C Validator, set the user to "testguy", so
// that it can see the page content properly.  Represents something of a
// security hole, but nothing too significant.
if (ereg('^W3C_Validator'$HTTP_USER_AGENT)) {
    
$webuser->handle 'testguy';
}

// Set status flag to ensure we can talk to the database.
$webuser->dbok = !(DB::isError($regdb));

// Get email address(es) for the maintainers
foreach ($master_admins as $adm_handle) {
    
$maint_mail[] = get_preferred_email($adm_handle);
}
$maint_mail implode(', '$maint_mail);
unset(
$adm_handle);
  
///////////////////////////
// End of header execution.
///////////////////////////

/*****
 * Registry-Wide Functions
 *
 * Any functions that are to be available throughout the registry should be
 * placed here.
 *****/


/*****
 * mail*()
 *
 * Misc. functions that give mailto links for various people or sets of
 * people.
 *****/
function mailus($text) {
    return 
"<a href=\"mailto:$GLOBALS[maint_mail]\">$text</a>";
}

function 
mailphil($text) {
    
$philMail get_preferred_email('lintec');
    return 
"<a href=\"mailto:$philMail\">$text</a>";
}

function 
mailkev($text) {
    
$kevMail get_preferred_email('flynn');
    return 
"<a href=\"mailto:$kevMail\">$text</a>";
}

/*****
 * get_preferred_email()
 *
 * Given a users handle, will return their preferred email address.
 *****/
function get_preferred_email($handle) {
    
$row $GLOBALS['regdb']->getRow("select email_preference, email_personal, 
                                      email_work from people where 
                                      handle='$handle'"
,
                                     
DB_FETCHMODE_ASSOC);
    
$pref $row['email_preference'];
    return 
$row["email_$pref"] ? $row["email_$pref"] : $row['email_personal'];
}

/*****
 * build_generation_query()
 *
 * This function returns an SQL "WHERE" clause to be used when looking for
 * all classes +-2 of the current class.
 *****/
function build_generation_query($class)
{
    
// Build generation query

    
$class += 100;
    
$gen_low $class-2;
    
$gen_high $class+2;
    
    if (
$gen_low 100) {
        
$gen_sql "(int4(class) >= $gen_low 
                    OR int4(class)+100 <= $gen_high)"
;
    } elseif (
$gen_high 200) {
        
$gen_high -= 100;
        
$gen_sql "(int4(class)+100 >= $gen_low
                    OR int4(class)+100 <= $gen_high)"
;
    } else {
        
$gen_sql "(int4(class)+100 >= $gen_low
                    AND int4(class)+100 <= $gen_high)"
;
    }
    return 
$gen_sql;
}


/*****
 * Common authentication handling and display functions.
 *
 * Each page has to call disp_header().  If authentication on a page is
 * required, call check_auth().  If check_auth fails, most pages will call
 * the disp_not_logged_in() function, but any page doing logins will handle
 * them.
 *****/


/*****
 * check_auth()
 *
 * Returns true if the user is allowed to see this page, false otherwise.
 * Catches the special case of a valid user who hasn't been approved yet,
 * and lets them know their application is still pending.
 *****/
function check_auth() {
    global 
$webuser;
    
$current_page basename($GLOBALS['PHP_SELF']);
    if (
$webuser->is_authenticated()) { 
        if (
$webuser->newuser) {
            print 
"<p>\n\tSorry, but you have not been validated ";
            print 
"yet.<br>\n\tWe have your information and just need time ";
            print 
"to verify it.<br>\n\tPlease check back later.\n</p>\n";
            
// log them out
            
$webuser->logout();
            include (
'footer.inc.php');
            exit();
        } else {
            
// User is authenticated and has been approved by an admin.
            
return true;
        } 
// end if newuser
    
} else {
        return 
false;
    }
}


/*****
 * disp_header()
 *
 * Spit out the common HTML headers for the site.
 *****/
function disp_header($pagetitle) {
    
// Set image and alt info for DB indicators.
    
global $webuser;
    
$sess_ok $webuser->is_authenticated();
    
$db_image 'dot_' . ($webuser->dbok 'green' 'red') .  '.png';
    
$db_alt $webuser->dbok 'ok' 'broken!';
    
$sess_image 'dot_' . ($sess_ok 'green' 'red') . '.png';
    
$sess_alt $sess_ok 'yes' 'no';

    
// Display the header.
    
print "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" ?>
<!DOCTYPE html PUBLIC 
    "-//W3C//DTD XHTML 1.0 Strict//EN"
    "DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
    <title><?php print $pagetitle ?></title>
    <link rel="stylesheet" href="registry.css" type="text/css" />
</head>
<body>
<table class="head" width="100%">
<tr><td rowspan="2"><img src="images/qe.png" alt="QE Logo" /></td>
    <td class="headTitle" rowspan="2">
    <img src="images/mr_clarkhall_new.png" alt="engineering society registry" /></td>
    <td><img src="images/db_check.png" alt="database:" /></td>
    <td><img src="images/<?php print $db_image ?>"
             alt="<?php print $db_alt ?>" /></td>
</tr>
<tr>
    <td><img src="images/sess_check.png" alt="logged in:" /></td>
    <td><img src="images/<?php print $sess_image ?>"
             alt="<?php print $sess_alt ?>" /></td>
</tr>
</table>
<?php
}


/*****
 * disp_not_logged_in()
 *
 * Notify user of the need to log in, and provide a
 * link to the main page.  Then stop.
 *****/
function disp_not_logged_in() {
    print 
"<p class=\"error\">\n";
    print 
"\tYou are not logged in.\n</p>\n<p>\n";
    print 
"Please go to the <a href=\"index.php\">login page</a>";
    print 
" to access the registry.\n</p>\n";
    include (
'footer.inc.php');
    exit();
}

/*****
 * disp_navbar()
 *
 * Display the navigation bar for the site.
 *****/
function disp_navbar() {
    
$current_page basename($GLOBALS['PHP_SELF']);
    print 
"<table class=\"nav\" cellspacing=\"0\" border=\"0\">\n";
    print 
"<tr align=\"center\">\n";
    
$page_name = array( 
            
// this may be adapted to hold image filenames..
            
"index.php"     => "home",
            
"search.php"    => "search",
            
"announce.php"  => "announcements",
            
"edit.php"      => "update your info",
            
"emailpref.php" => "email preferences",
            
"logout.php"    => "log out" );
    foreach(
$page_name as $menu_file => $menu_name) {
        print 
"<td ";
        if (
$current_page == $menu_file) {
            print 
"class=\"navCur\">$menu_name</td>";
        } else {
            print 
"class=\"nav\"><a class=\"nav\"";
            print 
" href=\"$menu_file\">$menu_name</a></td>";
        }
    }
    print 
"</tr>\n</table>\n"
}

?>