Using the phpBB users table for logging in


 

This is a very simple hack to get Wikka to read from the users table of a phpBB database rather than its own. It is assuming that you have installed your Wikka into the same database as phpBB and that your phpBB tables are prefixed with "phpbb_" ("phpbb3_" for the v3.0 examples) and that their names have not been edited.

This will allow users from your phpBB forum to login to your wiki with their existing username and password.

Please note that for suggested changes phpBB and wikka should use the same database - otherwise it is necessary to give rights to wikka's database to read phpBB's database - and to write name of phpBB's database before its tables.

Note: these methods are used to integrate phpBB 2.x. For phpBB 3.x, see Using Wikka with phpBB3



Method 1


/Wikka.php (in Wikka 1.1.6.2 its /libs/Wakka.class.php)
Find:
    function LoadUser($name, $password = 0) { return $this->LoadSingle("select * from ".$this->config['table_prefix']."users where name = '".mysql_real_escape_string($name)."' ".($password === 0 ? "" : "and password = '".mysql_real_escape_string($password)."'")." limit 1"); }


Replace with:
 function LoadUser($name, $password = 0) { return $this->LoadSingle("select * from ".phpbb_."users where username = '".mysql_real_escape_string($name)."' ".($password === 0 ? "" : "and user_password = '".mysql_real_escape_string($password)."'")." limit 1"); }


Find:
 function LoadUsers() { return $this->LoadAll("select * from ".$this->config['table_prefix']."users order by name"); }


Replace with:
 function LoadUsers() { return $this->LoadAll("select * from ".phpbb_."users order by username"); }


Find:
 function GetUserName() { if ($user = $this->GetUser()) $name = $user["name"]; else if (!$name = gethostbyaddr($_SERVER["REMOTE_ADDR"])) $name = $_SERVER["REMOTE_ADDR"]; return $name; }


Replace with:
 function GetUserName() { if ($user = $this->GetUser()) $name = $user["username"]; else if (!$name = gethostbyaddr($_SERVER["REMOTE_ADDR"])) $name = $_SERVER["REMOTE_ADDR"]; return $name; }


Find:
 function SetUser($user) { $_SESSION["user"] = $user; $this->SetPersistentCookie("user_name", $user["name"]); $this->SetPersistentCookie("pass", $user["password"]); }


Replace with:
 function SetUser($user) { $_SESSION["user"] = $user; $this->SetPersistentCookie("user_name", $user["username"]); $this->SetPersistentCookie("pass", $user["user_password"]); }


/handlers/page/acls.php
Find:
 echo "\t".'<option value="'.$this->htmlspecialchars_ent($user['name']).'">'.$user['name'].'</option>'."\n";


Replace with:
 echo "\t".'<option value="'.$this->htmlspecialchars_ent($user['username']).'">'.$user['username'].'</option>'."\n";


added by KiltanneN - feel free to remove or correct
/actions/usersettings.php
Find:
 case (md5($_POST['password']) != $existingUser['password']):


Replace with:
 case (md5($_POST['password']) != $existingUser['user_password']):


added by EniBevoli - fix to show the name of the user again in the User Settings page

Find:
 <td>Hello, <?php echo $this->Link($user['name']) ?>!</td>


Replace with:
 <td>Hello, <?php echo $this->Link($user['username']) ?>!</td>




added by KiltanneN - feel free to remove or correct
I changed several things in the highscores.php code. Mostly they were changing the "name" to "username" but there was also the table prefix thing that had to be fixed up. Here's the full code:
/actions/highscores.php
<?php
    # highscores.php {{HighScores}}
    # by Chris Tessmer
    # 19 Dec 2002
    # license: GPL

    $str = 'SELECT Count(*) AS cnt, `username`  FROM phpbb_users, ' ;
    $str .= $this->config["table_prefix"].'pages ';
    $str .= "WHERE `username` = `owner` AND `latest` = 'Y' GROUP BY username ORDER BY cnt DESC;";
    $rankQuery = $this->Query( $str );

    $str = 'SELECT COUNT(*) FROM '.$this->config["table_prefix"].'pages WHERE `latest` = \'Y\' ';
    $totalQuery = $this->Query( $str );
    $total  = mysql_result($totalQuery, 0);

    print( "<blockquote><table>" );

    $i = 0;    
    while( $row = mysql_fetch_array($rankQuery) )
    {
        $i++;
        $str = '<tr>';
        $str .= "<td>$i.  </td>";
        $str .= '<td>'. $this->Format( $row["username"] ) .'</td>';
        $str .= '<td> </td>';
        $str .= '<td>    </td>';
        $str .= '<td>'.$row["cnt"].'</td>';
        $str .= '<td>    </td>';
        $str .= '<td>'. round( ($row["cnt"]/$total)*100, 2).'% </td>';
        $str .= '</tr>';
        print( $str );
    }
    print( "</table></blockquote>" );    
