How to Create a Bridge?

  • Thread starter Thread starter Deleted member 15541
  • Start date Start date
Hi Jared

I think there's a bug with the setPassword function - it's just a query which isn't valid PHP:

PHP:
public static function setPassword($iID, $sPassword) {
 
query(
UPDATE xf_user_authenticate
SET data = BINARY
CONCAT(
CONCAT(
CONCAT('a:3:{s:4:"hash";s:40:"', SHA1(CONCAT(SHA1('$sPassword'), SHA1('salt')))),
CONCAT('";s:4:"salt";s:40:"', SHA1('salt'))
),
'";s:8:"hashFunc";s:4:"sha1";}'
),
scheme_class = 'XenForo_Authentication_Core'
WHERE user_id = $iID;
);
}

Cheers
 
Hi Lucas,
I put it there for you to put into your own query function, everyone will use different ones.
I've updated it and added getRecentThreads() with RagTeks' permission.
JB
 
After much searching I stumbled on this thread : http://xenforo.com/community/threads/user-class.16846/ and copied some of the routines, and added a few bits:
PHP:
//Create and login a new user
appXenForo::createUser("jared", "jared@email.com", "testing");
//Login an existing user
appXenForo::login("jared@email.com", "testing");
//Kill all loggedin sessions
appXenForo::logout();
//Get user information
appXenForo::getCurrentUser();
appXenForo::getUserByEmail("jared@email.com");
//Change User Password
appXenForo::setPassword(12, "newPassword");
//Link to the Threads:
appXenForo::getThreadURL("Thread Name", 12);
appXenForo::getForumURL("Forum Name", 14);
//Get the latest posts: (needs minimum 2 posts in board)
appXenForo::getLatestPosts($iMax)
//Check if the username is already in use:
appXenForo::bUsernameInUse($sUsername);

Using only one hack :unsure:
In Session.php // function set(): comment out the line "throw new XenForo_Exception('The session has been saved and is now read-only.');"

