Using xenforo permission outside of xenforo?

Turned out to be pretty easy to re-purpose what Jeremy did and use it for CakePHP instead. Like Jeremy's code I used two files a config file though rather than adding to the library I did the other file as a component.

In the config file I used the WWW_ROOT constant for the file directory so that I didn't need to update the path between my development and live environments:

PHP:
$config['xf']['fileDir'] = WWW_ROOT.'/community';

The only main thing I had to change in the component file (other than normal cakephp component things) was to do with Xen's error management. It started throwing up quite a few Strict errors over cake's code (as far as I could tell) so I put the following three lines just after the initialize function call (in the authenticateSession function):

PHP:
//restore cake's error handling
restore_error_handler();
restore_exception_handler();
error_reporting(E_ALL & ~E_DEPRECATED);

Whether you'll need to do that yourself or not I'm not sure.

And then in my app controller I just told it to use the component I'd defined and I was ready to go. I'm still not really convinced on using Xen's own auto loaders but I'll see how it goes performance wise. Makes things easier from a programming point of view but using two frameworks must cause extra processing.
 
I'm not sure if this would be better as a separate thread (due to going on about sessions) but we'll see. I've made some progress since my last post. It's been quite a bit of experimentation and a lot of failure tbh lol. As detailed in my last post I have the initialization in place but this is trying to take it further than that.

I started looking into checking whether a user was logged in or not and thought I'd cracked it by using the last_activity field on the user table. I even used Xen's own online timeout option (code below for that) rather than defining it manually.

PHP:
$cutOff = XenForo_Application::$time - XenForo_Application::get('options')->onlineStatusTimeout * 60;

I quickly found out that this field doesn't get updated whilst the user is browsing the site/forum. Has anyone come up with a way to access the correct info (session details) from Xenforo?

Ideally I want to be able to login from the site, have the user's last activity update whilst their on the site and also be able to see what their last activity is (whether that be on the forum or the site). Any help with any of those things would be greatly appreciated.

I found this thread http://xenforo.com/community/threads/setting-session-activity.8246/ but that's for an addon and isn't really applicable for me as I'm using my own framework (cakephp) with my own controllers etc not xenforo ones so that function would do nothing for me.

Plus that function seems to require an activities array(the format of which I do not know) and I couldn't just call it for a random controller (all of my existing controllers are cakephp controllers) . Would I need to create a dummy/basic xenforo controller with that function defined and then call it when I initialize the xenforo application? Would that even work? And if so how would I then access that information for my member list?

Or would I be better off trying to load the data myself from the database? Seeing as I'm already suffering the overhead of using Xenforo's Framework on-top of my own I thought I should at least use Xenforo to do some of the messy stuff rather than trying to replicate it all.

Side Note: Lastly for anyone looking to link to Xenforo items from the website I've managed to get it working by using the following lines of code where I initialize the application:

PHP:
$request = new Zend_Controller_Request_Http();
$request->setBasePath('/community');

Otherwise I found when using Xenforo_Link it would try to refer from the site rather than the forum. After that it should be as simple as doing the following:
PHP:
XenForo_Link::buildPublicLink('canonical:members',  $userarray);

I've currently got that code in my model i.e. setting an extra variable up with the url but I'm thinking it'll work better as a helper. But I thought I should at least share that bit of code in-case anyone else comes up against that problem.
 
This isn't intended as a bump as I'm posting some solutions to the questions I was asking yesterday.

I've not yet looked into Logging In/Registering (presumably someone will have already solved that) but I now have my application updating the session activity time and I'm also able to access that time value. I found it was stored in the xf_session_activity table so thought about doing a manual query like I had done for the user data (as it was being joined from another table - though only 1 record at a time anyway).

Instead I found the XenForo_Model_User class and some useful functions which helped me solve the problems I was having. First of all I added the below bit of code to where I instantiated the Xenforo Application. The $request variable carries on from my last post (though I guess you could just replace that with a call to the respective $_SERVER variable). For the time being I'm just setting the Controller and Action to the main index as I'm not sure what else I should be setting that to when my Application isn't part of Xenforo.

PHP:
XenForo_Model::create('XenForo_Model_User')->updateSessionActivity(
                $userid, $request->getClientIp(false),
                "XenForo_ControllerPublic_Index", "Index", "valid", $request->getUserParams()
);