?>


Method 2

Added by JeremyCoates

Advantages over Method 1:

  • Better SQL reduces number of code changes required
  • Still allows use of Wakka user settings
  • Shows how to enforce Wiki Names in phpBB code

/Wikka.php (in Wikka 1.1.6.2 its /libs/Wakka.class.php)

Find:
    function LoadUser($name, $password = 0) { return $this->LoadSingle("select * from ".$this->config['table_prefix']."users where name = '".mysql_real_escape_string($name)."' ".($password === 0 ? "" : "and password = '".mysql_real_escape_string($password)."'")." limit 1"); }


Replace with:
    /**
     * PHPBB Integration
     *
     * function LoadUser($name, $password = 0) { return $this->LoadSingle("select * from ".$this->config['table_prefix']."users where name = '".mysql_real_escape_string($name)."' ".($password === 0 ? "" : "and password = '".mysql_real_escape_string($password)."'")." limit 1"); }
     */

    function LoadUser($name, $password = 0) { $user = $this->LoadSingle("select
        p.username as name
        ,p.user_password as password
        ,p.user_email as email
        ,p.user_regdate as signuptime
        ,w.revisioncount
        ,w.changescount
        ,w.doubleclickedit
        ,w.show_comments
        from "
.phpbb_."users p
        left join "
. $this->config['table_prefix'] . "users w ON p.username = w.name
        where p.username = '"
.mysql_real_escape_string($name)."' ".($password === 0 ? "" : "and p.user_password = '".mysql_real_escape_string($password)."'")." and p.user_active = 1 limit 1");
        if (isset($user['signuptime'])) {
            $user['signuptime'] = date('Y-m-d H:i:s', $user['signuptime']);
        }

        return $user;
    }


Find:
 function LoadUsers() { return $this->LoadAll("select * from ".$this->config['table_prefix']."users order by name"); }


Replace with:
    /**
     * PHPBB Integration
     *
     * function LoadUsers() { return $this->LoadAll("select * from ".$this->config['table_prefix']."users order by name"); }
     */

    function LoadUsers() { $users = $this->LoadAll("select
        p.username as name
        ,p.user_password as password
        ,p.user_email as email
        ,p.user_regdate as signuptime
        ,w.revisioncount
        ,w.changescount
        ,w.doubleclickedit
        ,w.show_comments
        from "
.phpbb_."users p
        left join "
. $this->config['table_prefix'] . "users w ON p.username = w.name
        where p.user_active = 1
        order by username"
);

        foreach ($users as $key => $user) {

            if (isset($user['signuptime'])) {
                $user['signuptime'] = date('Y-m-d H:i:s', $user['signuptime']);
            }
            $users[$key] = $user;
        }

        return $users;
    }



/actions/usersettings.php

Find:
            default: // input is valid
                $this->Query('UPDATE '.$this->config['table_prefix'].'users SET '.
                    "email = '".mysql_real_escape_string($email)."', ".
                    "doubleclickedit = '".mysql_real_escape_string($doubleclickedit)."', ".
                    "show_comments = '".mysql_real_escape_string($show_comments)."', ".
                    "revisioncount = '".mysql_real_escape_string($revisioncount)."', ".
                    "changescount = '".mysql_real_escape_string($changescount)."' ".
                    "WHERE name = '".$user['name']."' LIMIT 1");


