❯~/pixelastic

Integration of a bbPress forum into a cakePHP application (part 4)

We're almost done. There is just one last thing we must do. We don't want our dear user to have to login twice, once for the main app and once for the form, do we?

Creating the Configure keys

So first, go back to your bb-config.php file and if you haven't already, define the BB_AUTH_KEY and BB_LOGGED_IN_KEY.

Go to your app/config/bootstrap.php and create entries in Configure for this same keys. I named mine bbPress.authKey and bbPress.logKey.

Now, go back to your database, open the bb_meta table and find the bb_auth_salt and bb_loggued_in_salt values. Copy them to two more Configure keys (bbPress.authSalt and bbPress.logSalt).

One last key to create. Head back to bb-config.php and add the following line:

define('BB_HASH', 'XXXXX');

Of course, set XXXX to a unique string. The name of your website should suffice, it is just used to differenciate between cookies on the same domain. Report the same value in Configure: bbPress.hash.

Creating the cookies

You're now ready to create bbPress cookies. bbPress will need to create two different sets of cookie.

A bbPress cookie contain a value formatted like: <login>|<expiration>|<hash>

The hash is based on the user password, login, expiration and several other keys. It also involve double hashing of the value, with different salt and key values.

I've eased the pain of understanding how to create a cookie value, just use the following function:

function __getCookieValue($options = array()) {
   // We will need the login, pass and expiration date to create the cookie
   $userLogin = $options['name']; // The user login
   $userPass = $options['password']; // The password encrypted in the database
   $userPassFragment = substr($userPass, 8, 4);    // We will take only a small part of the password
   $expiration = $options['expiration'];
   $data = $userLogin.$userPassFragment."|".$expiration;    // The main data that will be used create the final hash

   // We first get a first hash key that we will use to generate a second one
   $firstKey = hash_hmac('md5', $data, $options['salt']);
   // Then we create the final hash saved in the cookie
   $finalHash = hash_hmac('md5', $userLogin.'|'.$expiration, $firstKey);

   // The final data to store in the cookie
   return $userLogin."|".$expiration."|".$finalHash;
}

You should pass to this function an array containing a name, password and expiration date. The password should be exactly as it is stored in the database.

You should also pass a 4th value, named salt, that is different depending of the type of cookie you're trying to create. For a auth cookie, use Configure::read('bbPress.authKey').Configure::read('bbPress.authSalt') and for a log cookie, use Configure::read('bbPress.logKey').Configure::read('bbPress.logSalt').

You will need to create two log cookies (for / and /forum/) and three auth cookies (for /forum/bb-admin,/forum/bb-plugins and /forum/my-plugins).

Here is the complete method for creating all these cookies. Just call it in your app whenever your want to log the current user to the forum. Just feed it a user and password.

/**
*    createCookies
*    Create the cookies that can be used to connect to the bbPress forum
*    bbPress does a lot of complicating stuff with hashing when creating its cookie. We replicate it here
*
*    The content of the cookie is formed in the format username|expirationDate|hash
*
*    The hash part is the most difficult, it involve double hashing based on various salt and values
**/
function createCookies($name, $pass) {
 $expirationDate = time() + 1209600; // When the cookie should stop working (2 weeks)

 // Getting the log in salt
 $completeSalt = Configure::read('bbPress.logKey').Configure::read('bbPress.logSalt');
 // The log in cookie name
 $cookieName = "bbpress_logged_in_".Configure::read('bbPress.hash');
 // Getting the value
 $cookieValue = __getCookieValue(array(
   'name' => $name,
   'password' => $pass,
   'salt' => $completeSalt,
   'expiration' => $expirationDate
 ));
 // Setting the cookie for the correct path
 setcookie($cookieName, $cookieValue, $expirationDate, "/", false, false, true);
 setcookie($cookieName, $cookieValue, $expirationDate, "/forum/", false, false, true);

 // Getting the auth salt
 $completeSalt = Configure::read('bbPress.authKey').Configure::read('bbPress.authSalt');
 // The auth cookie name
 $cookieName = "bbpress_".Configure::read('bbPress.hash');
 // Getting the value
 $cookieValue = __getCookieValue(array(
   'name' => $name,
   'password' => $pass,
   'salt' => $completeSalt,
   'expiration' => $expirationDate
 ));
 // Setting the cookie for the correct path
 setcookie($cookieName, $cookieValue, $expirationDate, '/forum/bb-admin', false, false, true);
 setcookie($cookieName, $cookieValue, $expirationDate, '/forum/bb-plugins', false, false, true);
 setcookie($cookieName, $cookieValue, $expirationDate, '/forum/my-plugins', false, false, true);
}

And for logging out, just delete the cookies:

