vBulletin 5 API tutorial

vBulletin version used in this tutorial: 5.1.4

If vBulletin.com don’t want to place documentation about their API, I will do it here.

Little about API is here: http://www.vbulletin.com/vbcms/content.php/334-mobile-api , this is about vB4 but pretty similiar to vB5.

Theory:

vB API uses GET calls to communicate with external application, so you better take care about SSL connection.

When using API you call certain methods that are spread in classes which you can find in directory /PathToYourVbulletin/core/vb/api/. Each file contains class with the same name and some methods which you can call. I couldn’t find documentation other than inline so I ran PHPDoc on vB source. You can see it here: vBulletin 5 API

To call certain method you have to name it in request. Because all vB API classes extends API main class vB_Api and name convention is that each API class name begins with “vB_Api_” (?!). After that comes class name related to class function. Call contains part of class name and method name separated with dot “.”, eg. “user.login“.

Method parameters can be passes in GET request. Simply parameters request have to be called exactly the same as in class method.

Better understanding of how vBulletin structure looks like and how does it work will certainly help you in finding right method that you actually require [@TODO Tutorial about how vB works].

Practice:

Initalization

First of all you have to initialize API. You do it by calling address like this:

http://yoursite.com/forum/api.php?
	api_m=api.init&
	clientname=client_name&
	clientversion=1.1&
	platformname=CMSx&
	platformversion=0.9&
	uniqueid=uniqueId

Only api_m parameter is mandatory. Rest of parameters is metadata about connection that is stored in database. Because you can have more than one application using the API, you might want to control them. All actions made by API are stored in the database, so you can track and eliminate eventual bad apples.

You can find init() method in api.php file.

In response you will receive few identifiers that you should store somewhere as they are required for any further call. They are:

  • apiaccesstoken – this one you will need to send to authenticate the request
  • apiclientid – this one you will need to send to authenticate the request
  • secret – this one is needed only to generate signature

There is one more value that you will need to generate signature API key which you generate individually in admincp of your vBulletin instance.

Calling

After that you can start communicating with API. But one more thing. Each API call requires to send signature of this call, so vBulletin can verify that call wasn’t malformed. Signature is md5 shorcut of method name + method parameters + apiaccesstoken + apiclientid + secret + apikey. Here is example how code generating such signature would look like:

// Method name and its aruments
$request_params = [
	'api_m' => 'user.login', 
	'username' => 'username', 
	'password' => 'password'
]; 

// Sort them so they are in same order on client and server side
ksort($request_params); 

//Change parameters into string
$signstr = http_build_query($requestparams, '', '&'); 
// $signstr = 'api_m=user.login&password=password&username=username';

// Add rest and made md5 out of it signstr + accesstoken + clientid + secret + API key
$sig = md5($signstr . $apiaccesstoken . $apiclientid . $secret . $apikey);

Example request for User::login() method should look like this:

http://yoursite.com/forum/api.php?
	api_m=user.login&
	api_s=api_access_token&
	api_c=api_client_id&
	username=username&
	password=some_password&
	api_sig=api_signature

 Response

Response is either JSON string, vB page or JSON string with error messages.

Successful response varies for each method called. Usually it is  array of data where you have to find what interests you the most. Sometimes it is Boolean value if you just check access for example.

Debugging

Error response depends on state of forum. If it is in debug mode you might receive JSON with error message or HTML page with debug part. JSON error messages are very rare, mostly it is HTML document. Don’t know why exactly, you have to ask vB developers. Looks like JSON errors shows only when API call is sucessful and errors come form other reasons like incorrect password. When vB is in normal state, in case of error you will receive HTML document with message that request cannot be completed. So you might have troubles in debugging when you’re trying to call API on a live site. How to deal with it. You can have an if condition in your configuration file, like this:

if($_SERVER['REMOTE_ADDR'] == "127.0.0.1"){
	$config['debug'] = true;
}

You have to do it in two places to be sure that forum will be in debug state for your every call. There are two config.php files and I’m not sure if in every situation the same is used or the override each other. Again You have to ask vB developers. Here are locations of config.php files:

/PathToYourVbulletin/config.php
/PathToYourVbulletin/core/includes/config.php

