User Tools

Site Tools


userpoints:developer

UserPoints Integrations and API

This is an introduction to UserPoints integrations with Joomla or third party extensions. It is dedicated to developers and anyone with a sufficient knowledge of the PHP language and Joomla 4/5 extension development. There is a UserPoints API which has recently been simplified.

Licence: UserPoints is released under license GNU/GPL License. Author: Bernard Gilly – Adrien Roussel - Martin Brampton. This project started as AlphaUserPoints back in 2008.

Basic Operation of UserPoints

UserPoints provides a way to award users points for specific actions on a Joomla based web site. Points can also be “spent” in order to permit other actions. The actions involved are specific to whatever applications are appropriate for the site. It is possible, but not necessary, to equate points to monetary value.

The handling of points is determined by what are called rules in UserPoints. A rule is triggered by something happening as a result of user action. The rule determines what happens in the way of awarding or deducting points. UserPoints automatically installs some plugins and rules that support actions triggered by standard Joomla extensions. These include actions to do with content (articles) and to do with user registration.

Unfortunately, for historic reasons, rules are identified by a plugin name. It is often not necessary for there to be an actual plugin corresponding to the name. The term plugin name should be understood as being the rule name.

Ways to Connect Software to UserPoints

The approach is different, depending on whether the author of the software to be connected is implementing code to help the integration. If this is the case, then any rules needed for the integration can be specified by an XML file in the root of the component involved. The software then uses the API described below to interact with UserPoints. No new plugin is needed for this kind of integration.

Alternatively, it may be possible to achieve integration without modifying the relevant software. If it provides plugin hooks, then a plugin can be written that will be triggered by events in the third party software. The plugin can use the API. The administrator UI of UserPoints provides the ability to create and modify rules to manage the integration.

Basic API

The UserPoints code has been fully namespaced and will autoload when used correctly. In addition, for Joomla 3.x, UserPoints automatically installs and enables a plugin that will establish the namespacing. This is not necessary with Joomla 4+ which takes account of the namespace in the UserPoints packaging XML.

