PHP code example of hampel / xenforo-api

1. Go to this page and download the library: Download hampel/xenforo-api library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

hampel / xenforo-api example snippets


use GuzzleHttp\Client as Guzzle;
use Hampel\XenForo\Api\Client;

$xf = Client::withKey('https://forum.example.com', $key, new Guzzle());

$thread = $xf->threads()->get(1234);

echo $thread->title;

use Hampel\XenForo\Api\Authentication\SuperUserKey;
use Hampel\XenForo\Api\Config;

$xf = new Client(new Config('https://forum.example.com'), new SuperUserKey($key, actingAs: 42), new Guzzle());

$info = $xf->index()->get();

$info->version();          // '2.3.12'
$info->keyType;            // 'guest', 'user' or 'super'
$info->hasScope('user:write');

new ApiKey($key);                              // a guest or user key
new SuperUserKey($key, actingAs: 42);          // acts as user 42
new SuperUserKey($key, bypassPermissions: true);
new BearerToken($accessToken);                 // OAuth2
new ClientCredentials($clientId, $clientSecret);
new Guest();                                   // no credential

foreach ($userIds as $userId) {
    $xf->actingAs($userId)->me()->update(['timezone' => 'Australia/Sydney']);
}

$xf = new Client(new Config($boardUrl), new Guest(), $http);

$token = $xf->oauth2()->exchangeCode($clientId, $code, $redirectUri, $clientSecret);

$asUser = $xf->withCredential($token->credential());   // same forum, now as the user
$asUser->me()->get();

$xf->oauth2()->exchangeCode($clientId, $code, $redirectUri, codeVerifier: $verifier);

$info = $xf->oauth2()->introspect($clientId, $clientSecret, $token);

$info->active;              // the only field guaranteed to be there
$info->hasScope('user:write');
$info->expiresAt;           // RFC 7662 calls this exp; also issuedAt, userId, issuer

$page = $xf->users()->list(2);

$page->currentPage;    // 2
$page->lastPage;       // 9
$page->total;          // 173
$page->hasMore();      // true

foreach ($page as $user) { … }

foreach ($xf->users()->each() as $user) { … }

use Hampel\XenForo\Api\Upload;

$xf->me()->uploadAvatar(Upload::fromPath('/tmp/avatar.png'));

$key = $xf->attachments()->newKey('post', ['thread_id' => 42])['key'];

$xf->attachments()->upload($key, Upload::fromPath('/tmp/screenshot.png'));

$xf->posts()->create(42, 'See attached', $key);

$download = $xf->attachments()->download($attachmentId);

$download->saveTo('/tmp/' . $attachmentId . '.bin');   // a chunk at a time
$download->contents();                                 // or the lot, as a string
$download->filename;                                   // what the forum called it
$download->contentType;                                // what it will serve it as

$xf->media()->create(['album_id' => 4, 'title' => 'Sunset'], Upload::fromPath('/tmp/sunset.jpg'));

$xf->resources()->versions($resourceId);
$xf->resourceVersions()->download($versionId, $fileId)->saveTo('/tmp/release.zip');

use Hampel\XenForo\Api\Exception\{ApiException, ClientException, NotFoundException, RequestException};

try {
    $xf->threads()->get(1234);
} catch (NotFoundException $e) {
    // no such thread - or the acting user may not see it, which is the same 404
} catch (ClientException $e) {
    // any other 4xx. Read the code, not the status:
    if ($e->hasCode('invalid_page')) { … }
} catch (RequestException $e) {
    // never reached the forum: DNS, TLS, a connect timeout. Safe to retry.
}

$xf->connection()->get('users/find-criteria', ['email' => $email])->data;

use Hampel\XenForo\Api\Endpoint\Endpoint;
use Hampel\XenForo\Api\Generated\Schema\User;

final class UserFindCriteria extends Endpoint
{
    /** @return array{user: User, urls: array<string, string>}|null */
    public function byEmail(string $email): ?array
    {
        $response = $this->apiFindResponse('users/find-criteria', ['email' => $email]);

        if ($response === null) {
            return null;                                  // 404: no such user
        }

        return [
            'user' => User::fromArray($response->array('user')),
            'urls' => $response->array('urls'),
        ];
    }
}

$xf->endpoint(UserFindCriteria::class)->byEmail('[email protected]');

$thread->thread_id;
$thread->Forum->title;      // nested entities are resolved
$thread->raw['whatever'];   // fields no specification mentions
json_encode($thread);       // the payload as it arrived - no more, no less

$mock = new \GuzzleHttp\Handler\MockHandler([
    new \GuzzleHttp\Psr7\Response(200, [], json_encode(['user' => ['user_id' => 1]])),
]);

$xf = new Client(
    new Config('https://forum.example.com'),
    new ApiKey('test'),
    new \GuzzleHttp\Client(['handler' => \GuzzleHttp\HandlerStack::create($mock)])
);