Replace with:
            default: // input is valid
                /**
                 * PHPBB Integration
                 *
                 * Insert the user into the Wakka users table
                 */

                $tmpUser = $this->LoadUser($user['name']);
                if (is_null($tmpUser['show_comments'])) {
                    $this->Query("INSERT INTO ".$this->config['table_prefix']."users SET ".
                        "signuptime = '".mysql_real_escape_string($user['signuptime'])."',".
                        "name = '".mysql_real_escape_string($user['name'])."', ".
                        "email = '".mysql_real_escape_string($user['email'])."'");
                }
                /**
                 * End PHPBB Integration
                 */

                $this->Query('UPDATE '.$this->config['table_prefix'].'users SET '.
                    "email = '".mysql_real_escape_string($email)."', ".
                    "doubleclickedit = '".mysql_real_escape_string($doubleclickedit)."', ".
                    "show_comments = '".mysql_real_escape_string($show_comments)."', ".
                    "revisioncount = '".mysql_real_escape_string($revisioncount)."', ".
                    "changescount = '".mysql_real_escape_string($changescount)."' ".
                    "WHERE name = '".$user['name']."' LIMIT 1");



/actions/highscores.php

Find:
    $str = 'SELECT Count(*) AS cnt, `name`  FROM ';
    $str .= $this->config["table_prefix"] . 'users, ' ;
    $str .= $this->config["table_prefix"].'pages ';
    $str .= "WHERE `name` = `owner` AND `latest` = 'Y' GROUP BY name ORDER BY cnt DESC;";


Replace with:
    $str = 'SELECT Count(*) AS cnt, `username` AS name  FROM phpbb_users, ' ;
    $str .= $this->config["table_prefix"].'pages ';
    $str .= "WHERE `username` = `owner` AND `latest` = 'Y' GROUP BY username ORDER BY cnt DESC;";



Configuration to disable UserRegistration is still required, either patch for 1.1.6.2 or update config setting in 1.1.6.3 (or later) see UserRegistration for more details.



PHPBB 2.0.x


If you want to force Wiki names in PHPBB logins (it will save pain later!)

/includes/functions_validate.php

Find (in function validate_username):
    // Don't allow " and ALT-255 in username.
    if (strstr($username, '"') || strstr($username, '"') || strstr($username, chr(160)))
    {
        return array('error' => true, 'error_msg' => $lang['Username_invalid']);
    }

    return array('error' => false, 'error_msg' => '');


Replace with:
    // Don't allow " and ALT-255 in username.
    if (strstr($username, '"') || strstr($username, '"') || strstr($username, chr(160)))
    {
        return array('error' => true, 'error_msg' => $lang['Username_invalid']);
    }

    /**
     * Wikka Integration
     * Wiki Username validation
     */

    $include_path = get_include_path();
    set_include_path(get_include_path() . PATH_SEPARATOR . realpath(dirname(__FILE__) . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . '..'));
    include_once('wikka.config.php');
    include_once('libs/Wakka.class.php');

    class WakkaPHPBBHack extends Wakka {
        function WakkaPHPBBHack($config) {
            parent::Wakka($config);
            ob_start();
            include_once('actions/usersettings.php');
            ob_end_clean();
        }
    }
    $wakka = new WakkaPHPBBHack($wakkaConfig);
    set_include_path($include_path);
    // Check for wiki names
    if (!$wakka->IsWikiName($username)) {
        return array('error' => true, 'error_msg' => preg_replace('`[#"]`', '', ERROR_WIKINAME));
    }
    // Check for reserved pages in wiki
    if ($wakka->ExistsPage($username)) {
        return array('error' => true, 'error_msg' => ERROR_RESERVED_PAGENAME);
    }
    /**
     * End Wikka integration
     */


    return array('error' => false, 'error_msg' => '');



 



Wikka Wiki and phpBB: using phpBB user information and allow Wikka-specific user settings

Added on July 29, 2005 by EniBevoli

I still have to make a easily readable diff output (such as "Find" - "Replace with" above; I already translated some text strings to German, so diff'ing is currently a mess) so that other users can edit their own files, but since I have finally come to a solution outlined below, I thought it would be a beneficial for others to simply post my results right away. The existing work on the Wikka Wiki / phpBB integration was a big starting point; without this information, I wouldn't even had a clue what to do. :)

Features / How it works:

