api.class.php 106 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
namespace Glpi\Api;

use APIClient;
use Auth;
use Change;
Adrien Clairembault's avatar
Adrien Clairembault committed
43
use CommonDBTM;
44
use CommonDevice;
45
use CommonITILObject;
46
47
48
49
use Config;
use Contract;
use Document;
use Dropdown;
50
use Glpi\Toolbox\Sanitizer;
51
52
53
54
use Html;
use Infocom;
use Item_Devices;
use Log;
Adrien Clairembault's avatar
Adrien Clairembault committed
55
use MassiveAction;
56
57
58
59
60
61
62
63
64
65
use Michelf\MarkdownExtra;
use NetworkEquipment;
use NetworkPort;
use Notepad;
use Problem;
use QueryExpression;
use SavedSearch;
use Search;
use Session;
use Software;
Adrien Clairembault's avatar
Adrien Clairembault committed
66
use Symfony\Component\DomCrawler\Crawler;
67
68
69
use Ticket;
use Toolbox;
use User;
70

71
abstract class API {
Alexandre Delaunay's avatar
Alexandre Delaunay committed
72
73
74
75
76

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

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

Anael Mobilia's avatar
PHPdoc    
Anael Mobilia committed
85
86
87
88
89
90
   /**
    * 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
91
92
   abstract public function call();

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

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

113
114
115
116
117
118
   /**
    * 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
119

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

131
132
133
134
135
136
137
138
139
      // 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
140
141
142
143
144
145
146
      // 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
147
      $_SESSION["MESSAGE_AFTER_REDIRECT"] = [];
Alexandre Delaunay's avatar
Alexandre Delaunay committed
148
149
150
151
152
153
154
155

      // 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
156
      $this->iptxt = Toolbox::getRemoteIpAddress();
Alexandre Delaunay's avatar
Alexandre Delaunay committed
157
158
159
160
      $this->ipnum = (strstr($this->iptxt, ':')===false ? ip2long($this->iptxt) : '');

      // check ip access
      $apiclient = new APIClient;
161
      $where_ip = [];
Alexandre Delaunay's avatar
Alexandre Delaunay committed
162
      if ($this->ipnum) {
163
164
165
166
         $where_ip = [
            'OR' => [
               'ipv4_range_start' => null,
               [
Cédric Anne's avatar
Cédric Anne committed
167
168
                  'ipv4_range_start'   => ['<=', $this->ipnum],
                  'ipv4_range_end'     => ['>=', $this->ipnum]
169
170
171
               ]
            ]
         ];
Alexandre Delaunay's avatar
Alexandre Delaunay committed
172
      } else {
173
174
175
176
177
178
         $where_ip = [
            'OR' => [
               ['ipv6'  => null],
               ['ipv6'  => $this->iptxt]
            ]
         ];
Alexandre Delaunay's avatar
Alexandre Delaunay committed
179
      }
180
      $found_clients = $apiclient->find(['is_active' => 1] + $where_ip);
Alexandre Delaunay's avatar
Alexandre Delaunay committed
181
      if (count($found_clients) <= 0) {
Johan Cwiklinski's avatar
Johan Cwiklinski committed
182
         $this->returnError(__("There isn't an active API client matching your IP address in the configuration").
Alexandre Delaunay's avatar
Alexandre Delaunay committed
183
184
185
186
187
188
189
190
                            " (".$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
191
192
193
194
195
196
197
   /**
    * 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
198
199
200
201
202
   protected function cors($verb = 'GET') {
      if (isset($_SERVER['HTTP_ORIGIN'])) {
         header("Access-Control-Allow-Origin: *");
      }

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

207
      if ($this->verb == "OPTIONS") {
Alexandre Delaunay's avatar
Alexandre Delaunay committed
208
209
210
211
212
213
         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: ".
214
                   "origin, content-type, accept, session-token, authorization");
Alexandre Delaunay's avatar
Alexandre Delaunay committed
215
216
217
218
219
220
221
222
223
         }
         exit(0);
      }
   }


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

Alexandre Delaunay's avatar
Alexandre Delaunay committed
234
235
236
237
238
239
240
241
242
      $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
243
         $this->returnError(__("parameter(s) login, password or user_token are missing"), 400,
Alexandre Delaunay's avatar
Alexandre Delaunay committed
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
                            "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']) {
263
         $this->returnError(__("usage of initSession resource with credentials is disabled"), 400,
264
                            "ERROR_LOGIN_WITH_CREDENTIALS_DISABLED", false);
Alexandre Delaunay's avatar
Alexandre Delaunay committed
265
266
      }

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

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

      // stop session and return session key
      session_write_close();
283
284
285
286
287
288
289
290
291
      $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
292
293
294
295
296
297
298
299
   }


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

Alexandre Delaunay's avatar
Alexandre Delaunay committed
303
304
305
306
307
308
309
310
      $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
311
312
313
    *
    * @return void
    */
Alexandre Delaunay's avatar
Alexandre Delaunay committed
314
   protected function retrieveSession() {
yllen's avatar
CS    
yllen committed
315

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

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

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

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

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

      if (!isset($params['is_recursive'])) {
         $params['is_recursive'] = false;
356
357
358
359
360
361
      } 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
362
363
      }

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


