PHP Class API, glpi

Author: : Tracy Lauren for Heimdall Networks April, 2012
Show file Open project: glpi-project/glpi Class Usage Examples

Public Properties

Property Type Description
$api_url

Protected Properties

Property Type Description
$apiclients_id
$app_tokens
$format
$ipnum
$iptxt
$session_write permit writing to $_SESSION

Public Methods

Method Description
__construct ( )
call ( ) first function used on api call
getHatoasClasses ( $itemtype ) : array retrieve all child class for itemtype parameter
inlineDocumentation ( $file ) Display the API Documentation in Html (parsed from markdown)
messageBadArrayError ( $return_error = true ) Send 400 error to client
messageLostError ( $return_error = true ) Send 405 error to client
messageNotfoundError ( $return_error = true ) Send 404 error to client
messageRightError ( $return_error = true ) Send 401 error to client
messageSessionError ( $return_error = true ) Session Token KO
messageSessionTokenMissing ( $return_error = true ) Session Token missing
returnError ( $message = "Bad Request", $httpcode = 400, $statuscode = "ERROR", $docmessage = true, $return_response = true ) Generic function to send a error message and an error code to client

Protected Methods

Method Description
arrayRightError ( ) Fill a sub array with a right error
changeActiveEntities ( $params = [] ) : boolean Change active entity to the entities_id one.
changeActiveProfile ( $params = [] ) : boolean set a profile to active
checkSessionToken ( ) : boolean Check that the session_token is provided and match to a valid php session
cors ( $verb = 'GET' )
createItems ( $itemtype, $params = [] ) : array Add an object to GLPI
deleteItems ( $itemtype, $params = [] ) : boolean delete one or more objects in GLPI
getActiveEntities ( ) : array return active entities of current logged user
getActiveProfile ( ) : integer return the current active profile
getFullSession ( ) : array return the current php $_SESSION
getGlpiConfig ( ) : array return the current $CFG_GLPI
getItem ( $itemtype, $id, $params = [] ) : array Return the instance fields of itemtype identified by id
getItems ( $itemtype, $params = [], &$totalcount ) : array Return a collection of rows of the desired itemtype
getMultipleItems ( $params = [] ) : array Return a collection of items queried in input ($items)
getMyEntities ( ) : array return all the possible entity of the current logged user (and for current active profile)
getMyProfiles ( ) : array Return all the profiles associated to logged user
header ( $html = false, $title = "" ) Show API header in debug, it add body and some libs (essentialy to colorise markdown) otherwise, it change only Content-Type of the page
initSession ( $params = [] ) : array Init GLPI Session
killSession ( ) : boolean Kill GLPI Session Use 'session_token' param in $this->parameters
listSearchOptions ( $itemtype, $params = [] ) : array List the searchoptions of provided itemtype. To use with searchItems function
parseDropdowns ( $fields, $params = [] ) : array transform array of fields passed in parameter : change value from integer id to string name of foreign key You can pass an array of array, this method is recursive.
parseIncomingParams ( ) needed to transform params of called api in $this->parameters attribute
retrieveSession ( ) Retrieve GLPI Session initialised by initSession function Use 'session_token' param in $this->parameters
returnResponse ( $response, $code, $additionalheaders ) generic messages
searchItems ( $itemtype, $params = [] ) : Array Expose the GLPI searchEngine
showDebug ( ) Show API Debug
updateItems ( $itemtype, $params = [] ) : array update an object to GLPI

Private Methods

Method Description
checkAppToken ( ) check if the app_toke in case of config ask to
getGlpiLastMessage ( ) : array Get last message added in $_SESSION by Session::addMessageAfterRedirect
getSearchOptionUniqID ( $itemtype, $option = [] ) : string Generate an unique id of a searchoption based on: - itemtype - linkfield - joinparams - field
getSearchOptionUniqIDJoins ( $option ) : array Generate subpart of a unique id of a search option with parsing joinparams recursively
initEndpoint ( $unlock_session = true, $endpoint = "" ) Function called by each commun function of the api.
inputObjectToArray ( mixed $input ) : array Transform all stdobject retrieved from a json_decode into arrays
logEndpointUsage ( $endpoint = "" ) Log usage of the api into glpi historical or log files (defined by api config) It stores the ip and the username of the current session.
unlockSessionIfPossible ( ) Unlock the current session (readonly) to permit concurrent call

