Page 1 of 1

Howto: embed phpBB2 with automatic login (combine phpbbx and embed)

Posted: Sat Apr 07, 2007 11:57 pm
by henrik
Hi,

I was wondering how to integrate a phpBB2 bulletin board into my website and found two solutions which both seemed not to be perfect:
"phpBBx" automatically registers and logs in front-end users but then redirects to the forum.
"embed" can embed the forum but not auto-login the users.

So I combined both solutions. Therefor I had to modify the source code of phpBBx.

This is what I did:

Modify phpBBx
1. Open the file plugins/function.phpbbx.php
2. Add the following lines to the start of the function "smarty_cms_function_phpbbx":

Code: Select all

global $phpbbx_redirect;
$phpbbx_redirect  =      (isset($params['refresh'])       ? $params['refresh']       : true);
3. Remove the line "exit;" after each occurence (should be 7) of the line "goToForum();"
4. Add the following lines to the start of the function "goToForum":

Code: Select all

global $phpbbx_refresh;
if (!$phpbbx_redirect) return; 
5. Add a line with "exit;" to the end of the function "goToForum".

Modify the template and create the page
1. Follow the instructions in http://forum.cmsmadesimple.org/index.ph ... 859.0.html
2. Add the tag {phpbbx redirect=false} in front of the "embed" tag. The "phpbbx" tag may need further parameters.

Now it should work. I hope this helps.

Suggestion to the phpBBx-developer: It would be great if you made the "redirect" parameter a default part of the tag.

Regards,
Henrik

Re: Howto: embed phpBB2 with automatic login (combine phpbbx and embed)

Posted: Wed Apr 11, 2007 11:33 am
by sungji yang
Is it working?  I.m not..!! I envy you...
I followed you step!! but not working
I don't know what's the problem
====================my error massage===========================
Fatal error: Call to a member function FetchRow() on a non-object in C:\xampp\xampp\htdocs\cmsmadesimple\lib\smarty\plugins\function.phpbbx.php on line 117

I spent a lot of time this..
and
Could you tell me about your version such as  cms, phpbbx.. something like that...
help me!!

Re: Howto: embed phpBB2 with automatic login (combine phpbbx and embed)

Posted: Wed Apr 18, 2007 1:51 pm
by henrik
I also had this problem. phpBBx seems not to work with the latest version auf CMS Made Simple, but I'm sure there will be an update which fixes that issue.

To solve it by hand do the following steps:

Open "function.phpbbx.php"

Replace each occurence of  the line

Code: Select all

global $db;
by

Code: Select all

global $gCms;
$db =& $gCms->GetDb();
You can leave out the first line if it is already there but make sure that the second line follows the first one.

Regards,
Henrik

Re: Howto: embed phpBB2 with automatic login (combine phpbbx and embed)

Posted: Fri Dec 14, 2007 10:32 am
by Moae
I do the login with FEU, but it doesn't make the login with the forum, i must do the login with FEU and the login with the forum 
separately, how can i do to make the login together?

Re: Howto: embed phpBB2 with automatic login (combine phpbbx and embed)

Posted: Thu Jan 03, 2008 1:05 am
by droeske
I changed phpbbx and FrontEndUsers.api.php. Features:
  • - automatic login after being logged in in FE (I found a lot of bugs in the old version)
  • - FE-groups also create in phpbb
  • - Memberschip of FE-groups copy to phpbb-groups
This was fully working with CMS 1.2 and phpbb 2.0.22

