Git Product home page Git Product logo

php-library-glpi's People

Contributors

ajsb85 avatar btry avatar c-duv avatar diohz0r avatar naylin15 avatar tomolimo avatar traviscibot avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

php-library-glpi's Issues

Documentation display

Observed Results:

Files must be removed so the documentation follows the styles

Expected behavior:

For Code Documentation it is required to:

  • Remove build/docs/master/css/sami.css and links related
  • Remove build/docs/master/css/bootstrap-theme.min.css and links related
  • Remove build/docs/master/css/bootstrap.min.css and links related
  • Remove build/docs/master/js/bootstrap.min.js and links related
  • Change the layout of the files to layout: jazzy

For Coverage it is required to:

  • Change the layout of the files to layout: coverage

GitHub App Settings

Hi, @Naylin15

  • Create a file settings.yml in the folder .github (content below in the issue)
  • Commit the file with this commit message: build(settings): add YAML for the bot Settings
  • Create a Pull-Request
  • Repeat the steps for each repository, changing the proper name, topics, homepage and description.
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

License Header

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/
#  --------------------------------------------------------------------

Compatibility Matrix

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

Update to Guzzle 7

Is it possible to update composer.json to use latest guzzlehttp/guzzle package (7.5)?

Range in getAllItems method

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 ?

Migrate project site information to glpi-project.org

Observed Results:

As requested, the information in the project sites will be migrated to the main site of GLPI Project (glpi-project.org)

Expected behavior:

  • Wordpress plugin to sync the content with GitHub
  • Migrate How tos section
    • Installation
    • Getting started
    • How it works
    • Use cases
    • How to contribute
  • Migrate development section
    • Code Documentation
    • Coverage
    • Test reports
  • Screenshots (When applied)
  • Versioning

Code documentation

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.

Generate Changelog

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
---

Cannot connect to API server using user token

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

Reproduction code

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();

Observed Results:

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

Expected behavior:

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:

  • GLPI v9.2.2
  • php-library-glpi v0.1.0

Undefined index with the session token using app token

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();

Observed Results:

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)

Expected behavior:

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

Syntax query searchItems

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"

Observed Results:

$response = $this->client->searchItems('Ticket', array( 'criteria' => array( 'itemtype' => 'Ticket', 'field' => 1, 'searchType' => 'contains', 'value' => 'aaa', ) ) );

Expected behavior:

Thx !

Fix code coverage styles

Observed Results:

Code coverage style for web site are messed up

Expected behavior:

Page styles according with project branding guides.

BUG: Upload a Document file using addItems() fails

Observed Results:

It is not possible to upload files using addItems() method because of the following wrong assumptions:

  • addItems() method of ItemHandler class assumes that queryString is input parameter
  • request() method of Client class forces Content-type as 'application/json'

Expected behavior:

Code should respect for 'multipart/data' content_type

Get an itemtype with all sub-items

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

InitSession -> requires an App-Token header for using its methods

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

Project board

Hi, @DIOHz0r

I will add a bot soon, to create the project board and the label of the issues

Regards

Create documentation

Hi, @Naylin15

Please, create these files in this repository

  • README in markdown file format
  • LICENSE in markdown file format (GPL 3.0)
  • GitHub templates for issues and PRs
  • Contribute Guidelines

Thank you.

Connection with user_token and app_token fails

Description
With a user_token that enforces using with app_token, the authentication fails

To Reproduce
Steps to reproduce the behavior:

  1. Install package on any PHP project, i'm using laravel 5.6.*

  2. 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

  1. function request on php-library-glpi/src/Glpi/Api/Rest/Client.php
    failure to check for Session-Token before adding it to the headers, breaks the execution
    Suggested replace for line 137:
$sessionHeaders = [];
             if (key_exists('Session-Token', $apiToken)) {
                 $sessionHeaders['Session-Token'] = $apiToken['Session-Token'];
             }
  1. function initSessionByUserToken on php-library-glpi/src/Glpi/Api/Rest/Client.php
    failure to call request function because the user_token is to be passed on the header and not on the body.
    Suggested replace for line 100:
    $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(),
      ];
   }
}

Publish to Composer

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

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.