phpBB 3 Script Integration – New Threads and Replies from an External Script

This is the third article I’ve written for pulling functions in phpBB3 for external use. This one allows you to either create new posts in a forum or reply to a thread. This was created for use with a text system, where users could text in comments which would be added to a thread.

Article on phpBB3 Integration
Article on sending PM’s

I’ve put everything needed into one file as I don’t want to go through and break it up. The previous two posts (linked above) used a seperate phpbb.php file with part of the code in but this just includes everything.

<?php
// This is not set up for new thread posting, and has been config'd to not increment post count as this is for a bot.
// Further changes will be needed to clean up code as this is using external functions instead of clear documentation. --dc
define('IN_PHPBB', true);
$phpbb_root_path = (defined('PHPBB_ROOT_PATH')) ? PHPBB_ROOT_PATH : './phpBB3/';
$phpEx = substr(strrchr(__FILE__, '.'), 1);
include($phpbb_root_path . 'common.' . $phpEx);

// Start session management
$user->session_begin();
$auth->acl($user->data);
$user->setup();

// post send controller
function sendphpbbpost($pmmessage,$userid,$pmsubject) {

include_once('phpBB3/includes/functions_posting.php');
$my_subject = utf8_normalize_nfc(request_var('$pmsubject', '', true));
$message = utf8_normalize_nfc($pmmessage, '', true);
$uid = $bitfield = $options = '';
$allow_bbcode = $allow_smilies = true;
$allow_urls = true;
generate_text_for_storage($message, $uid, $bitfield, $options, $allow_bbcode, $allow_urls, $allow_smilies);
$data = array(
// General Posting Settings
'forum_id'          => 7,    // The forum ID in which the post will be placed. (int)
'topic_id'          => 5,    // Post a new topic or in an existing one? Set to 0 to create a new one, if not, specify your topic ID here instead.
'icon_id'           => false,    // The Icon ID in which the post will be displayed with on the viewforum, set to false for icon_id. (int)

// Defining Post Options
'enable_bbcode' => false, // Enable BBcode in this post. (bool)
'enable_smilies'    => true, // Enabe smilies in this post. (bool)
'enable_urls'       => false, // Enable self-parsing URL links in this post. (bool)
'enable_sig'        => true, // Enable the signature of the poster to be displayed in the post. (bool)

// Message Body
'message'           => $message,     // Your text you wish to have submitted. It should pass through generate_text_for_storage() before this. (string)
'message_md5'   => md5($message),    // The md5 hash of your message

// Values from generate_text_for_storage()
'bbcode_bitfield'   => $bitfield,    // Value created from the generate_text_for_storage() function.
'bbcode_uid'        => $uid,     // Value created from the generate_text_for_storage() function.

// Other Options
'post_edit_locked'  => 0,
'topic_title'       => $subject, // Subject/Title of the topic. (string). This is needed for new posts but for our purposes isn't.

// Email Notification Settings
'notify_set'        => false,        // (bool)
'notify'            => false,        // (bool)
'post_time'         => 0,        // Set a specific time, use 0 to let submit_post() take care of getting the proper time (int)
'forum_name'        => '',       // For identifying the name of the forum in a notification email. (string)

// Indexing
'enable_indexing'   => true,
'force_approved_state' => true, // Only runs on 6 onwards...check SUCC
);

//Now send that post...
submit_post('reply', '', '', POST_NORMAL, &$poll, &$data, $update_message = true);

}

$user->data['user_id'] = 2;    // User id of poster.
$auth->acl($user->data); // Re-initiate user after recall
$userid = $user->data['user_id'];
$pmmessage = 'This is a new reply, change this to whatever you want.';
sendphpbbpost($pmmessage,$userid,$pmsubject);

?>

Looking through the code above you will see several points that need changing. It’s currently set to ‘reply’ (change this to ‘post’ for a new post). Change all details to suit really – it’s easy to customise.

phpBB 3 Script Integration – Sending Private Messages (PM’s) From an External Script

A while back I posted an article about integrating your site to use the phpBB3 user and login system (here). When I wrote that I also used phpBB as a message system for a site; so when a user did something they were sent a private message automatically.

This bit of code (use it in conjunction with phpbb.php mentioned in the post linked to above) allows you to call a function to send a PM to any user as long as you have their ID.

<?php
// PM send controller
include_once("phpbb.php");

function sendphpbbpm($pmmessage,$userid,$pmsubject) {
include_once('forum/includes/functions_privmsgs.php');

$message = utf8_normalize_nfc($pmmessage);
$uid = $bitfield = $options = ''; // will be modified by generate_text_for_storage
$allow_bbcode = $allow_smilies = true;
$allow_urls = true;
generate_text_for_storage($message, $uid, $bitfield, $options, $allow_bbcode, $allow_urls, $allow_smilies);
$pm_data = array(
'from_user_id'        => 2,
'from_user_ip'        => "127.0.0.1",
'from_username'        => "admin",
'enable_sig'            => false,
'enable_bbcode'        => true,
'enable_smilies'        => true,
'enable_urls'        => false,
'icon_id'            => 0,
'bbcode_bitfield'    => $bitfield,
'bbcode_uid'         => $uid,
'message'            => $message,
'address_list'        => array('u' => array($userid => 'to')),
);

//Now We Have All Data Lets Send The PM!!
submit_pm('post', $pmsubject, $pm_data, false, false);
}

?>

You’ll need to modify the code above slightly to fit your needs, for example changing the admin username and user id, and then calling the function but it’s all pretty simple stuff one you’ve got all this.