   /**
Anael Mobilia's avatar
PHPdoc    
Anael Mobilia committed
369
    * Return all the possible entity of the current logged user (and for current active profile)
Alexandre Delaunay's avatar
Alexandre Delaunay committed
370
    *
371
372
373
    * @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
374
    * @return array of entities (with id and name)
Anael Mobilia's avatar
PHPdoc    
Anael Mobilia committed
375
    */
376
   protected function getMyEntities($params = []) {
yllen's avatar
CS    
yllen committed
377

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

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

384
      $myentities = [];
Alexandre Delaunay's avatar
Alexandre Delaunay committed
385
      foreach ($_SESSION['glpiactiveprofile']['entities'] as $entity) {
386
387
388
389
390
391
392
393
394
395
396
397
398
         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
399
      }
400
      return ['myentities' => $myentities];
Alexandre Delaunay's avatar
Alexandre Delaunay committed
401
402
403
   }


yllen's avatar
CS    
yllen committed
404
405


Alexandre Delaunay's avatar
Alexandre Delaunay committed
406
407
408
409
410
411
412
   /**
    * 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
413
    */
Alexandre Delaunay's avatar
Alexandre Delaunay committed
414
   protected function getActiveEntities() {
yllen's avatar
CS    
yllen committed
415

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

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

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

   }


yllen's avatar
CS    
yllen committed
431
432


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

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

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

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

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


yllen's avatar
CS    
yllen committed
458
459


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

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

469
      $myprofiles = [];
Anael Mobilia's avatar
Anael Mobilia committed
470
      foreach ($_SESSION['glpiprofiles'] as $profiles_id => $profile) {
471
         // append if of the profile into values
472
473
474
475
476
477
478
479
         $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;
      }
480
      return ['myprofiles' => $myprofiles];
Alexandre Delaunay's avatar
Alexandre Delaunay committed
481
482
483
   }


yllen's avatar
CS    
yllen committed
484
485


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

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


yllen's avatar
CS    
yllen committed
498
499


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

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

yllen's avatar
CS    
yllen committed
511
512


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

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


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

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

      // default params
558
      $default = ['expand_dropdowns'  => false,
Alexandre Delaunay's avatar
Alexandre Delaunay committed
559
                       'get_hateoas'       => true,
560
                       'get_sha1'          => false,
561
                       'with_devices'   => false,
Alexandre Delaunay's avatar
Alexandre Delaunay committed
562
563
564
565
566
567
568
569
570
571
572
                       '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,
573
574
575
                       'with_logs'         => false,
                       'add_keys_names'    => [],
      ];
