Back to vBulletin 3 Articles

[How-To] vBulletin API Basics: Variables, Functions, Objects
by akanevsky 10 Oct 2005
Rating: (4 votes - 4.75 average)

vBulletin API Basics: Variables, Functions, Objects

This How-To should serve as a reference to coders, who have a basic knowledge of PHP and who want to make their own mods.

$vbulletin (Type: Object)

Contains vBulletin data that has been in separate variables in vB 3.0.x.
Below you can find a translation table of changed variables and functions.
This is an expanded version of the list that you can find in vBulletin's source code (functions_legacy.php).
vBulletin 3.0.3 locations are on the left hand side, and the corresponding vBulletin 3.5.0 locations are on the right hand side.
Legacy locations can be enabled by running legacy_enable(), although this is officially not recommended for long term compatibility.

Code:
* $vboptions['x']                            --> $vbulletin->options['x']
* $iforumcache                               --> $vbulletin->iforumcache
* $forumcache                                --> $vbulletin->forumcache
* $usergroupcache                            --> $vbulletin->usergroupcache
* $datastore['wol_spiders']                  --> $vbulletin->wol_spiders
* $smiliecache                               --> $vbulletin->smiliecache
* $stylechoosercache                         --> $vbulletin->stylecache
* $datastore['x']                            --> $vbulletin->x
* $bbuserinfo['x']                           --> $vbulletin->userinfo['x']
* $session['x']                              --> $vbulletin->session->vars['x']
*
* $_BITFIELD['usergroup']                    --> $vbulletin->bf_ugp
* $_BITFIELD['usergroup']['x']               --> $vbulletin->bf_ugp_x
* $_BITFIELD['usergroup']['x']['y']          --> $vbulletin->bf_ugp_x['y']
* $_BITFIELD['calmoderatorpermissions']['x'] --> $vbulletin->bf_misc_calmoderatorpermissions['x']
* $_BITFIELD['moderatorpermissions']['x']    --> $vbulletin->bf_misc_moderatorpermissions['x']
* $_BITFIELD['languageoptions']['x']         --> $vbulletin->bf_misc_languageoptions['x']
* $_USEROPTIONS['x']                         --> $vbulletin->bf_misc_useroptions['x']
* $_FORUMOPTIONS['x']                        --> $vbulletin->bf_misc_forumoptions['x']
* $_INTPERMS                                 --> $vbulletin->bf_misc_intperms
* $_INTPERMS['x']                            --> $vbulletin->bf_misc_intperms['x']
*
* ------------------------------------------------------------------------------
* Variables and Functions below are NOT affected/re-enabled by legacy_enable()
* ------------------------------------------------------------------------------
*
* $_GET/$_POST/$_REQUEST/$_COOKIE/$_FILES    --> $vbulletin->GPC['x']
* $DB_Site->x()                              --> $vbulletin->db->x()
* $url                                       --> $vbulletin->url
* $nozip                                     --> $vbulletin->nozip
* $script                                    --> $vbulletin->script
* $scriptpath                                --> $vbulletin->scriptpath
*
* HTML_SELECTED                              --> not defined anymore in vB 3.5
* HTML_CHECKED                               --> not defined anymore in vB 3.5
*
* bbcode_parse()                             --> $bbcode_parser->parse
* iif($condition, $r_true, $r_false)         --> obsolete, use ($condition ? $r_true : $r_false) instead;
Please note the following:
  1. $vbulletin
    Inside of object classes, you should access $vbulletin->[...] as $this->registry->[...]. Therefore, use that structure when modifying code inside of any classes.
    .
  2. VARIABLES ENABLED FOR TEMPLATES
    $vboptions['x'], $bbuserinfo['x'] and $session['x'] do work in the template system without running legacy_enable().
    .
  3. SUPERGLOBALS
    $_GET/$_POST/$_REQUEST/$_COOKIE/$_FILES/$_SERVER/$_ENV are available anywhere, but generally you should avoid using them. Instead, "clean" those variables and place them into $vbulletin->GPC using $vbulletin->input->clean_gpc() and $vbulletin->input->clean_array_gpc() methods.
    You can read more about these two "cleaning" methods http://www.vbulletin.com/docs/html/codestandards_gpc.

    As a summary:
    1. Use $vbulletin->input->clean_gpc() for a single variable, and $vbulletin->input->clean_array_gpc() for arrays.
    2. After variables are patched through, they can be accessed using $vbulltin->GPC (which is an array).
    3. Cleaning 'somevar' will not create variable $somevar.
    4. $vbulletin->input->clean_gpc() returns the clean value, therefore the following code will work out nicely:

      Code:
      $id = $vbulletin->input->clean_gpc('r', 'id', TYPE_UINT);

    Once you get to know the syntax of those functions, you can use the following as a reference:

    Code:
    ------------------------------------
    SOURCES AND THEIR EQUIVALENTS
    ------------------------------------
    'g'                    - $_GET
    'p'                    - $_POST
    'r'                    - $_REQUEST
    'c'                    - $_COOKIE
    's'                    - $_SERVER
    'e'                    - $_ENV
    'f'                    - $_FILES
    ------------------------------------
    VALID DATA TYPES
    ------------------------------------
    TYPE_BOOL              - Boolean
    TYPE_INT               - Integer
    TYPE_UINT              - Unsigned Integer
    TYPE_NUM               - Floating Point Number
    TYPE_UNUM              - Unsigned Floating Point Number
    TYPE_UNIXTIME          - Unix Timestamp (Unsigned Integer)
    TYPE_STR               - Trimmed String (No leading or trailing whitespace)
    TYPE_NOTRIM            - String
    TYPE_NOHTML            - Trimmed String sent through htmlspecialchars_uni()
    TYPE_ARRAY             - Array
    TYPE_FILE              - File
    TYPE_NOCLEAN           - Unvalidated
  4. GLOBALIZING VARIABLES IN FUNCTIONS
    Since most of the variables can be found within the $vbulletin class, there is generally no need to globalize more than one variable (which is $vbulletin). An exception would be the $vbphrase array, which currently cannot be found within the $vbulletin class.

    Taking the above account, the following code is not good:

    Code:
    function foo()
    {
        global $forumcache, $vbulletin, $vboptions;
        $forumcache =& $vbulletin->forumcache;
        $vboptions =& $vbulletin->options;
        foreach ($forumcache AS $forumid => $forum)
        {
            if ($vboptions['something'])
            {
                // do stuff
            }
        }
    }
    Instead, you should use the following code (which is, obviously, shorter and easier to use):

    Code:
    function foo()
    {
        global $vbulletin;
        foreach ($vbulletin->forumcache AS $forumid => $forum)
        {
            if ($vbulletin->options['something'])
            {
                // do something
            }
        }
    }
  5. DATASTORE ITEMS
    In vBulletin 3.0.x you could commonly see the following code:

    PHP Code:
    if (isset($datastore_item)) 
    Unfortunately, this does not work in vBulletin 3.5.0, since the datastore items are now contained within $vbulletin class.
    You need to use the following code instead:

    PHP Code:
    if ($vbulletin->datastore_item !== null
  6. BITFIELDS
    In case you have been wondering, "ugp" stands for "UserGroup Permissions".
    To avoid the confusing "$object->array[key1][key2][key3][key4]...[key10]" stuff, there are references set up that allow you to talk to deep elements quickly. For example, $vbulletin->bf_ugp_adminpermissions is a reference to $vbulletin->bf_ugp['adminpermissions'].
    .
  7. BBCODE PARSE
    BBCode Parser has changed slightly in vBulletin 3.5.
    To familiarize yourself with the new syntax, check out KirbyDE's How-To.
    .
  8. MISCELLANEOUS
    It is impossible to list here every aspect of vBulletin code, therefore you should familizarize yourself with the contents of init.php and class_core.php before beginning to hack into the system (and I know you are in a rush ).

$db (Type: Object)

As you might have judged from the Table 1 in this tutorial, the database object in vB3.5 is $vbulletin->db.
However, $db is another way to access that object; it is the way that used everywhere unless you call it from within a function. In functions, use $vbulletin->db.
Obviously, the purpose of the database method is to perform various operations on the database. Most common methods are described below.
  • $db->query();
    Deprecated in favor of below methods (to save memory).
    Returns: MySQL Resource
    .
  • $db->query_read();
    Performs SELECT and SHOW operations only.
    These queries will execute on the slave server, if one is defined.
    Returns: MySQL Resource
    .
  • $db->query_write();
    Performs INSERT, REPLACE, UPDATE, DROP, ALTER and other data-modifying queries.
    These queries will execute on the master server.
    Returns: MySQL Resource
    .
  • $db->query_first();
    Same as query_read(), but returns first result as an array.
    Returns: array on success / boolean false on failure
    .
  • $db->num_rows($mysql_resource_var);
    Input: A MySQL resource variable (usually output of the first three methods).
    Returns: int Amount of Resulting Rows
    .
  • $db->fetch_array($mysql_resource_var);
    Input: A MySQL resource variable (usually output of the first three methods).
    Returns: array One row from the mysql results on success / boolean false on failure

    To fetch each row consecutively, use the following code:

    Code:
    while ($var = $db->fetch_array($mysql_resource_var))
    {
    	// your code ($var contains the array);
    }
  • $db->insert_id();
    Input: None.
    Returns: int Row ID of the latest INSERT operation.
    .
  • $db->escape_string(); and $db->escape_string_like();
    Input: String.
    Returns: string A string with appropriate characters escaped.

    These two functions must be used instead of the PHP built-in addslashes() and addslashes_like().
    Using the PHP built-in functions may cause problems on non-MySQL systems.
    .
  • $db->show_errors(); and $db->hide_errors();
    Input: None.
    Returns: None.

    The first function enables sql error output (default), whereas the second function disables such output.
    Useful when you do not want the script to die on error (example: no die on product installation if a table already exists).

Data Managers

Data Managers (DMs) are an interface to various data objects used within vBulletin. They enforce necessary constraints and administrator-set options on the data to ensure that the data is valid.
You can read more about Data Managers in http://www.vbulletin.com/docs/html/data_managers.
Also, you can read specifically about the User DM in this KirbyDE's How-To, and about Thread DM here.

Authentication Storage

The authentication data is stored in the following way (thank to Kirby for this info):

$_COOKIE:
{cookiepfx}userid - plain(userid)
{cookiepfx}password - md5(md5(md5('PlaintextPassword') . salt) . 'LicenseNo').

TABLE user:
password - md5(md5('PlaintextPassword') . salt)

Note that for cookie, {cookiepfx} is your board's cookie prefix. It is configurable via admincp and is accessible via the COOKIE_PREFIX constant.

Important Functions
  • construct_page_nav($pagenumber, $perpage, $results, $address, $address2 = '');

    Returns the HTML for multi-page navigation.
    Two latest arguments are not used yet, therefore they are not documented.

    Code:
    $pagenumber	int     Total number of items found
    $perpage        string  Base address for links eg: index.php?t=99{&page=4}
    $results        string  Ending portion of address for links
  • eval(standard_error(fetch_error('error_phrase')));

    Outputs a standard error message with a phrase of your choice.
    fetch_error looks up the phrase you specify in the "Front-End Error Messages" phrase category.
    Error phrases must be prefixed with "error_".
    .
  • print_standard_redirect($redir_phrase, $doquery = true, $forceredirect = false);

    Returns eval()-able code to initiate a standard redirect
    $vbulletin->url should contain the target url for the redirect.

    Code:
    $redir_phrase	string   Name of redirect phrase
    $doquery        boolean  If true, it will fetch $redir_phrase from "Front-End Redirect Messages" phrase category. Must be prefixed with "redirect_".
                             If false, it will use the value of $redir_phrase as the phrase itself.
    $forceredirect  boolean  Should generally be set to true.
  • is_valid_email($email);

    Checks an email for validity and returns true or false.
    .
  • can_moderate($forumid = 0, $do = '', $userid = -1, $usergroupids = '');

    Checks whether a user can moderate a certain forum.

    Code:
    $forumid       int       Specific forum to check. If not set, will check whether the user is a moderator of any forum at all.
    $do            string    Specific mod action to check. If not set, will check whether the user is a moderator of the forum specified in $forumid.
    $userid        int       User ID to check. If not set, will use $vbulletin->userinfo.
    $usergroupids  string    List of group IDs, separate by commas, to which the user belongs. Should be generally left blank.
  • can_administer();

    Checks whether or not the visiting user has administrative permissions

    This function can optionally take any number of parameters, each of which
    should be a particular administrative permission you want to check. For example:
    can_administer('canadminsettings', 'canadminstyles', 'canadminlanguages')
    If any one of these permissions is met, the function will return true.
    If no parameters are specified, the function will simply check that the user is an administrator.
    .
  • convert_bits_to_array(&$bitfield, $_FIELDNAMES);

    Converts a bitfield into an array of 1 / 0 values based on the array describing the resulting fields. Returns an array.

    Code:
    &$bitfield      int      (ref) Bitfield
    $_FIELDNAMES    array     Array containing field definitions - array('canx' => 1, 'cany' => 2, 'canz' => 4) etc.
  • function convert_array_to_bits(&$arry, $_FIELDNAMES, $unset = 0);

    Takes an array and returns the bitwise value.

    Code:
    &arry           array     Array for input.
    $_FIELDNAMES    array     Array containing field definitions - array('canx' => 1, 'cany' => 2, 'canz' => 4) etc.
    $unset          int       Defines whether to unset the array data once it has been converted to bits
  • fetch_template($templatename, $escape = 0, $gethtmlcomments = true);

    Returns a single template from the templatecache or the database.

    Code:
    $templatename    string   Name of template to be fetched
    $escape          int      Escape quotes in template? 1: escape; -1: unescape; 0: do nothing
    $gethtmlcomments boolean  Wrap template in HTML comments showing the template name?
    Two most common uses are:

    Code:
    eval('$mycustomvar .= "' . fetch_template('mycustomtemplate') . '";');
    eval('print_output("' . fetch_template('mycustomtemplate') . '");');
  • vbsetcookie($name, $value = '', $permanent = true);

    Sets a cookie based on vBulletin environmental settings.

    Code:
    $name           string    Cookie name
    $value          mixed     Value to store in the cookie
    $permanent      boolean   If true, do not set an expiry date for the cookie
  • vb_number_format($number, $decimals = 0, $bytesize = false, $decimalsep = null, $thousandsep = null);

    Formats a number with user's own decimal and thousands chars and returns the formatted number.

    Code:
    $number          mixed     Number to be formatted: integer / 8MB / 16 GB / 6.0 KB / 3M / 5K / ETC
    $decimals        integer   Number of decimal places to display
    $bytesize        boolean   Special case for byte-based numbers
    $decimalsep      string    Custom decimal separator (to override user's preference) 
    $thousandsep     string    Custom thousands separator (to override user's preference)
  • vbmail($toemail, $subject, $message, $notsubscription = false, $from = '', $uheaders = '', $username = '');

    Starts the process of sending an email - either immediately or by adding it to the mail queue.

    Code:
    $toemail          string     Destination email address
    $subject          string     Email message subject
    $message	  string     Email message body
    $notsubscription  boolean    If true, do not use the mail queue and send immediately
    $from             string     Optional name/email to use in 'From' header
    $uheaders         string     Additional headers
    $username         string     Username of person sending the email
Sources Used
  • vBulletin's source code
  • http://www.vbulletin.com/docs/html/
  • Kier's message for developers, released here by Wayne Luke

    Spoiler (click to open)


    The following was written by Kier for the developers. He has agreed to release it here.

    Variables in the $vbulletin (vB_Registry) class


    Just about all the variables that used to get set up by init.php have now been migrated to the $vbulletin class.

    When migrating the old code, I don't want to see this sort of thing unless there's a specific reason for it:
    PHP Code:
    function foo()
    {
        global 
    $forumcache$vbulletin$vboptions;

        
    $forumcache =& $vbulletin->forumcache;
        
    $vboptions =& $vbulletin->options;

        foreach (
    $forumcache AS $forumid => $forum)
        {
            if (
    $vboptions['something'])
            {
                
    // do stuff
            
    }
        }

    Rather, the code should look like this:
    PHP Code:
    function foo()
    {
        global 
    $vbulletin;

        foreach (
    $vbulletin->forumcache AS $forumid => $forum)
        {
            if (
    $vbulletin->options['something'])
            {
                
    // do something
            
    }
        }

    Database

    The MySQL database class has been totally rewritten, and the object is now called $db, rather than the old $DB_site.

    You can also reference the database object via $vbulletin->db, so there is no real need to put $db into the list of globals in functions.
    PHP Code:
    function foo()
    {
        global 
    $vbulletin;

        
    $items $vbulletin->db->query_read("SELECT * FROM " TABLE_PREFIX "user");
        while (
    $item $vbulletin->db->fetch_array($items))
        {
            
    // do stuff
        
    }
        
    $vbulletin->db->free_result($items);

    Outside of function scope however, continue to use $db rather than $vbulletin->db.

    Whereas we used to have a single $DB_site->query() function to run SQL queries, there are now three public functions to execute SQL. They are:

    $db->query_read
    Use this function to execute SELECT and SHOW queries only. If the user is using MySQL replication, these queries will execute on their slave server.
    PHP Code:
    $db->query_read("SELECT * FROM customer WHERE clue > 0"); 
    $db->query_write
    Use this function to execute UPDATE, ALTER and all other data-modifying queries. query_write() will execute on the master server in a replication situation.
    PHP Code:
    $db->query_write("UPDATE customer SET description = 'Clueless' WHERE clue <= 0"); 

    addslashes() and addslashes_like() should be dropped in query strings, as it's problematic for some non-MySQL systems. Right now, the correct way to replace these functions is to use the newly defined functions in the database class, like this:
    PHP Code:
    $item $db->query_first("
        SELECT * FROM table
        WHERE foo = '" 
    $db->escape_string($foo) . "'
        AND bar LIKE('%" 
    $db->escape_string_like($bar) . "%')
    "
    ); 
    Please also note that when escaping quotes for Javascript strings, you should no longer use 'addslashes()', but rather use 'js_addslashes()'.

    Datastore

    All items from the datastore now get fed directly into the $vbulletin class.
    They become $vbulletin->itemname.

    If their title is in the $unserialize array in the datastore class, they will be automatically unserialized when they are fetched.

    Note that the code currently has a lot of code that is equivalent to
    PHP Code:
    if (isset($datastore_item)) 
    That will not work any more, as the datastore item variables are initialized with the datastore class.

    Therefore, instead of checking 'isset' you will need to check
    PHP Code:
    if ($vbulletin->datastore_item !== null
    Bitfields

    The old $_BITFIELDS, $_FORUMOPTIONS, $_USEROPTIONS etc. arrays no longer exist as individual entities. They are now part of the $vbulletin data registry object and go by different names. All the data they contained is still there, but you'll need to talk to them differently.

    If you look at the top of includes/class_core.php I have left a 'translation lookup table' so that it's easier to see where the data you are looking for has gone.

    To avoid too much $object->array[key1][key2][key3][key4] stuff, there are references set up to allow you to talk to deep elements quickly. For example, $vbulletin->bf_ugp_adminpermissions is a reference to $vbulletin->bf_ugp['adminpermissions']... it makes more sense when you start using them

    Oh... 'ugp' stands for usergroup permissions.

    vB_Input Class

    If you read includes/class_core.php, you'll notice that there's a class called vB_Input. This class deals with input into vBulletin and stuff that's related to the superglobal arrays ($_REQUEST, $_ENV, $_SERVER etc.)


    Misc


    As lots of variables have been shuffled around, you'll need to keep your eyes open for them. For example, $scriptpath is now $vbulletin->scriptpath and $nozip is now $vbulletin->nozip.

    I strongly suggest that you read and familiarize yourself with the new init.php and the contents of includes/class_core.php before diving in.

    Close
  • Scotsmist's contribution post (nice one!)

    Spoiler (click to open)


    While looking at the changes needed for vbportal, I wanted to share what I found.

    I see you have $bbuserinfo is now $vbulletin->userinfo listed, you may want to add $session is now $vbulletin->session

    $session[sessionurl] for example is now $vbulletin->session->vars[sessionurl]
    $session[sessionurl_js] is now $vbulletin->session->vars[sessionurl_js]

    another is with the datastore caches which are unserialised in init.php

    $forumcache is now $vbulletin->forumcache
    $iconcache is now $vbulletin->iconcache
    etc

    another is $url is now $vbulletin->url
    also $nozip is now $vbulletin->nozip
    plus $scipt is now $vbulletin->script
    and $scriptpath is now $vbulletin->scriptpath

    in addition to $vbulletin->input->clean_array_gpc you can also use $vbulletin->input->clean_gpc when there is only one variable. you may wish to use something like $perpage = $vbulletin->input->clean_gpc('r', 'perpage', TYPE_UINT); so you can use $perpage in a template

    the bitwise $_FORUMOPTIONS and $_USEROPTIONS have been replaced by $vbulletin->bf_ugp_forumoptions and $vbulletin->bf_ugp_useroptions

    notice that HTML_SELECTED and HTML_CHECKED are not defined now

    function iif() is marked as obsolete to ! (one of my personal favourites)

    function bbcode_parse is now $bbcode_parser->parse

    the print_standard_redirect function has changed a little and it doesn't pass the $url anymore, so you need to set $vbulletin->url first. the function also supports forceredirect, so there's no need to set $GLOBALS['forceredirect'] anymore.

    Close

>> EOD

vblts.ru supports vBulletin®, 2022-2024