Requirements:
- After the integration of Wikka Wiki and phpBB is done, user registration via Wikka Wiki must be disabled, new accounts should only be added via phpBB; see UserRegistration for more information about how to disable user registration

It took me quite some time to figure out why turning off "double click edit" didn't work - it is a bug with Wikka Wiki 1.1.6.0. :) I don't include the bug fix here, since it is already outlined in WikkaBugs.

Changed files:


As I said, I'm still compiling the changes in an easily readable format and will update this page when I'm done.

To Do / Questions / Open Issues:


CategoryUserContributions
Comments
Comment by YanB
2005-05-14 13:07:28
this looks good! Does it take into account the fact that phpbb usernames aren't necessarily camel-cased WikiNames? And does it work both ways: can someone with a wikiname automatically log in to phpbb with the same username? (I guess not)
Comment by NilsLindenberg
2005-05-14 15:22:25
From looking at the code:
1) No :)
2) If you register a new user in wikka, the data is written into wikkas user table. So you'd have to change the registration to write into the phpBB table.
Comment by KiltanneN
2005-05-15 02:51:03
I added a piece of code modification to enable the users to actually log in.

Seems to me you'll need to modify the structure on the phpBB_users table as well. There are some fields wikkawiki wants that phpBB does not have...
Comment by MyTreo
2005-06-25 13:12:31
Excellent contribution, I intend to use this as the basis for a bridge to SMF. Has anyone thought of tackling the camel-case WikiNames issue?
Comment by pcp08376522pcs.cnclrk01.pa.comcast.net
2005-07-17 20:21:39
you will need to create a user named administrator in phpbb in order to perform administrative duties.

wiki.anim8or.org
Comment by BaW
2005-07-24 19:19:30
Well their is a problem a user who is logged in from phpbb, cant edit their user page
Comment by EniBevoli
2005-07-29 12:21:06
Clarification to what BaW wrote: if a user tries to update her/his settings in the User Settings page, she/he gets logged out without the changes to the user settings being applied.
Comment by CrossAndFlame
2005-08-29 19:24:41
I've got the wiki setup and it draws from my phpbb usernamebase in phpbb. Perfect execution, even with a name like mine (Cross_+_Flame...though I can't edit my UserNamePage, which is fine).

However, I am stuck on how to integrate the wiki into the phpbb templates. With most phpbb files, you just stick on the following code in php:


define('IN_PHPBB', true);
$phpbb_root_path = '../';
include($phpbb_root_path . 'extension.inc');
include($phpbb_root_path . 'common.'.$phpEx);
//
// Start session management
//
$userdata = session_pagestart($user_ip, PAGE_INDEX);
init_userprefs($userdata);
//
// End session management
//
include($phpbb_root_path . 'includes/page_header.'.$phpEx);
include($phpbb_root_path . 'includes/page_tail.'.$phpEx);


and yer set.

However, with Wikka, I have found header.php which has most of the header information, but I always get errors with phpbb when I try to add the above in multiple ways to the file.

Has anyone successfully integrated the phpbb overall_header/footer into their Wikka installation? If not, any more hints on how to get past the errors?
Comment by NilsLindenberg
2005-08-31 20:37:22
CrossAndFlame, perhaps it's the best if you open up a new section on this page and tell in detail the errors that you get?
Comment by ADSL-TPLUS-16-31.intnet.mu
2005-09-03 08:29:01
great mod! question would be for me, how can i just hide the registration.
so that the users see only log on nothing else, as there need to register in the forum and if there lose there passowrd, there need to request this from the forum, any idea, how i can hide that part in wikki?
regards
Comment by NilsLindenberg
2005-09-05 14:46:55
Try out if UserRegistration works with the mod too. :)
Comment by 41-74-174-206.gci.net
2005-10-31 09:47:29
I've installed this mod, which I'm hoping will make our life much easier. My problem is now the options to Edit ACLs on all pages is gone. ?
Comment by 41-74-174-206.gci.net
2005-10-31 09:56:31
Nevermind I figured out that I had to edit the "admin users" line in the wikka config.
Comment by ppp-62-10-97-68.dialup.tiscali.it
2006-01-05 19:38:32
Finally.. does this mod works? Even if the account names are not Camel-Cased names?
Thanks!
Comment by DarTar
2006-01-05 22:29:38
This is user-contributed code, you should try to contact one of the authors (KiltanneN, EniBevoli; OfficeRabbit) to get more information.
Comment by LordofHaha
2006-04-22 01:32:46
just a minor suggestion if your trying to improve a few things...