Using the class:
PHP:
<?php
/*
*XenForo Support Functions
*/
class appXenForo {
 
//Singleton Storage
private static $bInitialized = false;
 
/**
* Initialise XenForo Functions
*/
function __construct(){}
 
/*
*Initialise the XenForom Controllers:
*/
public static function init() {
define('XF_ROOT', $_SERVER['DOCUMENT_ROOT'] . '/forum'); // set this!
define('TIMENOW', time());define('SESSION_BYPASS', false);
require_once(XF_ROOT . '/library/XenForo/Autoloader.php');
XenForo_Autoloader::getInstance()->setupAutoloader(XF_ROOT . '/library');
XenForo_Application::initialize(XF_ROOT . '/library', XF_ROOT);
XenForo_Application::set('page_start_time', TIMENOW);
XenForo_Application::disablePhpErrorHandler();
XenForo_Session::startPublicSession();
error_reporting(E_ALL & ~E_NOTICE);
}
 
 
/*
*Set the user password.
*/
public static function setPassword($iID, $sPassword) {
 
$sQuery = "UPDATE xf_user_authenticate SET data = BINARY
CONCAT(CONCAT(CONCAT('a:3:{s:4:\"hash\";s:40:\"',
SHA1(CONCAT(SHA1('$sPassword'), SHA1('salt')))),
CONCAT('\";s:4:\"salt\";s:40:\"', SHA1('salt'))),
'\";s:8:\"hashFunc\";s:4:\"sha1\";}'),scheme_class = 'XenForo_Authentication_Core'
WHERE user_id = $iID;";
 
query($sQuery);
}
 
 
/*
*Get an array of the latest posts:
*/
public static function getLatestPosts($iMax) {
$sQuery = "
SELECT thread.last_post_id as post_id,
thread.last_post_user_id as user_id,
thread.last_post_username as username ,
thread.discussion_state,
thread.last_post_date,
thread.title as threadtitle,
thread.thread_id as thread_id,
forum.title as node_title, forum.node_id as node_id
FROM xf_thread as thread
LEFT JOIN xf_node as forum ON (forum.node_id = thread.node_id)
ORDER BY thread.last_post_date DESC
LIMIT $iMax";
 
//Get the rows:
$aLatest = query($sQuery);
 
// Loop over each post, get the message
foreach ($aLatest as &$cPost) {
//Get the message:
$aRow = query("SELECT * FROM xf_post WHERE post_id = ? LIMIT 1", array($cPost['post_id']));
$cPost['message'] = self::stripBBCode($aRow['message']);
 
}
 
return $aLatest;
}
 
 
 
/*
*Get a filtered string URL for the thread:
*/
public static function getThreadURL($sThreadTitle, $iThreadID) {
$sThreadURL = strtolower(str_replace(" ", "-", $sThreadTitle));
$sThreadURL = preg_replace("/[^A-Za-z0-9-]/",'', $sThreadURL);
return "forum/index.php?threads/{$sThreadURL}.{$iThreadID}";
}
 
 
/*
*Get a filtered string URL for a node / forum/.
*/
public static function getNodeURL($sNodeTitle, $iNodeID) {
$sForumURL = strtolower(str_replace(" ", "-", $sNodeTitle));
$sForumURL = preg_replace("/[^A-Za-z0-9-]/",'', $sForumURL);
return "forum/index.php?forums/{$sNodeURL}.{$cPost['node_id']}/";
}
 
 
/*
*Strip out BB code from xfPosts
*/
public static function stripBBCode($sMessage) {
return strip_tags(str_replace(array('[',']'), array('<','>'), $sMessage));
}
 
 
/*
*Create a XenForo User:
*/
public static function createUser($sUsername, $sEmail, $sPassword, array $aAdditionalData = array()) {
 
//Create the username from the person's name:
$sUsername = str_replace(' ', "_", $sUsername);
 
//Set User Data
$cWriter = XenForo_DataWriter::create('XenForo_DataWriter_User');
$cWriter->set('username', $sUsername);
$cWriter->set('email', $sEmail);
$cWriter->setPassword($sPassword);
$cWriter->set('user_group_id', XenForo_Model_User::$defaultRegisteredGroupId);
$cWriter->set('user_state', 'email_confirm');
foreach ($aAdditionalData AS $data => $key) {
$cWriter->set($data, $key);
}
$cWriter->save();
$cUser = $cWriter->getMergedData();
 
//Login new user: Log the ip of the user registering
XenForo_Model_Ip::log($cUser['user_id'], 'user', $cUser['user_id'], 'register');
//Set the user back to the browser session
XenForo_Application::get('session')->changeUserId($cUser['user_id']);
XenForo_Visitor::setup($cUser['user_id']);
 
return $cUser['user_id'];
}
 
 
/*
*Get the current user:
*/
public static function getCurrentUser() {
 
XenForo_Session::startPublicSession();
$cVisitor = XenForo_Visitor::getInstance();
if($cVisitor->getUserId()){
$dbUserModel = XenForo_Model::create('XenForo_Model_User');
$cUserInfo = $dbUserModel->getFullUserById($cVisitor->getUserId());
}
return $cUserInfo;
}
 
 
 
/*
*Get the current user:
*/
public static function getUserByEmail($sEmail) {
$dbUserModel = XenForo_Model::create('XenForo_Model_User');
$cUser = $dbUserModel->getUserByEmail($sEmail, array('join' => XenForo_Model_User::FETCH_USER_PROFILE + XenForo_Model_User::FETCH_LAST_ACTIVITY));
return $cUser;
}
 
 
/*
*Set the user state: from email_confirm to valid.
*/
public static function setUserState($iXFID, $sState) {
//'valid'
//'email_confirm'
 
//query("UPDATE xf_user SET user_state = ? WHERE user_id = ? LIMIT 1", array($sState, $iXFID));
}
 
 
/*
*Login a XenForo User // Set the cookie.
*/
public static function login($sEmail, $sPassword, $bRemember = true) {
 
//Get this class; delete existing login information
error_reporting(E_ALL);
restore_error_handler();
restore_exception_handler();
 
$dbLoginModel = XenForo_Model::create('XenForo_Model_Login');
$dbUserModel = XenForo_Model::create('XenForo_Model_User');
$sError = "";
 
$iUserID = $dbUserModel->validateAuthentication($sEmail, $sPassword, $sError);
if (!$iUserID) {
$dbLoginModel->logLoginAttempt($sEmail);
return $sError;
}
 
$dbLoginModel->clearLoginAttempts($sEmail);
 
if ($bRemember) {
$dbUserModel->setUserRememberCookie($iUserID);
}
 
XenForo_Model_Ip::log($iUserID, 'user', $iUserID, 'login');
 
$dbUserModel->deleteSessionActivity(0, $_SERVER['REMOTE_ADDR']);
 
$cSession = XenForo_Application::get('session');
$cSession->changeUserId($iUserID);
XenForo_Visitor::setup($iUserID);
 
return $iUserID;
}
 
 
/*
*Set this user ID as logged in.
*/
public static function setLogin($iUserID) {
$dbUserModel = XenForo_Model::create('XenForo_Model_User');
$dbUserModel->setUserRememberCookie($iUserID);
XenForo_Model_Ip::log($iUserID, 'user', $iUserID, 'login');
$dbUserModel->deleteSessionActivity(0, $_SERVER['REMOTE_ADDR']);
$cSession = XenForo_Application::get('session');
$cSession->changeUserId($iUserID);
XenForo_Visitor::setup($iUserID);
}
 
 
/*
*Check if this user name is in use, return true for already exists.
*/
public static function bUsernameInUse($sUsername) {
$cUser = appDB::query("SELECT * FROM xf_user WHERE username = ? LIMIT 1", array($sUsername));
 
if (is_numeric($cUser['user_id'])) {
return true;
} else {
return false;
}
}
 
 
/*
*Delete the current session and log out.
*/
public static function logout() {
if (XenForo_Visitor::getInstance()->get('is_admin')) {
$adminSession = new XenForo_Session(array('admin' => true));
$adminSession->start();
if ($adminSession->get('user_id') == XenForo_Visitor::getUserId()) {
$adminSession->delete();
}
}
XenForo_Model::create('XenForo_Model_Session')->processLastActivityUpdateForLogOut(XenForo_Visitor::getUserId());
XenForo_Application::get('session')->delete();
XenForo_Helper_Cookie::deleteAllCookies(
          array('session'),
          array('user' => array('httpOnly' => false))
      );
XenForo_Visitor::setup(0);
return;
}
}
?>