Alexandre Delaunay's avatar
Alexandre Delaunay committed
576
577
578
579
580
581
582
583
584
585
      $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
586
      $fields = $item->fields;
587

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

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

Cédric Anne's avatar
Cédric Anne committed
606
            foreach ($found_devices as &$device) {
Alexandre Delaunay's avatar
Alexandre Delaunay committed
607
608
609
610
611
612
613
614
615
616
617
618
619
620
               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
621
          && $params['with_disks']
Johan Cwiklinski's avatar
Johan Cwiklinski committed
622
          && in_array($itemtype, $CFG_GLPI['itemdeviceharddrive_types'])) {
Alexandre Delaunay's avatar
Alexandre Delaunay committed
623
         // build query to retrive filesystems
Johan Cwiklinski's avatar
Johan Cwiklinski committed
624
625
626
627
628
629
         $fs_iterator = $DB->request([
            'SELECT'    => [
               'glpi_filesystems.name AS fsname',
               'glpi_items_disks.*'
            ],
            'FROM'      => 'glpi_items_disks',
cconard96's avatar
cconard96 committed
630
            'LEFT JOIN'  => [
Johan Cwiklinski's avatar
Johan Cwiklinski committed
631
632
633
634
635
636
637
638
639
640
641
642
643
               'glpi_filesystems' => [
                  'ON' => [
                     'glpi_items_disks'   => 'filesystems_id',
                     'glpi_filesystems'   => 'id'
                  ]
               ]
            ],
            'WHERE'     => [
               'items_id'     => $id,
               'itemtype'     => $itemtype,
               'is_deleted'   => 0
            ]
         ]);
644
         $fields['_disks'] = [];
Johan Cwiklinski's avatar
Johan Cwiklinski committed
645
646
647
648
         while ($data = $fs_iterator->next()) {
            unset($data['items_id']);
            unset($data['is_deleted']);
            $fields['_disks'][] = ['name' => $data];
Alexandre Delaunay's avatar
Alexandre Delaunay committed
649
650
651
652
653
         }
      }

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

      // retrieve item connections
      if (isset($params['with_connections'])
yllen's avatar
CS    
yllen committed
702
703
          && $params['with_connections']
          && $itemtype == "Computer") {
704
         $fields['_connections'] = [];
Alexandre Delaunay's avatar
Alexandre Delaunay committed
705
706
707
         foreach ($CFG_GLPI["directconnect_types"] as $connect_type) {
            $connect_item = new $connect_type();
            if ($connect_item->canView()) {
Johan Cwiklinski's avatar
Johan Cwiklinski committed
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
734
               $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
735
736
737
738
739
740
               }
            }
         }
      }

      // retrieve item networkports
741
742
      if (isset($params['with_networkports']) && $params['with_networkports']) {
         $fields['_networkports'] = $this->getNetworkPorts($id, $itemtype);
Alexandre Delaunay's avatar
Alexandre Delaunay committed
743
744
745
746
      }

      // retrieve item infocoms
      if (isset($params['with_infocoms'])
yllen's avatar
CS    
yllen committed
747
          && $params['with_infocoms']) {
748
         $fields['_infocoms'] = [];
Alexandre Delaunay's avatar
Alexandre Delaunay committed
749
         if (!Infocom::canView()) {
750
            $fields['_infocoms'] = $this->arrayRightError();
Alexandre Delaunay's avatar
Alexandre Delaunay committed
751
752
753
754
755
756
757
758
759
760
         } 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
761
          && $params['with_contracts']) {
762
         $fields['_contracts'] = [];
Alexandre Delaunay's avatar
Alexandre Delaunay committed
763
         if (!Contract::canView()) {
764
            $fields['_contracts'] = $this->arrayRightError();
Alexandre Delaunay's avatar
Alexandre Delaunay committed
765
         } else {
Johan Cwiklinski's avatar
Johan Cwiklinski committed
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
            $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
791
792
793
794
            }
         }
      }

795
      // retrieve item documents