That updates the time in the xf_session_activity table. This should keep the user appearing as online whilst they're browsing the site. I haven't found out how to update the text where it says what the user is currently doing (outside of an addon).

After that you need to be able to access that the correct last activity property. You can do this fairly easily by again using the XenForo_Model_User class but this time using the getUserById function. This will load the userinfo into an array for you.

The join property tells the function which user tables it should join to. In this case 17 is telling it to get the profile info (1) as well as the session activity (16) info (on-top of the main user fields). I've also re-included the Xenforo_Link line from my last post so you can see that I'm populating it from the array that the other function generates.

PHP:
$userinfo = XenForo_Model::create('XenForo_Model_User')->
                    getUserById($userid,array('join' => XenForo_Model_User::FETCH_USER_PROFILE + XenForo_Model_User::FETCH_LAST_ACTIVITY));
$seourl = XenForo_Link::buildPublicLink('canonical:members',  $userinfo);

The field to look at for when the user was last active is: effective_last_activity

My own code is a little bit more advanced than the sample above sample as I already have some db results with the userids that I need the info for. Rather than call that function several times I looped through my results, appended the userid to an array and then used the getUsersByIds function which accepts an array of userids instead of a single userid but other than that works exactly the same.

As you'd expect it then returns a multidimensional array of the user info. I then had to merge that info back into my results array so that I could return it as a single results variable from my Model. A simplified example is below. Keep in mind that the order of your user array is ignored (default ordering is by username) so I had to go off the userid index instead.

PHP:
        foreach ($results as $result)
        {
            if (isset($result['CustomTable']['userid']))
                $userids[] = $result['CustomTable']['userid'];
        }
        $userarray = XenForo_Model::create('XenForo_Model_User')->
            getUsersByIds($userids,array('join' => 17));
        foreach ($results as $key => $result)
        {
            if (isset($result['CustomTable']['userid']))
            {
                $results[$key]['User'] = $userarray[$result['CustomTable']['userid']];
                $results[$key]['User']['seourl'] =
                    XenForo_Link::buildPublicLink('canonical:members',  $results[$key]['User']);
            }
        }
        return $results;

I hope that gives you a bit of an idea of how I managed to do those things. Obviously if anyone has come up with a better way of doing things please feel free to correct me lol. I'd still like to be able to update the message saying what the user is currently doing even if I can just make it say a generic Viewing the Website message (that's all I did for VB anyway) but for now I'm happy with the above lol.

Sorry for the very long post :D.
 
Trying to use the code with xf 1.0.2 and just getting an output of 0 from the below:

PHP:
<?php
..issue solved
?>

Any thoughts on why this isn't putting out my user id? The php file is in the httpdocs dir. I'm logged in on the forum

Thanks
Andy
 
I don't see anything blatantly wrong with the code but in-case it was an issue with 1.0.2 I upgraded the software on my local but what I've got is still working fine for me. Unless you've got errors hidden then the paths can't be wrong else you'd be seeing those errors. Have you tried logging out and then logging back in? Maybe the session got a bit messed up during the upgrade.
 
Ha - good job Rjs37, logged out, dumped cache and logged back in, and hey presto. Always the simple things eh?!
 