Method Details

__construct() public method

public __construct ( )

arrayRightError() protected method

Fill a sub array with a right error
protected arrayRightError ( )

call() abstract public method

first function used on api call
abstract public call ( )

changeActiveEntities() protected method

Change active entity to the entities_id one.
protected changeActiveEntities ( $params = [] ) : boolean
$params array with theses options : - 'entities_id': (default 'all') ID of the new active entity ("all" = load all possible entities). Optionnal - 'is_recursive': (default false) Also display sub entities of the active entity. Optionnal
return boolean

changeActiveProfile() protected method

set a profile to active
protected changeActiveProfile ( $params = [] ) : boolean
$params with theses options : - profiles_id : identifier of profile to set
return boolean

checkSessionToken() protected method

Check that the session_token is provided and match to a valid php session
protected checkSessionToken ( ) : boolean
return boolean

cors() protected method

protected cors ( $verb = 'GET' )

createItems() protected method

Add an object to GLPI
protected createItems ( $itemtype, $params = [] ) : array
$itemtype string itemtype (class) of object
$params array with theses options : - 'input' : object with fields of itemtype to be inserted. You can add several items in one action by passing array of input object. Mandatory.
return array of id

deleteItems() protected method

delete one or more objects in GLPI
protected deleteItems ( $itemtype, $params = [] ) : boolean
$itemtype string itemtype (class) of object
$params array with theses options : - 'input' : Array of objects with fields of itemtype to be updated. Mandatory. You must provide in each object a key named 'id' to identify item to delete.* - 'force_purge' : boolean, if itemtype have a dustbin, you can force purge (delete finally). Optionnal. - 'history' : boolean, default true, false to disable saving of deletion in global history. Optionnal.
return boolean or array of boolean

getActiveEntities() protected method

return active entities of current logged user
protected getActiveEntities ( ) : array
return array with 3 keys : - active_entity : current set entity - active_entity_recursive : boolean, if we see sons of this entity - active_entities : array all active entities (active_entity and its sons)

getActiveProfile() protected method

return the current active profile
protected getActiveProfile ( ) : integer
return integer the profiles_id

getFullSession() protected method

return the current php $_SESSION
protected getFullSession ( ) : array
return array

getGlpiConfig() protected method

return the current $CFG_GLPI
protected getGlpiConfig ( ) : array
return array

getHatoasClasses() static public method

retrieve all child class for itemtype parameter
static public getHatoasClasses ( $itemtype ) : array
$itemtype string
return array child classes

getItem() protected method

Return the instance fields of itemtype identified by id
protected getItem ( $itemtype, $id, $params = [] ) : array
$itemtype string itemtype (class) of object
$id integer identifier of object
$params array with theses options : - 'expand_dropdowns': Show dropdown's names instead of id. default: false. Optionnal - 'get_hateoas': Show relation of current item in a links attribute. default: true. Optionnal - 'get_sha1': Get a sha1 signature instead of the full answer. default: false. Optionnal - 'with_components': Only for [Computer, NetworkEquipment, Peripheral, Phone, Printer], Optionnal. - 'with_disks': Only for Computer, retrieve the associated filesystems. Optionnal. - 'with_softwares': Only for Computer, retrieve the associated softwares installations. Optionnal. - 'with_connections': Only for Computer, retrieve the associated direct connections (like peripherals and printers) .Optionnal. - 'with_networkports':Retrieve all network connections and advanced network informations. Optionnal. - 'with_infocoms': Retrieve financial and administrative informations. Optionnal. - 'with_contracts': Retrieve associated contracts. Optionnal. - 'with_documents': Retrieve associated external documents. Optionnal. - 'with_tickets': Retrieve associated itil tickets. Optionnal. - 'with_problems': Retrieve associated itil problems. Optionnal. - 'with_changes': Retrieve associated itil changes. Optionnal. - 'with_notes': Retrieve Notes (if exists, not all itemtypes have notes). Optionnal. - 'with_logs': Retrieve historical. Optionnal.
return array fields of found object