Alexandre Delaunay's avatar
Alexandre Delaunay committed
796
      if (isset($params['with_documents'])
yllen's avatar
CS    
yllen committed
797
          && $params['with_documents']) {
798
         $fields['_documents'] = [];
799
         if (!($item instanceof CommonITILObject)
Alexandre Delaunay's avatar
Alexandre Delaunay committed
800
801
802
             && $itemtype != 'KnowbaseItem'
             && $itemtype != 'Reminder'
             && !Document::canView()) {
803
            $fields['_documents'] = $this->arrayRightError();
Alexandre Delaunay's avatar
Alexandre Delaunay committed
804
         } else {
805
806
807
808
809
810
811
812
813
814
            $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
815
816
817
            $doc_iterator = $DB->request([
               'SELECT'    => [
                  'glpi_documents_items.id AS assocID',
818
                  'glpi_documents_items.date_creation AS assocdate',
Johan Cwiklinski's avatar
Johan Cwiklinski committed
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
                  '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'
                     ]
                  ]
               ],
845
               'WHERE'     => $doc_criteria,
Johan Cwiklinski's avatar
Johan Cwiklinski committed
846
847
848
            ]);
            while ($data = $doc_iterator->next()) {
               $fields['_documents'][] = $data;
Alexandre Delaunay's avatar
Alexandre Delaunay committed
849
850
851
852
853
854
            }
         }
      }

      // retrieve item tickets
      if (isset($params['with_tickets'])
yllen's avatar
CS    
yllen committed
855
          && $params['with_tickets']) {
856
         $fields['_tickets'] = [];
Alexandre Delaunay's avatar
Alexandre Delaunay committed
857
         if (!Ticket::canView()) {
858
            $fields['_tickets'] = $this->arrayRightError();
Alexandre Delaunay's avatar
Alexandre Delaunay committed
859
         } else {
860
861
862
863
864
865
866
867
            $criteria = Ticket::getCommonCriteria();
            $criteria['WHERE'] = [
               'glpi_items_tickets.items_id' => $id,
               'glpi_items_tickets.itemtype' => $itemtype
            ] + getEntitiesRestrictCriteria(Ticket::getTable());
            $iterator = $DB->request($criteria);
            while ($data = $iterator->next()) {
               $fields['_tickets'][] = $data;
Alexandre Delaunay's avatar
Alexandre Delaunay committed
868
869
870
871
872
873
            }
         }
      }

      // retrieve item problems
      if (isset($params['with_problems'])
yllen's avatar
CS    
yllen committed
874
          && $params['with_problems']) {
875
         $fields['_problems'] = [];
Alexandre Delaunay's avatar
Alexandre Delaunay committed
876
         if (!Problem::canView()) {
877
            $fields['_problems'] = $this->arrayRightError();
Alexandre Delaunay's avatar
Alexandre Delaunay committed
878
         } else {
879
880
881
882
883
884
885
886
            $criteria = Problem::getCommonCriteria();
            $criteria['WHERE'] = [
               'glpi_items_problems.items_id' => $id,
               'glpi_items_problems.itemtype' => $itemtype
            ] + getEntitiesRestrictCriteria(Problem::getTable());
            $iterator = $DB->request($criteria);
            while ($data = $iterator->next()) {
               $fields['_problems'][] = $data;
Alexandre Delaunay's avatar
Alexandre Delaunay committed
887
888
889
890
891
892
            }
         }
      }

      // retrieve item changes
      if (isset($params['with_changes'])
yllen's avatar
CS    
yllen committed
893
          && $params['with_changes']) {
894
         $fields['_changes'] = [];
Alexandre Delaunay's avatar
Alexandre Delaunay committed
895
         if (!Change::canView()) {
896
            $fields['_changes'] = $this->arrayRightError();
Alexandre Delaunay's avatar
Alexandre Delaunay committed
897
         } else {
898
899
900
901
902
903
904
905
            $criteria = Change::getCommonCriteria();
            $criteria['WHERE'] = [
               'glpi_changes_items.items_id' => $id,
               'glpi_changes_items.itemtype' => $itemtype
            ] + getEntitiesRestrictCriteria(Change::getTable());
            $iterator = $DB->request($criteria);
            while ($data = $iterator->next()) {
               $fields['_changes'][] = $data;
Alexandre Delaunay's avatar
Alexandre Delaunay committed
906
907
908
909
910
911
            }
         }
      }

      // retrieve item notes
      if (isset($params['with_notes'])
yllen's avatar
CS    
yllen committed
912
          && $params['with_notes']) {
913
         $fields['_notes'] = [];
Alexandre Delaunay's avatar
Alexandre Delaunay committed
914
         if (!Session::haveRight($itemtype::$rightname, READNOTE)) {
915
            $fields['_notes'] = $this->arrayRightError();
Alexandre Delaunay's avatar
Alexandre Delaunay committed
916
         } else {
917
            $fields['_notes'] = Notepad::getAllForItem($item);
Alexandre Delaunay's avatar
Alexandre Delaunay committed
918
919
920
921
922
         }
      }

      // retrieve item logs
      if (isset($params['with_logs'])
yllen's avatar
CS    
yllen committed
923
          && $params['with_logs']) {
924
         $fields['_logs'] = [];
Alexandre Delaunay's avatar
Alexandre Delaunay committed
925
         if (!Session::haveRight($itemtype::$rightname, READNOTE)) {
926
            $fields['_logs'] = $this->arrayRightError();
Alexandre Delaunay's avatar
Alexandre Delaunay committed
927
         } else {
928
            $fields['_logs'] = getAllDataFromTable(
929
930
931
932
933
               "glpi_logs", [
                  'items_id'  => $item->getID(),
                  'itemtype'  => $item->getType()
               ]
            );
Alexandre Delaunay's avatar
Alexandre Delaunay committed
934
935
936
937
938
939
940
941
942
         }
      }

      // expand dropdown (retrieve name of dropdowns) and get hateoas from foreign keys
      $fields = self::parseDropdowns($fields, $params);

      // get hateoas from children
      if ($params['get_hateoas']) {
         $hclasses = self::getHatoasClasses($itemtype);
Anael Mobilia's avatar
Anael Mobilia committed
943
         foreach ($hclasses as $hclass) {
944
945
            $fields['links'][] = ['rel'  => $hclass,
                                       'href' => self::$api_url."/$itemtype/".$item->getID()."/$hclass/"];
Alexandre Delaunay's avatar
Alexandre Delaunay committed
946
947
948
         }
      }