a small addition to the demo code:
without the dependency, the event listener system won't be initialised, which means that non add-on code will be loaded....
this will cause problems with add-ons (like in my example with http://xenforo.com/community/resources/inactive-user-mail-notifier.517/ or other add-ons changing the session/user/etc... depending on what your external script is doing;))

so if you have add-ons installed, you should use

PHP:
$startTime = microtime(true);
$fileDir = '/absolute/path/to/xenforo/root/directory';
 
require($fileDir . '/library/XenForo/Autoloader.php');
XenForo_Autoloader::getInstance()->setupAutoloader($fileDir . '/library');
 
XenForo_Application::initialize($fileDir . '/library', $fileDir);
XenForo_Application::set('page_start_time', $startTime);
 
$dependencies = new XenForo_Dependencies_Public();
$dependencies->preLoadData();
XenForo_Session::startPublicSession();

instead only
PHP:
$startTime = microtime(true);
$fileDir = '/absolute/path/to/xenforo/root/directory';
 
require($fileDir . '/library/XenForo/Autoloader.php');
XenForo_Autoloader::getInstance()->setupAutoloader($fileDir . '/library');
 
XenForo_Application::initialize($fileDir . '/library', $fileDir);
XenForo_Application::set('page_start_time', $startTime);
 
XenForo_Session::startPublicSession();
 
I tried following some of the samples provided here but without much luck. I suspect there's something (obvious) that I'm missing but I'm unsure as to what it is. Quite simply, I have the following in a PHP file living outside my xf installation:

PHP:
<?php
 
$startTime = microtime(true);
$xenforoRoot = '/my/path/to/xenforo';
 
require_once($xenforoRoot . '/library/XenForo/Autoloader.php');
XenForo_Autoloader::getInstance()->setupAutoloader($xenforoRoot . '/library');
 
XenForo_Application::initialize($xenforoRoot . '/library', $xenforoRoot);
XenForo_Application::set('page_start_time', $startTime);
 
$dependencies = new XenForo_Dependencies_Public();
$dependencies->preLoadData();
XenForo_Session::startPublicSession();
 
/* Simple user check */
if ($visitor->get('is_admin'))
{
    echo "Welcome!";
} else {
    echo "Go away!";
}

But the HTTP returned is:

Code:
Fatal error: Call to a member function get() on a non-object in index.php on line 33

If someone could point me in the right direction, I'd really appreciate it!
 
I tried following some of the samples provided here but without much luck. I suspect there's something (obvious) that I'm missing but I'm unsure as to what it is. Quite simply, I have the following in a PHP file living outside my xf installation:

PHP:
<?php
 
$startTime = microtime(true);
$xenforoRoot = '/my/path/to/xenforo';
 
require_once($xenforoRoot . '/library/XenForo/Autoloader.php');
XenForo_Autoloader::getInstance()->setupAutoloader($xenforoRoot . '/library');
 
XenForo_Application::initialize($xenforoRoot . '/library', $xenforoRoot);
XenForo_Application::set('page_start_time', $startTime);
 
$dependencies = new XenForo_Dependencies_Public();
$dependencies->preLoadData();
XenForo_Session::startPublicSession();
 
/* Simple user check */
if ($visitor->get('is_admin'))
{
    echo "Welcome!";
} else {
    echo "Go away!";
}

But the HTTP returned is:

Code:
Fatal error: Call to a member function get() on a non-object in index.php on line 33

If someone could point me in the right direction, I'd really appreciate it!
You're calling a function get() on a $visitor variable that hasn't been defined.
 
See? I knew it was something obvious. Trouble is, I wasn't sure how to define $visitor properly as it wasn't in the original sample code I followed. But looking in an earlier post I found this:

Code:
$visitor = XenForo_Visitor::getInstance();

which did the trick. So thanks!
 
A quick follow-up: how can I check to see if the user belongs to a particular (custom) User Group?
 
Thanks again, James!

Code:
$visitor->isMemberOf( GroupId )

is what I needed, and works perfectly.
 
Hey All,

I added this:
PHP:
$startTime = microtime(true);
$fileDir = '/absolute/path/to/xenforo/root/directory';
require($fileDir . '/library/XenForo/Autoloader.php');
XenForo_Autoloader::getInstance()->setupAutoloader($fileDir . '/library');
XenForo_Application::initialize($fileDir . '/library', $fileDir);
XenForo_Application::set('page_start_time', $startTime);
XenForo_Session::startPublicSession();

And I get the error below bacause the system is now trying to instantiate the stream wrapper twice. Is there a way to have it not do the stream warpper for this sperate service.
PHP:
An exception occurred: stream_register_wrapper(): Protocol s3:// is already defined. in /site/forum.bonusfeber.com/library/Zend/Service/Amazon/S3.php on line 940
ALSO!! maybe there is a different way! I am just trying to call the User ID of the logged in user on the custom PHP page. Do I need to do all of this stuff in this thread?

Thanks,
-Bill
 
Correct, I tried moving the settings to the index and admin php files, but then it broke all of the images and other s3 content!

NOTE** this is to help solve the issue on this thread: http://xenforo.com/community/threads/cometchat-xenforo-w-memcache-help-needed.58643/#post-624221

Cometchat is not very helpful! But i am getting close because of the information here.
 
OK.. Thought!! Is there a way to call the user_id in the page_container template? I can possible use a script that cometchat has and I may be able to get around this problem! Or maybe through it in the cookie?
 
Top Bottom