getItems() protected method

Return a collection of rows of the desired itemtype
protected getItems ( $itemtype, $params = [], &$totalcount ) : array
$itemtype string itemtype (class) of object
$params array with theses options : - 'expand_dropdowns' (default: false): show dropdown's names instead of id. Optionnal - 'get_hateoas' (default: true): show relations of items in a links attribute. Optionnal - 'only_id' (default: false): keep only id in fields list. Optionnal - 'range' (default: 0-50): limit the list to start-end attributes - 'sort' (default: id): sort by the field. - 'order' (default: ASC): ASC(ending) or DESC(ending). - 'searchText' (default: NULL): array of filters to pass on the query (with key = field and value the search)
$totalcount integer output parameter who receive the total count of the query resulat. As this function paginate results (with a mysql LIMIT), we can have the full range. (default 0)
return array collection of fields

getMultipleItems() protected method

Call self::getItem for each line of $items
protected getMultipleItems ( $params = [] ) : array
$params array with theses options : - items: array containing lines with itemtype and items_id keys Ex: [ [itemtype => 'Ticket', id => 102], [itemtype => 'User', id => 10], [itemtype => 'User', id => 11], ] - 'expand_dropdowns': Show dropdown's names instead of id. default: false. Optionnal - 'get_hateoas': Show relation of current item in a links attribute. default: true. Optionnal - 'get_sha1': Get a sha1 signature instead of the full answer. default: false. Optionnal - 'with_components': Only for [Computer, NetworkEquipment, Peripheral, Phone, Printer], Optionnal. - 'with_disks': Only for Computer, retrieve the associated filesystems. Optionnal. - 'with_softwares': Only for Computer, retrieve the associated softwares installations. Optionnal. - 'with_connections': Only for Computer, retrieve the associated direct connections (like peripherals and printers) .Optionnal. - 'with_networkports': Retrieve all network connections and advanced network informations. Optionnal. - 'with_infocoms': Retrieve financial and administrative informations. Optionnal. - 'with_contracts': Retrieve associated contracts. Optionnal. - 'with_documents': Retrieve associated external documents. Optionnal. - 'with_tickets': Retrieve associated itil tickets. Optionnal. - 'with_problems': Retrieve associated itil problems. Optionnal. - 'with_changes': Retrieve associated itil changes. Optionnal. - 'with_notes': Retrieve Notes (if exists, not all itemtypes have notes). Optionnal. - 'with_logs': Retrieve historical. Optionnal.
return array collection of glpi object's fields

getMyEntities() protected method

return all the possible entity of the current logged user (and for current active profile)
protected getMyEntities ( ) : array
return array of entities (with id and name)

getMyProfiles() protected method

Return all the profiles associated to logged user
protected getMyProfiles ( ) : array
return array of profiles (with associated rights)

header() protected method

Show API header in debug, it add body and some libs (essentialy to colorise markdown) otherwise, it change only Content-Type of the page
protected header ( $html = false, $title = "" )
$html (default false)
$title (default '')

initSession() protected method

Init GLPI Session
protected initSession ( $params = [] ) : array
$params array with theses options : - a couple 'name' & 'password' : 2 parameters to login with user auhentication OR - an 'user_token' defined in User Configuration
return array with session_token

inlineDocumentation() public method

Display the API Documentation in Html (parsed from markdown)
public inlineDocumentation ( $file )
$file string relative path of documentation file

killSession() protected method

Kill GLPI Session Use 'session_token' param in $this->parameters
protected killSession ( ) : boolean
return boolean

listSearchOptions() protected method

List the searchoptions of provided itemtype. To use with searchItems function
protected listSearchOptions ( $itemtype, $params = [] ) : array
$itemtype string itemtype (class) of object
$params array
return array all searchoptions of specified itemtype

messageBadArrayError() public method

@param $return_error (default true)
public messageBadArrayError ( $return_error = true )

