glpi-project / php-library-glpi Goto Github PK
View Code? Open in Web Editor NEWGLPI API Client Library for PHP
Home Page: https://glpi-project.github.io/php-library-glpi/
License: GNU General Public License v3.0
GLPI API Client Library for PHP
Home Page: https://glpi-project.github.io/php-library-glpi/
License: GNU General Public License v3.0
Files must be removed so the documentation follows the styles
For Code Documentation it is required to:
layout: jazzy
For Coverage it is required to:
layout: coverage
Hi, @Naylin15
Please, write an article per each method of the library (https://prose.io).
Try to use common name and information for all the libraries and report issues related to missed or different information with other libraries.
/cc @DIOHz0r
Hi, @Naylin15
settings.yml
in the folder .github
(content below in the issue)build(settings): add YAML for the bot Settings
repository:
name: composer-package-glpi
description: GLPI API Client Library for PHP
homepage: http://flyve.org/composer-package-glpi/
private: false
has_issues: true
has_wiki: false
has_downloads: true
default_branch: develop
allow_squash_merge: true
allow_merge_commit: false
allow_rebase_merge: true
labels:
- name: bug
color: f44336
- name: build
color: 795548
- name: ci
color: fbca04
- name: documentation
color: 607d8b
- name: duplicate
color: 9e9e9e
- name: feature
color: 3f51b5
- name: hacktoberfest
color: ff625f
- name: invalid
color: cddc39
- name: performance
color: 009688
- name: question
color: ff5722
- name: refactor
color: 9c27b0
- name: style
color: 2196f3
- name: test
color: 8bc34a
- name: wontfix
color: ffffff
- name: help wanted
color: 33aa3f
- name: good first issue
color: 7057ff
Hi, @Naylin15
Could you add a README.md file in the example folder with the information about how to install and run the example?
Thanks
Hi, @DIOHz0r
Please, use this header for the copyright information.
#
# LICENSE
#
# This file is part of the GLPI API Client Library for PHP,
# a subproject of GLPI. GLPI is a free IT Asset Management.
#
# GLPI is free software: you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 3
# of the License, or (at your option) any later version.
#
# GLPI is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# --------------------------------------------------------------------
# @author Domingo Oropeza - <[email protected]>
# @copyright (C) 2017 Teclib' and contributors.
# @license GPLv3 https://www.gnu.org/licenses/gpl-3.0.html
# @link https://github.com/glpi-project/php-library-glpi
# @link http://www.glpi-project.org/
# --------------------------------------------------------------------
Hi, @Naylin15
Could you add a compatibility matrix to the README file?
Similar to this format:
GLPI | 9.1.1 | 9.1.2 | 9.1.3 | 9.2.0 |
---|---|---|---|---|
GLPI API Client | 1.x.x | 1.x.x | 1.x.x | 2.0.0-dev |
Is it possible to update composer.json
to use latest guzzlehttp/guzzle
package (7.5)?
Hi,
I try to use the getAllItems method but i can't use range option.
My code is :
`$client = new Glpi\Api\Rest\Client(URL_GLPI.'/apirest.php/', new GuzzleHttp\Client());
$client->setAppToken(GLPI_APPTOKEN);
$client->initSessionByCredentials(GLPI_USER, GLPI_PASS);
$itemHandler = new \Glpi\Api\Rest\ItemHandler($client);
$response = $itemHandler->getAllItems("user",array("'range'=>'0-500'"));
`
If i use 0-500 range or 0-10 range, i always obtain the same result with statusCode 206 for partial result.
Any idea ?
As requested, the information in the project sites will be migrated to the main site of GLPI Project (glpi-project.org)
Hi, @Naylin15
Could you write the documentation of the code?
And please share with us the feedback to merge in all client libraries common error messages.
Thanks.
Hi, @DIOHz0r
In every release you need to generate and push the changelog file to the gh-pages with this header:
---
layout: modal
title: changelog
---
I cannot connect to API using user token (initSessionByUserToken()
): I get rejected by the server:
One of theses parameter(s) is missing: login and password or user_token
require_once __DIR__ . '/vendor/autoload.php';
$client = new Glpi\Api\Rest\Client(
'http://localhost/glpi/apirest.php/',
new GuzzleHttp\Client()
);
$client->setAppToken('abcdef....');
$client->initSessionByUserToken('secret');
var_dump($client->getFullSession()['statusCode']);
$client->killSession();
PHP Fatal error: Uncaught exception 'Exception' with message 'One of theses parameter(s) is missing: login and password or user_token' in .../myexample/vendor/glpi-project/php-library-glpi/src/Glpi/Api/Rest/Client.php on line 104
Stack trace:
#0 .../myexample/test.php(7): Glpi\Api\Rest\Client->initSessionByUserToken('secret')
#1 {main}
thrown in .../myexample/vendor/glpi-project/php-library-glpi/src/Glpi/Api/Rest/Client.php on line 104
There should be not "PHP Fatal error", only:
int(200)
It may be related/similar to http://forum.glpi-project.org/viewtopic.php?id=159187 which seems to question glpi-project/glpi@5bd4284.
Using:
I get PHP notice about an undefined Session-Token
index when authenticating on the API when setting an application token (using setAppToken()
).
require_once __DIR__ . '/vendor/autoload.php';
$client = new Glpi\Api\Rest\Client(
'http://localhost/glpi/apirest.php/',
new GuzzleHttp\Client()
);
$client->setAppToken('abcdef....');
$client->initSessionByCredentials(
'glpi',
'glpi'
);
var_dump($client->getFullSession()['statusCode']);
$client->killSession();
PHP Notice: Undefined index: Session-Token in .../myexample/vendor/glpi-project/php-library-glpi/src/Glpi/Api/Rest/Client.php on line 137
PHP Stack trace:
PHP 1. {main}() .../myexample/test.php:0
PHP 2. Glpi\Api\Rest\Client->initSessionByCredentials() .../myexample/test.php:10
PHP 3. Glpi\Api\Rest\Client->request() .../myexample/vendor/glpi-project/php-library-glpi/src/Glpi/Api/Rest/Client.php:81
int(200)
There should be not "PHP Notice", only:
int(200)
If I disable the app_token filtering on GLPI server side and comment the `setAppToken()`` call, the PHP notice disappears.
I tried various settings and got the following:
Application token filtering on server side | Calling setAppToken() |
Result |
---|---|---|
No | No | Works OK without notice/errors |
No | Yes | PHP Notice: Undefined index: Session-Token (in Client.php:137 ) and PHP Notice: Undefined index: ERROR_WRONG_APP_TOKEN_PARAMETER (in ErrorHandler.php:69 ) and PHP Fatal error: Uncaught exception 'Exception' (in Client.php:8 ) |
Yes | No | Works OK, it rejects the client because no token was provided (PHP Fatal error: Uncaught exception 'Exception' with message 'The current API requires an App-Token header for using its methods.') |
Yes | Yes | PHP Notice: Undefined index: Session-Token |
Hi,
I'm trying to make a query "searchItems" but I can not find the syntax in the documentation.
Someone could give me an example of a simple query "search items"
$response = $this->client->searchItems('Ticket', array( 'criteria' => array( 'itemtype' => 'Ticket', 'field' => 1, 'searchType' => 'contains', 'value' => 'aaa', ) ) );
Thx !
Hi, @DIOHz0r
For the next milestone (v2) of the library, please remove external dependencies of the HTTP requests (Guzzle)
Thanks
The code documentation link of the project site has the wrong URL.
The correct link for the menu is the develop folder (https://glpi-project.github.io/php-library-glpi/build/docs/develop/)
Code coverage style for web site are messed up
Page styles according with project branding guides.
Hi, @Naylin15
Please, replace this URL in the README file:
https://dev.flyve.org/glpi/apirest.php
To this one:
https://github.com/glpi-project/glpi/blob/master/apirest.md
And the new install command is:
composer require glpi-project/php-library-glpi
Thank you.
Hi, @DIOHz0r
Please, fix the name of the composer package
Thanks.
https://github.com/glpi-project/php-library-glpi/blob/develop/composer.json#L2
It is not possible to upload files using addItems() method because of the following wrong assumptions:
Code should respect for 'multipart/data' content_type
For example: get a computer or a ticket should allow to get linked items and return as answer an object for the main item, and sub objects for linked ones.
Getting sub items must be optional
Hello,
I have a problem when calling the initSession method. I use the example of documentation to initialize a failed session with the following error message "The current API requires an App-Token header for using its methods."
I added the call to the setAppToken method by passing a token as a parameter without any more success:
$client = new Client('http:///apirest.php', new \GuzzleHttp\Client());
$client->setAppToken('');
$client->initSessionByCredentials('*******','*****');
However it work when I initialize a session using the curl php functions:
$ch = curl_init();
curl_setopt_array($ch, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => "http://********/apirest.php/initSession",
CURLOPT_HTTPHEADER => array(
"Content-Type" => "application/json",
Authorization' => "Basic ".base64_encode(':'),
"App-Token" =>"*******''
)
));
$result = curl_exec($ch);
curl_close($ch);
print_r($result);
I use GLPI 9.1.4, PHP7+ and Guzzle 6.3.
Have you ever heard other people who would have encountered this problem? Do you have a solution?
Thank you
Hi, @Naylin15
Please, create these files in this repository
Thank you.
Hi, @DIOHz0r
I will put here all possible errors for the library.
Hi, @Gianfranco97
Could you create the project site of this repository?
Using the theme of GLPI Network (blue)
Thanks
Description
With a user_token that enforces using with app_token, the authentication fails
To Reproduce
Steps to reproduce the behavior:
Install package on any PHP project, i'm using laravel 5.6.*
Paste the folowing code on any class
`
$appToken = config('custom-values.glpi.app-token');
$userToken = config('custom-values.glpi.user-token');
$baseUrlToken = config('custom-values.glpi.base-url');
$client = new GlpiClient($baseUrlToken, new Client());
$client->setAppToken($appToken);
$client->initSessionByUserToken($userToken);
`
3. Run it
4. See error: PHP Notice: Undefined index: Session-Token in vendor/glpi-project/php-library-glpi/src/Glpi/Api/Rest/Client.php on line 137
5. After fixing with my next suggestion, throws following exception:
Exception with message 'The current API requires an App-Token header for using its methods.'
Causes
$sessionHeaders = [];
if (key_exists('Session-Token', $apiToken)) {
$sessionHeaders['Session-Token'] = $apiToken['Session-Token'];
}
$response = $this->request('get', 'initSession', ['headers'=> ['Authorization' => "user_token $userToken"]]);
Full class change:
<?php
/**
* --------------------------------------------------------------------
*
* LICENSE
*
* This file is part of the GLPI API Client Library for PHP,
* a subproject of GLPI. GLPI is a free IT Asset Management.
*
* GLPI is free software: you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 3
* of the License, or (at your option) any later version.
*
* GLPI is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* --------------------------------------------------------------------
* @author Domingo Oropeza - <[email protected]>
* @copyright (C) 2017 Teclib' and contributors.
* @license GPLv3 https://www.gnu.org/licenses/gpl-3.0.html
* @link https://github.com/glpi-project/php-library-glpi
* @link http://www.glpi-project.org/
* --------------------------------------------------------------------
*/
namespace Glpi\Api\Rest;
use GuzzleHttp\Client as HttpClient;
use Exception;
use Glpi\Api\Rest\Exception\InsufficientArgumentsException;
use GuzzleHttp\Exception\ClientException;
use GuzzleHttp\Exception\RequestException;
/**
* Class Client
* @package Glpi\Api\Rest
*/
class Client {
/** @var HttpClient instance of the HTTP client */
private $httpClient = null;
/** @var string URL to the GLPI API rest */
private $url;
/** @var $appToken string an application token to use for requests */
private $appToken = null;
/** @var string Session token obtained after initSession() */
private $sessionToken = null;
/**
* Client constructor.
* @param string $url
* @param HttpClient $httpClient
*/
public function __construct($url, HttpClient $httpClient) {
$this->httpClient = $httpClient;
$this->url = trim($url, '/') . '/';
}
/**
* Set an application token to be used for each request
*
* @param string $appToken
*/
public function setAppToken($appToken = null) {
$this->appToken = $appToken;
}
/**
* Initialize a session with user credentials
* @param string $user
* @param string $password
* @throws Exception
* @return boolean
*/
public function initSessionByCredentials($user, $password) {
$response = $this->request('get', 'initSession', ['auth' => [$user, $password]]);
if ($response->getStatusCode() != 200
|| !$this->sessionToken = json_decode($response->getBody()->getContents(), true)['session_token']) {
$body = json_decode($response->getBody()->getContents());
throw new Exception(ErrorHandler::getMessage($body[0]));
}
return true;
}
/**
* initialize a session with a user token
*
* @param string $userToken
*
* @throws Exception
*
* @return boolean True if success
*/
public function initSessionByUserToken($userToken) {
$response = $this->request('get', 'initSession', ['headers'=> ['Authorization' => "user_token $userToken"]]);
if ($response->getStatusCode() != 200
|| !$this->sessionToken = json_decode($response->getBody()->getContents(), true)['session_token']) {
$body = json_decode($response->getBody()->getContents());
throw new Exception(ErrorHandler::getMessage($body[0]));
}
return true;
}
/**
* Kill client session.
* @return bool
* @throws Exception
*/
public function killSession() {
$response = $this->request('get', 'killSession');
if ($response->getStatusCode() != 200) {
$body = json_decode($response->getBody()->getContents());
throw new Exception(ErrorHandler::getMessage($body[0]));
}
return true;
}
/**
* Prepare and send a request to the GLPI Api.
*
* @param $method
* @param $uri
* @param array $options
* @return mixed|null|\Psr\Http\Message\ResponseInterface
* @throws Exception
*/
public function request($method, $uri, array $options = []) {
$apiToken = $this->addTokens();
try {
$options['headers']['Content-Type'] = "application/json";
if ($apiToken) {
$sessionHeaders = [];
if (key_exists('Session-Token', $apiToken)) {
$sessionHeaders['Session-Token'] = $apiToken['Session-Token'];
}
if (key_exists('App-Token', $apiToken)) {
$sessionHeaders['App-Token'] = $apiToken['App-Token'];
}
$options = array_merge_recursive($options, ['headers' => $sessionHeaders]);
}
$response = $this->httpClient->request($method, $this->url . $uri, $options);
return $response;
} catch (ClientException $e) {
$response = $e->getResponse();
/*$body = $response->getBody()->getContents();
$reasonPhrase = $response->getReasonPhrase() . (($body) ? ' ' . $body : '');*/
return $response;
} catch (RequestException $e) {
$hasResponse = $e->hasResponse();
$statusCode = ($hasResponse) ? $e->getResponse()->getStatusCode() : '500';
$contents = ($hasResponse) ? $e->getResponse()->getReasonPhrase() : 'Request Error';
throw new Exception($contents, $statusCode);
}
}
/**
* Return the current php $_SESSION.
* @return array
*/
public function getFullSession() {
$response = $this->request('get', 'getFullSession');
return ['statusCode' => $response->getStatusCode(), 'body' => $response->getBody()->getContents()];
}
/**
* Return the current $CFG_GLPI.
* @return array
*/
public function getGlpiConfig() {
$response = $this->request('get', 'getGlpiConfig');
return ['statusCode' => $response->getStatusCode(), 'body' => $response->getBody()->getContents()];
}
/**
* generate headers containing session and app tokens for Http client object
*
* @return string[]
*/
private function addTokens() {
$headers = [];
if ($this->appToken !== null) {
$headers['App-Token'] = $this->appToken;
}
if ($this->sessionToken !== null) {
$headers['Session-Token'] = $this->sessionToken;
}
return $headers;
}
/**
* Allows to request password recovery.
* This endpoint works under the following conditions:
* - GLPI has notifications enabled
* - The email address of the user belongs to a user account.
*
* @param string $email
* @return array
*/
public function recoveryPassword($email) {
$options['body'] = json_encode($params['email'] = $email);
$response = $this->request('put', 'lostPassword', $options);
return [
'statusCode' => $response->getStatusCode(),
'body' => $response->getBody()->getContents(),
];
}
/**
* Allows to request a password reset.
* This endpoint works under the following conditions:
* - GLPI has notifications enabled
* - The email address of the user belongs to a user account.
*
* @param $email
* @param string $recoveryToken
* @param string $newPassword
* @return array
*/
public function resetPassword($email, $recoveryToken, $newPassword) {
if (($recoveryToken && !$newPassword) || (!$recoveryToken && $newPassword)) {
throw new InsufficientArgumentsException(ErrorHandler::getMessage('ERROR_APILIB_ARGUMENTS'));
}
$options['body'] = json_encode([
'email' => $email,
'password_forget_token' => $recoveryToken,
'password' => $newPassword,
]);
$response = $this->request('put', 'lostPassword', $options);
return [
'statusCode' => $response->getStatusCode(),
'body' => $response->getBody()->getContents(),
];
}
}
Hi, @DIOHz0r
You need to integrate the task in Travis CI to publish the package to Packagist.
The script will run in every push of the master branch.
Thanks
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.