api.class.php 98.8 KB
Newer Older
Alexandre Delaunay's avatar
Alexandre Delaunay committed
1
<?php
2

3
4
5
/**
 * ---------------------------------------------------------------------
 * GLPI - Gestionnaire Libre de Parc Informatique
6
 * Copyright (C) 2015-2021 Teclib' and contributors.
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
 *
 * http://glpi-project.org
 *
 * based on GLPI - Gestionnaire Libre de Parc Informatique
 * Copyright (C) 2003-2014 by the INDEPNET Development Team.
 *
 * ---------------------------------------------------------------------
 *
 * LICENSE
 *
 * This file is part of GLPI.
 *
 * 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 2 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.
 *
 * You should have received a copy of the GNU General Public License
 * along with GLPI. If not, see <http://www.gnu.org/licenses/>.
 * ---------------------------------------------------------------------
Alexandre Delaunay's avatar
Alexandre Delaunay committed
32
33
 */

Anael Mobilia's avatar
PHPdoc    
Anael Mobilia committed
34
/**
Anael Mobilia's avatar
Anael Mobilia committed
35
 * @since 9.1
Anael Mobilia's avatar
PHPdoc    
Anael Mobilia committed
36
 */
Alexandre Delaunay's avatar
Alexandre Delaunay committed
37

38
39
40
41
42
43
44
namespace Glpi\Api;

use APIClient;
use Auth;
use Change;
use CommonDevice;
use CommonGLPI;
45
use CommonITILObject;
46
47
48
49
use Config;
use Contract;
use Document;
use Dropdown;
50
51
use Glpi\Exception\ForgetPasswordException;
use Glpi\Exception\PasswordTooWeakException;
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
use Html;
use Infocom;
use Item_Devices;
use Log;
use Michelf\MarkdownExtra;
use NetworkEquipment;
use NetworkPort;
use Notepad;
use Problem;
use QueryExpression;
use SavedSearch;
use Search;
use Session;
use Software;
use Ticket;
use Toolbox;
use User;
69

Alexandre Delaunay's avatar
Alexandre Delaunay committed
70
71
72
73
74
75
abstract class API extends CommonGLPI {

   // permit writing to $_SESSION
   protected $session_write = false;