Given the above, use of the API becomes in its simplest form:

    use BlackSheepResearch\Component\UserPoints\Site\UserPoints;
    if (class_exists(UserPoints::class) {
        UserPoints::newpoints('rule_name');
    }

rule_name is the name of the rule that will be used to attribute points to the current user (if logged in). For each UserPoints integrated rule (system rules), names syntax is as follows:

example: sysplgbup_newregistered for new users points attribution

You should select names for rules that are unlikely to conflict with other integrations.

Keep in mind that this method only gives points to the current user logged in. This is the Basic API.

Attribute points to another user than the current user

To give points to another user than the one connected, only the rule and user ID is required. To get his UserPoints (BUPID) Identity, we just need to use the getAnyUserReferreID(). This method is the one used to give points to an article author when the article is being read by someone on the site.

    use BlackSheepResearch\Component\UserPoints\Site\UserPoints;
    if (class_exists(UserPoints::class) {
        $upid = UserPoints::getAnyUserReferreID( $userID );
        if ( $bupid ) UserPoints::newpoints( 'rule_name', $upid );
    }

Avoid attributing points more than once for the same action

To avoid a user getting points many times for something already done, we can add a reference key. When calling the UserPoints::newpoints function, a precheck is done on this reference key. This method is used in the rule where a user reading an article would give points to the author.

    use BlackSheepResearch\Component\UserPoints\Site\UserPoints;
    if (class_exists(UserPoints::class) {
        $keyreference = UserPoints::buildKeyreference('rule_name', 'item id' );  
        UserPoints::newpoints( 'rule_name', '', $keyreference);
    }

Adding information data

To add information data to be displayed in the action details, just add a new parameter as follows:

    use BlackSheepResearch\Component\UserPoints\Site\UserPoints;
    if (class_exists(UserPoints::class) {
        $keyreference = UserPoints::buildKeyreference('rule_name', 'item id' );  
        UserPoints::newpoints( rule_name','', $keyreference,'information_data');
    }

Using different amounts of points on the same rule

A component might also need to add or to take points for different amounts. For example, when buying goods with points. Products have different prices, a fixed amount in the rule would not work. The API $randompoints parameter comes instead of the amount of points set in the rule. It can be negative in case of purchases or penalities.

    use BlackSheepResearch\Component\UserPoints\Site\UserPoints;
    if (class_exists(UserPoints::class) {
        $keyreference = UserPoints::buildKeyreference('rule_name', 'item id' );  
        UserPoints::newpoints( 'rule_name','', $keyreference,'',-1450);
    }

Get the result from a successful operation

In more advanced code, if the new software needs to know if the operation has been successful or not, (enough amount of points for a purchase in a user account), we can add a 'feedback' parameter. It has a Boolean type value. Code example:

    use BlackSheepResearch\Component\UserPoints\Site\UserPoints;
    if (class_exists(UserPoints::class) {
        $keyreference=UserPoints::buildKeyreference('up_purchasewithvirtuemart', $transactionID );
        if (UserPoints::newpoints( 'up_purchasewithvirtuemart', '', $keyreference, 'Product reference: AM-5245', -1290, true))
        {
            [... code for successful operation ...]
        }
    }

Remove the constraint on the type of user

In a customized code component, you can force and remove the constraint on a rule to the user level by adding the parameter _force = 1_. The existing rule will be available now for _guest, registered_ and _special_.

Display an additional system message to the user

you can display a specific message to the user by adding the parameter frontmessage=”You custom message”. API full implementation

    use BlackSheepResearch\Component\UserPoints\Site\UserPoints;
    if (class_exists(UserPoints::class) {
      UserPoints::newpoints(
        string $pluginfunction,
        [string $BUPIDotheruser = ''],
        [string $keyreference = ''],
        [string $data = ''],
        [integer $randompoints = 0],
        [boolean $feedback = false],
        [integer $force=0],
        [string $frontmessage='']
      );
    }

Note: If the operation is a points substraction, the account has to have at least the same amount of points. If not, a notice warns the user that he does not have enough points to complete the action (by default). You can set up an option in the configuration of UserPoints, as administrator to allow your users to have a negative account.

Step 2 - XML file creation

Then developers have to create an xml file to make easier the installation process in the UserPoints component. This xml file has to be utf-8 encoded (required). All developers of third party extensions for Joomla! can add directly at the root of their frontend component a unique xml file containing all the rules for a single component. Deveoper has to respect the ordering and tags: structure example: [betauserpoints_rule.xml](images/stories/documentation/betauserpoints/betauserpoints_rule.xml) Tag “component” is the name of the third component like “com_kunena” or other. As it is the same component, it is worth repeating for each rule in the tag “rule”. Administrator of the website which install a third component with this xml file can autodetect directly from the button “auto-detect plugins” in control panel of UserPoints. This xml file has to be utf-8 encoded (required) but not be zipped! Just put this file at the root of frontend component folder or plugin or module and include this file in your installer extension. This file must be named exactly as follows: betauserpoints_rule.xml

Code list for categories :

ar -> articles
cd -> coupons
co -> community
fo -> forums/comments
li -> links
mu -> music
ot -> other
ph -> photo
po -> polls
pu -> purchase
re -> recommend/send to a friend
sh -> shopping
su -> private
sy -> system rules
us -> users
vi -> video

NOTE : Optionally, you can avoid this step manually by filling all the fields in the creation of a new rule directly in the rule manager (button 'New' in toolbar).

Plugin/Rule installation

- auto-detect xml file at the root of frontend component: Click on the button “Auto-detect plugins” in the control panel of UserPoints after installation of third component, plugin or module. Check regularly or periodically by clicking on this button.

Using UserPoints information in a third party component

You can use easily the profil informations of a user directly in a third component. ⇒ Before using a function, you must include the API at least once in your page like this:

$api_UP = JPATH_SITE.'/components/com_userpoints/helper.php'; if ( file_exists($api_UP)) { require_once $api_UP; }

Profile information

To get the entire profil information, just use the function getUserInfo(); Just use the referreid of UserPoints user or the joomla ID of the user (Id of Joomla users table).

Use the first method with the referreid to get user Information profile like this :

UserPoints::getUserInfo($referrerid );

If you do not have the referreid, you can use the ID of user in second parameter like this :

$user = JFactory::getUser(); $userid = $user->id ; $profil = UserPoints::getUserInfo ( '', $user->id );

Then you can get the following user informations:

$profil->name
$profil->username
$profil->registerDate
$profil->lastvisitDate
$profil->email
$profil->referreid
$profil->points
$profil->max_points
$profil->last_update
$profil->referraluser
$profil->referrees
$profil->blocked
$profil->birthdate
$profil->avatar
$profil->levelrank
$profil->leveldate
$profil->gender
$profil->aboutme
$profil->website
$profil->phonehome
$profil->phonemobile
$profil->address
$profil->zipcode
$profil->city
$profil->country
$profil->education
$profil->graduationyear
$profil->job
$profil->facebook
$profil->twitter
$profil->icq
$profil->aim
$profil->yim
$profil->msn
$profil->skype
$profil->gtalk
$profil->xfire
$profil->profileviews

Get BUP avatar of user

Display the image of avatar from UserPoints.

$avatar = UserPoints:: getAupAvatar( $userid, [$linktoprofil=0], [ $width=48], [$height=48], [$class=''], [$otherprofileurl=''] ) echo $avatar ;

if $linktoprofil set to 1, display avatar with the link to the BUP profil of this user.

Get the url to show the profil of user.

$linktoBUPprofil = UserPoints::getAupLinkToProfil($userid);

Get the url to show the list of users with points etc…

$linktoBUPusersList = UserPoints:: getAupUsersURL();

Get avatar Path of a user

Get the path avatar path of a specific user

$avatarPath = UserPoints:: getAvatarPath( $userid );

Get avatar Live Path of a user

Get the live url avatar path of a specific user

$avatarLivePath = UserPoints:: getAvatarLivePath( $userid );

Get the medals list of a user

$medalslistuser = getUserMedals($referrerid);

or

$medalslistuser = getUserMedals('', $userid);
return $medallistuser->id
return $medallistuser->rank (name of medal)
return $medallistuser->description (reason for awarded)
return $medallistuser->icon (name file icon)
return $medallistuser->image (name file image) Complete example to display large image of medals:
    $user = JFactory::getUser();
    $userid = $user->id;
    if(!defined("_BUP_MEDALS_PATH"))
    {
        define('_BUP_MEDALS_PATH', JURI::root() . 'components/com_userpoints/assets/images/awards/large/');
    }
    if(!defined("_BUP_MEDALS_LIVE_PATH"))
    {
        define('_BUP_ MEDALS _LIVE_PATH', JURI::base(true) . '/components/com_userpoints/assets/images/awards /large/');
    }
    $medalslistuser = UserPoints::getUserMedals( '', $userid );
    for each ( $medalslistuser as $medallistuser )
    {
        echo '<img src="'. _BUP_MEDALS_LIVE_PATH'.$medallistuser->image . '" alt="" />';
    }

Get the ReferreID of any user

$referreid = UserPoints::getAnyUserReferreID( $userID );

Get the current total points of any user

Use the first method with the referreid to get the total of points

$totalPoints = UserPoints::getCurrentTotalPoints( $referrerid );

If you have not the referreid, you can use the ID of user (joomla) in second parameter like this :

$user = JFactory::getUser(); $userid = $user->id ; $totalPoints = UserPoints::getCurrentTotalPoints( '', $userid );

Get the list of activities

$listActivities = UserPoints::getListActivity($type='all', $userid='all', $numrows=0); 
$params $type = all | positive | negative
$params $userid = all or unique userID
$params $limit = int (0 by default)
example-1 -> -------------------------------------------------------------------------
example-1 -> $listActivities = UserPoints::getListActivity('all', 'all');
example-1 SAME AS -> $listActivities = UserPoints::getListActivity();
example-1 -> show all activities with pagination, positive and negative points of activity for all users
-----------------------------------------------------------------------------------
example-2 -> -------------------------------------------------------------------------
example-2 -> $user = JFactory::getUser();
example-2 -> $userID = $user->id;
example-2 -> $listActivities = UserPoints::getListActivity('positive',$userID,20);
example-2 -> show only positive points of activity for the current user logged in and show only 20 rows of recent activities

Returns an array or $rows

List of available fields :

insert_date
referreid
points (of this activity)
datareference
rule_name
plugin_function
category

Get the next user rank

$nextrankinfo = UserPoints::getNextUserRank($referrerid='', $userid='0', currentrank);
return $nextrankinfo->id
return $nextrankinfo->rank (name of rank)
return $nextrankinfo->description (description of rank)
return $nextrankinfo->levelpoints (level points to reach this rank)
return $nextrankinfo->typerank (return 0)
return $nextrankinfo->icon (name file icon)
return $nextrankinfo->image (name file image)

Get version of BUP

$num_bup_version = UserPoints::getBupVersion();

Returns the current version of UserPoints like → 4.0.0

UserPoints is open for third component

Create your own plugin for UserPoints ! Plugins provide functions which are associated with trigger events.

Available events in UserPoints:

- onBeforeInsertUserActivityUserPoints - onUpdateUserPoints
- onAfterUpdateUserPoints
- onChangeLevelUserPoints
- onUnlockMedalUserPoints
- onGetNewRankUserPoints
- onResetGeneralPointsUserPoints
- onBeforeDeleteUserActivityUserPoints
- onAfterDeleteUserActivityUserPoints
- onBeforeDeleteAllUserActivitiesUserPoints
- onAfterDeleteAllUserActivitiesUserPoints
- onBeforeMakeRaffleUserPoints
- onAfterMakeRaffleUserPoints

You can see the example file /plugins/betauserpoints/example_plugin_bup.php in your Joomla directory with parameters for each functions.

[betauserpoints](/extensions/index.php?option=com_tags&view=tag&id=4-betauserpoints)

* Created on 15 January 2016.

* Last updated on 7 February 2024.

userpoints/developer.txt · Last modified: 2024/04/02 18:39 by admin