messageLostError() public method

@param $return_error (default true)
public messageLostError ( $return_error = true )

messageNotfoundError() public method

Send 404 error to client
public messageNotfoundError ( $return_error = true )
$return_error (default true)

messageRightError() public method

Send 401 error to client
public messageRightError ( $return_error = true )
$return_error (default true)

messageSessionError() public method

@param $return_error (default true)
public messageSessionError ( $return_error = true )

messageSessionTokenMissing() public method

@param $return_error (default true)
public messageSessionTokenMissing ( $return_error = true )

parseDropdowns() protected static method

transform array of fields passed in parameter : change value from integer id to string name of foreign key You can pass an array of array, this method is recursive.
protected static parseDropdowns ( $fields, $params = [] ) : array
$fields array to check and transform
return array altered $fields

parseIncomingParams() abstract protected method

needed to transform params of called api in $this->parameters attribute
abstract protected parseIncomingParams ( )

retrieveSession() protected method

Retrieve GLPI Session initialised by initSession function Use 'session_token' param in $this->parameters
protected retrieveSession ( )

returnError() public method

Generic function to send a error message and an error code to client
public returnError ( $message = "Bad Request", $httpcode = 400, $statuscode = "ERROR", $docmessage = true, $return_response = true )
$message string message to send (human readable)(default 'Bad Request')
$httpcode integer http code (see : https://en.wikipedia.org/wiki/List_of_HTTP_status_codes) (default 400)
$statuscode string API status (to represend more precisely the current error) (default ERROR)
$docmessage boolean if true, add a link to inline document in message (default true)
$return_response boolean if true, the error will be send to returnResponse function (who may exit after sending data), otherwise, we will return an array with the error (default true)

returnResponse() abstract protected method

generic messages
abstract protected returnResponse ( $response, $code, $additionalheaders )

searchItems() protected method

Expose the GLPI searchEngine
protected searchItems ( $itemtype, $params = [] ) : Array
$itemtype string itemtype (class) of object
$params array with theses options : - 'criteria': array of criterion object to filter search. Optionnal. Each criterion object must provide : - link: (optionnal for 1st element) logical operator in [AND, OR, AND NOT, AND NOT]. - field: id of searchoptions. - searchtype: type of search in [contains, equals, notequals, lessthan, morethan, under, notunder]. - value : value to search. - 'metacriteria' (optionnal): array of metacriterion object to filter search. Optionnal. A meta search is a link with another itemtype (ex: Computer with softwares). Each metacriterion object must provide : - link: logical operator in [AND, OR, AND NOT, AND NOT]. Mandatory - itemtype: second itemtype to link. - field: id of searchoptions. - searchtype: type of search in [contains, equals, notequals, lessthan, morethan, under, notunder]. - value : value to search. - 'sort' : id of searchoption to sort by (default 1). Optionnal. - 'order' : ASC - Ascending sort / DESC Descending sort (default ASC). Optionnal. - 'range' : a string with a couple of number for start and end of pagination separated by a '-'. Ex : 150-200. (default 0-50) Optionnal. - 'forcedisplay': array of columns to display (default empty = empty use display pref and search criterias). Some columns will be always presents (1-id, 2-name, 80-Entity). Optionnal. - 'rawdata': boolean for displaying raws data of Search engine of glpi (like sql request, and full searchoptions)
return Array of raw rows from Search class

showDebug() protected method

Show API Debug
protected showDebug ( )

updateItems() protected method

update an object to GLPI
protected updateItems ( $itemtype, $params = [] ) : array
$itemtype string itemtype (class) of object
$params array with theses options : - 'input' : Array of objects with fields of itemtype to be updated. Mandatory. You must provide in each object a key named 'id' to identify item to update.
return array of boolean

Property Details

$api_url static public property

static public $api_url

$apiclients_id protected property

protected $apiclients_id

$app_tokens protected property

protected $app_tokens

$format protected property

protected $format

$ipnum protected property

protected $ipnum

$iptxt protected property

protected $iptxt

$session_write protected property

permit writing to $_SESSION
protected $session_write