   static $api_url = "";
76
   static $content_type = "application/json";
Alexandre Delaunay's avatar
Alexandre Delaunay committed
77
78
79
   protected $format;
   protected $iptxt         = "";
   protected $ipnum         = "";
80
   protected $app_tokens    = [];
Alexandre Delaunay's avatar
Alexandre Delaunay committed
81
   protected $apiclients_id = 0;
82
   protected $deprecated_item = null;
Alexandre Delaunay's avatar
Alexandre Delaunay committed
83

Anael Mobilia's avatar
PHPdoc    
Anael Mobilia committed
84
85
86
87
88
89
   /**
    * First function used on api call
    * Parse sended query/parameters and call the corresponding API::method
    *
    * @return void self::returnResponse called for output
    */
Alexandre Delaunay's avatar
Alexandre Delaunay committed
90
91
   abstract public function call();

Anael Mobilia's avatar
PHPdoc    
Anael Mobilia committed
92
93
94
95
96
   /**
    * Needed to transform params of called api in $this->parameters attribute
    *
    * @return string endpoint called
    */
Alexandre Delaunay's avatar
Alexandre Delaunay committed
97
98
   abstract protected function parseIncomingParams();

Anael Mobilia's avatar
PHPdoc    
Anael Mobilia committed
99
100
101
   /**
    * Generic messages
    *
102
103
    * @since 9.1
    *
Anael Mobilia's avatar
PHPdoc    
Anael Mobilia committed
104
    * @param mixed   $response          string message or array of data to send
105
    * @param integer $httpcode          http code (see : https://en.wikipedia.org/wiki/List_of_HTTP_status_codes)
Anael Mobilia's avatar
PHPdoc    
Anael Mobilia committed
106
107
108
109
    * @param array   $additionalheaders headers to send with http response (must be an array(key => value))
    *
    * @return void
    */
110
   abstract protected function returnResponse($response, $httpcode = 200, $additionalheaders = []);
Alexandre Delaunay's avatar
Alexandre Delaunay committed
111

112
113
114
115
116
117
   /**
    * Upload and validate files from request and append to $this->parameters['input']
    *
    * @return void
    */
   abstract protected function manageUploadedFiles();
Alexandre Delaunay's avatar
Alexandre Delaunay committed
118

Anael Mobilia's avatar
PHPdoc    
Anael Mobilia committed
119
120
121
122
123
124
125
126
   /**
    * Constructor
    *
    * @var array $CFG_GLPI
    * @var DBmysql $DB
    *
    * @return void
    */
127
   public function initApi() {
Thierry Bugier's avatar
Thierry Bugier committed
128
      global $CFG_GLPI;
Alexandre Delaunay's avatar
Alexandre Delaunay committed
129

130
131
132
133
134
135
136
137
138
      // Load GLPI configuration
      include_once (GLPI_ROOT . '/inc/includes.php');
      $variables = get_defined_vars();
      foreach ($variables as $var => $value) {
         if ($var === strtoupper($var)) {
            $GLOBALS[$var] = $value;
         }
      }

Alexandre Delaunay's avatar
Alexandre Delaunay committed
139
140
141
142
143
144
145
      // construct api url
      self::$api_url = trim($CFG_GLPI['url_base_api'], "/");

      // Don't display error in result
      ini_set('display_errors', 'Off');

      // Avoid keeping messages between api calls
btry's avatar
btry committed
146
      $_SESSION["MESSAGE_AFTER_REDIRECT"] = [];
Alexandre Delaunay's avatar
Alexandre Delaunay committed
147
148
149
150
151
152
153
154

      // check if api is enabled
      if (!$CFG_GLPI['enable_api']) {
         $this->returnError(__("API disabled"), "", "", false);
         exit;
      }

      // retrieve ip of client
btry's avatar
btry committed
155
      $this->iptxt = Toolbox::getRemoteIpAddress();
Alexandre Delaunay's avatar
Alexandre Delaunay committed
156
157
158
159
      $this->ipnum = (strstr($this->iptxt, ':')===false ? ip2long($this->iptxt) : '');

      // check ip access
      $apiclient = new APIClient;
160
      $where_ip = [];
Alexandre Delaunay's avatar
Alexandre Delaunay committed
161
      if ($this->ipnum) {
162
163
164
165
         $where_ip = [
            'OR' => [
               'ipv4_range_start' => null,
               [
Cédric Anne's avatar
Cédric Anne committed
166
167
                  'ipv4_range_start'   => ['<=', $this->ipnum],
                  'ipv4_range_end'     => ['>=', $this->ipnum]
168
169
170
               ]
            ]
         ];
Alexandre Delaunay's avatar
Alexandre Delaunay committed
171
      } else {
172
173
174
175
176
177
         $where_ip = [
            'OR' => [
               ['ipv6'  => null],
               ['ipv6'  => $this->iptxt]
            ]
         ];
Alexandre Delaunay's avatar
Alexandre Delaunay committed
178
      }
179
      $found_clients = $apiclient->find(['is_active' => 1] + $where_ip);
Alexandre Delaunay's avatar
Alexandre Delaunay committed
180
      if (count($found_clients) <= 0) {
Johan Cwiklinski's avatar
Johan Cwiklinski committed
181
         $this->returnError(__("There isn't an active API client matching your IP address in the configuration").
Alexandre Delaunay's avatar
Alexandre Delaunay committed
182
183
184
185
186
187
188
189
                            " (".$this->iptxt.")",
                            "", "ERROR_NOT_ALLOWED_IP", false);
      }
      $app_tokens = array_column($found_clients, 'app_token');
      $apiclients_id = array_column($found_clients, 'id');
      $this->app_tokens = array_combine($apiclients_id, $app_tokens);
   }

Anael Mobilia's avatar
PHPdoc    
Anael Mobilia committed
190
191
192
193
194
195
196
   /**
    * Set headers according to cross origin ressource sharing
    *
    * @param string $verb Http verb (GET, POST, PUT, DELETE, OPTIONS)
    *
    * @return void
    */
Alexandre Delaunay's avatar
Alexandre Delaunay committed
197
198
199
200
201
   protected function cors($verb = 'GET') {
      if (isset($_SERVER['HTTP_ORIGIN'])) {
         header("Access-Control-Allow-Origin: *");
      }

202
      if ($this->verb == 'GET' || $this->verb == 'OPTIONS') {
Alexandre Delaunay's avatar
Alexandre Delaunay committed
203
         header("Access-Control-Expose-Headers: content-type, content-range, accept-range");
204
      }
Alexandre Delaunay's avatar
Alexandre Delaunay committed
205

206
      if ($this->verb == "OPTIONS") {
Alexandre Delaunay's avatar
Alexandre Delaunay committed
207
208
209
210
211
212
         if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD'])) {
            header("Access-Control-Allow-Methods: PUT, GET, POST, DELETE, OPTIONS");
         }

         if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS'])) {
            header("Access-Control-Allow-Headers: ".
213
                   "origin, content-type, accept, session-token, authorization");
Alexandre Delaunay's avatar
Alexandre Delaunay committed
214
215
216
217
218
219
220
221
222
         }
         exit(0);
      }
   }


   /**
    * Init GLPI Session
    *
Anael Mobilia's avatar
PHPdoc    
Anael Mobilia committed
223
    * @param array $params array with theses options :
224
    *    - a couple 'name' & 'password' : 2 parameters to login with user authentication
Alexandre Delaunay's avatar
Alexandre Delaunay committed
225
226
227
228
    *         OR
    *    - an 'user_token' defined in User Configuration
    *
    * @return array with session_token
Anael Mobilia's avatar
PHPdoc    
Anael Mobilia committed
229
    */