949
950
      // get sha1 footprint if needed
      if ($params['get_sha1']) {
951
952
953
         $fields = sha1(json_encode($fields, JSON_UNESCAPED_UNICODE
                                             | JSON_UNESCAPED_SLASHES
                                             | JSON_NUMERIC_CHECK));
954
955
      }

956
      if (count($params['add_keys_names']) > 0) {
957
         $fields["_keys_names"] = $this->getFriendlyNames(
958
959
960
961
962
963
            $fields,
            $params,
            $itemtype
         );
      }

964
965
966
967
968
969
970
971
      // Convert fields to the format expected by the deprecated type
      if ($this->isDeprecated()) {
         $fields = $this->deprecated_item->mapCurrentToDeprecatedFields($fields);
         $fields["links"] = $this->deprecated_item->mapCurrentToDeprecatedHateoas(
            $fields["links"] ?? []
         );
      }

Alexandre Delaunay's avatar
Alexandre Delaunay committed
972
973
974
      return $fields;
   }

yllen's avatar
CS    
yllen committed
975
976


Alexandre Delaunay's avatar
Alexandre Delaunay committed
977
978
   /**
    * Fill a sub array with a right error
Anael Mobilia's avatar
PHPdoc    
Anael Mobilia committed
979
980
981
    *
    * @return array
    */