To call the function (send the PM) to a fictional user 11:

<?php

$pmsubject = 'Please read this PM.';
$pmmessage = 'Thank you for reading this PM!';

$userid = '11';

sendphpbbpm($pmmessage,$userid,$pmsubject);

?>

Posting threads and replying to threads uses a similar system so I’ll put up some script for that shortly.

Integrating your existing site into phpBB3

One way of making an existing site dynamic is to integrate it with a phpBB forum. This is actually very easy, and allows you to quickly pull data about your users; control page access by groups and more.

Page type

The page you’re integrating phpBB with needs to be a php page! (pretty obvious really seeing as phpBB is a PHP forum)

Connect to phpBB to get variables, etc.

You will need to include a file containing the phpBB connection information (essentially plugs the page into the rest of phpBB). This file should contain the following

<?php
define('IN_PHPBB', true);
$phpbb_root_path = (defined('PHPBB_ROOT_PATH')) ? PHPBB_ROOT_PATH : 'change_this_to_phpbb_dir';
$phpEx = substr(strrchr(__FILE__, '.'), 1);
include($phpbb_root_path . 'common.' . $phpEx);
// Start session management
$user->session_begin();
$auth->acl($user->data);
$user->setup();
?>

Save this file as phpbb.php, or put this code in some other file you will include in every page you want to integrate. All this code does is define where phpbb can be found, and include the common.php file from within phpbb. It also starts a user session, which we can use on our page.

Get our page to interact with phpBB

So now we go to the page we want to integrate with phpBB. In this case I’m going to use a blank file as an example but obviously you can use any file. This bit of code checks to see if the user is logged in or not and displays an appropriate message

<?php include_once("phpbb.php"); ?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>phpBB conn test</title>
</head>
<body>
<?php
// PHPBB LOGIN AUTH
if ($user->data['user_id'] == ANONYMOUS) {
?>
Welcome, anomalous!
<?php
} else {
?>
Welcome back, <?php echo $user->data['username_clean']; ?> | You have <?php echo $user->data['user_unread_privmsg']; ?> new messages
<?php } ?>
</body>
</html>

This will display “Welcome, anomalous!” if you’re not logged into phpBB or “Welcome back, username | You have 0 new messages” if you are logged in. Note the placement of the include_once ABOVE the <head> tag – this is required if you don’t want any errors.

This is a very simple example and doesn’t tell our user how to log in or log out…which are pretty critical activities.

How about a login form?

The simple way to login is to push all logins through the phpBB system. This form does just that.

<form method="POST" action="forum/ucp.php?mode=login">
Username: <input type="text" name="username" size="20"><br />
Password: <input type="password" name="password" size="20"><br />
Remember Me?: <input type="checkbox" name="autologin"><br />
<input type="submit" value="Login" name="login">
<input type="hidden" name="redirect" value="">
</form>

This collect the login data and posts it to the phpBB ucp.php. We can make phpBB redirect the user back to any page by changing the value of the redirect input field.

<input type="hidden" name="redirect" value="../somefile.php">

Once this form has been posted the user will be logged in. But how about logging out?

Logging out of phpBB

You could just navigate to the forum and click the link there, but hey – might as well do this in as few clicks as possible. So we need a link to log out…

<a href="somefile.php?cp=logout">Log Out</a>

and in the same file we could put the following at the top of the document:

<?php
// check for logout request
$cp = $_GET['cp'];
// is it a logout? then kill the session!
if ($cp == "logout") {
$user->session_kill();
$user->session_begin();
echo "Successfully Logged Out.";
}
?>

So when cp is set to logout (when the user visits somefile.php?cp=logout) the session containing the userdata is destroyed and reset. ‘Succssfully Logged Out’ is also shown for the user’s benefit.

Combining conditional, login & logout

As a summary, I’ve combined what we looked at above.

In phpbb.php:

<?php
define('IN_PHPBB', true);
$phpbb_root_path = (defined('PHPBB_ROOT_PATH')) ? PHPBB_ROOT_PATH :  'change_this_to_phpbb_dir';
$phpEx = substr(strrchr(__FILE__, '.'), 1);
include($phpbb_root_path . 'common.' . $phpEx);
// Start session management
$user->session_begin();
$auth->acl($user->data);
$user->setup();
?>

In somefile.php:

<?php include_once("phpbb.php");
// check for logout request
$cp = $_GET['cp'];
// is it a logout? then kill the session!
if ($cp == "logout") {
$user->session_kill();
$user->session_begin();
echo "Successfully Logged Out.";
}
?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>phpBB conn test</title>
</head>
<body>
<?php
// Page login notice
if ($user->data['user_id'] == ANONYMOUS)
{
?>
<center>Welcome! Please login below or click <a href="forum/ucp.php?mode=register">here</a> to register.<br />
<form method="POST" action="forum/ucp.php?mode=login">
Username: <input type="text" name="username" size="20"><br />
Password: <input type="password" name="password" size="20"><br />
Remember Me?: <input type="checkbox" name="autologin"><br />
<input type="submit" value="Login" name="login">
<input type="hidden" name="redirect" value="../somefile.php">
</form>
<?php
} else { ?>
Welcome back, <?php echo $user->data['username_clean']; ?> | You have <?php echo $user->data['user_unread_privmsg']; ?> new messages | <a href="somefile.php?cp=logout">Log Out</a>
<?php } ?>
</body>
</html>

This will give you basic integration with an existing phpBB forum, we’ll look at further integration including private messenging in contact boxes soon.