230
   protected function initSession($params = []) {
Alexandre Delaunay's avatar
Alexandre Delaunay committed
231
      global $CFG_GLPI;
yllen's avatar
CS    
yllen committed
232

Alexandre Delaunay's avatar
Alexandre Delaunay committed
233
234
235
236
237
238
239
240
241
      $this->checkAppToken();
      $this->logEndpointUsage(__FUNCTION__);

      if ((!isset($params['login'])
           || empty($params['login'])
           || !isset($params['password'])
           || empty($params['password']))
         && (!isset($params['user_token'])
             || empty($params['user_token']))) {
Alexandre Delaunay's avatar
Alexandre Delaunay committed
242
         $this->returnError(__("parameter(s) login, password or user_token are missing"), 400,
Alexandre Delaunay's avatar
Alexandre Delaunay committed
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
                            "ERROR_LOGIN_PARAMETERS_MISSING");
      }

      $auth = new Auth();

      // fill missing params (in case of user_token)
      if (!isset($params['login'])) {
         $params['login'] = '';
      }
      if (!isset($params['password'])) {
         $params['password'] = '';
      }

      $noAuto = true;
      if (isset($params['user_token']) && !empty($params['user_token'])) {
         $_REQUEST['user_token'] = $params['user_token'];
         $noAuto = false;

      } else if (!$CFG_GLPI['enable_api_login_credentials']) {
262
         $this->returnError(__("usage of initSession resource with credentials is disabled"), 400,
263
                            "ERROR_LOGIN_WITH_CREDENTIALS_DISABLED", false);
Alexandre Delaunay's avatar
Alexandre Delaunay committed
264
265
      }

266
267
268
269
      if (!isset($params['auth'])) {
         $params['auth'] = '';
      }

Alexandre Delaunay's avatar
Alexandre Delaunay committed
270
      // login on glpi
271
      if (!$auth->login($params['login'], $params['password'], $noAuto, false, $params['auth'])) {
Alexandre Delaunay's avatar
Alexandre Delaunay committed
272
273
274
         $err = Html::clean($auth->getErr());
         if (isset($params['user_token'])
             && !empty($params['user_token'])) {
275
            return $this->returnError(__("parameter user_token seems invalid"), 401, "ERROR_GLPI_LOGIN_USER_TOKEN", false);
Alexandre Delaunay's avatar
Alexandre Delaunay committed
276
         }
277
         return $this->returnError($err, 401, "ERROR_GLPI_LOGIN", false);
Alexandre Delaunay's avatar
Alexandre Delaunay committed
278
279
280
281
      }

      // stop session and return session key
      session_write_close();
282
283
284
285
286
287
288
289
290
      $data = ['session_token' => $_SESSION['valid_id']];

      // Insert session data if requested
      $get_full_session = $params['get_full_session'] ?? false;
      if ($get_full_session) {
         $data['session'] = $_SESSION;
      }

      return $data;
Alexandre Delaunay's avatar
Alexandre Delaunay committed
291
292
293
294
295
296
297
298
   }


   /**
    * Kill GLPI Session
    * Use 'session_token' param in $this->parameters
    *
    * @return boolean
Anael Mobilia's avatar
PHPdoc    
Anael Mobilia committed
299
    */
Alexandre Delaunay's avatar
Alexandre Delaunay committed
300
   protected function killSession() {
yllen's avatar
CS    
yllen committed
301

Alexandre Delaunay's avatar
Alexandre Delaunay committed
302
303
304
305
306
307
308
309
      $this->initEndpoint(false, __FUNCTION__);
      return Session::destroy();
   }


   /**
    * Retrieve GLPI Session initialised by initSession function
    * Use 'session_token' param in $this->parameters
Anael Mobilia's avatar
PHPdoc    
Anael Mobilia committed
310
311
312
    *
    * @return void
    */
Alexandre Delaunay's avatar
Alexandre Delaunay committed
313
   protected function retrieveSession() {
yllen's avatar
CS    
yllen committed
314

Alexandre Delaunay's avatar
Alexandre Delaunay committed
315
316
317
318
319
      if (isset($this->parameters['session_token'])
          && !empty($this->parameters['session_token'])) {
         $current = session_id();
         $session = trim($this->parameters['session_token']);

320
321
         if (file_exists(GLPI_ROOT . '/inc/downstream.php')) {
            include_once (GLPI_ROOT . '/inc/downstream.php');
Alexandre Delaunay's avatar
Alexandre Delaunay committed
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
         }

         if ($session!=$current && !empty($current)) {
            session_destroy();
         }
         if ($session!=$current && !empty($session)) {
            session_id($session);
         }
      }
   }


   /**
    * Change active entity to the entities_id one.
    *
Anael Mobilia's avatar
PHPdoc    
Anael Mobilia committed
337
    * @param array $params array with theses options :
Alexandre Delaunay's avatar
Alexandre Delaunay committed
338
339
    *   - '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
yllen's avatar
CS    
yllen committed
340
    *
341
    * @return array|bool
Anael Mobilia's avatar
PHPdoc    
Anael Mobilia committed
342
    */
343
   protected function changeActiveEntities($params = []) {
yllen's avatar
CS    
yllen committed
344

Alexandre Delaunay's avatar
Alexandre Delaunay committed
345
346
347
      $this->initEndpoint();

      if (!isset($params['entities_id'])) {
348
349
350
         $entities_id = 'all';
      } else {
         $entities_id = intval($params['entities_id']);
Alexandre Delaunay's avatar
Alexandre Delaunay committed
351
352
353
354
      }

      if (!isset($params['is_recursive'])) {
         $params['is_recursive'] = false;
355
356
357
358
359
360
      } else if (!is_bool($params['is_recursive'])) {
         return $this->returnError();
      }

      if (!Session::changeActiveEntities($entities_id, $params['is_recursive'])) {
         return $this->returnError();
Alexandre Delaunay's avatar
Alexandre Delaunay committed
361
362
      }

363
      return true;
Alexandre Delaunay's avatar
Alexandre Delaunay committed
364
365
366
367
   }


   /**
Anael Mobilia's avatar
PHPdoc    
Anael Mobilia committed
368
    * Return all the possible entity of the current logged user (and for current active profile)
Alexandre Delaunay's avatar
Alexandre Delaunay committed
369
    *
370
371
372
    * @param array $params array with theses options :
    *   - 'is_recursive': (default false) Also display sub entities of the active entity. Optionnal
    *
Alexandre Delaunay's avatar
Alexandre Delaunay committed
373
    * @return array of entities (with id and name)
Anael Mobilia's avatar
PHPdoc    
Anael Mobilia committed
374
    */