Alexandre Delaunay's avatar
Alexandre Delaunay committed
982
   protected function arrayRightError() {
yllen's avatar
CS    
yllen committed
983

984
985
      return ['error'   => 401,
                   'message' => __("You don't have permission to perform this action.")];
Alexandre Delaunay's avatar
Alexandre Delaunay committed
986
987
988
989
   }



yllen's avatar
CS    
yllen committed
990
991


Alexandre Delaunay's avatar
Alexandre Delaunay committed
992
993
994
   /**
    * Return a collection of rows of the desired itemtype
    *
Anael Mobilia's avatar
PHPdoc    
Anael Mobilia committed
995
996
    * @param string  $itemtype   itemtype (class) of object
    * @param array   $params     with theses options :
Alexandre Delaunay's avatar
Alexandre Delaunay committed
997
998
999
1000
    * - '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
1001
1002
1003
    * - '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)
1004
    * - 'is_deleted'       (default: false): show trashbin. Optionnal
1005
    * - 'add_keys_names'   (default: []): insert raw name(s) for given itemtype(s) and fkey(s)
1006
    * - 'with_networkports'(default: false): Retrieve all network connections and advanced informations. Optional.
Anael Mobilia's avatar
PHPdoc    
Anael Mobilia committed
1007
1008
1009
    * @param integer $totalcount 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)
Alexandre Delaunay's avatar
Alexandre Delaunay committed
1010
    *
Anael Mobilia's avatar
PHPdoc    
Anael Mobilia committed
1011
1012
    * @return array collection of fields
    */
