This forum is in READ-ONLY mode.
You can look around, but if you want to ask a new question, please use the new forum.
Home » support » General discussion » phpBB Connector ?
phpBB Connector ? [message #29883] Thu, 21 June 2007 15:37 Go to next message
dmirulescu  is currently offline dmirulescu
Messages: 3
Registered: June 2007
Location: Bucharest
Junior Member

Hi guys,
I need to integrate sfGuardPlugin with phpBB users management and
I'm looking for a phpBB connector or api but I can't fine one.
Also I'll need the other methods like "add thread" , "delete forum" .. etc. to be disponible from symfony.
Can you guys find something like that ?

Thanks.
Re: phpBB Connector ? [message #30121 is a reply to message #29883 ] Mon, 25 June 2007 12:03 Go to previous messageGo to next message
naholyr  is currently offline naholyr
Messages: 223
Registered: June 2007
Faithful Member
I did something similar for PunBB, i think it's not more complicated for PhpBB, the easiest way to access your forum data is to generate your schema from the tables created.

  1. Install the board
  2. Init Symfony project, configure database access > symfony new myProject
  3. Generate schema from board tables > symfony propel-build-schema
  4. Now you have all your forum tables converted into schemas in config/schema.yml. You can edit it to define the foreign keys which would have not been automatically defined, delete the tables you don't want to have access to, etc...


You're now ready to add your own models, and simply generate your models as usually : you could configure sfGuard to user the phpbbUsers model as profile.
For better readability, i create 2 new classes User and UserPeer that extend ForumUsers and ForumUsersPeer, this way I can change forum only changing User.php and UserPeer.php, if my new forum doesn't use the same tables names this is not a problem. It's sorta forum-abstraction-layer Laughing

But of course that requires a good knowledge of the tables structure of the forum. I'm ok with PunBB, I'm not comfortable enought with phpBB.
Re: phpBB Connector ? [message #30132 is a reply to message #30121 ] Mon, 25 June 2007 12:35 Go to previous messageGo to next message
dmirulescu  is currently offline dmirulescu
Messages: 3
Registered: June 2007
Location: Bucharest
Junior Member

Ahh, this seems to be a good idea, but it sounds more like a plugin approach.
My picture about this was to create just one class that will hold all basic methods for the forum, the only problem with this is that if you use the phpBB's dbs abstraction you'll get results that are not much like symfony and you can't process and apply symfony methods on that.
So yeah, generating the models for forum's tables is the best approach to that. The only thing I need to do now is to identify some forum's mechanics .. like login .. to be able to write my own methods that will join together sfGuard's login with phpBB's login.

Thanks.
Re: phpBB Connector ? [message #58760 is a reply to message #30132 ] Fri, 15 August 2008 10:39 Go to previous messageGo to next message
colnector
Messages: 162
Registered: July 2008
Senior Member
How have you managed in integrating phpBB with Symfony? I'm about to do the same and wish to gather some tips Smile


Colnect Collectors Club Community
http://colnect.com

http://i.colnect.net/images/colnect_logo_255.png
Re: phpBB Connector ? [message #58763 is a reply to message #58760 ] Fri, 15 August 2008 11:20 Go to previous messageGo to next message
dmirulescu  is currently offline dmirulescu
Messages: 3
Registered: June 2007
Location: Bucharest
Junior Member

Hi,

We did something at that time to make it work at the basics, but wasn't a formal and reusable code. Since than, after updating PhpBB we had issues with some parts of the code because phpBB changed the database schema.

We haven't actually integrated sfGuard with phpBB authentication, We used phpBB login form on the website and created a symfony filer that will check for phpBB session and create a symfony one if the case. For creating new forms we did some custom code that was createing entries directly into phpbb's tables, but that broke after the update.

Now we are thinking to let phpbb go, and just use sfGuard, and for the forums part will think of something later.

Re: phpBB Connector ? [message #58765 is a reply to message #58763 ] Fri, 15 August 2008 11:52 Go to previous messageGo to next message
colnector
Messages: 162
Registered: July 2008
Senior Member
Thank you for your reply.

I'm still looking for a solution to this issue though it's possible to do what's currently done on my site:
The phpBB user creation module is disabled and when a new account is created on my site I update the phpBB tables. A problematic issue is the sessions and that the integrations are with an old version on phpBB.


Colnect Collectors Club Community
http://colnect.com

http://i.colnect.net/images/colnect_logo_255.png
Re: phpBB Connector ? [message #58773 is a reply to message #58760 ] Fri, 15 August 2008 13:52 Go to previous messageGo to next message
skywalker  is currently offline skywalker
Messages: 334
Registered: March 2008
Location: Norway
Faithful Member
colnector wrote on Fri, 15 August 2008 10:39

How have you managed in integrating phpBB with Symfony? I'm about to do the same and wish to gather some tips Smile


When a user log in to the symfony application we also log in to the phpbb system (by adding records to the phpbb_sessions and phpbb_sessions_keys tables and by setting the cookies phpbb use). So the user can move between the symfony part and the phpbb part of our application.

We have made classes for all the phpbb tables.

Works well Razz


May the source be with you
Re: phpBB Connector ? [message #58786 is a reply to message #58773 ] Fri, 15 August 2008 15:41 Go to previous messageGo to next message
colnector
Messages: 162
Registered: July 2008
Senior Member
Hi Skywalker,

Thank you for your reply. Have you integrated phpBB v3? Would it be possible to get the source code you've used?

10x Smile


Colnect Collectors Club Community
http://colnect.com

http://i.colnect.net/images/colnect_logo_255.png
Re: phpBB Connector ? [message #58904 is a reply to message #58786 ] Mon, 18 August 2008 07:55 Go to previous messageGo to next message
skywalker  is currently offline skywalker
Messages: 334
Registered: March 2008
Location: Norway
Faithful Member
Yes, it is phpBB3.

In short, our symfony application has a module called user, which handle the login using the phpbb_user table to verify the user and to log the user into both symfony and phpbb.

What you need is to generate the right cookies for the three cookies that phpbb is using:

class myUser extends sfBasicSecurityUser
{
  public function signIn(User $user)
  {
    // Log in to phpBB
    $sessionId = $this->random() . $this->random();
    $sessionId = substr($sessionId, 0, 32); // Just in case
    $sessionKey = $this->random();
    $phpbbCookieName = ConfigPeer::getCookieName();

    $this->insertDbSession($sessionId, $sessionKey, $user);
    $this->setCookies($phpbbCookieName, $sessionId, $sessionKey, $user);

    // Now we have logged in to phpBB, and go on to loggin in to symfony

    $this->setAttribute('user', $user);
    $this->setAuthenticated(true);

    // Update the last_visit field in the phpbb_users table.
    $user->setUserLastvisit(time());
    $user->save();

    return true;
  }

  private function insertDbSession($sessionId, $sessionKey, User $user)
  {
    $db_session_key = new SessionKey();
    $db_session_key->setKeyId(md5($sessionKey));
    $db_session_key->setUserId($user->getUserId());
    $db_session_key->setLastIp(sfContext::getInstance()->getRequest()->getHttpHeader('addr', 'remote'));
    $db_session_key->setLastLogin(time());
    $db_session_key->save();

    $dbSession = new Session();
    $dbSession->setSessionId(md5($sessionId));
    $dbSession->setSessionUserId($user->getUserId());
    $dbSession->setSessionStart(time());
    $dbSession->setSessionLastVisit(time());
    $dbSession->setSessionTime(time());
    $dbSession->setSessionBrowser($_SERVER['HTTP_USER_AGENT']);
    $dbSession->setSessionIp(sfContext::getInstance()->getRequest()->getHttpHeader('addr', 'remote'));
    $dbSession->setSessionAutologin(1);
    $dbSession->setSessionAdmin(0);
    $dbSession->setSessionViewonline(1);
    $dbSession->save();
  }

  private function setCookies($phpbbCookieName, $sessionId, $sessionKey, User $user)
  {
    $domain = ConfigPeer::getCookieDomain();

    // Two weeks should be ample
    $response = sfContext::getInstance()->getResponse();
    $response->setCookie($phpbbCookieName . '_k', $sessionKey, time() + 1209600, '/', $domain);
    $response->setCookie($phpbbCookieName . '_u', $user->getUserId() , time() + 1209600, '/', $domain);
    $response->setCookie($phpbbCookieName . '_sid', $sessionId, time() + 1209600, '/', $domain);
  }


Hope this help Smile


May the source be with you
Re: phpBB Connector ? [message #59048 is a reply to message #58904 ] Tue, 19 August 2008 18:45 Go to previous messageGo to next message
colnector
Messages: 162
Registered: July 2008
Senior Member
Thanks Smile
I'll give it a go. I'm using Doctrine ORM so I'll create the classes with them. Will update here with news.


Colnect Collectors Club Community
http://colnect.com

http://i.colnect.net/images/colnect_logo_255.png
Re: phpBB Connector ? [message #59223 is a reply to message #29883 ] Thu, 21 August 2008 16:47 Go to previous messageGo to next message
naholyr  is currently offline naholyr
Messages: 223
Registered: June 2007
Faithful Member
Where the classes Session, SessionKey and ConfigPeer come from ?
Is there a possibility you publish your work as a plugin ?
Re: phpBB Connector ? [message #59253 is a reply to message #59223 ] Fri, 22 August 2008 08:46 Go to previous messageGo to next message
skywalker  is currently offline skywalker
Messages: 334
Registered: March 2008
Location: Norway
Faithful Member
Session is a class for the phpbb_sessions table, Sessionkey is the class for the phpbb_sessions_key table and the Config (and ConfigPeer) is the phpbb_config table.

The function ConfigPeer::getCookieDomain() returns the value for the key 'cookie_domain' in the phpbb_config table while the ::getCookieName() return the value for the key 'cookie_name'.

Don't think I will have time to make this a plugin. My primary goal is to launch the project I work on soon.


May the source be with you
Re: phpBB Connector ? [message #61230 is a reply to message #58904 ] Thu, 18 September 2008 10:13 Go to previous messageGo to next message
skywalker  is currently offline skywalker
Messages: 334
Registered: March 2008
Location: Norway
Faithful Member
An update. The previous posted code was not 100% accurate (it worked most of the time).

Quote:


public function signIn(User $user)
{
// Is user banned?
if ($this->isUserBanned($user)) {
myLogger::logEvent(__METHOD__, myLogger::LOGEVENT_SECURITY, $user->getUsername());
return false;
}

// Log in to phpBB
$sessionId = $this->random() . $this->random();
$sessionId = substr($sessionId, 0, 32); // Just in case
$sessionKey = '';
...
}

private function insertDbSession($sessionKey, $sessionId, User $user)
{
$dbSession = new Session();
$dbSession->setSessionId($sessionId);
$dbSession->setSessionUserId($user->getUserId());
$dbSession->setSessionStart(time());
$dbSession->setSessionLastVisit(time());
$dbSession->setSessionTime(time());
$dbSession->setSessionBrowser($_SERVER['HTTP_USER_AGENT']);
$dbSession->setSessionIp(sfContext::getInstance()->getRequest()- >getHttpHeader('addr', 'remote'));
$dbSession->setSessionAutologin(1);
$dbSession->setSessionAdmin(0);
$dbSession->setSessionViewonline(1);
$dbSession->save();
}


May the source be with you
icon14.gif  Re: phpBB Connector ? [message #63016 is a reply to message #61230 ] Mon, 13 October 2008 21:24 Go to previous messageGo to next message
colnector
Messages: 162
Registered: July 2008
Senior Member
[EDITED] NOW WORKS Smile

Some time has passed but I'm finally about to use your code (I'm actually using Doctrine but would prefer to do the SQL queries here directly and not via the ORM).

A few more question:
1/ Regarding the last post you've made: why should sessionKey simply be blank?

2/ What about signOut()? Should the session be deleted from the phpbb database?

3/ You're calling $this->random(). Where is this function defined? I guess I can simply create a function to generate a random string. Are there any limitations there or would the following work? UPDATE: it seems to work well
md5(uniqid('some_seed_string'.rand(), true))


4/ Have you created other functions that integrate with phpBB such as creating an account?

Many thanks

[Updated on: Mon, 13 October 2008 22:39]


Colnect Collectors Club Community
http://colnect.com

http://i.colnect.net/images/colnect_logo_255.png
Re: phpBB Connector ? [message #63029 is a reply to message #63016 ] Tue, 14 October 2008 07:50 Go to previous messageGo to next message
skywalker  is currently offline skywalker
Messages: 334
Registered: March 2008
Location: Norway
Faithful Member
Answers to your questions:

1 Because I found that phpbb set this only in some cases. It is not required to set it.

2 When signing out, you clear the cookies and delete the entries in the database.

3 $this->random() is just another function that return a string filled with random characters which is at least 32 char long.

Glad it works. It took me some time to do some reverse engineering of the phpbb code and it seems to work now


May the source be with you
Re: phpBB Connector ? [message #63032 is a reply to message #63029 ] Tue, 14 October 2008 08:30 Go to previous messageGo to next message
colnector
Messages: 162
Registered: July 2008
Senior Member
Thanks again for sharing your code.

You can see my intermediate code here. It appears to be working quite well but I'm still missing parts like signOut(), sendPM(), changePassword() etc. I'll appreciate some leads on these.

I will perhaps use other scripts which 'fake' phpBB environment. This topic has a lot of information about it. I still need to resolve some name collisions but let's see how it works.

Since my code doesn't use an ORM and has some more phpBB related function, I'm including it here for the benefit of others.

    <?php
    /**
    * Integration with phpBB v3 forums
    * (c)Colnector 2008 - http://colnect.com
    *
    */
    class PhpbbIntegration
    {
       const DB_SERVER = 'server';
       const DB_USER = 'user';
       const DB_PASSWORD = 'pass';
       const DB_DATABASE = 'database';
       static $link = null;   
       
       /**
        * Connect to phpBB database
        *
        * @return resource - a MySQL link identifier on success, or false on failure.
        */
       public static function getDbConnection() {      
          if(is_null(self::$link) &&
             (!(self::$link = mysql_connect(self::DB_SERVER, self::DB_USER, self::DB_PASSWORD))
              || !mysql_select_db(self::DB_DATABASE)
              || !mysql_query("SET NAMES 'utf8'"))) {
             usleep(5000000); // 5 sec - wait for your error to prevent too many requests
             throw new Exception("getDbConnection failed. MESSAGE [[".mysql_error()."]]");
          }
          return self::$link;
       }
       
       /**
        * Execute SQL query on phpBB database
        *
        * @param string $sql
        * @return resource
        */
       public static function sqlExec($sql) {
          $link = self::getDbConnection();
          if (!($result = mysql_query($sql, $link))) {
             throw new Exception("SqlExec failed. QUERY [[$sql]] MESSAGE [[".mysql_error()."]]");
          }
          return $result;
       }

       /**
        * Set a field in the users table
        *
        * @param integer $user_id
        * @param array of string $field_name => $field_value - without the user_ prefix, for example: email
        * @param string $field_value- new field value
        */
       public static function updateUserFields($user_id, $new_values) {
          # TODO: check that strings are escaped properly to prevent SQL injection
          if (empty($new_values) || !is_array($new_values)) throw new Exception('setUser() got invalid $new_values');
          $sSqlExtra = '';
          foreach($new_values as $field_name => $field_value) {
             $sSqlExtra .= ",`user_$field_name`='$field_value'";         
          }
          $sSqlExtra = substr($sSqlExtra, 1);      
          $sql = "UPDATE phpbb_users SET $sSqlExtra WHERE `user_id`='$user_id' LIMIT 1";
          self::sqlExec($sql);
       }
       
       public static function changeEmail($user_id, $new_email) {
          self::updateUserFields($user_id, array('email' => $new_email));
       }
       
       public static function changeWebsite($user_id, $new_website) {
          self::updateUserFields($user_id, array('website' => $new_email));
       }

       
       public static function signIn($user_id) {
        // Log in to phpBB
        $sessionId = md5(uniqid('something'.rand(), true));#$this->random().$this->random();
        #$sessionId = substr($sessionId, 0, 32); // Just in case
        $sessionKey = '';#$this->random();
        $phpbbCookieName = self::getConfigVal('cookie_name');

        self::insertDbSession($sessionId, $sessionKey, $user_id);
        self::setCookies($phpbbCookieName, $sessionId, $sessionKey, $user_id);

        // Update the last_visit field in the phpbb_users table.
        $now = time();
        $sql = "UPDATE `phpbb_users` SET `user_lastvisit` = '$now' WHERE `phpbb_users`.`user_id`=$user_id LIMIT 1;";
        self::sqlExec($sql);      
       }
       
       public static function signOut($user_id) {
          
       }

       /**
        * Return the new Private Messages (PM) count
        *
        * @param integer $user_id
        * @return integer
        */
       public static function getCountNewPM($user_id) {
          $r = mysql_fetch_row(self::SqlExec('SELECT user_new_privmsg FROM `phpbb_users` WHERE user_id='.$user_id.' LIMIT 1'));
          return intval($r[0]);
       }

      private static function insertDbSession($sessionId, $sessionKey, $user_id) {
         $key_id = $sessionKey;
         $remote_ip = sfContext::getInstance()->getRequest()->getHttpHeader('addr', 'remote');
         $now = time();
         $sql = "REPLACE INTO `phpbb_sessions_keys` (`key_id` ,`user_id` ,`last_ip` ,`last_login`)"
          ."VALUES ('$key_id', '$user_id', '$remote_ip', '$now');";
          self::sqlExec($sql);       

          $browser = $_SERVER['HTTP_USER_AGENT'];
         $sql = "REPLACE INTO `phpbb_sessions` (`session_id` ,`session_user_id` ,`session_forum_id` ,"
          ."`session_last_visit` ,`session_start` ,`session_time` ,`session_ip` ,`session_browser` ,"
          ."`session_forwarded_for` ,`session_page` ,`session_viewonline` ,`session_autologin` ,"
          ."`session_admin`) VALUES ("
          ."'$sessionId', '$user_id', '0', '$now', '$now', '$now', '$remote_ip', '$browser', '', '', '1', '1', '0');";
          self::sqlExec($sql);
      }
     
      public static function getConfigVal($name) {
         $sql = "SELECT `config_value` FROM `phpbb_config` WHERE `config_name` LIKE '$name'";
         $result = self::sqlExec($sql);
         $ar = mysql_fetch_array($result);
         #Echoer::e($ar['config_value']);
         return $ar['config_value'];
      }

      private static function setCookies($phpbbCookieName, $sessionId, $sessionKey, $user_id)
      {
        $domain = self::getConfigVal('cookie_domain');   

        // Two weeks should be ample
        $response = sfContext::getInstance()->getResponse();
        $expiry = time() + 1209600;
        $response->setCookie($phpbbCookieName . '_k', $sessionKey, $expiry, '/', $domain);
        $response->setCookie($phpbbCookieName . '_u', $user_id, $expiry, '/', $domain);
        $response->setCookie($phpbbCookieName . '_sid', $sessionId, $expiry, '/', $domain);
      }


    }


Colnect Collectors Club Community
http://colnect.com

http://i.colnect.net/images/colnect_logo_255.png
Re: phpBB Connector ? [message #63033 is a reply to message #63032 ] Tue, 14 October 2008 08:40 Go to previous messageGo to next message
skywalker  is currently offline skywalker
Messages: 334
Registered: March 2008
Location: Norway
Faithful Member
Our logout (or singOut) code:

class myUser extends sfBasicSecurityUser
{
  public function logout()
  {
    if (!$this->isAuthenticated()) {
      return false;
    }

    // log out of phpBB
    $this->sessionDestroy();

    // log out of symfony
    $this->getAttributeHolder()->clear();
    $this->setAuthenticated(false);
    $this->clearCredentials();

    return true;
  }

  private function sessionDestroy()
  {
    $phpbbCookieName = ConfigPeer::getCookieName();

    // Collect information from phpBBs cookies
    $cookies = $this->readCookies($phpbbCookieName);

    $userId = $cookies->get('UserId');
    $sessionKey = $cookies->get('SessionKey');
    $sessionId = $cookies->get('SessionId');

    $user = UserPeer::retrieveByPK($userId);

    if (!$user) {
      return false;
    }

    // Update the last logged in timestamp
    $user->setUserLastvisit(time());
    $user->save();

    // Delete by session id if possible, user id otherwise
    if ($userId && ($sessionKey || $sessionId)) {
      $this->deleteDbSessionKeys($user, $sessionId, $sessionKey);
    } elseif ($user->uid) {
      $this->deleteDbSessionUid($user);
    }

    $this->unsetCookies($phpbbCookieName);

    return true;
  }

  private function deleteDbSessionUid(User $user)
  {
    $c = new Criteria();

    $c->add(SessionPeer::SESSION_USER_ID, $user->getUserId());
    $c->add(SessionPeer::SESSION_IP, sfContext::getInstance()->getRequest()->getHttpHeader('addr', 'remote'));

    SessionPeer::doDelete($c);

    $c = new Criteria();

    $c->add(SessionKeyPeer::USER_ID, $user->getUserId());
    $c->add(SessionKeyPeer::LAST_IP, sfContext::getInstance()->getRequest()->getHttpHeader('addr', 'remote'));

    SessionKeyPeer::doDelete($c);
  }

  private function deleteDbSessionKeys(User $user, $sessionId, $sessionKey)
  {
    if ($sessionId) {
      $c = new Criteria();

      $c->add(SessionPeer::SESSION_USER_ID, $user->getUserId());
      $c->add(SessionPeer::SESSION_ID, md5($sessionId));

      SessionPeer::doDelete($c);
    }

    if ($sessionKey) {
      $c = new Criteria();

      $c->add(SessionKeyPeer::USER_ID, $user->getUserId());
      $c->add(SessionKeyPeer::KEY_ID, md5($sessionKey));

      SessionKeyPeer::doDelete($c);
    }
  }

  private function readCookies($phpbbCookieName)
  {
    $cookies = new generic();

    $cookies->set('SessionId',  $_COOKIE[$phpbbCookieName . '_sid']);
    $cookies->set('SessionKey', $_COOKIE[$phpbbCookieName . '_k']);
    $cookies->set('UserId',     $_COOKIE[$phpbbCookieName . '_u']);

    return $cookies;
  }

  private function unsetCookies($phpbbCookieName)
  {
    $domain = ConfigPeer::getCookieDomain();

    $response = sfContext::getInstance()->getResponse();
    $response->setCookie($phpbbCookieName . '_k', '', time() - 3600, '/', $domain);
    $response->setCookie($phpbbCookieName . '_u', 0, time() - 3600, '/', $domain);
    $response->setCookie($phpbbCookieName . '_sid', '', time() - 3600, '/', $domain);
  }
}


Hope this help.


May the source be with you
Re: phpBB Connector ? [message #63087 is a reply to message #63033 ] Tue, 14 October 2008 20:57 Go to previous messageGo to next message
colnector
Messages: 162
Registered: July 2008
Senior Member
Thank you for this code. I've decided to erase all user sessions on logout since the same user shouldn't probably not be connected on different machines at the same time anyway.


Colnect Collectors Club Community
http://colnect.com

http://i.colnect.net/images/colnect_logo_255.png
Re: phpBB Connector ? [message #63112 is a reply to message #63087 ] Wed, 15 October 2008 08:25 Go to previous messageGo to next message
skywalker  is currently offline skywalker
Messages: 334
Registered: March 2008
Location: Norway
Faithful Member
But if (s)he does connect from to computers at the same time? Rolling Eyes


May the source be with you
Re: phpBB Connector ? [message #63146 is a reply to message #63112 ] Wed, 15 October 2008 12:12 Go to previous messageGo to next message
colnector
Messages: 162
Registered: July 2008
Senior Member
Not very relevant for my site (and worst case is he'll have to login again on the other machine) but I'll think about it. Thanks again for the code! Smile

Last thing I'm about to do is create an account.

BTW: I did try using phpBB's files (it makes the hacks a lot easier and more compatible) but so far it's not that easy from within the symfony project and I couldn't get it to work.

Here's an example for a registration form


Colnect Collectors Club Community
http://colnect.com

http://i.colnect.net/images/colnect_logo_255.png
Re: phpBB Connector ? [message #63152 is a reply to message #63146 ] Wed, 15 October 2008 13:22 Go to previous messageGo to next message
skywalker  is currently offline skywalker
Messages: 334
Registered: March 2008
Location: Norway
Faithful Member
The User and UserPeer classes reflect the phpbb_users table. The code we use to create a user is:

class UserPeer extend BaseUserPeer
{
  const USERTYPE_NORMAL = 0;
  const USERTYPE_BOTS = 2;

  public static function create($userInfo)
  {
    if (isset($userInfo['id']) && UserPeer::retrieveByPK($userInfo['id'])) {
      throw new Exception('User id already exists');
    }

    if ('' == $userInfo['username']) {
      throw new Exception('Username missing');
    }

    if ('' == $userInfo['password']) {
      throw new Exception('Missing password');
    }

    if ('' == $userInfo['email']) {
      throw new Exception('Email missing');
    }

    // Get the group id.
    $group = GroupPeer::getRegisteredGroup();
    if (!$group) {
      throw new Exception('User group not found');
    }

    // Make e-mail addresse in lower case
    $email = strtolower($userInfo['email']);

    // Add the user to the database
    $user = new User();

    $user->setUsername($userInfo['username']);
    $user->setUsernameClean(myTools::slug($userInfo['username']));
    $user->setGroupId($group->getGroupId());
    $user->setUserPassword($userInfo['password']);
    $user->setUserPassConvert(0);
    $user->setUserPasschg(time());
    $user->setUserRegdate(time());
    $user->setUserEmail($email);
    $user->setUserEmailHash(crc32(strtolower($email)) . strlen($email));
    $user->setUserLang(ConfigPeer::getConfigValueFor('default_lang'));
    $user->setUserTimezone(ConfigPeer::getConfigValueFor('board_timezone'));
    $user->setUserDateformat(ConfigPeer::getDefaultDateformat());
    $user->setUserAllowPm(1);
    $user->setUserAllowViewemail(1);
    $user->setUserOptions(895);
    $user->setUserSig('');
    $user->setUserLastpage('');
    $user->setUserPermissions('');
    $user->setUserFrom('');
    $user->setUserAim('');
    $user->setUserYim('');
    $user->setUserMsnm('');
    $user->setUserJabber('');
    $user->setUserWebsite('');
    $user->setUserOcc('');
    $user->setUserInterests('');
    $user->setUserActkey(md5(time() . sfConfig::get('app_secret')));

    $user->save();

    $userId = self::getUserIdByUsername($userInfo['username']);

    // Insert the user into the group_name = REGISTERED group
    $group = new UserGroup();

    $group->setGroupId($group->getGroupId());
    $group->setUserId($userId);
    $group->setGroupLeader(0);
    $group->setUserPending(0);

    $group->save();

    // Update newest user on the front of the forum
    ConfigPeer::setConfigValueFor('newest_user_id', $userId);
    ConfigPeer::setConfigValueFor('newest_username', $userInfo['username']);

    // Increment total number of users
    ConfigPeer::setConfigValueFor('num_users', ConfigPeer::getConfigValueFor('num_users') + 1);

    // Fetching 'show_name' field, we need it for default value
    $showName = ProfileFieldPeer::retrieveByPK(5);
    if (!$showName) {
      throw Exception ('Database error');
    }

    // Create custom profile fields
    $profileFields = new ProfileFieldData();

    $profileFields->setUserId($userId);
    $profileFields->setPfShowName($showName->getFieldDefaultValue());

    $profileFields->save();

    // Clear cache
    myProcessCache::delete('user_count');

    return self::retrieveByPK($userId);
  }
}


Again, written by looking in the phpbb code. Rolling Eyes


May the source be with you
icon14.gif  Re: phpBB Connector ? [message #63433 is a reply to message #63152 ] Sun, 19 October 2008 00:25 Go to previous messageGo to next message
colnector
Messages: 162
Registered: July 2008
Senior Member
Thanks again for sharing. I've made my version with direct SQL and will post it if anyone asks for it. My site is now up and running Smile


Colnect Collectors Club Community
http://colnect.com

http://i.colnect.net/images/colnect_logo_255.png
Re: phpBB Connector ? [message #63627 is a reply to message #63152 ] Wed, 22 October 2008 08:09 Go to previous messageGo to next message
skywalker  is currently offline skywalker
Messages: 334
Registered: March 2008
Location: Norway
Faithful Member
There is another issue regarding phpBB intergration.

Our specification says that the user should only log in to the symfony application and cookies should be set to simulate phpbb login. So far so good.

The phpBB forums are shown for guests. The problem occurs when a forum is accessable for registered users only. Then the phpBB login box appears. This cannot be avoided without rewriting the phpbb code (by adding a redirect to the symfony applications login page).

Rewriting the phpBB code is not a good idea since it makes it difficult to upgrade phpBB (fixes etc).

I'm currently in the "think box" with this issue...


May the source be with you
icon1.gif  Re: phpBB Connector ? [message #63632 is a reply to message #63627 ] Wed, 22 October 2008 10:22 Go to previous messageGo to next message
colnector
Messages: 162
Registered: July 2008
Senior Member
Well, I'm not so afraid of changing phpBB's code and have done so for different reasons. The whole concept of MODs in phpBB is about changing the code to better suite your needs. I've put the original code in svn and so wouldn't have such big problems merging future updates.

There are so many issues relevant for a proper integration and trying to avoid changing phpBB code at all cost may prove to be much more costly than doing it.


Colnect Collectors Club Community
http://colnect.com

http://i.colnect.net/images/colnect_logo_255.png
Re: phpBB Connector ? [message #63637 is a reply to message #63632 ] Wed, 22 October 2008 11:19 Go to previous messageGo to next message
skywalker  is currently offline skywalker
Messages: 334
Registered: March 2008
Location: Norway
Faithful Member
I have managed to avoid the phpBB login screen by removing the login form from our phpBB templates. Instead, the user get a link that says "click here to log in to <our application name>".

Not a perfect solution, but at least I stick the the system specification for our project that says "No phpBB modification".


May the source be with you
Re: phpBB Connector ? [message #63638 is a reply to message #63637 ] Wed, 22 October 2008 11:28 Go to previous messageGo to next message
colnector
Messages: 162
Registered: July 2008
Senior Member
IMO modifying the template is modifying phpBB Smile
Again, there's a whole scene of MODs (many of which are on phpBB's site itself) so it's more common than uncommon to modify it.

Personally, I'm using a redirect occasionally when I'm not interested in phpBB's pages.
Registration, Login, Logout, Members List and more redirect back to my application. It's essential to make the site look like a whole and not confuse its members.
Other stuff I did was to ensure avatar pictures are loaded from an external url rather than the same server. Many things cannot be done without hacking into phpBB's code.


Colnect Collectors Club Community
http://colnect.com

http://i.colnect.net/images/colnect_logo_255.png
Re: phpBB Connector ? [message #79867 is a reply to message #63433 ] Mon, 15 June 2009 12:42 Go to previous messageGo to next message
charles  is currently offline charles
Messages: 14
Registered: August 2008
Junior Member
@colnector

Quote:

Thanks again for sharing. I've made my version with direct SQL and will post it if anyone asks for it


Yeah colnector please do.

I try to achieve the same here and any higlights would be reaaly appreciated.

[Updated on: Mon, 15 June 2009 12:45]

icon12.gif  Re: phpBB Connector ? [message #80476 is a reply to message #79867 ] Tue, 23 June 2009 15:18 Go to previous messageGo to next message
colnector
Messages: 162
Registered: July 2008
Senior Member
Sorry, I cannot afford the time to assist now but here's the code I'm using for some basic functions. This is the code currently operational. It's not very ordered though but I'm sure it can be figured out. I hope it'll help you. If you find any issues that may need fixin', please also let me know. Good luck Smile

<?php
/**
 * Integration with phpBB v3 forums
 * (c)Amir Wald 2008 - http://colnect.com
 *
 */
class PhpbbIntegration
{
	const DB_SERVER = '---';
	const DB_USER = '---';
	const DB_PASSWORD = '---';
	const DB_DATABASE = '---';
	static $link = null;

	/**
	 * Connect to phpBB database
	 *
	 * @return resource - a MySQL link identifier on success, or false on failure.
	 */
	public static function getDbConnection() {
		if(is_null(self::$link) &&
			(!(self::$link = mysql_connect(self::DB_SERVER, self::DB_USER, self::DB_PASSWORD))
			 || !mysql_select_db(self::DB_DATABASE)
			 || !mysql_query("SET NAMES 'utf8'"))) {
			usleep(5000000); // 5 sec - wait for your error to prevent too many requests
			throw new Exception("getDbConnection failed. MESSAGE [[".mysql_error()."]]");
		}
		return self::$link;
	}

	/**
	 * Execute SQL query on phpBB database
	 *
	 * @param string $sql
	 * @return resource
	 */
	public static function sqlExec($sql) {
		#Echoer::e("sqlExec($sql)");
		$link = self::getDbConnection();
		if (!($result = mysql_query($sql, $link))) {
			throw new Exception("SqlExec failed. QUERY [[$sql]] MESSAGE [[".mysql_error()."]]");
		}
		return $result;
	}

	/**
	 * Set a field in the users table
	 *
	 * @param integer $user_id
	 * @param array of string $field_name => $field_value - without the user_ prefix, for example: email
	 * @param string $field_value- new field value
	 */
	public static function updateUserFields($user_id, $new_values) {
		# TODO: check that strings are escaped properly to prevent SQL injection
		if (empty($new_values) || !is_array($new_values)) throw new Exception('setUser() got invalid $new_values');
		$sSqlExtra = '';
		foreach($new_values as $field_name => $field_value) {
			$sSqlExtra .= ",`user_$field_name`='$field_value'";
		}
		$sSqlExtra = substr($sSqlExtra, 1);
		$sql = "UPDATE phpbb_users SET $sSqlExtra WHERE `user_id`='$user_id' LIMIT 1";
		self::sqlExec($sql);
	}

	/**
	 * Set the user's email in phpBB
	 *
	 * @param integer $user_id
	 * @param string $new_email
	 */
	public static function changeEmail($user_id, $new_email) {
		self::updateUserFields($user_id, array('email' => $new_email));
	}

	/**
	 * Set the user's website in phpBB
	 *
	 * @param integer $user_id
	 * @param string $new_email
	 */
	public static function changeWebsite($user_id, $new_website) {
		self::updateUserFields($user_id, array('website' => $new_email));
	}
	
	/**
	 * Sets wether or not the user has an avatar picture
	 *
	 * @param integer $user_id
	 * @param boolean $bHasAvatar
	 */
	public static function changeAvatar($user_id, $bHasAvatar) {
		if ($bHasAvatar) {
			$user_avatar_type = 1;
			$user_avatar = $user_id.'.png';			
		} else {
			$user_avatar_type = 0;
			$user_avatar = '';			
		}
		
		self::updateUserFields($user_id, array('avatar' => $user_avatar, 
			'avatar_type' => $user_avatar_type));
	}
	

	/**
	 * Sign in to phpBB by creating a session on the server and a matching cookie
	 * on the client.
	 *
	 * @param integer $user_id
	 */
	public static function signIn($user_id) {
		###use $_SERVER["PATH"] to launch php with external script

		// Log in to phpBB
		$sessionId = md5(uniqid('something'.rand(), true));#$this->random().$this->random();
		#$sessionId = substr($sessionId, 0, 32); // Just in case
		$sessionKey = '';#$this->random();
		$phpbbCookieName = self::getConfigVal('cookie_name');

		self::insertDbSession($sessionId, $sessionKey, $user_id);
		self::setCookies($phpbbCookieName, $sessionId, $sessionKey, $user_id);

		// Update the last_visit field in the phpbb_users table.
		self::updateUserFields($user_id, array('lastvisit' => time()));
	}

	/**
	 * Sign out from phpBB by unsetting the session on the server and expiring
	 * the cookie on the client.
	 *
	 * @param integer $user_id
	 */
	public static function signOut($user_id) {
		$phpbbCookieName = self::getConfigVal('cookie_name');

		// Update the last_visit field in the phpbb_users table.
		self::updateUserFields($user_id, array('lastvisit' => time()));

		self::deleteDbSession($user_id);
		self::unsetCookies($phpbbCookieName);
	}

	/**
	 * Get a configuration value from phpBB's database
	 *
	 * @param string $name - value name
	 * @return string - the value
	 */
	public static function getConfigVal($name) {
		$sql = "SELECT `config_value` FROM `phpbb_config` WHERE `config_name` LIKE '$name'";
		$result = self::sqlExec($sql);
		$ar = mysql_fetch_array($result);
		return $ar['config_value'];
	}

	/**
	 * Insert a session to phpBB's database
	 *
	 * @param integer $user_id
	 *
	 */
	private static function insertDbSession($sessionId, $sessionKey, $user_id) {
		$remote_ip = sfContext::getInstance()->getRequest()->getHttpHeader('addr', 'remote');
		$now = time();
		$sql = "REPLACE INTO `phpbb_sessions_keys` (`key_id` ,`user_id` ,`last_ip` ,`last_login`)"
 		."VALUES ('$sessionKey', '$user_id', '$remote_ip', '$now');";
 		self::sqlExec($sql);

 		$browser = $_SERVER['HTTP_USER_AGENT'];
		$sql = "REPLACE INTO `phpbb_sessions` (`session_id` ,`session_user_id` ,`session_forum_id` ,"
		."`session_last_visit` ,`session_start` ,`session_time` ,`session_ip` ,`session_browser` ,"
		."`session_forwarded_for` ,`session_page` ,`session_viewonline` ,`session_autologin` ,"
		."`session_admin`) VALUES ("
		."'$sessionId', '$user_id', '0', '$now', '$now', '$now', '$remote_ip', '$browser', '', '', '1', '1', '0');";
		self::sqlExec($sql);
	}

	/**
	 * Delete user's session(s) from phpBB's database
	 *
	 * @param integer $user_id
	 */
	private static function deleteDbSession($user_id) {
		if (intval($user_id) < 1) {
			return false;
			# an extra check since DELETE without LIMIT is about to be performed
			#throw new Exception('PhpbbIntegration::deleteDbSession() got invalid user');
		}

		$sql = "DELETE FROM `phpbb_sessions_keys` WHERE `user_id`='$user_id'";
 		self::sqlExec($sql);

		$sql = "DELETE FROM `phpbb_sessions` WHERE `session_user_id`='$user_id'";
		self::sqlExec($sql);
	}

	/**
	 * Set client cookies to allow auto-login to phpBB
	 *
	 * @param string $phpbbCookieName
	 * @param unknown_type $sessionId
	 * @param unknown_type $sessionKey
	 * @param unknown_type $user_id
	 */
	private static function setCookies($phpbbCookieName, $sessionId, $sessionKey, $user_id) {
		$domain = self::getConfigVal('cookie_domain');

		$response = sfContext::getInstance()->getResponse();
		$expiry = time() + 1209600; # two weeks should be ample
		$response->setCookie($phpbbCookieName.'_k', $sessionKey, $expiry, '/', $domain);
		$response->setCookie($phpbbCookieName.'_u', $user_id, $expiry, '/', $domain);
		$response->setCookie($phpbbCookieName.'_sid', $sessionId, $expiry, '/', $domain);
	}

	/**
	 * Unset client cookies
	 *
	 * @param string $phpbbCookieName
	 */
	private static function unsetCookies($phpbbCookieName) {
		$domain = self::getConfigVal('cookie_domain');

		$response = sfContext::getInstance()->getResponse();
		$expiry = time() - 86400; # set to expired yesterday
		$response->setCookie($phpbbCookieName.'_k', '', $expiry, '/', $domain);
		$response->setCookie($phpbbCookieName.'_u', 0, $expiry, '/', $domain);
		$response->setCookie($phpbbCookieName.'_sid', '', $expiry, '/', $domain);
	}

	/**
	 * Return the new Private Messages (PM) count
	 *
	 * @param integer $user_id
	 * @return integer
	 */
	public static function getCountNewPM($user_id) {
		$r = mysql_fetch_row(self::SqlExec('SELECT user_new_privmsg FROM `phpbb_users` WHERE user_id='.$user_id.' LIMIT 1'));
		return intval($r[0]);
	}




	////////// the following not yet implemented

	public static function syncUser($user_id) {
		/*
		 // UPDATE DB - phpBB
$sql = "UPDATE phpbb_users"
	." SET user_email='$email'"
	.",user_viewemail='$prefShowEmail'"
	.",user_website='$homepage'"
	.$extra_phpbb
	." WHERE user_id=".$UserID;
dbconn::SqlExec($sql);
		 */

	}

	public static function syncUsers() {
		# TODO: implement
		# iterate users list and create acounts
		# sync emails, homepages etc.

	}

	public static function fakeInsidePhpBB() {
	}


	public static function createAccount($user_id, $username, $password, $email,
		$language = 'en', $timezone = '0.00', $date_format = 'd M Y H:i') {
		/*
		$_REQUEST['submit'] = true;
		$_REQUEST['username'] = $username;
		$_REQUEST['password'] = $password;
		$_REQUEST['email'] = $email;

		require_once dirname(__FILE__).'/../../web/forums/externals/new_account.php';

		return;*/


    //do the date format thingy
    $group_id = 12;
    $user_regdate = time();
    $username_clean = strtolower($username);
    $user_email_hash = crc32(strtolower($email));
    $ip = $_SERVER['REMOTE_ADDR'];

    //deleted user_permissions - 3rd field before user_perm_from
    /* All these fields were removed in favor of defaults
    user_type, user_perm_from, user_pass_convert, user_lastvisit, user_lastmark, user_lastpost_time,
    '0', '0', '0', '0', '$user_regdate', '0',
    user_last_search, user_warnings, user_last_warning, user_login_attempts, user_inactive_reason,
    '0', '0', '0', '0', '0',
    user_inactive_time, user_posts, user_dst,
    '0', '0', '1',
    user_rank, user_new_privmsg, user_unread_privmsg, user_last_privmsg, user_message_rules,
    '0', '0', '0',  '0', '0',
    user_full_folder, user_emailtime,
    '-3', '0',
		user_topic_show_days, user_topic_sortby_type, user_topic_sortby_dir, user_post_show_days,
		'0', 't', 'd', '0',
		user_post_sortby_type, user_post_sortby_dir,
		't', 'a',
		user_notify_type,
		'0',
		user_allow_pm, user_allow_viewonline, user_allow_viewemail, user_allow_massemail,
		'1', '1', '1', '1',
		*/
    $sql = "INSERT INTO phpbb_users (user_id, group_id, user_ip, user_regdate,
    	username, username_clean, user_password, user_passchg, user_email,
    	user_email_hash, user_lang, user_timezone, user_dateformat,
    	user_style, user_notify, user_notify_pm, user_options)
    	VALUES('$user_id', '$group_id', '$ip', '$user_regdate',
    	'$username', '$username_clean', '$password', '$user_regdate',	'$email',
    	'$user_email_hash', '$language', '$timezone',	'$date_format',
    	'1', '1', '1', '1855')";
    self::sqlExec($sql);


    // Authorize user as a part of the group
    $sql = "INSERT INTO phpbb_user_group (group_id, user_id, user_pending) "
    	."VALUES('$group_id', '$user_id', '0')";
    self::sqlExec($sql);

    // Update relevant config values
    $sql = "UPDATE phpbb_config SET config_value="
    	."(SELECT count( user_id ) FROM phpbb_users WHERE user_type <>2) WHERE config_name='num_users'";
    self::sqlExec($sql);

    $sql = "UPDATE phpbb_config SET config_value='$user_id' WHERE config_name='newest_user_id'";
    self::sqlExec($sql);

    $sql = "UPDATE phpbb_config SET config_value='$username' WHERE config_name='newest_username'";
    self::sqlExec($sql);

	}

	public static function changePassword($user_id, $new_password) {
		return;
		/*
		#Echoer::e("changePassword($user_id, $new_password)");
		require_once dirname(__FILE__).'/../../web/forums/externals/fakeInsidePhpBB.php';
		#Echoer::e("OK");
		self::updateUserFields($user_id, array(
			'password' => mysql_escape_string(phpbb_hash($new_password)),
			'pass_convert' => 0, # AW: using old password hashing
			'passchg' => time(),
			));*/
	}

	public static function setUserLanguage($user_id, $culture) {
  	$arColnectToPhpbb = array(
  		'zh' => 'zh_cmn_hans',
  		'br' => 'pt_br',
  		);
  	if (isset($arColnectToPhpbb[$culture])) $culture = $arColnectToPhpbb[$culture]; 
		$sql = "UPDATE phpbb_users SET user_lang='$culture' WHERE user_id='$user_id' LIMIT 1";
		self::sqlExec($sql);
	}


}



Colnect Collectors Club Community
http://colnect.com

http://i.colnect.net/images/colnect_logo_255.png
Re: phpBB Connector ? [message #98290 is a reply to message #58773 ] Thu, 29 April 2010 22:07 Go to previous messageGo to next message
comb  is currently offline comb
Messages: 25
Registered: March 2010
Junior Member
Hi

first: great thread! Thank you so much!

skywalker wrote on Fri, 15 August 2008 13:52



When a user log in to the symfony application we also log in to the phpbb system (by adding records to the phpbb_sessions and phpbb_sessions_keys tables and by setting the cookies phpbb use). So the user can move between the symfony part and the phpbb part of our application.


Has anyone figured out how to do this the otherway round?
A user loggs in using the normal login-form of phpbb3 and he's automatically logged in into the symfony app, too.


Basically it's a symfony function that check's the phpbb3 cookies/sessions_table for a logged in user and in case authenticates the user for the symfony application.

But what and how do I check the phpBB3-session within the PhpbbIntegration-Class posted above?

[Updated on: Thu, 29 April 2010 22:09]

Re: phpBB Connector ? [message #98295 is a reply to message #29883 ] Fri, 30 April 2010 01:47 Go to previous messageGo to next message
comb  is currently offline comb
Messages: 25
Registered: March 2010
Junior Member
after some hours of implementing and testing ... this works great for me and maybe someone will need it:

PhpbbUser is just a class providing some operations and constants.

<?php
/**
 * Integration with phpBB v3 forums
 * (c)Amir Wald 2008 - http://colnect.com
 * (c) modified by Robert Heim 2010
 *
 * see: http://forum.symfony-project.org/index.php/m/29883/
 */
class PhpbbIntegration
{
	//... see post above ...

	/**
	 * Checks if the user is logged in to the Phpbb3
	 *
	 * @param integer $user_id
	 * @return boolean - true if the user is logged in to Phpbb3, false otherwise
	 * @author (c) Robert Heim 2010 - http://blog.robert-heim.de
	 */
	public static function isUserLoggedIn($user_id) {
		return (self::checkCookieSession() > 0) && self::checkDbSession($user_id);
	}

	/**
	 * Check user's session(s) from phpBB's database
	 *
	 * @param integer $user_id
	 * @return boolean - true if the user is logged in to Phpbb3, false otherwise
	 * @author (c) Robert Heim 2010 - http://blog.robert-heim.de
	 */
	public static function checkDbSession($user_id) {
		if (!is_int($user_id) || $user_id < 1 || $user_id === PhpbbUser::ANONYMOUS) {
			return false;
		}

		$sql = "SELECT * FROM `".PhpbbUser::DB_PREFIX."_sessions_keys` WHERE `user_id`='$user_id'";
		$result = self::sqlExec($sql);
		if (mysql_num_rows($result) <= 0) {
			#no session_key found
			return false;
		}
		#$session_key_ar = mysql_fetch_array($result);


		$sql = "SELECT * FROM `".PhpbbUser::DB_PREFIX."_sessions` WHERE `session_user_id`='$user_id'";
		$result = self::sqlExec($sql);
		if (mysql_num_rows($result) <= 0) {
			#no session found
			return false;
		}
		#$session_ar = mysql_fetch_array($result);

		return true;
	}

	/**
	 * Check user's session(s) from phpBB's cookies
	 *
	 * @return integer - user_id if the user is logged in to Phpbb3, 0 otherwise
	 * @author (c) Robert Heim 2010 - http://blog.robert-heim.de
	 */
	public static function checkCookieSession() {
		$cookies = self::readCookies(self::getConfigVal('cookie_name'));
		if ($cookies['sessionKey'] == null || $cookies['user_id'] == null || $cookies['sessionId'] == null )
		{
			#something is missing
			return 0;
		}

		return (int)$cookies['user_id'];
	}

	/**
	 * reads client cookies of the phpBB3
	 *
	 * @param string $phpbbCookieName
	 * @return array - $phpbbCookieName
	 * @author (c) Robert Heim 2010 - http://blog.robert-heim.de
	 */
	private static function readCookies($phpbbCookieName)
	{
		$sessionKey = sfContext::getInstance()->getRequest()->getCookie($phpbbCookieName.'_k');
		$user_id = sfContext::getInstance()->getRequest()->getCookie($phpbbCookieName.'_u');
		$sessionId = sfContext::getInstance()->getRequest()->getCookie($phpbbCookieName.'_sid');
		$cookies = array('sessionKey' => $sessionKey,
						'user_id' => $user_id,
						'sessionId' => $sessionId,
		);
		return $cookies;
	}

}
Re: phpBB Connector ? [message #98297 is a reply to message #29883 ] Fri, 30 April 2010 02:29 Go to previous messageGo to next message
comb  is currently offline comb
Messages: 25
Registered: March 2010
Junior Member
One issue left..

if the user does not login with the "Log me on automatically" checked, the sessions-data is not stored in the cookie and we need to get it from the phpbb3 session... but I cannot figure out how... any ideas?
that's the relevant part of the phpbb3-sessions-management, but if I copy the request_var('sid', '')-function and try to receive the sid that way I always end up with an empty SID. Sad

function session_begin($update_session_page = true)
{
	global $phpEx, $SID, $_SID, $_EXTRA_URL, $db, $config, $phpbb_root_path;
//...
		if (isset($_COOKIE[$config['cookie_name'] . '_sid']) || isset($_COOKIE[$config['cookie_name'] . '_u']))
		{
			//...
		}
		else
		{
			$this->session_id = $_SID = request_var('sid', '');
			$SID = '?sid=' . $this->session_id;
		}
		//...
}
Re: phpBB Connector ? [message #98360 is a reply to message #29883 ] Sat, 01 May 2010 19:27 Go to previous messageGo to next message
comb  is currently offline comb
Messages: 25
Registered: March 2010
Junior Member
Solved Smile We did need to differentiate between session and session-keys etc....

TODO: If there is no valid session, their could be created a new one. And on each interaction with the website you could update the existing session. But this is not a MUST for me. If you need it, I marked the parts in the code with TODO.

In the hope to save someones time.. here is my final heavily modified version of the posts above to fit my needs for PhpBB-Session-Integration:

<?php
/**
 * Integration with phpBB v3 forums
 * (c)Amir Wald 2008 - http://colnect.com
 * (c) modified by Robert Heim 2010 - http://blog.robert-heim.de
 *
 * see: http://forum.symfony-project.org/index.php/m/29883/
 */
class PhpbbIntegration
{
	// adjust these constants to your needs..
	const FORUM_URL = 'http://localhost:8046/';
	const FORUM_PATH = '/../../../../forum/';
	const DB_SERVER = 'localhost';
	const DB_USER = 'root';
	const DB_PASSWORD = '';
	const DB_DATABASE = 'phpbb3';
	const DB_PREFIX = 'phpbb';
	const ANONYMOUS = 1;

	private static $link = null;
	private static $cookies = null;

	/**
	 * Gets the link to phpBB database
	 *
	 * @return resource - a MySQL link identifier on success, throws Exception on error
	 * @author (c) Robert Heim 2010 - http://blog.robert-heim.de
	 */
	public static function getDbConnection()
	{
		if (!is_null(self::$link))
		{
			return self::$link;
		}

		self::$link = @mysql_connect(self::DB_SERVER, self::DB_USER, self::DB_PASSWORD);
		if (self::$link && @mysql_select_db(self::DB_DATABASE, self::$link))
		{
			return self::$link;
		}

		throw new Exception("getDbConnection failed. MESSAGE [[file:".__FILE__.' line:'.__LINE__.": ".mysql_error()."]]");
		return self::$link;
	}

	/**
	 * Execute SQL query on phpBB database
	 *
	 * @param string $sql
	 * @return resource
	 */
	public static function sqlExec($sql)
	{
		if (!($result = @mysql_query($sql, self::getDbConnection()))) {
			throw new Exception("SqlExec failed. QUERY [[$sql]] MESSAGE [[".mysql_error()."]]");
		}
		return $result;
	}

	/**
	 * Checks if the user is logged in to the Phpbb
	 *
	 * @param integer $user_id
	 * @return boolean - true if the user is logged in to Phpbb, false otherwise
	 * @author (c) Robert Heim 2010 - http://blog.robert-heim.de
	 */
	public static function isUserLoggedIn($user_id)
	{
		return (self::checkSession() > 0);
	}

	/**
	 * Validates a users session from phpBB cookies against the db.
	 *
	 * @return integer - user_id if the user is logged in to Phpbb, 0 otherwise
	 * @author (c) Robert Heim 2010 - http://blog.robert-heim.de
	 */
	public static function checkSession()
	{
		$cookies = self::readCookies(self::getConfigVal('cookie_name'));

		if ($cookies['user_id'] != null && $cookies['sessionId'] != null )
		{
			// check session
			$user_id = self::checkDbSession((int)$cookies['user_id'], $cookies['sessionId']);
			if ($user_id > 0)
			{
				// user is logged in and has a valid session
				return $user_id;
			}
		}

		// no valid session yet.

		// check session-key ("remember me"-feature)
		if ($cookies['sessionKey'] == null)
		{
			// key is missing
			return 0;
		}

		// get/create and update session within checkDbSessionKey
		$user_id = self::checkDbSessionKey($cookies['sessionKey']);
		if ($user_id <= 0)
		{
			// the session key was not found in the db
			return 0;
		}

		$sessionId = self::getSessionId($cookies['user_id']);
		if ($sessionId == '')
		{
			// there was no valid session and a new one was not created during the getSessionId(...)
			// so we don't have a session and the user is not logged in.
			return 0;
		}

		return $user_id;
	}


	/**
	 * Get a configuration value from phpBB's database
	 *
	 * @param string $name - value name
	 * @return string - the value
	 */
	private static function getConfigVal($name)
	{
		$sql = "SELECT `config_value` FROM `".self::DB_PREFIX."_config` WHERE `config_name` LIKE '$name'";
		$result = self::sqlExec($sql);
		$ar = mysql_fetch_array($result);
		return $ar['config_value'];
	}

	/**
	 * Gets the session_id for a user_id from the sessions-table of te phpbb3.
	 * TODO: If there is none a new session is created. Existing sessions will be updated.
	 *
	 * @param integer $user_id
	 * @return string - session_id if the user is logged in to Phpbb, '' otherwise
	 * @author (c) Robert Heim 2010 - http://blog.robert-heim.de
	 */
	private static function getSessionId($user_id)
	{
		if (!is_int($user_id) || $user_id < 1 || $user_id === self::ANONYMOUS) {
			return '';
		}
		$user_id = mysql_real_escape_string($user_id, self::getDbConnection());

		$sql = "SELECT * FROM `".self::DB_PREFIX."_sessions` WHERE `session_user_id`=$user_id";
		$result = self::sqlExec($sql);

		if (mysql_num_rows($result) <= 0) 
		{
			// no session found
			// TODO insert a new phpbb session  - see phpbb3/includes/session.php for how this should be done
			// TODO set $session_ar;
			return '';
		}
		else
		{
			$session_ar = mysql_fetch_array($result);
			// TODO update current phpbb session - see phpbb3/includes/session.php for how this should be done
			return $session_ar['session_id'];
		}
		return '';
	}

	/**
	 * Check user's session(s) from phpBB's database
	 *
	 * @param integer $user_id
	 * @param integer $sid session_id
	 * @return integer - user_id if the user is logged in to Phpbb, 0 otherwise
	 * @author (c) Robert Heim 2010 - http://blog.robert-heim.de
	 */
	private static function checkDbSession($user_id, $sid)
	{
		if (!is_int($user_id) || $user_id < 1 || $user_id === self::ANONYMOUS) {
			return 0;
		}
		$user_id = mysql_real_escape_string($user_id, self::getDbConnection());
		$sid = mysql_real_escape_string($sid, self::getDbConnection());

		$sql = "SELECT * FROM `".self::DB_PREFIX."_sessions` WHERE `session_user_id`=$user_id AND `session_id` = '".$sid."'";
		$result = self::sqlExec($sql);
		if (mysql_num_rows($result) <= 0) 
		{
			// no session found
			return 0;
		}
		#$session_ar = mysql_fetch_array($result);

		return $user_id;
	}

	/**
	 * Validates a users session_key with the phpBB's database
	 *
	 * @param string $sessoin_key
	 * @return integer - user_id if the key is in the db, 0 otherwise
	 * @author (c) Robert Heim 2010 - http://blog.robert-heim.de
	 */
	private static function checkDbSessionKey($session_key)
	{
		$session_key = mysql_real_escape_string($session_key, self::getDbConnection());

		$sql = "SELECT * FROM `".self::DB_PREFIX."_sessions_keys` WHERE `key_id`='$session_key'";
		$result = self::sqlExec($sql);
		if (mysql_num_rows($result) <= 0) 
		{
			// no session_key found
			return 0;
		}
		$session_key_ar = mysql_fetch_array($result);

		return (int)$session_ar['user_id'];
	}

	/**
	 * reads client cookies of the phpBB3
	 *
	 * @param string $phpbbCookieName
	 * @return array - $phpbbCookieName
	 * @author (c) Robert Heim 2010 - http://blog.robert-heim.de
	 */
	private static function readCookies($phpbbCookieName)
	{
		if(is_null(self::$cookies))
		{
			$sessionKey = sfContext::getInstance()->getRequest()->getCookie($phpbbCookieName.'_k');
			$user_id = sfContext::getInstance()->getRequest()->getCookie($phpbbCookieName.'_u');
			$sessionId = sfContext::getInstance()->getRequest()->getCookie($phpbbCookieName.'_sid');
			$cookies = array('sessionKey' => $sessionKey,
							'user_id' => $user_id,
							'sessionId' => $sessionId,
			);
			self::$cookies = $cookies;
		}
		return self::$cookies;
	}

}


Best greets
Re: phpBB Connector ? [message #103267 is a reply to message #98360 ] Fri, 30 July 2010 04:14 Go to previous messageGo to next message
fortx  is currently offline fortx
Messages: 28
Registered: June 2010
Location: Santo Domingo, Dominican ...
Junior Member
And how I am suppose to use this class, because i started using prestaforumconnectorplugin and now this sound better.
Re: phpBB Connector ? [message #103269 is a reply to message #103267 ] Fri, 30 July 2010 07:19 Go to previous messageGo to next message
ricardojguzman  is currently offline ricardojguzman
Messages: 26
Registered: March 2010
Junior Member
Hello

I'm working with fortx on the same project.

I think I have an idea of how to use this class.3 weeks ago I implemented phoogle on our project.


  • The PhpbbIntegration class should be in /lib/
  • In the layout.php of the app use $phpbb3= new getDbConnection()
  • After that I can access all of the methods with $phpbb3->method(). From any module


My question is the following.
How can I call those methods from the sfForkedApplyPlugin login,logout and apply for new account ?

I kmow that I can access to the info of the user with commands like this one:
$sf_user->getGuardUser()->getUsername()

But I don't know where to give the method these values.

Thanks for your help.
Re: phpBB Connector ? [message #103270 is a reply to message #103269 ] Fri, 30 July 2010 09:05 Go to previous messageGo to next message
comb  is currently offline comb
Messages: 25
Registered: March 2010
Junior Member
I guess you're talking about the latest post of the class.

Quote:

The PhpbbIntegration class should be in /lib/
yes.
Quote:


[*]In the layout.php of the app use $phpbb3= new getDbConnection()


no. It's a static method and should be:

$phpbb3 = PhpbbIntegration::getDbConnection();

Quote:

After that I can access all of the methods with $phpbb3->method(). From any module


Well all methods are static.. so you want to call them with PhpbbIntegration::method();

Quote:


How can I call those methods from the sfForkedApplyPlugin login,logout and apply for new account ?

You may want to implement those. See phpbb3/includes/session.php for how this should be done. Maybe some of the first posts may help you, too.

Quote:


I kmow that I can access to the info of the user with commands like this one:
$sf_user->getGuardUser()->getUsername()

But I don't know where to give the method these values.


I don't understand that question.. what kind of values for which method?
Re: phpBB Connector ? [message #103312 is a reply to message #103270 ] Fri, 30 July 2010 16:27 Go to previous messageGo to next message
ricardojguzman  is currently offline ricardojguzman
Messages: 26
Registered: March 2010
Junior Member
Quote:


I don't understand that question.. what kind of values for which method?


For the methods of the sfForkedDoctrineApply. When I log in or create a new account, the values are of sf_guard_user like username , userid and such.

Quote:

You may want to implement those. See phpbb3/includes/session.php for how this should be done. Maybe some of the first posts may help you, too.


That's where I'm lost :s.
Re: phpBB Connector ? [message #103313 is a reply to message #103312 ] Fri, 30 July 2010 17:09 Go to previous messageGo to next message
comb  is currently offline comb
Messages: 25
Registered: March 2010
Junior Member
We cannot help you if you are not concrete within your question... .

What's the use-case? What did you try? What fails? Error-Messages?

I would guess this use-case: You can already register on your page through the sfForkedDoctrineApply plugin and now you want to create a phpbb3-user, too, during the registration-process?
Re: phpBB Connector ? [message #103316 is a reply to message #103313 ] Fri, 30 July 2010 18:10 Go to previous messageGo to next message
ricardojguzman  is currently offline ricardojguzman
Messages: 26
Registered: March 2010
Junior Member
Hello Comb

Sorry my English is not that good.

[QUOTE]I would guess this use-case: You can already register on your page through the sfForkedDoctrineApply plugin and now you want to create a phpbb3-user, too, during the registration-process?[/QUOTE

Yeah thats what we want to do.
Re: phpBB Connector ? [message #103318 is a reply to message #103316 ] Fri, 30 July 2010 18:21 Go to previous messageGo to next message
comb  is currently offline comb
Messages: 25
Registered: March 2010
Junior Member
and what did you try? Where get you stuck?

Methods for phpbb3-integration are posted in the thread already. SignIn and logout are implemented, too. for user-creation just look in the session.php of the phpbb3. There is a method insert/create_user(...) or something like that.
Then you can adapt it to your needs and post it here if someone needs it. Wink
Re: phpBB Connector ? [message #103333 is a reply to message #103318 ] Sat, 31 July 2010 02:20 Go to previous messageGo to previous message
fortx  is currently offline fortx
Messages: 28
Registered: June 2010
Location: Santo Domingo, Dominican ...
Junior Member
there isn't an insert/create user method in session.php only methods for creating session and for user already registered. There is a function for log in but nothing tu create users.
Previous Topic:How to validate data for a restful service ?
Next Topic:Doctrin Admin Generator: Preview Before Save
Goto Forum:
  

powered by FUDforum - copyright ©2001-2004 FUD Forum Bulletin Board Software