375
   protected function getMyEntities($params = []) {
yllen's avatar
CS    
yllen committed
376

Alexandre Delaunay's avatar
Alexandre Delaunay committed
377
378
      $this->initEndpoint();

379
380
381
382
      if (!isset($params['is_recursive'])) {
         $params['is_recursive'] = false;
      }

383
      $myentities = [];
Alexandre Delaunay's avatar
Alexandre Delaunay committed
384
      foreach ($_SESSION['glpiactiveprofile']['entities'] as $entity) {
385
386
387
388
389
390
391
392
393
394
395
396
397
         if ($entity['is_recursive'] == 1 && $params['is_recursive'] == 1) {
            $sons = getSonsOf('glpi_entities', $entity['id']);
            foreach ($sons as $entity_id) {
               if ($entity_id != $entity['id']) {
                  $myentities[] = ['id'   => $entity_id,
                                   'name' => Dropdown::getDropdownName("glpi_entities",
                                                                       $entity_id)];
               }
            }
         }
         $myentities[] = ['id' => $entity['id'],
                          'name' => Dropdown::getDropdownName("glpi_entities",
                                                                   $entity['id'])];
Alexandre Delaunay's avatar
Alexandre Delaunay committed
398
      }
399
      return ['myentities' => $myentities];
Alexandre Delaunay's avatar
Alexandre Delaunay committed
400
401
402
   }


yllen's avatar
CS    
yllen committed
403
404


Alexandre Delaunay's avatar
Alexandre Delaunay committed
405
406
407
408
409
410
411
   /**
    * return active entities of current logged user
    *
    * @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)
Anael Mobilia's avatar
PHPdoc    
Anael Mobilia committed
412
    */
Alexandre Delaunay's avatar
Alexandre Delaunay committed
413
   protected function getActiveEntities() {
yllen's avatar
CS    
yllen committed
414

Alexandre Delaunay's avatar
Alexandre Delaunay committed
415
416
      $this->initEndpoint();

417
418
419
420
421
      $actives_entities = [];
      foreach (array_values($_SESSION['glpiactiveentities']) as $active_entity) {
         $actives_entities[] = ['id' => $active_entity];
      }

422
      return ["active_entity" => [
423
424
                     "id"                      => $_SESSION['glpiactive_entity'],
                     "active_entity_recursive" => $_SESSION['glpiactive_entity_recursive'],
425
                     "active_entities"         => $actives_entities]];
Alexandre Delaunay's avatar
Alexandre Delaunay committed
426
427
428
429

   }


yllen's avatar
CS    
yllen committed
430
431


Alexandre Delaunay's avatar
Alexandre Delaunay committed
432
433
434
   /**
    * set a profile to active
    *
Anael Mobilia's avatar
PHPdoc    
Anael Mobilia committed
435
    * @param array $params with theses options :
Alexandre Delaunay's avatar
Alexandre Delaunay committed
436
    *    - profiles_id : identifier of profile to set
yllen's avatar
CS    
yllen committed
437
    *
Anael Mobilia's avatar
PHPdoc    
Anael Mobilia committed
438
439
    * @return boolean
    */
440
   protected function changeActiveProfile($params = []) {
yllen's avatar
CS    
yllen committed
441

Alexandre Delaunay's avatar
Alexandre Delaunay committed
442
443
      $this->initEndpoint();

444
445
446
447
      if (!isset($params['profiles_id'])) {
         $this->returnError();
      }

Alexandre Delaunay's avatar
Alexandre Delaunay committed
448
449
450
451
      $profiles_id = intval($params['profiles_id']);
      if (isset($_SESSION['glpiprofiles'][$profiles_id])) {
         return Session::changeProfile($profiles_id);
      }
452
453

      $this->messageNotfoundError();
Alexandre Delaunay's avatar
Alexandre Delaunay committed
454
455
456
   }


yllen's avatar
CS    
yllen committed
457
458


Alexandre Delaunay's avatar
Alexandre Delaunay committed
459
460
461
462
   /**
    * Return all the profiles associated to logged user
    *
    * @return array of profiles (with associated rights)
Anael Mobilia's avatar
PHPdoc    
Anael Mobilia committed
463
    */
Alexandre Delaunay's avatar
Alexandre Delaunay committed
464
465
   protected function getMyProfiles() {

yllen's avatar
CS    
yllen committed
466
      $this->initEndpoint();
467

468
      $myprofiles = [];
Anael Mobilia's avatar
Anael Mobilia committed
469
      foreach ($_SESSION['glpiprofiles'] as $profiles_id => $profile) {
470
         // append if of the profile into values
471
472
473
474
475
476
477
478
         $profile = ['id' => $profiles_id] + $profile;

         // don't keep keys for entities
         $profile['entities'] = array_values($profile['entities']);

         // don't keep keys for profiles
         $myprofiles[] = $profile;
      }
479
      return ['myprofiles' => $myprofiles];
Alexandre Delaunay's avatar
Alexandre Delaunay committed
480
481
482
   }


yllen's avatar
CS    
yllen committed
483
484


Alexandre Delaunay's avatar
Alexandre Delaunay committed
485
   /**
Anael Mobilia's avatar
PHPdoc    
Anael Mobilia committed
486
    * Return the current active profile
Alexandre Delaunay's avatar
Alexandre Delaunay committed
487
488
    *
    * @return integer the profiles_id
Anael Mobilia's avatar
PHPdoc    
Anael Mobilia committed
489
    */
Alexandre Delaunay's avatar
Alexandre Delaunay committed
490
   protected function getActiveProfile() {
yllen's avatar
CS    
yllen committed
491

Alexandre Delaunay's avatar
Alexandre Delaunay committed
492
      $this->initEndpoint();
493
      return ["active_profile" => $_SESSION['glpiactiveprofile']];
Alexandre Delaunay's avatar
Alexandre Delaunay committed
494
495
496
   }


yllen's avatar
CS    
yllen committed
497
498


Alexandre Delaunay's avatar
Alexandre Delaunay committed
499
   /**
Anael Mobilia's avatar
PHPdoc    
Anael Mobilia committed
500
    * Return the current php $_SESSION
Alexandre Delaunay's avatar
Alexandre Delaunay committed
501
502
    *
    * @return array
Anael Mobilia's avatar
PHPdoc    
Anael Mobilia committed
503
    */
