MyBB Bitwise Operators Explained

So today after an interesting discussion with Joseph, one of the other MyBB developers, about showing different notices to users and such (such as if their private messaging quota is used) I suggested we use a bitfield/bitwise system for storing which “notices” the user still has visible (and hasn’t dismissed). Not knowing much about how bitwise works in PHP apart from how it’s calculated using binary I set out to do some experiementation and find out the end results.

MyBB Bitwise img

Along with everything in PHP, bitwise operators are easy to grasp and can easily be used in IF statements to check the value of a “bit field”. Take a look at the following code:
$notices['can_view'] = 1;
$notices['can_post_threads'] = 2;
$notices['can_post_replies'] = 4;
$notices['can_edit'] = 8;

$testers[1] = 1;
$testers[2] = 5;
$testers[3] = 9;
$testers[4] = 14;

foreach($testers as $key => $tester)
echo "$key";
foreach($notices as $key => $notice)
if($tester & $notice)
echo " - $key";
echo "<br />";

Now thise code will print out the following:
1 - can_view
2 - can_view - can_post_replies
3 - can_view - can_edit
4 - can_post_threads - can_post_replies - can_edit

So basically we can store a lot of data (be it preferences, yes/no options, permissions) in the one column in the database and variable in PHP and just perform if()’s to see if a certain value is in the field. (or an option is selected in a users profile).

For example, using the above code the following code would calculate if a user ($tester[1]) had the can_edit permission:

if($tester[1] & $notices['can_edit'])
echo "This user can edit";
echo "This user cannot edit";

The other interesting this is that this would also allow users to easily and effectively add their own “user options” or “permissions” to MyBB without having to modify the database by adding a new column to store the data – in fact using bitwise operators would reduce the size of the database all together.

I can see many useful places this can be implemented in to MyBB:

  • The permissions system for user groups and forums
  • User options (such as if they want to receive email notification to threads)
  • Forum settings (such as is open, can use BB code)
  • Basically any other options which can have a yes/no or on/off value

Chances are we’ll end up moving to a system like this for MyBB for storing these preferences and permissions, but instead of running in to it we’ll research it some more and find out the best possible ways of implementing it.

(Someone sent me an email saying I should write more about PHP/MyBB here 🙂 )