PHP Класс API, glpi

Автор: : Tracy Lauren for Heimdall Networks April, 2012
Показать файл Открыть проект Примеры использования класса

Открытые свойства

Свойство Тип Описание
$api_url

Защищенные свойства (Protected)

Свойство Тип Описание
$apiclients_id
$app_tokens
$format
$ipnum
$iptxt
$session_write permit writing to $_SESSION

Открытые методы

Метод Описание
__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

Защищенные методы

Метод Описание
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

Приватные методы

Метод Описание
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

Описание методов

__construct() публичный Метод

public __construct ( )

arrayRightError() защищенный Метод

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

call() абстрактный публичный Метод

first function used on api call
abstract public call ( )

changeActiveEntities() защищенный Метод

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
Результат boolean

changeActiveProfile() защищенный Метод

set a profile to active
protected changeActiveProfile ( $params = [] ) : boolean
$params with theses options : - profiles_id : identifier of profile to set
Результат boolean

checkSessionToken() защищенный Метод

Check that the session_token is provided and match to a valid php session
protected checkSessionToken ( ) : boolean
Результат boolean

cors() защищенный Метод

protected cors ( $verb = 'GET' )

createItems() защищенный Метод

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.
Результат array of id

deleteItems() защищенный Метод

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.
Результат boolean or array of boolean

getActiveEntities() защищенный Метод

return active entities of current logged user
protected getActiveEntities ( ) : array
Результат 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() защищенный Метод

return the current active profile
protected getActiveProfile ( ) : integer
Результат integer the profiles_id

getFullSession() защищенный Метод

return the current php $_SESSION
protected getFullSession ( ) : array
Результат array

getGlpiConfig() защищенный Метод

return the current $CFG_GLPI
protected getGlpiConfig ( ) : array
Результат array

getHatoasClasses() статический публичный Метод

retrieve all child class for itemtype parameter
static public getHatoasClasses ( $itemtype ) : array
$itemtype string
Результат array child classes

getItem() защищенный Метод

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.
Результат array fields of found object

getItems() защищенный Метод

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)
Результат array collection of fields

getMultipleItems() защищенный Метод

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.
Результат array collection of glpi object's fields

getMyEntities() защищенный Метод

return all the possible entity of the current logged user (and for current active profile)
protected getMyEntities ( ) : array
Результат array of entities (with id and name)

getMyProfiles() защищенный Метод

Return all the profiles associated to logged user
protected getMyProfiles ( ) : array
Результат array of profiles (with associated rights)

header() защищенный Метод

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() защищенный Метод

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
Результат array with session_token

inlineDocumentation() публичный Метод

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

killSession() защищенный Метод

Kill GLPI Session Use 'session_token' param in $this->parameters
protected killSession ( ) : boolean
Результат boolean

listSearchOptions() защищенный Метод

List the searchoptions of provided itemtype. To use with searchItems function
protected listSearchOptions ( $itemtype, $params = [] ) : array
$itemtype string itemtype (class) of object
$params array
Результат array all searchoptions of specified itemtype

messageBadArrayError() публичный Метод

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

messageLostError() публичный Метод

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

messageNotfoundError() публичный Метод

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

messageRightError() публичный Метод

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

messageSessionError() публичный Метод

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

messageSessionTokenMissing() публичный Метод

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

parseDropdowns() защищенный статический Метод

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
Результат array altered $fields

parseIncomingParams() абстрактный защищенный Метод

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

retrieveSession() защищенный Метод

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

returnError() публичный Метод

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() абстрактный защищенный Метод

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

searchItems() защищенный Метод

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)
Результат Array of raw rows from Search class

showDebug() защищенный Метод

Show API Debug
protected showDebug ( )

updateItems() защищенный Метод

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.
Результат array of boolean

Описание свойств

$api_url статическое публичное свойство

static public $api_url

$apiclients_id защищенное свойство

protected $apiclients_id

$app_tokens защищенное свойство

protected $app_tokens

$format защищенное свойство

protected $format

$ipnum защищенное свойство

protected $ipnum

$iptxt защищенное свойство

protected $iptxt

$session_write защищенное свойство

permit writing to $_SESSION
protected $session_write