Alexandre Delaunay's avatar
Alexandre Delaunay committed
504
   protected function getFullSession() {
yllen's avatar
CS    
yllen committed
505

Alexandre Delaunay's avatar
Alexandre Delaunay committed
506
      $this->initEndpoint();
507
      return ['session' => $_SESSION];
Alexandre Delaunay's avatar
Alexandre Delaunay committed
508
509
   }

yllen's avatar
CS    
yllen committed
510
511


512
   /**
Anael Mobilia's avatar
PHPdoc    
Anael Mobilia committed
513
    * Return the current $CFG_GLPI
514
515
    *
    * @return array
Anael Mobilia's avatar
PHPdoc    
Anael Mobilia committed
516
     */
517
518
519
   protected function getGlpiConfig() {
      $this->initEndpoint();

520
      return ['cfg_glpi' => Config::getSafeConfig()];
521
522
523
   }


Alexandre Delaunay's avatar
Alexandre Delaunay committed
524
525
526
   /**
    * Return the instance fields of itemtype identified by id
    *
Anael Mobilia's avatar
PHPdoc    
Anael Mobilia committed
527
528
529
    * @param string  $itemtype itemtype (class) of object
    * @param integer $id       identifier of object
    * @param array   $params   with theses options :
530
531
532
    *    - '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
533
    *    - 'with_devices':  Only for [Computer, NetworkEquipment, Peripheral, Phone, Printer], Optionnal.
534
535
536
537
538
539
540
541
542
543
544
545
    *    - '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.
546
    *    - 'add_keys_names':   Get friendly names. Optionnal.
Alexandre Delaunay's avatar
Alexandre Delaunay committed
547
    *
Anael Mobilia's avatar
PHPdoc    
Anael Mobilia committed
548
549
    * @return array    fields of found object
    */