With debug mode you can just var_dump() answer to see what happend.

Some examples

Here are some examples of functions that I had used.

User login

Api call: user.login

Parameters: 

  • username – user login
  • password(optional) – not really optional if you want to login, You cannot login without a password. I didn’t check what you can get with only username.
  • md5password(optional) – md5 shortcut of password, never used it
  • md5passwordutf(optional) – well its good that this is optional, because i have no idea what is it for
  • logintype – looks like any value used by this parameter is “fbauto”, and it allows to login you through Facebook. But I don’t see how you can use it in API.

Result:

JSON with user data or JSON with errors.

Fetch(Get) User Data

Api call: user.fetchCurrentUserinfo

Parameters: 

  • none

Result:

JSON Array with a lot of user data

Get Node (this could be Thread, Post or Private Message)

Api call: node.getNode

Parameters: 

  • none

Result:

JSON Array with node data, most of it covers contents of table {prefix}_node

[CakePHP] Jak renderować / używać element() w Helper.

Helper jest używany żeby wykonywać te same zadania, ten sam kod, w różnych widokach. Z czasem jak projekty robią się większe i skomplikowane, metody HtmlHelper przestają wystarczać. Powstaje potrzeba renderowania w wielu miejscach dużych fragmentów HTML. CakePHP nie wspiera bezpośrednio takiej konstrukcji, ale jest to możliwe i działa prawidłowo. Musimy dobrać się do widoku, który nie jest bezpośrednio dostępny, jakby podpowiadała to inturicja. Na szczęście można się do niego odwołać poprzez zmienną $this->_View , widok jest przekazywany w konstruktorze. Jeśli ktoś wie dlaczego nie powinno się odwoływać w ten, sposób albo co takie manipulowanie może popsuć proszę o wpis w komentarzu. W każdym razie developer frameworka ADmad tak twierdzi tutaj: http://stackoverflow.com/questions/12935517/using-this-element-inside-a-customhelper

Kod renderowania element() w Helper CakePHP:

<?php
App::uses('AppHelper', 'View/Helper');

class SliderRendererHelper extends AppHelper {

    public function __construct(View $View, $settings = array()) {
        parent::__construct($View, $settings);        
    }

    public function render_sliders_in_content(){
        return $this->_View->element('some_element');
    }

}

 

Konfiguracja języka C++ w NetBeans pod Windows.

Prędzej czy później każdy zaczyna korzystać z IDE (środowiska programowania) żeby ułatwić sobie życie i programowanie. Postaram się tutaj opisać jak poprawnie skonfigurować sobie do pracy z językiem c++ jedno z moich ulubionych IDE – NetBeans w kilku krokach.

1. Pobierz Javę

Jeżeli jeszcze nie macie, pobierzcie JAVA SE:  http://www.oracle.com/technetwork/java/javase/downloads/index.html

2. Pobierz NetBeans

Jeżeli też jeszcze nie macie możecie pobrać stąd: https://netbeans.org/downloads/index.html . Tutaj wystarczy wersja C/C++ , choć NetBeans jest na tyle wszechstronne,  że można w nim robić wiele innych rzeczy.

3. Stwórz nowy projekt

Po ogarnięciu instalacji uruchamiamy NetBeans i z menu File , wybieramy opcję New Project… . W wyświetlonym oknie z lewej kolumny wybieramy C/C++, a z prawej C/C++ Application klikamy next. NetBeans sam aktywuje sobie moduł C/C++ , a następnie poinformuje nas o braku potrzebnych kompilatorów i odeśle do stronki z instrukcjami: http://netbeans.org/kb/trails/cnd.html . Ale my pominiemy tutaj większość tego co jest na tej stronce i przejdziemy do podstawowej konfiguracji IDE, jaka potrzebna jest na początku przygody z C++.

4. Zainstaluj kompilator C++

Najlepszym dostępną opcją na początek jest minimalny system Unixowy MinGW, można go pobrać stąd: http://sourceforge.net/projects/mingw/ . Jakby ktoś miał wątpliwości które pakiety zainstalować to niech zainstaluje wszystkie, najważniejsze są kompilatory gcc oraz g++.

5. Ustaw zmienne środowiskowe