Remarks:
  • - To use the FE-groups features, the database of phpbb MUST HAVE the prefix 'phpbb_' (otherwise, you have to change 'phpbb_' everywere in FrontEndUsers.api.php to the prefix you want.
  • - If you change the properties of a user in FE, and accordingly you change in the function registernewuser (phpbbx) the properties (like "if($row['title']=='country') $country = $row['data'];") ,and in FrontEndUsers.api.php the function SetUserProperty to update by changes
All code is below here:
phpbbx:

Code: Select all

<?php
function smarty_cms_function_phpbbx($params, &$smarty) 
{
    global $phpbbx_redirect;
    $phpbbx_redirect  =      (isset($params['refresh'])       ? $params['refresh']       : true);
	
	require_once('include.php');
;
	global $gCms;
	$db =& $gCms->GetDb();
	global $lan;
	global $path;
	global $tablepref;
	global $logdir;
	$tablepref=	(isset($params['tablepref']) ? $params['tablepref']	: 'phpbb_');
	$logdir=	(isset($params['logdir'])	 ? $params['logdir']	: false);
	$dir =		(isset($params['dir'])		 ? $params['dir']		: 'phpBB2');
	$lan =		(isset($_REQUEST['lan'])	 ? $_REQUEST['lan']		: 'en');
	$current_time = time();

	$path = $gCms->config['root_url']."/".$dir;
	log_message("\n" . date("F j, Y, g:i a") . "\n", true);
	if( session_id() != "" )	// if we are logged in as a FE user
	{
		// read from FE users table
		$userdata = getDataFromFEUsers();
		if (!$userdata)
		{
			log_message("User not registered in the FE module.  Going to forum without login.\n");
			goToForum();
		}
		// read from phpBB2 config
		$board_config = getBBConfig(); 
		if (!$board_config)
		{
			log_message("Failed to get phpBB configs.  Going to forum without login.\n"); 
			goToForum();
		}
		if ($userdata['userid']!="")
		{if (!isUserRegistered($userdata))
		{
			registerNewUser($board_config, $userdata);
			log_message("user not registered.\n");
		}

		// Checking if user is logged in
		if(!isset($session_id) || !$session_id)
		{
			$session_id = forceUserLogin($userdata);
		}}
		setCookies($board_config, $userdata, $session_id);
	
		
		
	}

	goToForum();
	
} //End of main function






function getDataFromFEUsers(){
	global $gCms;
	$db =& $gCms->GetDb();
        $sql="SELECT l.userid, u.username, u.password FROM ".$gCms->config["db_prefix"]."module_feusers_loggedin l, ".$gCms->config["db_prefix"]."module_feusers_users u WHERE l.sessionid='".session_id()."' and u.id=l.userid";
	log_message("GetData, SQL: $sql \n");
	if( ($result = $db->Execute($sql)) )
	{
		$resArr = $result->FetchRow(); 
		$userdata['userid'] = $resArr['userid'];
		$userdata['username'] = $resArr['username'];
		$userdata['password'] = $resArr['password'];
		if($userdata['userid'] && $userdata['username'] && $userdata['password'])
		{
			log_message("user data obtained\n");
			return $userdata;
		}
	} 
	
	return false;
}




function getBBConfig(){
	global $gCms;
                $db =& $gCms->GetDb();
	global $tablepref;
	$sql = "SELECT * FROM " . $tablepref . "config";
	if( ($result = $db->Execute($sql)) )
	{
		while ( $row = $result->FetchRow() )
		{
			$board_config[$row['config_name']] = $row['config_value']; 
		}	
		log_message("board config obtained\n");
		return $board_config;
	} 
	return false;
}




function isUserRegistered($userdata)
{
	global $gCms;
	$db =& $gCms->GetDb();
	global $tablepref;
	$sql = "select count(*) from " . $tablepref . "users where user_id=".$userdata['userid'];
	$result = $db->Execute($sql);
	$checkRes = $result->FetchRow();
	if($checkRes['count(*)'])
	{
		log_message("user is registered\n"); 
		return true;
	}
	else
	{
		log_message("user is not registered\n");
		return false;
	}
}




function registerNewUser($board_config, $userdata)
{
	global $gCms;
	$db =& $gCms->GetDb();
	global $lan;
	global $tablepref;

	$user_id = $userdata['userid'];
	$username = $userdata['username'];
	$password = $userdata['password'];

	$email = '';
	$country = '';
	log_message("Registering new user $user_id.\n");
	$sql="SELECT title, data FROM ".$gCms->config["db_prefix"]."module_feusers_properties WHERE userid=".$userdata['userid'];
	if( ($result = $db->Execute($sql)) )
	{
		while ( $row = $result->FetchRow() )
		{
			if($row['title']=='country') $country = $row['data'];
			if($row['title']=='email')	$email = $row['data'];
		}	
	} 
	switch($lan){
		case 'ua' :	$user_lang = 'ukrainian'; break;
		case 'de' :	$user_lang = 'german'; break;
		case 'se' :	$user_lang = 'swedish'; break;
		default   : $user_lang = 'english';
	}

	$attachsig = $board_config['allow_sig'];
	$allowhtml = $board_config['allow_html'];
	$allowbbcode = $board_config['allow_bbcode'];
	$allowsmilies = $board_config['allow_smilies'];
	$user_style = $board_config['default_style'];
	$user_timezone = $board_config['board_timezone'];
	$user_dateformat = $board_config['default_dateformat'];
	$user_avatar_local = '';
	$user_avatar_remoteurl = '';
	$user_avatar_name = '';
	$user_avatar_size = 0;
	$user_avatar_filetype = '';
	$user_avatar = '';
	$user_avatar_type = '';
    
	$sql = "INSERT INTO " . $tablepref . "users	(user_id, username, user_regdate, user_password, user_email, user_icq, user_website, user_occ, user_from, user_interests, user_sig, user_sig_bbcode_uid, user_avatar, user_avatar_type, user_viewemail, user_aim, user_yim, user_msnm, user_attachsig, user_allowsmile, user_allowhtml, user_allowbbcode, user_notify, user_notify_pm, user_popup_pm, user_dateformat, user_lang, user_style, user_level, user_allow_pm, user_active, user_actkey) VALUES ("
		. $user_id . ", '"
		. str_replace("\'", "''", $username) . "', "
		. time() . ", '"
		. str_replace("\'", "''", $password) . "', '"
		. $email . "', '', '', '', '"
		. $country . "', '', '', 0, '', '', 0, '', '', '', "
		. $attachsig . ", "
		. $allowsmilies . ", "
		. $allowhtml . ", "
		. $allowbbcode .", 0, 0, 0, '" 
		. str_replace("\'", "''", $user_dateformat) . "', '" 
		. str_replace("\'", "''", $user_lang) . "', " 
		. $user_style . ", 0, 1, 1, '')";
	if ( !($result = $db->Execute($sql)) )
	{
		log_message("Failed to insert data into users table. SQL:\n $sql\n");
		return false;
	}
	$sql="SELECT * FROM ".$gCms->config["db_prefix"]."module_feusers_belongs WHERE userid = $user_id";
	$result = $db->Execute($sql);
	if($result) {
		while ( $row = $result->FetchRow() ) {
			log_message("inserting in group ".$row['group_id']);
			$sql = "INSERT INTO " . $tablepref ."user_group (user_id, group_id, user_pending)
		         VALUES ($user_id, ". $row['groupid'].", 1)";
			if ( !($result2 = $db->Execute($sql)) )
			{
				log_message("Failed to insert data into phpbb groups table. SQL:\n $sql\n");
				return false;
			}
		}
	}
	else { 
		log_message("failet to search groups belongings from user $user_id");
	}
	
	
	log_message("ok");
	
	if(!($session_id=createSession($user_id))) 
	{
		log_message("Failed to create new session.\n");
		return false;
	}
	log_message("User $user_id successfully registered.\n");
	return true;
	
}




function forceUserLogin($userdata)
{
	global $gCms;
	$db =& $gCms->GetDb();
	global $lan;
	global $tablepref;
	$session_id = '';

	$user_id = $userdata['userid'];
	$username = $userdata['username'];
	$password = $userdata['password'];

	$sql = 'select session_id from ' . $tablepref . 'sessions where session_user_id='.$user_id; 
	log_message("ForceUserLogin, SQL: $sql \n");
	if (!$result = $db->Execute($sql))
	{
		log_message("Failed to query database when looking for registered user $user_id. SQL:\n$sql\n"); 
		goToForum();
	}
	elseif ( !($row = $result->FetchRow()) )
	{
		log_message("No logged-in user $user_id in the sessions table.\n");
		$user_ip = encode_ip();
		$sql = "select session_id from " . $tablepref . "sessions where session_user_id=-1 and session_ip='".$user_ip."'";
		if ( !($result = $db->Execute($sql)) )
		{
			log_message("Failed to query database when looking for logged-out user $user_id. SQL:\n$sql\n");
			goToForum();
		}
		elseif ( !($row = $result->FetchRow()) )
		{
			log_message("Failed to find logged-out user $user_id in the sessions table. Going to forum without login.\n");
			if(!($session_id = createSession($user_id)))
			{
				log_message("goto");
				
				goToForum();
			}
		}
		else
		{
			log_message("Logged-out user $user_id found in the sessions table.  Updating session to log in.\n");
			$session_id = $row['session_id'];
			$sql = "update ". $tablepref ."sessions set session_user_id=".$user_id.", session_logged_in=1 where session_id='".$session_id."'";
			if ( !$db->Execute($sql) )
			{
				log_message("Error updating session for user $user_id.  Going to forum without login.  SQL: \n$sql\n");
				goToForum();
			}
		}
	} 
	else 
	{
		$session_id = $row['session_id']; 
	}
	log_message("sessie: $session_id.\n");
	return $session_id;
} // end function forceUserLogin






function setCookies($board_config, $userdata, $session_id)
{
	log_message("Setting cookies.\n");
	$user_id = $userdata['userid'];
	$username = $userdata['username'];
	$password = $userdata['password'];

	$cookiename = $board_config['cookie_name'];
	$cookiepath = $board_config['cookie_path'];
	$cookiedomain = $board_config['cookie_domain'];
	$cookiesecure = $board_config['cookie_secure'];

	$sessiondata = array();
	$sessiondata['autologinid'] = $password;
	$sessiondata['userid'] = $user_id;

	setcookie($cookiename . '_data', serialize($sessiondata), 0, $cookiepath, $cookiedomain, $cookiesecure);
	setcookie($cookiename . '_sid', $session_id, 0, $cookiepath, $cookiedomain, $cookiesecure);
}




function goToForum()
{
	global $phpbbx_refresh;
    if (!$phpbbx_redirect) {
	return; 
	}
    global $path;
	global $lan;
	header("Refresh: 0; URL=".$path."/index.php?lan=".$lan);
	exit;
}




function createSession($user_id)
{
	global $gCms;
	$db =& $gCms->GetDb();
	$current_time = time();
	global $tablepref;

	list($sec, $usec) = explode(' ', microtime());
	mt_srand((float) $sec + ((float) $usec * 100000));
	$session_id = md5(uniqid(mt_rand(), true));

	$user_ip = encode_ip();

	$sql = "INSERT INTO ". $tablepref ."sessions
		(session_id, session_user_id, session_start, session_time, session_ip, session_page, session_logged_in, session_admin)
		VALUES ('$session_id', $user_id, ". $current_time .", ". $current_time. ", '$user_ip', 0, 1, 0)";
	if ( !$db->Execute($sql) )
	{
		log_message("Error creating session for user $user_id.  SQL: \n$sql\n  ");
		return 0;
	
	}
		
	return $session_id;
}




function encode_ip()
{
	$dotquad_ip = ( !empty($HTTP_SERVER_VARS['REMOTE_ADDR']) ) ? $HTTP_SERVER_VARS['REMOTE_ADDR'] : ( ( !empty($HTTP_ENV_VARS['REMOTE_ADDR']) ) ? $HTTP_ENV_VARS['REMOTE_ADDR'] : getenv('REMOTE_ADDR') );
	$ip_sep = explode('.', $dotquad_ip);
	return sprintf('%02x%02x%02x%02x', $ip_sep[0], $ip_sep[1], $ip_sep[2], $ip_sep[3]);
}



function log_message($message, $startnew=false){
	global $logdir;
	
	if($logdir){
		global $gCms;
//		$logdir = "./tmp/cache";
		if($startnew){
			$h = fopen($logdir . '/phpbbx.log', 'w+');
		}
		else {
			$h = fopen($logdir . '/phpbbx.log', 'a+');
		}
		fwrite($h, $message);
		fclose($h);
	}
}



function smarty_cms_help_function_phpbbx() {
	?>

	<h3>What does this do?</h3>
	<p>Redirects you to the phpBB2 directory, and if you are logged in as a FrontEnd user, logs you into phpBB2 with your FrontEndUser credentials.</p>
	<h3>How do I use it?</h3>
        <ol>
          <li>Install phpBB2 in a directory in CMSMadeSimple home.  E.g.: mywebsite/phpBB2.
		  Make sure to use <b>the same database</b> as cmsmadesimple. </li>
	  <li>Insert the following tag into any page:<br />
		<code>{phpbbx tablepref="cmsms_phpbb_" dir="forum"}</code></li>
        </ol>

	<h3>What parameters does it take?</h3>
	<ul>
	  <li><i>tablepref</i> - the table prefix you specified at phpBB2 installation. The default is phpbb_.</li>
	  <li><i>dir</i> - phpBB2 directory name inside CMSMadeSimple directory. No trailing slash. The default is phpBB2.</li>
	  <li><i>logdir</i> - directory for phpBBX debug log, e.g. "./tmp/cache".  Must be writable.  If not specified, log won't be written.</li>
	</ul>
	<?php
}

function smarty_cms_about_function_phpbbx() {
	?>
	<p>Version: 0.2 beta 1</p>
	<p>Authors: Yuriy Kvasnyuk (kvas@zebrus.net) and Victor Katolyk (katonchik@gmail.com)</p>
	<?php
}


?>
FrontEndUSers.api.php (in module>FrontEndUsers)

Function:
After:
Insert:
  DeleteUserFull

Code: Select all

// delete user record
    $db =& $this->GetDb();
    $q = "DELETE FROM ".cms_db_prefix()."module_feusers_users
          WHERE id = ?";

Code: Select all

$dbresult2 = $db->Execute( "DELETE FROM phpbb_users WHERE user_id = ?", array($id) );
    $dbresult = $db->Execute( $q, array( $id ) );
    if( !$dbresult || !$dbresult2)
      {
	return array( FALSE< $db->ErrorMsg() );
      }

RemoveUserFromGroup

Code: Select all

$q .= " AND groupid = ?";
	array_push( $parms, $gid );
      }
    $dbresult = $db->Execute( $q, $parms );