550
   protected function getItem($itemtype, $id, $params = []) {
Alexandre Delaunay's avatar
Alexandre Delaunay committed
551
      global $CFG_GLPI, $DB;
yllen's avatar
CS    
yllen committed
552

Alexandre Delaunay's avatar
Alexandre Delaunay committed
553
      $this->initEndpoint();
554
      $itemtype = $this->handleDepreciation($itemtype);
Alexandre Delaunay's avatar
Alexandre Delaunay committed
555
556

      // default params
557
      $default = ['expand_dropdowns'  => false,
Alexandre Delaunay's avatar
Alexandre Delaunay committed
558
                       'get_hateoas'       => true,
559
                       'get_sha1'          => false,
560
                       'with_devices'   => false,
Alexandre Delaunay's avatar
Alexandre Delaunay committed
561
562
563
564
565
566
567
568
569
570
571
                       'with_disks'        => false,
                       'with_softwares'    => false,
                       'with_connections'  => false,
                       'with_networkports' => false,
                       'with_infocoms'     => false,
                       'with_contracts'    => false,
                       'with_documents'    => false,
                       'with_tickets'      => false,
                       'with_problems'     => false,
                       'with_changes'      => false,
                       'with_notes'        => false,
572
573
574
                       'with_logs'         => false,
                       'add_keys_names'    => [],
      ];
Alexandre Delaunay's avatar
Alexandre Delaunay committed
575
576
577
578
579
580
581
582
583
584
      $params = array_merge($default, $params);

      $item = new $itemtype;
      if (!$item->getFromDB($id)) {
         return $this->messageNotfoundError();
      }
      if (!$item->can($id, READ)) {
         return $this->messageRightError();
      }

Anael Mobilia's avatar
PHPdoc    
Anael Mobilia committed
585
      $fields = $item->fields;
586

587
588
589
      // avoid disclosure of critical fields
      $item::unsetUndisclosedFields($fields);

Alexandre Delaunay's avatar
Alexandre Delaunay committed
590
591
      // retrieve devices
      if (isset($params['with_devices'])
yllen's avatar
CS    
yllen committed
592
593
          && $params['with_devices']
          && in_array($itemtype, Item_Devices::getConcernedItems())) {
594
         $all_devices = [];
Alexandre Delaunay's avatar
Alexandre Delaunay committed
595
         foreach (Item_Devices::getItemAffinities($item->getType()) as $device_type) {
596
            $found_devices = getAllDataFromTable(
597
598
599
600
601
602
603
               $device_type::getTable(), [
                  'items_id'     => $item->getID(),
                  'itemtype'     => $item->getType(),
                  'is_deleted'   => 0
               ],
               true
            );
Alexandre Delaunay's avatar
Alexandre Delaunay committed
604

Cédric Anne's avatar
Cédric Anne committed
605
            foreach ($found_devices as &$device) {
Alexandre Delaunay's avatar
Alexandre Delaunay committed
606
607
608
609
610
611
612
613
614
615
616
617
618
619
               unset($device['items_id']);
               unset($device['itemtype']);
               unset($device['is_deleted']);
            }

            if (!empty($found_devices)) {
               $all_devices[$device_type] = $found_devices;
            }
         }
         $fields['_devices'] = $all_devices;
      }

      // retrieve computer disks
      if (isset($params['with_disks'])
yllen's avatar
CS    
yllen committed
620
          && $params['with_disks']
Johan Cwiklinski's avatar
Johan Cwiklinski committed
621
          && in_array($itemtype, $CFG_GLPI['itemdeviceharddrive_types'])) {
Alexandre Delaunay's avatar
Alexandre Delaunay committed
622
         // build query to retrive filesystems
Johan Cwiklinski's avatar
Johan Cwiklinski committed
623
624
625
626
627
628
         $fs_iterator = $DB->request([
            'SELECT'    => [
               'glpi_filesystems.name AS fsname',
               'glpi_items_disks.*'
            ],
            'FROM'      => 'glpi_items_disks',
cconard96's avatar
cconard96 committed
629
            'LEFT JOIN'  => [
Johan Cwiklinski's avatar
Johan Cwiklinski committed
630
631
632
633
634
635
636
637
638
639
640
641
642
               'glpi_filesystems' => [
                  'ON' => [
                     'glpi_items_disks'   => 'filesystems_id',
                     'glpi_filesystems'   => 'id'
                  ]
               ]
            ],
            'WHERE'     => [
               'items_id'     => $id,
               'itemtype'     => $itemtype,
               'is_deleted'   => 0
            ]
         ]);
643
         $fields['_disks'] = [];
Johan Cwiklinski's avatar
Johan Cwiklinski committed
644
645
646
647
         while ($data = $fs_iterator->next()) {
            unset($data['items_id']);
            unset($data['is_deleted']);
            $fields['_disks'][] = ['name' => $data];
Alexandre Delaunay's avatar
Alexandre Delaunay committed
648
649
650
651
652
         }
      }

      // retrieve computer softwares
      if (isset($params['with_softwares'])
cconard96's avatar
cconard96 committed
653
654
            && $params['with_softwares']
            && in_array($itemtype, $CFG_GLPI['software_types'])) {
655
         $fields['_softwares'] = [];
Alexandre Delaunay's avatar
Alexandre Delaunay committed
656
         if (!Software::canView()) {
657
            $fields['_softwares'] = $this->arrayRightError();
Alexandre Delaunay's avatar
Alexandre Delaunay committed
658
         } else {
Johan Cwiklinski's avatar
Johan Cwiklinski committed
659
660
661
662
663
            $soft_iterator = $DB->request([
               'SELECT'    => [
                  'glpi_softwares.softwarecategories_id',
                  'glpi_softwares.id AS softwares_id',
                  'glpi_softwareversions.id AS softwareversions_id',
cconard96's avatar
cconard96 committed
664
                  'glpi_items_softwareversions.is_dynamic',
Johan Cwiklinski's avatar
Johan Cwiklinski committed
665
666
667
                  'glpi_softwareversions.states_id',
                  'glpi_softwares.is_valid'
               ],
cconard96's avatar
cconard96 committed
668
               'FROM'      => 'glpi_items_softwareversions',
Johan Cwiklinski's avatar
Johan Cwiklinski committed
669
670
671
               'LEFT JOIN' => [
                  'glpi_softwareversions' => [
                     'ON' => [
cconard96's avatar
cconard96 committed
672
673
                        'glpi_items_softwareversions' => 'softwareversions_id',
                        'glpi_softwareversions'       => 'id'
Johan Cwiklinski's avatar
Johan Cwiklinski committed
674
675
676
677
678
679
680
681
682
683
                     ]
                  ],
                  'glpi_softwares'        => [
                     'ON' => [
                        'glpi_softwareversions' => 'softwares_id',
                        'glpi_softwares'        => 'id'
                     ]
                  ]
               ],
               'WHERE'     => [
cconard96's avatar
cconard96 committed
684
685
686
                  'glpi_items_softwareversions.items_id'   => $id,
                  'glpi_items_softwareversions.itemtype'   => $itemtype,
                  'glpi_items_softwareversions.is_deleted' => 0
Johan Cwiklinski's avatar
Johan Cwiklinski committed
687
688
689
690
691
692
693
694
               ],
               'ORDERBY'   => [
                  'glpi_softwares.name',
                  'glpi_softwareversions.name'
               ]
            ]);
            while ($data = $soft_iterator->next()) {
               $fields['_softwares'][] = $data;
Alexandre Delaunay's avatar
Alexandre Delaunay committed
695
696
697
698
699
700
            }
         }
      }

      // retrieve item connections
      if (isset($params['with_connections'])
yllen's avatar
CS    
yllen committed
701
702
          && $params['with_connections']
          && $itemtype == "Computer") {
703
         $fields['_connections'] = [];
Alexandre Delaunay's avatar
Alexandre Delaunay committed
704
705
706
         foreach ($CFG_GLPI["directconnect_types"] as $connect_type) {
            $connect_item = new $connect_type();
            if ($connect_item->canView()) {
Johan Cwiklinski's avatar
Johan Cwiklinski committed
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
               $connect_table = getTableForItemType($connect_type);
               $iterator = $DB->request([
                  'SELECT'    => [
                     'glpi_computers_items.id AS assoc_id',
                     'glpi_computers_items.computers_id AS assoc_computers_id',
                     'glpi_computers_items.itemtype AS assoc_itemtype',
                     'glpi_computers_items.items_id AS assoc_items_id',
                     'glpi_computers_items.is_dynamic AS assoc_is_dynamic',
                     "$connect_table.*"
                  ],
                  'FROM'      => 'glpi_computers_items',
                  'LEFT JOIN' => [
                     $connect_table => [
                        'ON' => [
                           'glpi_computers_items'  => 'items_id',
                           $connect_table          => 'id'
                        ]
                     ]
                  ],
                  'WHERE'     => [
                     'computers_id'                      => $id,
                     'itemtype'                          => $connect_type,
                     'glpi_computers_items.is_deleted'   => 0
                  ]
               ]);
               while ($data = $iterator->next()) {
                  $fields['_connections'][$connect_type][] = $data;
Alexandre Delaunay's avatar
Alexandre Delaunay committed
734
735
736
737
738
739
740
               }
            }
         }
      }

      // retrieve item networkports
      if (isset($params['with_networkports'])
yllen's avatar
CS    
yllen committed
741
          && $params['with_networkports']) {
742
         $fields['_networkports'] = [];
Alexandre Delaunay's avatar
Alexandre Delaunay committed
743
         if (!NetworkEquipment::canView()) {
744
            $fields['_networkports'] = $this->arrayRightError();
Alexandre Delaunay's avatar
Alexandre Delaunay committed
745
746
         } else {
            foreach (NetworkPort::getNetworkPortInstantiations() as $networkport_type) {
747
               $netport_table = $networkport_type::getTable();
Johan Cwiklinski's avatar
Johan Cwiklinski committed
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
               $netp_iterator = $DB->request([
                  'SELECT'    => [
                     'netp.id AS netport_id',
                     'netp.entities_id',
                     'netp.is_recursive',
                     'netp.logical_number',
                     'netp.name',
                     'netp.mac',
                     'netp.comment',
                     'netp.is_dynamic',
                     'netp_subtable.*'
                  ],
                  'FROM'      => 'glpi_networkports AS netp',
                  'LEFT JOIN' => [
                     "$netport_table AS netp_subtable" => [
                        'ON' => [
                           'netp_subtable'   => 'networkports_id',
                           'netp'            => 'id'
                        ]
                     ]
                  ],
                  'WHERE'     => [
                     'netp.instantiation_type'  => $networkport_type,
                     'netp.items_id'            => $id,
                     'netp.itemtype'            => $itemtype,
                     'netp.is_deleted'          => 0
                  ]
               ]);

               while ($data = $netp_iterator->next()) {
                  if (isset($data['netport_id'])) {
                     // append network name
                     $concat_expr = new QueryExpression(
781
782
                        "GROUP_CONCAT(CONCAT(".$DB->quoteName('ipadr.id').", ".$DB->quoteValue(Search::SHORTSEP)." , ".$DB->quoteName('ipadr.name').")
                        SEPARATOR ".$DB->quoteValue(Search::LONGSEP).") AS ".$DB->quoteName('ipadresses')
Johan Cwiklinski's avatar
Johan Cwiklinski committed
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
                     );
                     $netn_iterator = $DB->request([
                        'SELECT'    => [
                           $concat_expr,
                           'netn.id AS networknames_id',
                           'netn.name AS networkname',
                           'netn.fqdns_id',
                           'fqdn.name AS fqdn_name',
                           'fqdn.fqdn'
                        ],
                        'FROM'      => [
                           'glpi_networknames AS netn'
                        ],
                        'LEFT JOIN' => [
                           'glpi_ipaddresses AS ipadr'               => [
                              'ON' => [
                                 'ipadr'  => 'items_id',
800
801
802
803
                                 'netn'   => 'id',
                                 [
                                    'AND' => ['ipadr.itemtype' => 'NetworkName']
                                 ]
Johan Cwiklinski's avatar
Johan Cwiklinski committed
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
                              ]
                           ],
                           'glpi_fqdns AS fqdn'                      => [
                              'ON' => [
                                 'fqdn'   => 'id',
                                 'netn'   => 'fqdns_id'
                              ]
                           ],
                           'glpi_ipaddresses_ipnetworks AS ipadnet'  => [
                              'ON' => [
                                 'ipadnet'   => 'ipaddresses_id',
                                 'ipadr'     => 'id'
                              ]
                           ],
                           'glpi_ipnetworks AS ipnet'                => [
                              'ON' => [
                                 'ipnet'     => 'id',
                                 'ipadnet'   => 'ipnetworks_id'
                              ]
                           ]
                        ],
                        'WHERE'     => [
                           'netn.itemtype'   => 'NetworkPort',
                           'netn.items_id'   => $data['netport_id']
                        ],
                        'GROUPBY'   => [
                           'netn.id',
                           'netn.name',
                           'netn.fqdns_id',
                           'fqdn.name',
                           'fqdn.fqdn'
                        ]
                     ]);

                     if (count($netn_iterator)) {
                        $data_netn = $netn_iterator->next();

                        $raw_ipadresses = explode(Search::LONGSEP, $data_netn['ipadresses']);
                        $ipadresses = [];
                        foreach ($raw_ipadresses as $ipadress) {
                           $ipadress = explode(Search::SHORTSEP, $ipadress);

                           //find ip network attached to these ip
                           $ipnetworks = [];
                           $ipnet_iterator = $DB->request([
                              'SELECT'       => [
                                 'ipnet.id',
                                 'ipnet.completename',
                                 'ipnet.name',
                                 'ipnet.address',
                                 'ipnet.netmask',
                                 'ipnet.gateway',
                                 'ipnet.ipnetworks_id',
                                 'ipnet.comment'
                              ],
                              'FROM'         => 'glpi_ipnetworks AS ipnet',
                              'INNER JOIN'   => [
                                 'glpi_ipaddresses_ipnetworks AS ipadnet' => [
                                    'ON' => [
                                       'ipadnet'   => 'ipnetworks_id',
                                       'ipnet'     => 'id'
                                    ]
                                 ]
                              ],
                              'WHERE'        => [
Johan Cwiklinski's avatar
Johan Cwiklinski committed
869
                                 'ipadnet.ipaddresses_id'  => $ipadress[0]
Johan Cwiklinski's avatar
Johan Cwiklinski committed
870
871
872
873
                              ]
                           ]);
                           while ($data_ipnet = $ipnet_iterator->next()) {
                              $ipnetworks[] = $data_ipnet;
874
875
                           }

Johan Cwiklinski's avatar
Johan Cwiklinski committed
876
877
878
879
                           $ipadresses[] = [
                              'id'        => $ipadress[0],
                              'name'      => $ipadress[1],
                              'IPNetwork' => $ipnetworks
880
                           ];
881
882
                        }

Johan Cwiklinski's avatar
Johan Cwiklinski committed
883
884
885
886
887
888
889
890
891
892
893
894
                        $data['NetworkName'] = [
                           'id'         => $data_netn['networknames_id'],
                           'name'       => $data_netn['networkname'],
                           'fqdns_id'   => $data_netn['fqdns_id'],
                           'FQDN'       => [
                              'id'   => $data_netn['fqdns_id'],
                              'name' => $data_netn['fqdn_name'],
                              'fqdn' => $data_netn['fqdn']
                           ],
                           'IPAddress' => $ipadresses
                        ];
                     }
Alexandre Delaunay's avatar
Alexandre Delaunay committed
895
                  }
Johan Cwiklinski's avatar
Johan Cwiklinski committed
896
897

                  $fields['_networkports'][$networkport_type][] = $data;
Alexandre Delaunay's avatar
Alexandre Delaunay committed
898
899
900
901
902
903
904
               }
            }
         }
      }

      // retrieve item infocoms
      if (isset($params['with_infocoms'])
yllen's avatar
CS    
yllen committed
905
          && $params['with_infocoms']) {
906
         $fields['_infocoms'] = [];
Alexandre Delaunay's avatar
Alexandre Delaunay committed
907
         if (!Infocom::canView()) {
908
            $fields['_infocoms'] = $this->arrayRightError();
Alexandre Delaunay's avatar
Alexandre Delaunay committed
909
910
911
912
913
914
915
916
917
918
         } else {
            $ic = new Infocom();
            if ($ic->getFromDBforDevice($itemtype, $id)) {
               $fields['_infocoms'] = $ic->fields;
            }
         }
      }

      // retrieve item contracts
      if (isset($params['with_contracts'])
yllen's avatar
CS    
yllen committed
919
          && $params['with_contracts']) {
920
         $fields['_contracts'] = [];
Alexandre Delaunay's avatar
Alexandre Delaunay committed
921
         if (!Contract::canView()) {
922
            $fields['_contracts'] = $this->arrayRightError();
Alexandre Delaunay's avatar
Alexandre Delaunay committed
923
         } else {
Johan Cwiklinski's avatar
Johan Cwiklinski committed
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
            $iterator = $DB->request([
               'SELECT'    => ['glpi_contracts_items.*'],
               'FROM'      => 'glpi_contracts_items',
               'LEFT JOIN' => [
                  'glpi_contracts'  => [
                     'ON' => [
                        'glpi_contracts_items'  => 'contracts_id',
                        'glpi_contracts'        => 'id'
                     ]
                  ],
                  'glpi_entities'   => [
                     'ON' => [
                        'glpi_contracts_items'  => 'entities_id',
                        'glpi_entities'         => 'id'
                     ]
                  ]
               ],
               'WHERE'     => [
                  'glpi_contracts_items.items_id'  => $id,
                  'glpi_contracts_items.itemtype'  => $itemtype
               ] + getEntitiesRestrictCriteria('glpi_contracts', '', '', true),
               'ORDERBY'   => 'glpi_contracts.name'
            ]);
            while ($data = $iterator->next()) {
               $fields['_contracts'][] = $data;
Alexandre Delaunay's avatar
Alexandre Delaunay committed
949
950
951
952
            }
         }
      }