I welcome suggestions to avoid the hack

[Edit] - 4/3/12 Bug fix in login routine + Moved init routines out of function, they need to be declared in global context.... Moved it back in so future people can see init() code.

[Edit] - 4/3/12 Added appXenForo::setLogin($iUserID) to bypass login routines and use your own login system (e.g. add setLogin when WordPress declares the user authenticated.)

[Edit] - 4/3/12 Lucas Bug fix getUserByEmail()

[Edit] - 6/3/12 Added Jake's User Password Reset Query

[Edit] - 7/3/12 Added Forum/Thread URL's
7/3/12 Added getLatestPosts(iMax)
7/3/12 Added bUsernameInUse()
nice idea, but you should sue more of xf api instead using own queries!

e.g
PHP:
/*
*Get a filtered string URL for the thread:
*/
public static function getThreadURL($sThreadTitle, $iThreadID) {
$sThreadURL = strtolower(str_replace(" ", "-", $sThreadTitle));
$sThreadURL = preg_replace("/[^A-Za-z0-9-]/",'', $sThreadURL);
return "forum/index.php?threads/{$sThreadURL}.{$iThreadID}";
}
 
 
/*
*Get a filtered string URL for a node / forum/.
*/
public static function getNodeURL($sNodeTitle, $iNodeID) {
$sForumURL = strtolower(str_replace(" ", "-", $sNodeTitle));
$sForumURL = preg_replace("/[^A-Za-z0-9-]/",'', $sForumURL);
return "forum/index.php?forums/{$sNodeURL}.{$cPost['node_id']}/";
}
 
