PHP Phorum on Rails restful_authentication database

With the help of a friend I created a module to allow an instance of the PHP forum package Phorum to integrate with an instance of the Rails restful_authentication database. Basically it perform authentication against the user table that the restful_authentication plugin produces, and then synchronizes that user record with a Phorum user record allow entry to the forums. Perhaps this will help others who need to achieve this.

One import part was to add the “priority” information to the module, otherwise it didn’t seem to kick in before the Phorum auth & hence failed to operate.In my case I allowed “admin” to be a local Phorum account.

<?php

/* phorum module info
title: WildObs
desc: WildObs tweaks...
version: 1.0.1
release_date: November  5th, 2008
url: http://www.wildobs.com

hook: user_authenticate|phorum_mod_wildobs_user_authenticate
priority: run module before *
*/

function phorum_mod_wildobs_user_authenticate($auth)
{
    // Only trust one admin...
    if ($auth["type"] == PHORUM_ADMIN_SESSION) {
        if ($auth["username"] == "admin") {
		$auth["user_id"] = NULL;
		return $auth;
	}
	else {
            $auth["user_id"] = FALSE;
            return $auth;
        }
    }

    // Authenticate other logins against an restful_auth DB
    $user_id = NULL; 

	// Hit the RoR database to go get the user...
 	$conn =	mysql_connect('localhost','username','pasword');
	mysql_select_db('ror_database');
	$query = sprintf("SELECT * FROM users " .
		" WHERE (login='%s' or email='%s') AND state='active'",
		mysql_real_escape_string($auth["username"]),
		mysql_real_escape_string($auth["username"]));
	$result = mysql_query($query);
	// If found, match the crypted password
	while ($row = mysql_fetch_array($result)){
		if (sha1(sprintf("--%s--%s--", $row["salt"], $auth["password"])) == $row["crypted_password"]) {
			// Keep the phorum user record synchronized with the RoR record, e.g. e-mail changes.
        		$user_id = phorum_api_user_search("username", $row["login"]);
			$user = array(
		 		"user_id"   => $user_id,
		 		"username"  => $row["login"],
		               	"real_name" => $row["fullname"],
		               	"display_name" => $row["fullname"],
				"password"  => 'not_used_here',
		 		"email"     => $row["email"],
		 		"admin"     => 0,
		 		"active"    => PHORUM_USER_ACTIVE
		 		);
		       	$user_id = phorum_api_user_save($user);
		}
	}
	mysql_close($conn);

    $auth["user_id"] = empty($user_id) ? FALSE : $user_id;
    return $auth;
}

?>

Leave a Reply