Wejdź do ustawień systemowych Windows (najłatwiej zrobić to wciskając klawisze Win + Pause ), następnie do Advanced System Settings , na dole jest przycisk Enviornament Variables. W tym oknie znajduje się konfiguracja zmiennych środowiskowych systemu Windows, nas interesuje zmienna PATH w dolnym obszarze.  Tam wybieramy Edit… i na końcu tej długiej listy dopisujemy średnik (;) i ścieżkę do katalogu bin miejsca instalacji MinGW (np. ;C:\MinGW\bin). Na koniec wszystko zatwierdzamy. Tak samo dodaj ścieżkę do katalogu msys (np. ;C:\MinGW\msys).

EDIT: Nie wiedzieć czemu w Windows 8 nie wystarcza dodanie katalogu msys. Musiałem dodać bezpośrednią ścieżkę do katalogu z programami minimalnego systemu (np. ;C:\MinGW\msys\1.0\bin). Znajdują się tam m. in. programy make.exe ; mkdir.exe ;

6. Skonfiguruj NetBeans

Jeśli wszystko z poprzednich kroków zostało ustawione prawidłowo to NetBeans powinien skonfigurować się sam. Magia 🙂 Jeśli NetBeans się nie udało poniżej jest screen z przykładową działającą konfiguracją.

przykladowa_konfiguracja_cpp_netbeans

Fat-Free framework na WAMP server. Błąd, pusta strona, framework nie działa po rozpakowaniu. Co za badziew!

Posługując się WAMP serwerem postanowiłem wypróbować mikro-freamework Fat-Free. Głównie ze względu na to, że chciałem napisać prostą i małą aplikajcę, a Cake czy Symphony to kobyły. Poza tym F3 oferuje routing, templatki, mini-ORM i ogólnie takie jakby MVC. Wiadomo, narzędzie musi być dostosowane do zadania, proste zadanie – proste narzędzia.

Ściągnąłem, rozpakowałem do katalogu, odpaliłem i nie działa. Wyświetla mi się pusta strona. Zaglądam do katalogu, do index.php i prubuję debugować. I do odpalenia metody

F3::run();

wszystko śmiga, później nic sie nie wyświetla, pusta strona. Próbuję ustawić wewnętrzny debugger frameworka:

F3::set('DEBUG',3);

Nadal nic się nie wyświetla, pusta strona. Przeglądam dalej plik index.php i znajduję to co powinno sie wyświetlić:

echo Template::serve('welcome.htm');

Pomyślałem, że może plik welcome.htm jest pusty, więc zaglądam do niego i widzę pełną soczystej treści stronę, która powinna być wyświetlona. Dalej to samo nic się nie wyświetla, pusta strona, a ja nie wiem o co chodzi.

Zaglądam w źródło strony może tam mnie olśni, niestety nic, źródło strony to samo, pusta strona. Porzucam F3 na rzecz Flight (http://flightphp.com/), jest jeszcze bardziej micro i niestety nie ma żadnego wsparcia dla Baz Danych, trzeba to sobie dopisać.

Po jakimś czase potrzebuję napisać aplikację intensywnie wykorzystująca bazę danych i przydałby mi się ten mini-ORM. Przyglądam się więc jeszcze raz F3. tym razem bardzo dokładnie. I przeglądając całe źródło strony linijka po linijce rozwinąłem to co pominiąłem wcześniej. Zwiniętą linię kodu w której pobierany jest plik CSS.

<style type="text/css">
	{{ Web::minify('ui/',array('style.css'),FALSE) }}
</style>

i tu znajduje się wydruk z debuggera i poszukiwany od stuleci błąd:

<style type="text/css">
<html>
 <head>
  <title>500 Internal Server Error</title>
 </head>
 <body>
  <h1>Internal Server Error</h1>
  <p><i>PHP extension sockets is not enabled</i></p>
  <p>#0 ***/fat3/lib/base.php:1749 F3::error(500,'PHP extension sockets is not enabled')<br />

a jego rozwiązanie mega-banalne. Wystarczy włączyć w PHP moduł:

php_sockets

I jest pięknie. Wszystko się wyświetla, nie ma pustej strony, a ja mogę korzystać z mini-ORM 🙂