function clearCookies() {
   // The name of the cookie to delete
   $cookieName = "bbpress_logged_in_".Configure::read('bbPress.hash');
   setcookie($cookieName, "", time()-3600, "/", false, false, true);
   setcookie($cookieName, "", time()-3600, "/forum/", false, false, true);
   // The auth cookie name
   $cookieName = "bbpress_".Configure::read('bbPress.hash');
   setcookie($cookieName, "", time()-3600, '/forum/bb-admin', false, false, true);
   setcookie($cookieName, "", time()-3600, '/forum/bb-plugins', false, false, true);
   setcookie($cookieName, "", time()-3600, '/forum/my-plugins', false, false, true);
 }

Hope all that helps! It took some time to put all this together but I hope it could help other bakers out there.

Downloading

For anyone interested, here is a link to download all the files: http://www.pixelastic.com/download/bbpress.rar

Note that it can't be used as-is because it involves a bbPress install, a custom Authentication system and also because I wrote it as part of a bigger plugin.

So, feel free to browse the files and get what you need, but consider it as a part of a bigger app, so you'll have to re-plug what's missing.

Integration of a bbPress forum into a cakePHP application (part 3)

Let's go back to bbPress now. With the previous post, you should be able to create bbPress user directly from your app.

Redirecting bbPress to the cakePHP app actions

What we'll be doing now is adding some hooks on every user-related action on bbPress to redirect them to their equivalent in your app. No need to have two different login form, hey?

Create a new php file in your app/webroot/forum/my-plugins/ directory, and copy and paste the following code:

/*
Plugin Name: cakePHP User
Description:  Remaps each login/register/forgotpass action to those of your own application
Version: 0.1
Author: Pixelastic
Author URI: http://www.pixelastic.com/

License: CC-GNU-GPL http://creativecommons.org/licenses/GPL/2.0/

*/

define( 'APP_URL', 'http://www.myapp.com/' );
/**
 *    __convertToAppUrl
 *    Convert a given bbPress URI to one mapped to the main application
 **/
function cake_convertToAppUrl($uri) {
   // We explode the path in different subdirs
   $paths = explode('/', $uri);
   $nbrPath = count($paths);

   // We get the last part of the url
   $endUri = substr($uri, strrpos($uri, "/")+1);

   $mappedUrl = array(
     // Register
     'register.php' => 'users/add',
     // Lost password
     'password-reset.php' => 'users/pass',
     // Login
     'bb-login.php' => 'users/login',
     // Logout
     'bb-login.php?action=logout' => 'users/logout',
     // Profile editing
     'edit' => 'users/edit/'.$paths[$nbrPath-2]
   );

   // If there is a mapping, we return it, otherwise we don't touch the uri
   return (!empty($mappedUrl[$endUri])) ? APP_URL.$mappedUrl[$endUri] : $uri;
}
// We filter both bb_uri and bb_get_uri
add_filter('bb_uri', 'cake_convertToAppUrl', 1);
add_filter('bb_get_uri', 'cake_convertToAppUrl', 1);

It will hook every method that ask for a url and convert the result to return the corresponding url in your own app.

Don't forget to enable this plugin in your bbPress admin panel.

Of course, feel free to change the destination url to reflect those of your app.

Additional information

Note that the users/edit/ method takes the bbPress nicename as argument, so you should have to convert it before displaying the edit form.

I also edited my template and added an hidden field in the bbPress login form to check if the login was coming from the app or the forum and redirect accordingly.

Integration of a bbPress forum into a cakePHP application (part 2)

We've done enough work on the forum for now. The time has come to edit our cake files.

Creating the cakePHP models

We will create two models to help in speaking with the bbPress database.

Create a bb_usermeta.php model:

class BbUsermeta extends AppModel {
  var $useTable = 'bb_usermeta';
  var $primaryKey = 'umeta_id';
}

Create a bb_user.php model:

class BbUser extends AppModel {
  var $primaryKey = 'ID';

  var $hasMany = array(
     'BbUsermeta' => array(
       'className' => 'BbUsermeta',
       'foreignKey' => 'user_id',
       'dependent' => true
    )
   );

  //We make sure, before saving, that the nicename is url-friendly
  function beforeSave() {
    if (!empty($this->data[$this->name]['user_nicename'])) {
      $this->data[$this->name]['user_nicename'] = Inflector::slug($this->data[$this->name]['user_nicename']);
    }
    return true;
  }

}

So, what was that about?

We created two models to communicate with bbPress. bbPress stores user-related information in bb_users as well as bb_usermeta. We defined the $primaryKey, $useTable and $foreignKey of the $hasMany because the bbPress tables do not follow the cakePHP convention.

We also add a nifty beforeSave() method to BbUser to make sure its user_nicename (used as an url slug) is url-friendly.