On the usersettings page the whole forgot password should be replaced with the following: (basically line 258 onwards should be this:
<?php
print($this->FormClose());
?>
<form action="../***YOURFORUMLOCATION***/profile.php?mode=sendpassword" method="post">
<input type="hidden" name="action" value="updatepass" />
<table>
<tr>
<td colspan="2"><br /><hr /><h4>Forget your password?</h4></td><td></td>
</tr>
<tr>
<td align="left">Your UserName:</td>
<td><input name="username" maxlength="40" size="40" value="" /></td>
</tr>
<tr>
<td align="left">Your Email:</td>
<td><input name="email" size="40" maxlength="255" value="" /></td>
</tr>
<tr>
<td></td>
<td><input type="submit" name="submit" value="Submit" class="mainoption" /></td>
</tr>
</table>
<?php
print($this->FormClose());
}
?>
--
That will now instead force the user to use your Forum's Forgot Password feature instead :o)
On an aside this wiki software is really nice just started using it today actually... I do see one feature that be nice to add to the software as people above mentioned the whole admin in forum == admin in wiki, the easiest way I think to do that be to check the user_level in the phpbb_users table, if I figure out a hack for that I will post it here too.
Comment by DarTar
2006-04-22 09:04:02
Hi LordofHaha and thanks for your contribution. Do keep us posted with further development on Wikka/phpBB integration.
Comment by LordofHaha
2006-04-22 14:42:35
ppp: mod appears to work with non camel case (ie: my username in phpbb is "Lord of Haha" not "LordofHaha")

for making phpbb admins / special rank admins in wikkawiki:
replace the IsAdmin() function with:
function IsAdmin() {
if ($this->config["admin_users"] == "")
{
$wakkaAdmins = $this->LoadSingle("SELECT count(username) FROM phpbb_users LEFT JOIN phpbb_user_group ON phpbb_users.user_id = phpbb_user_group.user_id WHERE group_id =2 OR group_id =3
AND username = \"".$this->GetUserName()."\" GROUP BY username");
$wakkaAdmins = implode(" ", $wakkaAdmins);
if ($wakkaAdmins == 1)
{
$this->config["admin_users"] = 1;
return true;
}
else
{
$this->config["admin_users"] = 0;
return false;
}
}
else
{
if ($this->config["admin_users"] == 1)
{
return true;
}
else
{
return false;
}
}
}
also make in your wikka.config.php file make the variable
"admin_users" into ""
--
groupid=2 -> Site Admin in phpbb
groupid=3 -> Not required if you dont want to give another group admin powers, in my case I created a group called "Wiki Wizards" in phpbb, assigned it to one person found out the actual id# by looking at the db (3 in this case) and I now can allow, people to be
--
Basically since this is called roughly 3-4 times each time the page is displayed, I made it that the very 1st time the script checks for admin rights, subsequent times it will look to see if your are admin(1) or not (0).

*and if the owner of the page wants to add this code feel free :o)*
Comment by YodaHome
2006-06-22 19:35:58
I applied the changes above to Wikka 1.1.6.2 (stuff for wikka.php of course went to the libs/Wakka.class.php) and it works well as far I tested it by now but there's one thing I don't really understand. When I'm logged in I can't see RecentChanges anymore, the page simply states that "There are no recently changed pages you have access to" which is obviously wrong because if not logged in I can see plenty of entries. Obviously the HasAccess() Function messes things up and says I can't read those pages although they're publically viewable, although I don't know by now if other users experience the same prob. I'm not sure where to look, anybody of you encountered that behaviour before?
Comment by VecnixWiki
2006-06-23 01:15:16
Needs an update most things can't be found in latest release
Comment by YodaHome
2006-06-23 14:05:47
Oh, just solved my own problem... *g*
The problem was that the number of recent changes to display could not be read from the users table (because it was missing) and therefore the script failed. Adding the necessary fields to the phpbb_users table solved the issue.
Comment by BevanR
2006-06-26 12:50:32
I couldn't get this working on 1.1.6.2. Has anyone been able to? Can you share how? We'd like to integrate docs.phplist.com and phplist.com/forums. phplist is an open-source mailing list manager.
Comment by NilsLindenberg
2006-06-26 16:27:30
It will surely help if you could define what kind of errors you get. Perhaps YodaHome could help here?
Comment by BevanR
2006-07-13 12:18:03
there were no error messages, but it was imporssible to log on with either phpbb user names or wikka user names.
Comment by YodaHome
2006-09-19 07:59:49
Well, I found it pretty straightforward to apply the changes mentioned on this site. Did you apply all of the changes? Probably your tables just use a different prefix or something? Or have you already solved the problem?
Comment by Jack063
2006-10-27 08:20:12
Hello all,