Code: Select all

$parms2 = array( $uid );
    $q2 = "DELETE FROM phpbb_user_group
          WHERE user_id = ?";
    if( $gid != '' )
      {
	$q .= " AND group_id = ?";
	array_push( $parms, $gid );
      }
    $dbresult2 = $db->Execute( $q2, $parms2 );
    if( $dbresult == false || $dbresult2 == false )
      {
	return array( FALSE, $db->ErrorMsg() );
SetGroup

Code: Select all

$q = "UPDATE ".cms_db_prefix()."module_feusers_groups SET
                groupname = ?, groupdesc = ? WHERE id = ?";
    $dbresult = $db->Execute( $q, array( $name, $desc, $id ) );

Code: Select all

$q = "UPDATE phpbb_groups SET
                group_name = ?, group_description = ? WHERE group_id = ?";
    $dbresult2 = $db->Execute( $q, array( $name, $desc, $id ) );
    if( !$dbresult || !$dbresult2 )
      {
	return array(FALSE,$db->ErrorMsg());
SetUserGroups

Code: Select all

// then remove all his current assignments
    $q = "DELETE FROM ".cms_db_prefix()."module_feusers_belongs 
          WHERE userid = ?";
    $dbresult = $db->Execute( $q, array( $uid ));

Code: Select all

$q = "DELETE FROM phpbb_user_group 
          WHERE user_id = ?";
    $dbresult2 = $db->Execute( $q, array( $uid ));
    if( !$dbresult || !$dbresult2)
      {
	return array( FALSE, $db->ErrorMsg()  );

Code: Select all

foreach( $grpids as $grpid )
    {
      $dbresult = $db->Execute( $q, array( $uid, $grpid ) );
      if( !$dbresult )
	{
	  return array( FALSE, $db->ErrorMsg()  );
	}
    }

Code: Select all

$q = "INSERT INTO phpbb_user_group
          VALUES (?,?,?)";
    foreach( $grpids as $grpid )
    {
      $dbresult = $db->Execute( $q, array( $grpid, $uid, "0" ) );
      if( !$dbresult )
	{
	  return array( FALSE, $db->ErrorMsg()  );
	}
    }
LogoutUser

Code: Select all

$q="DELETE FROM ".cms_db_prefix()."module_feusers_loggedin WHERE userid=?";
    $p=array($uid);
    $result=$db->Execute($q,$p);

Code: Select all

$q="DELETE FROM phpbb_sessions WHERE session_user_id=?";
    $result=$db->Execute($q,$p);
AddGroup

Code: Select all

$grpid = 
      $db->GenID( cms_db_prefix()."module_feusers_groups_seq" );
    $q = "INSERT INTO ".cms_db_prefix().
      "module_feusers_groups VALUES (?,?,?)";
    $dbresult = $db->Execute( $q, array( $grpid, $name, $description ) );
    if( !$dbresult )
      {
	return array(FALSE,$db->ErrorMsg());
      }

Code: Select all

//also insert in phpbb
	  $q2 = "INSERT INTO phpbb_groups VALUES (?,?,?,?,?,?)";
    $dbresult2 = $db->Execute( $q2, array( $grpid, "1",  $name, $description, "2", "0" ) );
    if( !$dbresult2 )
      {
	return array(FALSE,$db->ErrorMsg());
      }
Deletegroupfull

Code: Select all

$q = "DELETE FROM ".cms_db_prefix()."module_feusers_belongs WHERE groupid = ?";
    $dbresult = $db->Execute( $q, array( $id ) );
    if( !$dbresult )
      {
	return array( FALSE, $db->ErrorMsg() );
      }

Code: Select all

$q = "DELETE FROM phpbb_user_group WHERE group_id = ?";
    $dbresult = $db->Execute( $q, array( $id ) );
    if( !$dbresult )
      {
	return array( FALSE, $db->ErrorMsg() );
      }

Code: Select all

$q = "DELETE FROM ".cms_db_prefix()."module_feusers_groups WHERE id = ?";
    $dbresult = $db->Execute( $q, array( $id ) );
    if( !$dbresult )
      {
	return array( FALSE, $db->ErrorMsg() );
      }

Code: Select all

$q = "DELETE FROM phpbb_groups WHERE group_id = ?";
    $dbresult = $db->Execute( $q, array( $id ) );
    if( !$dbresult )
      {
	return array( FALSE, $db->ErrorMsg() );
      }

Re: Howto: embed phpBB2 with automatic login (combine phpbbx and embed)

Posted: Sun Jan 27, 2008 1:20 am
by xnau
I seem to be having a small problem getting this mod to work. Tried doing all the edits three separate times, and I keep getting the same error:

Code: Select all

Parse error: syntax error, unexpected $end in /home/beloved/public_html/sandbox/cms/modules/FrontEndUsers/FrontEndUsers.api.php on line 1779
Looked through the edited file (FrontEndUsers.api.php) for what might be a simple syntax error...don't see it.

Anyone else run into this? If not...would you mind posting your working FrontEndUsers.api.php?

Really want to see this mod working...I have it on a test site for now, but I got a client keeps asking me why their members have to have two separate profiles...this should solve that.

thanks!!

Re: Howto: embed phpBB2 with automatic login (combine phpbbx and embed)

Posted: Sun Jan 27, 2008 7:48 am
by xnau
I found the error--

the 2nd, 3rd and 4th pieces to paste into FrontEndUsers.api.php are missing a final close brace.

Thanks, droeske for posting this...it's helped a lot!

Re: Howto: embed phpBB2 with automatic login (combine phpbbx and embed)

Posted: Fri Feb 15, 2008 12:13 pm
by lriverstone
Hi all,
Has anyone been able to  you upgrade from phpBB2 to phpBB3?

I have tried upgrading however once I have installed and converted phpbb2 t0 3.0 the FEU and phpbbx no longer pass on the username and password to the new forum.

I have tried editing the phpbbx and the frontend user.api.php to reflect the new table prefixes however I can't seem to get it to work. 

I have to say I have only a very basic knowledge of php.

thank you for your time.

lriverstone.

Re: Howto: embed phpBB2 with automatic login (combine phpbbx and embed)

Posted: Tue Jul 15, 2008 11:58 am
by linekill
phpbb3 and cmsms 3...this mod seems to fail as it only gives me a blank page...are there updates?

thx.

Re: Howto: embed phpBB2 with automatic login (combine phpbbx and embed)

Posted: Wed Jul 29, 2009 12:08 am
by droeske
For all of you:

Some time after my last post, i've changed from CMS-system. I had a working version of the implementation of the mod (back-up), till earlier this year my computer crashed, and i lost all my data.

So I can't help anyone in the future, I'm sorry