How to save bbPress users from the cakePHP app

Great. Now you can easily add, edit and delete users from bbPress directly from your app.

There are some things you should know about before doing that:

  • first_name and last_name are stored in bb_usermeta
  • the access rights are defined in bb_usermeta too, using the bb_capabilities key

Now that you know all that, you can easily create a behavior creating a new bbPress user when creating a new user, deleting that bbPress user when deleting the main user and updating the bbPress user when updating the main user.

I myself wrote this behavior, but as it is part of a more general bbPress plugin it may not work as-is. I'll try to publish it if anyone is interested.

Integration of a bbPress forum into a cakePHP application (part 1)

Today I had to integrate a forum into an existing cakePHP app. I didn't want to code the whole thing from scratch and wanted to take advantage of one of the great opensource forums out there instead.

I wanted to keep the forum as a stand-alone part, with its own admin panel, and not mess with its core files, to allow me the possibility of updating it if needed. But I didn't want my user to register twice, for my app and for the forum, I wanted the whole register/login thing to be as smooth as possible.

After some trials, I finally choose bbPress, from the makers of WordPress.

I took me some time, digging into the online documentation (pretty much non- existent), digging into existing plugins and the source code to finally script what I needed. I had to code a cake behavior, a cake component, a bbPress plugin, overwriting some bbPress functions but it finally works.

Installing bbPress on a cakePHP app

First thing you need to do is installing bbPress. Just drop the files you downloaded into app/webroot/forum and follow the installation instruction. Set the admin login the same as your own admin login in your app. Type anything you want for the password, we'll change that later.

Once this is done, you should have a working forum, and being able to access it on /forum. It's a good start, isn't it?

Now, open your favorite mysql editor (Navicat or phpmyadmin) and connect to your database. Make sure the collation of the bb_ tables are the same as the collation of your cake tables. It will allow them to correctly communicate. My cake tables were set to utf8_unicode_ci and my bbPress tables were set to utf8_general_ci. I had to update all the bbPress tables to make sure no collation problems arise.

Using the same password hashing

Now let's look at our bb_users table. You should have one entry for your admin account. Go to your own cake users table, copy your password hash and paste it in place if the bbPress one. Cake and bbPress do not use the same hashing algorithm, so we are going to change that.

Open forum/bb-config.php and add the following code:

define('CAKE_SALT', "XXXXX");
// Check password using sha1
function bb_check_password( $password, $hash, $user_id = '' ) {
  // Does it match ?
  return sha1(CAKE_SALT.$password)==$hash;
}

Of course, replace the XXXXX value of CAKE_SALT with your own Security.Salt value (usually found in app/config/core.php). Also note that the default hashing method used by cake is sha1, but if you use an alternate md5 or sha256, you'll have to update the method above.

Doing all this, we change the way bbPress checks for a valid password. The method gets the plain password and the hashed version stored in the database and compare them. Cake does its comparison using its own internal salt value and applying sha1() on it. We just do the same here. That way, we can now login using the same password.

Reading my own code from 3 years ago

Today I had to update an old site I developped some years ago. I had to move it from one host to another and make sure all the configuration followed.

It scares me. What I wrote 3 years ago scares me. My code was... well there was some huge mistakes, things I would never ever do again. Today, I would severly frown upon any coder who wrote horribles things like that.

For the php part, here is a very good list of what NOT to do:

  • I used shorthand notation for my php tags: <? instead of <?php.
  • My server was set as register_global off, but I was circumventing it by doing my own register_global on:
extract($_SERVER);
extract($_COOKIE);
extract($_GET);
extract($_POST);
  • My files were encoded in Latin-1, my database was in latin1_swedish_ci and my html head was set to iso-8859-1. At least, that was consistent.
  • I wasn't EVER testing if my variables were set, so I had notices popping everywhere. I had the error_reporting set to disable them, hiding the error instead of writing better code.
  • The password of my users were stored UNCRYPTED in the database... And stored uncrypted in the cookie as well.
  • I was doing something that was supposed to be OOP, but I never used heritage, so all my classes were containing the same methods, copied and pasted from one file to another, and changing only some variable names...

And some other mistakes:

  • I included a whole bunch of Javascript files (like 15 or so) and was NOT using any js framework. Well, technically I was using a js framework, but one I developped. And let be honest, I can't really call it a framework today.
  • I used letter-spacing:-1000em to hide text (when using an image as a header for example). It broke on Firefox, I'm now using text-indent:-1000em; (really, I don't know if this is better).
  • There was a flash animation with sound, enabled by default and with auto-play. For my defense, I remember having told by ex boss that it was a bad idea but he insisted.

To be honest a part of me is horrified of what I wrote some years ago and thought was great. On the other hand, I'm quite proud of the progress I have made in so little time.