<?php

/**************************************************************************
***    Use:                     Retrieves Coppermine user data based on the session ID in CGP 1.4x
***    Retrieved By:      allow files by commonFiles.inc.php
***    Requires:            config.inc.php
***    Written By:        Jordan Coffey
***    Created:             September 12, 2008
***    Last Updated:     September 29, 2008
***    Notes:                 Requires $CONFIG['site_url'] to be defined in config.inc.php
                                      Adapted from auth.inc.php by Nibbler for CPG 1.3x found here:
                                      http://forum.coppermine-gallery.net/index.php/topic,11013.0.html
**************************************************************************/




/**************************************************************************
  Require config.inc for CPG settings.  **NOTE: this auth file requires $CONFIG['site_url']
  to be defined in config.inc because of its use outside Coppermine
 **************************************************************************/
require_once ($_SERVER['DOCUMENT_ROOT']."/photo/include/config.inc.php");

/**************************************************************************/



/**************************************************************************
  Encapsulate in a function to ensure the data is extracted upon inclusion of this file
 **************************************************************************/
function auth_me()
    {

        // Define the necessary globals
        global $CONFIG, $USER_DATA, $session_uid;

        // Set the tables used in this file
        $CONFIG['TABLE_USERGROUPS']        = $CONFIG['TABLE_PREFIX']."usergroups";
        $CONFIG['TABLE_USERS']             = $CONFIG['TABLE_PREFIX']."users";
        $CONFIG['TABLE_CONFIG']            = $CONFIG['TABLE_PREFIX']."config";
        $CONFIG['TABLE_SESSIONS']          = $CONFIG['TABLE_PREFIX']."sessions";


        // Process the queries after ensuring that a database connection is initiated
        function run_query($query)
            {
                global $CONFIG;
                static $auth_link;

                // If there is no database connection, connect
                if (!$auth_link){
                    $auth_link = mysql_connect($CONFIG['dbserver'], $CONFIG['dbuser'], $CONFIG['dbpass']);
                    mysql_select_db($CONFIG['dbname'], $auth_link);
                }

                // Close the database connection when the 'close' string is passed into the function,  otherwise query the database
                if ($query == 'close'){
                    mysql_close($auth_link);
                } else return mysql_query($query, $auth_link);
            }


        // Retrieve User settings for the primary group the user is a member of
        // $pri_groups is the primary group the user is a member of, $groups is the other groups the user is a member of, $default_group_id is used when no primary group is found (user is a guest)
        function cpgGetUserData($pri_group, $groups, $default_group_id = 3)
            {
                global $CONFIG;

                // If the user group that is passed is not an integer, unset that user group
                foreach ($groups as $key => $val)
                    if (!is_numeric($val)) unset ($groups[$key]);

                // If the primary user group that the user is a member of is not in the list of other groups they are a member of, append the primary group to the list
                if (!in_array($pri_group, $groups)) array_push($groups, $pri_group);

                // Set the limitations based on their group membership
                $result = run_query("SELECT MAX(group_quota) as disk_max, MIN(group_quota) as disk_min, " .
                    "MAX(can_rate_pictures) as can_rate_pictures, MAX(can_send_ecards) as can_send_ecards, " .
                    "MAX(upload_form_config) as ufc_max, MIN(upload_form_config) as ufc_min, " .
                    "MAX(custom_user_upload) as custom_user_upload, MAX(num_file_upload) as num_file_upload, " .
                    "MAX(num_URI_upload) as num_URI_upload, " .
                    "MAX(can_post_comments) as can_post_comments, MAX(can_upload_pictures) as can_upload_pictures, " .
                    "MAX(can_create_albums) as can_create_albums, " .
                    "MAX(has_admin_access) as has_admin_access, " .
                    "MIN(pub_upl_need_approval) as pub_upl_need_approval, MIN( priv_upl_need_approval) as  priv_upl_need_approval ".
                    "FROM {$CONFIG['TABLE_USERGROUPS']} WHERE group_id in (" .  implode(",", $groups). ")");

                // Check to see if any records were returned, if so define an array in USER_DATA
                if (mysql_num_rows($result)) {
                    // Load the limitations into USER_DATA as an array
                    $USER_DATA = mysql_fetch_assoc($result);
                    // Request the group name of the primary group
                    $result = run_query("SELECT group_name FROM  {$CONFIG['TABLE_USERGROUPS']} WHERE group_id= " . $pri_group);
                    $temp_arr = mysql_fetch_assoc($result);
                    // Add the group name to the USER_DATA array
                    $USER_DATA["group_name"] = $temp_arr["group_name"];
                // If no results, load the default id (3 for guests)
                } else {
                    // Request all the settings for a default (guest) user
                    $result = run_query("SELECT * FROM {$CONFIG['TABLE_USERGROUPS']} WHERE group_id = $default_group_id");
                    if (!mysql_num_rows($result)) die('<b>Coppermine critical error</b>:<br />The group table does not contain the Anonymous group !');
                    // Load the default user settings into the USER_DATA array
                    $USER_DATA = mysql_fetch_assoc($result);
                }

                // Free up system resources that were used by the query
                mysql_free_result($result);
                // Add the group_id as the primary group into the USER_DATA array
                $USER_DATA["group_id"] = $pri_group;
                // Add the additional groups into the USER_DATA array
                $USER_DATA['groups'] = $groups;

                // If magic quotes are turned off, then escape the string to ensure no problems
                if (get_magic_quotes_gpc() == 0)
                    $USER_DATA['group_name'] = mysql_escape_string($USER_DATA['group_name']);

                return($USER_DATA);
            }

        // Establish the user ID based on the retrieved session ID
        function extractSessionInfo()
            {
                global $CONFIG, $session_uid;

                //Generate the client_id
                $client_id = md5($_SERVER['HTTP_USER_AGENT'].$_SERVER['SERVER_PROTOCOL'].$CONFIG['site_url']);

                // Get the session cookie value
                $sessioncookie = $_COOKIE[$client_id];

                // Create the session id by concat(session_cookie_value, client_id)
                $session_id = $sessioncookie.$client_id;

                // Check for valid session
                $sql =  "SELECT user_id FROM {$CONFIG['TABLE_SESSIONS']} WHERE session_id=md5('$session_id');";
                $result = run_query($sql);

                $row = mysql_fetch_array($result);
                $session_uid = $row['user_id'];

            }


        extractSessionInfo();
        // If a user_id can be retrieved from the session, continue, otherwise load basic data
        if (!empty($session_uid)) {
            // Get all the user information from the database where the user_id matches that from the cookie, the user is active, the password is not empty, and the password matches that in the cookie
            $results = run_query("SELECT * FROM {$CONFIG['TABLE_USERS']} WHERE user_id='$session_uid' AND user_active = 'YES'");
            $USER_DATA = mysql_fetch_assoc($results);
            // For security measures, replace the user's password with a null string
            $USER_DATA['user_password'] = '********';
            // Free up the system resources used by the query
            mysql_free_result($results);
            // Append the user data from the user database with that gleaned from the usergroups database where the groups matched
            $USER_DATA = $USER_DATA + cpgGetUserData($USER_DATA['user_group'], explode(',', $USER_DATA['user_group_list']));
            // Define global values to be used anywhere on the site
            define('USER_ID', (int)$USER_DATA['user_id']);
            define('USER_NAME', $USER_DATA['user_name']);
            define('USER_GROUP', $USER_DATA['group_name']);
            define('USER_GROUP_SET', '(' . implode(',', $USER_DATA['groups']) . ')');
            define('USER_IS_ADMIN', (int)$USER_DATA['has_admin_access']);
            define('USER_CAN_SEND_ECARDS', (int)$USER_DATA['can_send_ecards']);
            define('USER_CAN_RATE_PICTURES', (int)$USER_DATA['can_rate_pictures']);
            define('USER_CAN_POST_COMMENTS', (int)$USER_DATA['can_post_comments']);
            define('USER_CAN_UPLOAD_PICTURES', (int)$USER_DATA['can_upload_pictures']);
            define('USER_CAN_CREATE_ALBUMS', (int)$USER_DATA['can_create_albums']);
            define('USER_UPLOAD_FORM', (int)$USER_DATA['upload_form_config']);
            define('CUSTOMIZE_UPLOAD_FORM', (int)$USER_DATA['custom_user_upload']);
            define('NUM_FILE_BOXES', (int)$USER_DATA['num_file_upload']);
            define('NUM_URI_BOXES', (int)$USER_DATA['num_URI_upload']);
        } else {
            $USER_DATA = cpgGetUserData(3, array(3));
            define('USER_ID', 0);
            define('USER_NAME', 'Anonymous');
            define('USER_GROUP', $USER_DATA['group_name']);
            define('USER_GROUP_SET', '(' . $USER_DATA['group_id'] . ')');
            define('USER_IS_ADMIN', 0);
            define('USER_CAN_SEND_ECARDS', (int)$USER_DATA['can_send_ecards']);
            define('USER_CAN_RATE_PICTURES', (int)$USER_DATA['can_rate_pictures']);
            define('USER_CAN_POST_COMMENTS', (int)$USER_DATA['can_post_comments']);
            define('USER_CAN_UPLOAD_PICTURES', (int)$USER_DATA['can_upload_pictures']);
            define('USER_CAN_CREATE_ALBUMS', 0);
            define('USER_UPLOAD_FORM', (int)$USER_DATA['upload_form_config']);
            define('CUSTOMIZE_UPLOAD_FORM', (int)$USER_DATA['custom_user_upload']);
            define('NUM_FILE_BOXES', (int)$USER_DATA['num_file_upload']);
            define('NUM_URI_BOXES', (int)$USER_DATA['num_URI_upload']);
        }
        run_query('close');
    }

/**************************************************************************/



/**************************************************************************
 Run function
 **************************************************************************/
auth_me();

/**************************************************************************/
?>