953
      // retrieve item documents
Alexandre Delaunay's avatar
Alexandre Delaunay committed
954
      if (isset($params['with_documents'])
yllen's avatar
CS    
yllen committed
955
          && $params['with_documents']) {
956
         $fields['_documents'] = [];
957
         if (!($item instanceof CommonITILObject)
Alexandre Delaunay's avatar
Alexandre Delaunay committed
958
959
960
             && $itemtype != 'KnowbaseItem'
             && $itemtype != 'Reminder'
             && !Document::canView()) {
961
            $fields['_documents'] = $this->arrayRightError();
Alexandre Delaunay's avatar
Alexandre Delaunay committed
962
         } else {
963
964
965
966
967
968
969
970
971
972
            $doc_criteria = [
               'glpi_documents_items.items_id'  => $id,
               'glpi_documents_items.itemtype'  => $itemtype
            ];
            if ($item instanceof CommonITILObject) {
               $doc_criteria = [
                  $item->getAssociatedDocumentsCriteria(),
                  'timeline_position' => ['>', CommonITILObject::NO_TIMELINE], // skip inlined images
               ];
            }
Johan Cwiklinski's avatar
Johan Cwiklinski committed
973
974
975
            $doc_iterator = $DB->request([
               'SELECT'    => [
                  'glpi_documents_items.id AS assocID',
976
                  'glpi_documents_items.date_creation AS assocdate',
Johan Cwiklinski's avatar
Johan Cwiklinski committed
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
                  'glpi_entities.id AS entityID',
                  'glpi_entities.completename AS entity',
                  'glpi_documentcategories.completename AS headings',
                  'glpi_documents.*'
               ],
               'FROM'      => 'glpi_documents_items',
               'LEFT JOIN' => [
                  'glpi_documents'           => [
                     'ON' => [
                        'glpi_documents_items'  => 'documents_id',
                        'glpi_documents'        => 'id'
                     ]
                  ],
                  'glpi_entities'            => [
                     'ON' => [
                        'glpi_documents'  => 'entities_id',
                        'glpi_entities'   => 'id'
                     ]
                  ],
                  'glpi_documentcategories'  => [
                     'ON' => [
                        'glpi_documents'           => 'documentcategories_id',
                        'glpi_documentcategories'  => 'id'
                     ]