public static function setPassword($iID, $sPassword) {
 
$sQuery = "UPDATE xf_user_authenticate SET data = BINARY
CONCAT(CONCAT(CONCAT('a:3:{s:4:\"hash\";s:40:\"',
SHA1(CONCAT(SHA1('$sPassword'), SHA1('salt')))),
CONCAT('\";s:4:\"salt\";s:40:\"', SHA1('salt'))),
'\";s:8:\"hashFunc\";s:4:\"sha1\";}'),scheme_class = 'XenForo_Authentication_Core'
WHERE user_id = $iID;";
 
query($sQuery);
}

also, sometimes you're using only a php function query(which isn't in your code and sometimes appDB::query
 
Hey RagTek,
Treat this as a open contribution - please I welcome your edits as a reply and we'll evolve it better!
"query()" was just a placeholder for whatever model people are using. appDB is my own model class will remove that.
 
This might be a stupid question, and maybe it has nothing to do with this class.

I managed to let people log in automatically when they log into my web-based game. But it only works for a subfolder (http://gtracer.net/forums).
Players are NOT automatically logged into the forums, using the subdomain http://forums.gtracer.net

I already have
Code:
php_value session.cookie_domain .gtracer.net
in both .htaccess files..

Any help is appreciated!


[EDIT]
Never mind, found it! If you need something like this, just add the following in your library/config.php:

Code:
$config['cookie']['domain'] = '.gtracer.net';
 
Added getMyPosts($iXFID) to get the posts by a certain user ID.
 
Added appXenForo::setAvatar() for uploaded a new avatar for the logged in user:

I couldn't add any more text to original message; will just post the future routines here:

PHP:
        /*
        * SET the Avatar for a user: use the image uploaded $_FILES['avatar']
        */
        public static function setAvatar() {
            if ($_FILES['avatar']) {
                XenForo_Session::startPublicSession();
                $cVisitor = XenForo_Visitor::getInstance();
                if($cVisitor->getUserId()){
                    $dbUserModel = XenForo_Model::create('XenForo_Model_User');
                    $cUserInfo = $dbUserModel->getFullUserById($cVisitor->getUserId());
                }
                $fAvatar = XenForo_Upload::getUploadedFile('avatar');
                $dbAvatarModel = new XenForo_Model_Avatar();
                $fAvatarData = $dbAvatarModel->uploadAvatar($fAvatar, $cVisitor['user_id'], $cVisitor->getPermissions());
            }
        }
 
#0: How to use XenForo Objects: Once initialized the below you can use XenForo objects:
PHP:
define('XF_ROOT', $_SERVER['DOCUMENT_ROOT'] . '/forum'); // set this!
define('TIMENOW', time());
define('SESSION_BYPASS', false); // if true: logged in user info and sessions are not needed
require_once(XF_ROOT . '/library/XenForo/Autoloader.php');
XenForo_Autoloader::getInstance()->setupAutoloader(XF_ROOT . '/library');
XenForo_Application::initialize(XF_ROOT . '/library', XF_ROOT);
XenForo_Application::set('page_start_time', TIMENOW);
XenForo_Application::disablePhpErrorHandler();
XenForo_Session::startPublicSession();
error_reporting(E_ALL & ~E_NOTICE); // Turn off the strict error reporting.


#1 : How to Create a User Using the DataWriter: Run the initialization above, then run the code below; (set the $data and $password arrays, it was in Register.php):
PHP:
//Set User Data
$data = array(
'username'  => "jaredNZ",
'email'      => "jared@email.com",//Must be unique
'timezone'  => "Europe/London",//Country/City
'gender'    => "male",//Gender in english
'dob_day'    => 12,
'dob_month'  => 12,
'dob_year'  => 1980,
);
 
//Set Raw Passwords
$passwords = array('password' => "testing", 'password_confirm' => "testing");
 
//Get the default options from XenForo.
$options = XenForo_Application::get('options');
 
//Create the dataWriter object, set the defaults.
$writer = XenForo_DataWriter::create('XenForo_DataWriter_User');
if ($options->registrationDefaults) {
$writer->bulkSet($options->registrationDefaults, array('ignoreInvalidFields' => true));
}
$writer->bulkSet($data);
$writer->setPassword($passwords['password'], $passwords['password_confirm']);
 
//If the email corresponds to an existing Gravatar, use it
if ($options->gravatarEnable && XenForo_Model_Avatar::gravatarExists($data['email'])) {
$writer->set('gravatar', $data['email']);
}
 
//Save the User to Database:
$writer->set('user_group_id', XenForo_Model_User::$defaultRegisteredGroupId);
$writer->set('language_id', XenForo_Visitor::getInstance()->get('language_id'));
$writer->advanceRegistrationUserState();
$writer->preSave();
$writer->save();
 
//Get the User as a Variable:
$user = $writer->getMergedData();
 
//Log the ip of the user registering
XenForo_Model_Ip::log($user['user_id'], 'user', $user['user_id'], 'register');
 
//Set the user back to the browser session
XenForo_Application::get('session')->changeUserId($user['user_id']);
XenForo_Visitor::setup($user['user_id']);
Does this code send the confirmation email?
 
No. It assumes this is a slave to a currently system. e.g. your current login system already has email confirmation, tap this "create user" function on once the email has been confirmed. Or create the user and then manually change the user state column from "email_confirm" to "valid" to manually verify email.
 
Bumping this thread so that it may be updated with my issue described there: http://xenforo.com/community/threads/issue-with-code-events-in-a-bridge.45498/

tl;dr:
The code in this topic did not preload code events listeners data, so when creating any Model, it was the actual XF base model without any custom member or modified behaviour from third-party addons.
I managed to preload listeners data by adding two lines below the #0 code block.
PHP:
$dependencies = new XenForo_Dependencies_Public();
$dependencies->preLoadData();
 
I know this is odd, but does anyone know if we can set a user_id as well using this function?

PHP:
appXenForo::createUser("jared", "jared@email.com", "testing");

I don't want to use the auto incrementing unique ID's by XF as I have a replicating system going on where I'm using records from another table (external website), its important I set-up XF accounts with same userID's as the primary database on the external website for syncing purposes.
 
I know this is odd, but does anyone know if we can set a user_id as well using this function?

PHP:
appXenForo::createUser("jared", "jared@email.com", "testing");

I don't want to use the auto incrementing unique ID's by XF as I have a replicating system going on where I'm using records from another table (external website), its important I set-up XF accounts with same userID's as the primary database on the external website for syncing purposes.

Try:

PHP:
appXenForo::createUser("jared", "jared@email.com", "testing", ['user_id' => $yourUserId]);

Though it's not a good idea. A better idea will be to add a new column to the user table (something like 'external_user_id') and set that and use it within your external script. Messing with the auto increment results usually in bad things happening.
 
Yeah that doesn't work. Just getting the usual An unexpected error occurred. Please try again later. Message as usual, I'm fairly comfortable with setting unique ID's manually as registrations only come in via our external site only.

Any other suggestions ?
 
Yeah that doesn't work. Just getting the usual An unexpected error occurred. Please try again later. Message as usual, I'm fairly comfortable with setting unique ID's manually as registrations only come in via our external site only.

Any other suggestions ?
What kind of error message is that? do some debugging. within createUser dump the $cWriter to see if it stores it. that error message is very generic and not sure where that is coming from.
 
It returns the user id, the UID is an auto increment field, you shouldn't interfere with it since other XF tables may depend on the UID they set,

$iVanillaID = appForum::createUser($cUser['id'], $cUser['name'], $cUser['email'], $sPassword);
 
Cant work it out, zzz alright well if setting the uid in the xf_user is bad ive created an user_extid field thats int(10) ive tried to

PHP:
$cWriter->set('user_extid', $sID);

and obvs added the $sID variable to parameter of createUser function but still doesnt like it, not exactly sure whats going on ive taken a dump of $cWriter but all i see is a heap of arrays that dont contains anything to do with the user part of it.

Have you got an updated class Jared?
 
Cant work it out, zzz alright well if setting the uid in the xf_user is bad ive created an user_extid field thats int(10) ive tried to

PHP:
$cWriter->set('user_extid', $sID);

and obvs added the $sID variable to parameter of createUser function but still doesnt like it, not exactly sure whats going on ive taken a dump of $cWriter but all i see is a heap of arrays that dont contains anything to do with the user part of it.

Have you got an updated class Jared?

Use:

PHP:
print_r($cWriter->getNewData());

to output the data.
 
I've been trying to use this class:
http://xenforo.com/community/threads/how-to-create-a-bridge.28515/#post-332676

I'm trying to log a user in using the following code:
$xenUser = appXenForo::login($email, $password);
appXenForo::setLogin($xenUser);

But I keep getting the following error:

Fatal error: Class 'XenForo_Model' not found in /home/ausfifac/public_html/inc/xenforo_functions.php on line 203

xenforo_functions.php is the appXenForo class with the additional setAvatar() function provided by JaredNZ.

The line causing the error:
$dbLoginModel = XenForo_Model::create('XenForo_Model_Login');

What would be causing this? I've set the forum directory properly and I have the Model.php file in the library/Xenforo directory.

Help would be greatly appreciated. Thanks!
 
1. first of all you create a file named xenforo_connect.php

<?php
class appXenForo {

//Singleton Storage
private static $bInitialized = false;

/**
* Initialise XenForo Functions
*/
function __construct() {

}

/*
* Initialise the XenForom Controllers:
*/

public static function init() {
define('XF_ROOT', $_SERVER['DOCUMENT_ROOT'] . '/testsite/forum'); // set this always to xenforo root folder!
define('TIMENOW', time());
define('SESSION_BYPASS', false);
require_once(XF_ROOT . '/library/XenForo/Autoloader.php');
XenForo_Autoloader::getInstance()->setupAutoloader(XF_ROOT . '/library');
XenForo_Application::initialize(XF_ROOT . '/library', XF_ROOT);
XenForo_Application::set('page_start_time', TIMENOW);
XenForo_Application::disablePhpErrorHandler();
XenForo_Session::startPublicSession();
error_reporting(E_ALL & ~E_NOTICE);
}

/*
* Set the user password.
*/

public static function setPassword($iID, $sPassword) {

$db = XenForo_Application::get('db');

$sQuery = "UPDATE xf_user_authenticate SET data = BINARY
CONCAT(CONCAT(CONCAT('a:3:{s:4:\"hash\";s:40:\"',
SHA1(CONCAT(SHA1('$sPassword'), SHA1('salt')))),
CONCAT('\";s:4:\"salt\";s:40:\"', SHA1('salt'))),
'\";s:8:\"hashFunc\";s:4:\"sha1\";}'),scheme_class = 'XenForo_Authentication_Core'
WHERE user_id = $iID;";

$db->fetchRow($sQuery);
}


/*
* Update email of xf_user
*/
public static function updateEmailUser($iId,$sEmail){

$db = XenForo_Application::get('db');

$sQuery = "UPDATE xf_user SET email = '$sEmail' WHERE user_id = $iId;";

$db->fetchRow($sQuery);

}


/*
* Get an array of the latest posts:
*/

public static function getLatestPosts($iMax) {
$sQuery = "SELECT thread.last_post_id as post_id,
thread.last_post_user_id as user_id,
thread.last_post_username as username ,
thread.discussion_state,
thread.last_post_date,
thread.title as threadtitle,
thread.thread_id as thread_id,
forum.title as node_title, forum.node_id as node_id
FROM xf_thread as thread
LEFT JOIN xf_node as forum ON (forum.node_id = thread.node_id)
ORDER BY thread.last_post_date DESC
LIMIT $iMax";

//Get the rows:
$aLatest = query($sQuery);

// Loop over each post, get the message
foreach ($aLatest as &$cPost) {
//Get the message:
$aRow = query("SELECT * FROM xf_post WHERE post_id = ? LIMIT 1", array($cPost['post_id']));
$cPost['message'] = self::stripBBCode($aRow['message']);
}

return $aLatest;
}

/*
* Get a filtered string URL for the thread:
*/

public static function getThreadURL($sThreadTitle, $iThreadID) {
$sThreadURL = strtolower(str_replace(" ", "-", $sThreadTitle));
$sThreadURL = preg_replace("/[^A-Za-z0-9-]/", '', $sThreadURL);
return "forum/index.php?threads/{$sThreadURL}.{$iThreadID}";
}

/*
* Get a filtered string URL for a node / forum/.
*/

public static function getNodeURL($sNodeTitle, $iNodeID) {
$sForumURL = strtolower(str_replace(" ", "-", $sNodeTitle));
$sForumURL = preg_replace("/[^A-Za-z0-9-]/", '', $sForumURL);
return "forum/index.php?forums/{$sNodeURL}.{$cPost['node_id']}/";
}

/*
* Strip out BB code from xfPosts
*/

public static function stripBBCode($sMessage) {
return strip_tags(str_replace(array('[', ']'), array('<', '>'), $sMessage));
}

/*
* Create a XenForo User:
*/

public static function createUser($sUsername, $sEmail, $sPassword, array $aAdditionalData = array()) {

//Create the username from the person's name:
$sUsername = str_replace(' ', "_", $sUsername);

//Set User Data
$cWriter = XenForo_DataWriter::create('XenForo_DataWriter_User');
$cWriter->set('username', $sUsername);
$cWriter->set('email', $sEmail);
$cWriter->setPassword($sPassword);
$cWriter->set('user_group_id', XenForo_Model_User::$defaultRegisteredGroupId);
$cWriter->set('user_state', 'valid');

//echo"<pre>";print_r($cWriter);

foreach ($aAdditionalData AS $data => $key) {
$cWriter->set($data, $key);
}
$cWriter->save();
$cUser = $cWriter->getMergedData();

//Login new user: Log the ip of the user registering
XenForo_Model_Ip::log($cUser['user_id'], 'user', $cUser['user_id'], 'register');
//Set the user back to the browser session
XenForo_Application::get('session')->changeUserId($cUser['user_id']);
XenForo_Visitor::setup($cUser['user_id']);

return $cUser['user_id'];
}

/*
* Get the current user:
*/

public static function getCurrentUser() {

XenForo_Session::startPublicSession();
$cVisitor = XenForo_Visitor::getInstance();
if ($cVisitor->getUserId()) {
$dbUserModel = XenForo_Model::create('XenForo_Model_User');
$cUserInfo = $dbUserModel->getFullUserById($cVisitor->getUserId());
}
return $cUserInfo;
}

/*
* Get the current user:
*/

public static function getUserByEmail($sEmail) {
$dbUserModel = XenForo_Model::create('XenForo_Model_User');
$cUser = $dbUserModel->getUserByEmail($sEmail, array('join' => XenForo_Model_User::FETCH_USER_PROFILE + XenForo_Model_User::FETCH_LAST_ACTIVITY));
return $cUser;
}

/*
* Set the user state: from email_confirm to valid.
*/

public static function setUserState($iXFID, $sState) {
//'valid'
//'email_confirm'
//query("UPDATE xf_user SET user_state = ? WHERE user_id = ? LIMIT 1", array($sState, $iXFID));
}

/*
* Login a XenForo User // Set the cookie.
*/

public static function login($sEmail, $sPassword, $bRemember = true) {

//Get this class; delete existing login information
error_reporting(E_ALL);
restore_error_handler();
restore_exception_handler();

$dbLoginModel = XenForo_Model::create('XenForo_Model_Login');
$dbUserModel = XenForo_Model::create('XenForo_Model_User');
$sError = "";

$iUserID = $dbUserModel->validateAuthentication($sEmail, $sPassword, $sError);
if (!$iUserID) {
$dbLoginModel->logLoginAttempt($sEmail);
return $sError;
}

$dbLoginModel->clearLoginAttempts($sEmail);

if ($bRemember) {
$dbUserModel->setUserRememberCookie($iUserID);
}

XenForo_Model_Ip::log($iUserID, 'user', $iUserID, 'login');

$dbUserModel->deleteSessionActivity(0, $_SERVER['REMOTE_ADDR']);

$cSession = XenForo_Application::get('session');
$cSession->changeUserId($iUserID);
XenForo_Visitor::setup($iUserID);

return $iUserID;
}

/*
* Set this user ID as logged in.
*/

public static function setLogin($iUserID) {
$dbUserModel = XenForo_Model::create('XenForo_Model_User');
$dbUserModel->setUserRememberCookie($iUserID);
XenForo_Model_Ip::log($iUserID, 'user', $iUserID, 'login');
$dbUserModel->deleteSessionActivity(0, $_SERVER['REMOTE_ADDR']);
$cSession = XenForo_Application::get('session');
$cSession->changeUserId($iUserID);
XenForo_Visitor::setup($iUserID);
}

/*
* Check if this user name is in use, return true for already exists.
*/

public static function bUsernameInUse($sUsername) {

$db = XenForo_Application::get('db');

$cUser = $db->fetchRow("SELECT * FROM xf_user WHERE `username` = '$sUsername' LIMIT 1");

if (is_numeric($cUser['user_id'])) {
return true;
} else {
return false;
}
}

/*
* Get all the posts belonging to this user: with this XFID, and limit X posts:
*/

public static function getMyPosts($iXFID, $iLimit = 10) {
//Get the rows:
$aMyPosts = query("SELECT * FROM xf_post WHERE user_id = ? ORDER BY post_date DESC LIMIT ?", array($iXFID, $iLimit));
//$aMyPosts = appDB::arrayify($aMyPosts); //Check is array for the foreach.
// Loop over each post, get the thread information:
foreach ($aMyPosts as &$cPost) {
//Process the BB code out:
$cPost['message'] = self::stripBBCode($cPost['message']);
//Get the Thread Title:
$cPost['thread'] = query("SELECT * FROM xf_thread WHERE thread_id = ? LIMIT 1", array($cPost['thread_id']));
//Get Forum Info:
$cPost['forum'] = query("SELECT * FROM xf_forum WHERE node_id = ? LIMIT 1", array($cPost['thread']['node_id']));
}
return $aMyPosts;
}

/*
* Delete the current session and log out.
*/

public static function logout() {
if (XenForo_Visitor::getInstance()->get('is_admin')) {
$adminSession = new XenForo_Session(array('admin' => true));
$adminSession->start();
if ($adminSession->get('user_id') == XenForo_Visitor::getUserId()) {
$adminSession->delete();
}
}
XenForo_Model::create('XenForo_Model_Session')->processLastActivityUpdateForLogOut(XenForo_Visitor::getUserId());
XenForo_Application::get('session')->delete();
XenForo_Helper_Cookie::deleteAllCookies(
array('session'), array('user' => array('httpOnly' => false))
);
XenForo_Visitor::setup(0);
return;
}

}

2. Include it in your connect.php or config file
in my case,
<?PHP
error_reporting(0);

include('xenforo_connect.php');
etc......

3. Open your login.php page,
<?PHP
ob_start();
session_start();

include_once("connect.php");
if (($_REQUEST['username']) && ($_REQUEST['password']))
{

$sid = DBGetUserAuthentication ($_REQUEST['username'], $_REQUEST['password']);

$_SESSION['ID'] = $sid;

if($_REQUEST['remember']=='true'){
setcookie("lib_kookie", $sid, time()+60*60*24*100,"/");
}else{
setcookie("lib_kookie", '', time()-60*60*24*100,"/");
}

//New Code Xenforo
appXenForo::init();
$username = $_REQUEST['username'];
$password = $_REQUEST['password'];
appXenForo::login($username,$password);//You can send cookies also as a 3rd argument which is not mandatory

//End New Code XenForo
}

?>
same as you can use all functions which are in xenforo_connect.php file like change your password,chjange your email,edit your profile etc same time in both of your site.


Enjoy yuppp :P
 
Top Bottom