I managed to launch this mod under version 1.1.6.2. Here come changes to given recommendations:

1. phpBB and wikka should use the same database - or it is necessary to give rights to wikka's database to read

phpBB's database - and to write name of phpBB's database before its tables.


/libs/Wakka.class.php

2. LoadUser - make as given, just don't forget about (1).

3. LoadUsers - same as (2).

4. GetUserName - same as (2).

5. SetUser - it might have another names of cookies instead of given ones:
function SetUser($user)
{
$_SESSION["user"] = $user;
$this->SetPersistentCookie("user_name", user["username"]);
$this->SetPersistentCookie("pass", $user["user_password"]);
}
(or check what are your cookies' names).


/handlers/page/acls.php

6. Operator "print" was replaced in Wikka by operator "echo", so we need to replace
echo "\t".'<option value="'.$this->htmlspecialchars_ent($user['name']).'">'.$user['name'].'</option>'."\n";
with
echo "\t".'<option value="'.$this->htmlspecialchars_ent($user['username']).'">'.$user['username'].'</option>'."\n";


/actions/usersettings.php
7. replace
case (md5($_POST['password']) != $existingUser['password']):
with
case (md5($_POST['password']) != $existingUser['user_password']):

8. /actions/highscores.php - make as given.


So everything works ok. We just have to remove fields for registering and changing of password.

To enhance - we might make wikka use phpBB's sessions in order not to enter login and password if we already did login

to phpBB.



I hope authors of mod will change according to last version of Wikka.

Thanks.
Comment by BrianKoontz
2006-10-27 13:46:41
Jack, why don't you submit your request as an enhancement in the Wikka issues database? Doing so will ensure your request isn't lost to the sands of time :)

http://wush.net/trac/wikka/newticket
Comment by DarTar
2006-10-28 06:52:09
Jack, thanks for sharing this, you're welcome to modify the body of this page to update the information as necessary. Brian, regarding the hacks Jack describes, I'm not sure they should go as a request in the tracker, we are not going to change Wikka to integrate it with phpBB out of the box, right?
OTOH,
> We just have to remove fields for registering and changing of password.
The good news is that Wikka admins can toggle on/off user registration as of Wikka 1.1.7 (code already available in our SVN repository).
Comment by BrianKoontz
2006-10-29 00:05:11
Obviously I have no clue what I'm talking about.
Comment by ErikM
2007-01-15 22:27:49
Switching to the phpBB user tables causes problems in 1.1.6.2 with the recent pages. When it tries to get the max revision number, it comes back null. This is a user field, but since we do not have the users in the wikka users table, it does not work. Changing the actions/recentchanges.phpfile will fix this for now. Starting on line 32-48:

$max = MAX_REVISION_NUMBER;
$readable = 0;

echo $this->Format(RECENT_CHANGES_HEADING.' --- ');
if ($pages = $this->LoadRecentlyChanged())
{
$curday = '';
//print feed link icon
echo '<p><a href="'.$this->href('recentchanges.xml', $this->page['tag']).'"><img src="images/xml.png" width="36" height="14" alt="XML" /></a></p>'."\n";

//if ($user = $this->GetUser())
//{
// $max = $user['changescount'];
//} else
//{
// $max = MAX_REVISION_NUMBER;
//}

Essentially, all this does is set
$max = MAX_REVISION_NUMBER; and the RecentChanges should work again.
Valid XHTML :: Valid CSS: :: Powered by WikkaWiki