1013
   protected function getItems($itemtype, $params = [], &$totalcount = 0) {
Alexandre Delaunay's avatar
Alexandre Delaunay committed
1014
      global $DB;
yllen's avatar
CS    
yllen committed
1015

Alexandre Delaunay's avatar
Alexandre Delaunay committed
1016
      $this->initEndpoint();
1017
      $itemtype = $this->handleDepreciation($itemtype);
Alexandre Delaunay's avatar
Alexandre Delaunay committed
1018
1019

      // default params
1020
      $default = ['expand_dropdowns' => false,
1021
1022
1023
1024
1025
1026
1027
1028
1029
                       'get_hateoas'       => true,
                       'only_id'           => false,
                       'range'             => "0-".$_SESSION['glpilist_limit'],
                       'sort'              => "id",
                       'order'             => "ASC",
                       'searchText'        => null,
                       'is_deleted'        => false,
                       'add_keys_names'    => [],
                       'with_networkports' => false,
1030
      ];
Alexandre Delaunay's avatar
Alexandre Delaunay committed
1031
1032
1033
1034
1035
1036
      $params = array_merge($default, $params);

      if (!$itemtype::canView()) {
         return $this->messageRightError();
      }

1037
      $found = [];
Alexandre Delaunay's avatar
Alexandre Delaunay committed
1038
1039
1040
1041
1042
1043
1044
1045
1046
      $item = new $itemtype();
      $item->getEmpty();
      $table = getTableForItemType($itemtype);

      // transform range parameter in start and limit variables
      if (isset($params['range']) > 0) {
         if (preg_match("/^[0-9]+-[0-9]+\$/", $params['range'])) {
            $range = explode("-", $params['range']);
            $params['start']      = $range[0];
1047
            $params['list_limit'] = $range[1]-$range[0]+1;
1048
            $params['range']      = $range;
Alexandre Delaunay's avatar
Alexandre Delaunay committed
1049
1050
1051
         } else {
            $this->returnError("range must be in format : [start-end] with integers");
         }
Anael Mobilia's avatar
Anael Mobilia committed
1052
      } else {
1053
         $params['range'] = [0, $_SESSION['glpilist_limit']];
Alexandre Delaunay's avatar
Alexandre Delaunay committed
1054
1055
1056
1057
      }

      // check parameters
      if (isset($params['order'])
1058
          && !in_array(strtoupper($params['order']), ['DESC', 'ASC'])) {
Alexandre Delaunay's avatar
Alexandre Delaunay committed
1059
1060
1061
1062
1063
1064
1065
         $this->returnError("order must be DESC or ASC");
      }
      if (!isset($item->fields[$params['sort']])) {
         $this->returnError("sort param is not a field of $table");
      }

      //specific case for restriction
1066
      $already_linked_table = [];
Alexandre Delaunay's avatar
Alexandre Delaunay committed
1067
      $join = Search::addDefaultJoin($itemtype, $table, $already_linked_table);
1068
      $where = Search::addDefaultWhere($itemtype);
Johan Cwiklinski's avatar
Johan Cwiklinski committed
1069

1070
1071
1072
      if ($where == '') {
         $where = "1=1 ";
      }
1073
      if ($item->maybeDeleted()) {
1074
         $where.= "AND ".$DB->quoteName("$table.is_deleted")." = ".(int)$params['is_deleted'];
1075
      }
Alexandre Delaunay's avatar
Alexandre Delaunay committed
1076
1077
1078
1079
1080
1081

      // add filter for a parent itemtype
      if (isset($this->parameters['parent_itemtype'])
          && isset($this->parameters['parent_id'])) {

         // check parent itemtype
1082
1083
1084
         if (!Toolbox::isCommonDBTM($this->parameters['parent_itemtype'])
            && !Toolbox::isAPIDeprecated($this->parameters['parent_itemtype'])
         ) {
Alexandre Delaunay's avatar
Alexandre Delaunay committed
1085
            $this->returnError(__("parent itemtype not found or not an instance of CommonDBTM"),
Alexandre Delaunay's avatar
Alexandre Delaunay committed
1086
1087
1088
1089
1090
                               400,
                               "ERROR_ITEMTYPE_NOT_FOUND_NOR_COMMONDBTM");
         }

         $fk_parent = getForeignKeyFieldForItemType($this->parameters['parent_itemtype']);
1091
         $fk_child = getForeignKeyFieldForItemType($itemtype);
Alexandre Delaunay's avatar
Alexandre Delaunay committed
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103

         // check parent rights
         $parent_item = new $this->parameters['parent_itemtype'];
         if (!$parent_item->getFromDB($this->parameters['parent_id'])) {
            return $this->messageNotfoundError();
         }
         if (!$parent_item->can($this->parameters['parent_id'], READ)) {
            return $this->messageRightError();
         }

         // filter with parents fields
         if (isset($item->fields[$fk_parent])) {
1104
            $where.= " AND ".$DB->quoteName("$table.$fk_parent")." = ".(int)$this->parameters['parent_id'];
Alexandre Delaunay's avatar
Alexandre Delaunay committed
1105
1106
         } else if (isset($item->fields['itemtype'])
                 && isset($item->fields['items_id'])) {
1107
1108
            $where.= " AND ".$DB->quoteName("$table.itemtype")." = ".$DB->quoteValue($this->parameters['parent_itemtype'])."
                       AND ".$DB->quoteName("$table.items_id")." = ".(int)$this->parameters['parent_id'];
Anael Mobilia's avatar
Anael Mobilia committed
1109
         } else if (isset($parent_item->fields[$fk_child])) {
1110
            $parentTable = getTableForItemType($this->parameters['parent_itemtype']);
1111
1112
            $join.= " LEFT JOIN ".$DB->quoteName($parentTable)." ON ".$DB->quoteName("$parentTable.$fk_child")." = ".$DB->quoteName("$table.id");
            $where.= " AND ".$DB->quoteName("$parentTable.id")." = " . (int)$this->parameters['parent_id'];
1113
1114
1115
         } else if (isset($parent_item->fields['itemtype'])
                 && isset($parent_item->fields['items_id'])) {
            $parentTable = getTableForItemType($this->parameters['parent_itemtype']);
1116
1117
            $join.= " LEFT JOIN ".$DB->quoteName($parentTable)." ON ".$DB->quoteName("itemtype")."=".$DB->quoteValue($itemtype)." AND ".$DB->quoteName("$parentTable.items_id")." = ".$DB->quoteName("$table.id");
            $where.= " AND ".$DB->quoteName("$parentTable.id")." = " . (int)$this->parameters['parent_id'];
Alexandre Delaunay's avatar
Alexandre Delaunay committed
1118
1119
1120
         }
      }

1121
1122
      // filter by searchText parameter
      if (is_array($params['searchText'])) {
1123
         if (array_keys($params['searchText']) == ['all']) {
1124
1125
1126
1127
1128
1129
1130
1131
            $labelfield = "name";
            if ($item instanceof CommonDevice) {
               $labelfield = "designation";
            } else if ($item instanceof Item_Devices) {
               $labelfield = "itemtype";
            }
            $search_value                      = $params['searchText']['all'];
            $params['searchText'][$labelfield] = $search_value;
1132
            if ($DB->fieldExists($table, 'comment')) {
1133
1134
1135
1136
1137
               $params['searchText']['comment'] = $search_value;
            }
         }

         // make text search
Anael Mobilia's avatar
Anael Mobilia committed
1138
         foreach ($params['searchText']  as $filter_field => $filter_value) {
1139
            if (!empty($filter_value)) {
1140
               $search_value = Search::makeTextSearch($DB->escape($filter_value));
1141
               $where.= " AND (".$DB->quoteName("$table.$filter_field")." $search_value)";
1142
1143
1144
1145
            }
         }
      }

Alexandre Delaunay's avatar
Alexandre Delaunay committed
1146
      // filter with entity
1147
1148
1149
      if ($item->getType() == 'Entity') {
         $where.= " AND (" . getEntitiesRestrictRequest("", $itemtype::getTable()) . ")";
      } else if ($item->isEntityAssign()
1150
          // some CommonDBChild classes may not have entities_id fields and isEntityAssign still return true (like ITILTemplateMandatoryField)
1151
          && array_key_exists('entities_id', $item->fields)) {
1152
         $where.= " AND (". getEntitiesRestrictRequest("",
Alexandre Delaunay's avatar
Alexandre Delaunay committed
1153
1154
                                             $itemtype::getTable(),
                                             '',
Alexandre Delaunay's avatar
Alexandre Delaunay committed
1155
                                             $_SESSION['glpiactiveentities'],
Adrien Clairembault's avatar
Adrien Clairembault committed
1156
                                             $item->maybeRecursive(),
Alexandre Delaunay's avatar
Alexandre Delaunay committed
1157
1158
                                             true);

Johan Cwiklinski's avatar
Johan Cwiklinski committed
1159
1160
         if ($item instanceof SavedSearch) {
            $where.= " OR ".$itemtype::getTable().".is_private = 1";
Alexandre Delaunay's avatar
Alexandre Delaunay committed
1161
1162
1163
         }

         $where.= ")";
Alexandre Delaunay's avatar
Alexandre Delaunay committed
1164
1165
      }

1166
1167
1168
      // Check if we need to add raw names later on
      $add_keys_names = count($params['add_keys_names']) > 0;

Alexandre Delaunay's avatar
Alexandre Delaunay committed
1169
      // build query
1170
      $query = "SELECT DISTINCT ".$DB->quoteName("$table.id").",  ".$DB->quoteName("$table.*")."
1171
                FROM ".$DB->quoteName($table)."
Alexandre Delaunay's avatar
Alexandre Delaunay committed
1172
1173
                $join
                WHERE $where
1174
1175
                ORDER BY ".$DB->quoteName($params['sort'])." ".$params['order']."
                LIMIT ".(int)$params['start'].", ".(int)$params['list_limit'];
Alexandre Delaunay's avatar
Alexandre Delaunay committed
1176
      if ($result = $DB->query($query)) {
Johan Cwiklinski's avatar
Johan Cwiklinski committed
1177
         while ($data = $DB->fetchAssoc($result)) {