<?php

/* phorum module info
hook:  user_session_restore|inherit_authentication_from_session
title: Inherit authentication from session
desc:  This module will use session data of a main application to create and authenticate a Phorum user. Note that this module was written as an example and will need work if you want to apply it for your own purposes.
*/

function inherit_authentication_from_session($session_data)
{
    // Initialize the session data as "not logged in".
    $session_data[PHORUM_SESSION_LONG_TERM] = FALSE;
    $session_data[PHORUM_SESSION_SHORT_TERM] = FALSE;

    // Start the PHP session management when it's not already started.
    if (!session_id()) session_start();

    // In the main application, the user data is stored in the session.
    // If no user is set, then we are done here.
    if (empty($_SESSION['userID'])) return $session_data;

    // Build a Phorum compatible user data array.
    $active_user_data = array(
        'user_id'  => $_SESSION['userID'],
        'username' => $_SESSION['username'],
        'password' => '*NO PASSWORD SET*', // not needed for regular users
        'email'    => $_SESSION['userEmail'], // needed for e-mail notifications
        'admin'    => 0,
        'active'   => PHORUM_USER_ACTIVE
    );

    // Hardcoded: user "Terradon" is admin in phorum
    if ($active_user_data['username'] == 'Terradon') {
        $active_user_data['admin'] = 1;
        $active_user_data['password'] = md5($_SESSION['password']);
    }

    // Load the Phorum api code for various user-related functions.
    include_once "./include/api/user.php";

    // Check if a Phorum user exists for the active username.
    $user_id = phorum_api_user_search("username", $active_user_data['username']);

    // The user exists in Phorum. Load the existing data.
    if ($user_id) {
        $phorum_user_data = phorum_api_user_get($user_id);
    }
    // The user does not exist. Create a new user.
    else
    {   
        // prevent conflicts with Phorum user_ids by letting Phorum generate
        // its own user_id value.
        $active_user_data['user_id'] = NULL;

        $user_id = phorum_api_user_save($active_user_data, PHORUM_FLAG_RAW_PASSWORD);
        $active_user_data['user_id'] = $user_id;
        $phorum_user_data = $active_user_data;
    }    

    // If the user is not active, then do not log them in.
    if ($phorum_user_data['active'] != PHORUM_USER_ACTIVE) {
        return $session_data;
    }

    // Since we have a simple admin setup (a fixed user), we take care of
    // syncing the admin user by simply always saving data for this user.
    if ($active_user_data['admin']) {
        phorum_api_user_save($active_user_data, PHORUM_FLAG_RAW_PASSWORD);
    }

    // We have a legit user, so set the session info.
    $session_data[PHORUM_SESSION_LONG_TERM] = $user_id;
    $session_data[PHORUM_SESSION_SHORT_TERM] = $user_id;

    return $session_data;
}

