dolibarr 24.0.1
api_users.class.php
1<?php
2/* Copyright (C) 2015 Jean-François Ferry <jfefe@aternatik.fr>
3 * Copyright (C) 2020-2025 Thibault FOUCART <support@ptibogxiv.net>
4 * Copyright (C) 2024-2025 MDW <mdeweerd@users.noreply.github.com>
5 * Copyright (C) 2024-2025 Frédéric France <frederic.france@free.fr>
6 * Copyright (C) 2025 William Mead <william@m34d.com>
7 * Copyright (C) 2025 Jean François Baillette <jean-francois@swiiptel.net>
8 * Copyright (C) 2026 Charlene Benke <charlene@patas-monkey.com>
9 *
10 * This program is free software; you can redistribute it and/or modify
11 * it under the terms of the GNU General Public License as published by
12 * the Free Software Foundation; either version 3 of the License, or
13 * (at your option) any later version.
14 *
15 * This program is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 * GNU General Public License for more details.
19 *
20 * You should have received a copy of the GNU General Public License
21 * along with this program. If not, see <https://www.gnu.org/licenses/>.
22 */
23
24use Luracast\Restler\RestException;
25
26require_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php';
27require_once DOL_DOCUMENT_ROOT.'/user/class/usergroup.class.php';
28require_once DOL_DOCUMENT_ROOT.'/core/class/notify.class.php';
29
30
39class Users extends DolibarrApi
40{
44 public static $FIELDS = array(
45 'login',
46 );
47
51 public $useraccount;
52
56 public function __construct()
57 {
58 global $db;
59
60 $this->db = $db;
61 $this->useraccount = new User($this->db);
62 }
63
64
86 public function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $user_ids = '0', $category = 0, $sqlfilters = '', $properties = '')
87 {
88 if (!DolibarrApiAccess::$user->hasRight('user', 'user', 'lire') && empty(DolibarrApiAccess::$user->admin)) {
89 throw new RestException(403, "You are not allowed to read list of users");
90 }
91
92 $obj_ret = array();
93
94 // case of external user, $societe param is ignored and replaced by user's socid
95 //$socid = DolibarrApiAccess::$user->socid ?: $societe;
96
97 $sql = "SELECT t.rowid";
98 $sql .= " FROM ".MAIN_DB_PREFIX."user AS t LEFT JOIN ".MAIN_DB_PREFIX."user_extrafields AS ef ON (ef.fk_object = t.rowid)"; // Modification VMR Global Solutions to include extrafields as search parameters in the API GET call, so we will be able to filter on extrafields
99 if ($category > 0) {
100 $sql .= ", ".$this->db->prefix()."categorie_user as c";
101 }
102 $sql .= ' WHERE t.entity IN ('.getEntity('user').')';
103 if ($user_ids) {
104 $sql .= " AND t.rowid IN (".$this->db->sanitize($user_ids).")";
105 }
106
107 // Select products of given category
108 if ($category > 0) {
109 $sql .= " AND c.fk_categorie = ".((int) $category);
110 $sql .= " AND c.fk_user = t.rowid";
111 }
112
113 // Add sql filters
114 if ($sqlfilters) {
115 // List of properties we can't filter on, whatever are permissions (to avoid guess by search binary attack)
116 $forbiddenfilterfields = array(
117 'pass',
118 'pass_crypted',
119 'pass_temp',
120 'api_key',
121 'openid'
122 );
123 $canreadsalary = ((isModEnabled('salaries') && DolibarrApiAccess::$user->hasRight('salaries', 'read')) || !isModEnabled('salaries'));
124 if (!$canreadsalary) {
125 $forbiddenfilterfields[] = 'salary';
126 $forbiddenfilterfields[] = 'salaryextra';
127 $forbiddenfilterfields[] = 'thm';
128 $forbiddenfilterfields[] = 'tjm';
129 }
130
131 $errormessage = '';
132 $sql .= forgeSQLFromUniversalSearchCriteria($sqlfilters, $errormessage, 0, 0, 0, $forbiddenfilterfields);
133 if ($errormessage) {
134 throw new RestException(400, 'Error when validating parameter sqlfilters -> '.$errormessage);
135 }
136 }
137
138 $sql .= $this->db->order($sortfield, $sortorder);
139 if ($limit) {
140 if ($page < 0) {
141 $page = 0;
142 }
143 $offset = $limit * $page;
144
145 $sql .= $this->db->plimit($limit + 1, $offset);
146 }
147
148 $result = $this->db->query($sql);
149
150 if ($result) {
151 $i = 0;
152 $num = $this->db->num_rows($result);
153 $min = min($num, ($limit <= 0 ? $num : $limit));
154 while ($i < $min) {
155 $obj = $this->db->fetch_object($result);
156 $user_static = new User($this->db);
157 if ($user_static->fetch($obj->rowid)) {
158 $obj_ret[] = $this->_filterObjectProperties($this->_cleanObjectDatas($user_static), $properties);
159 }
160 $i++;
161 }
162 } else {
163 throw new RestException(503, 'Error when retrieve User list : '.$this->db->lasterror());
164 }
165
166 return $obj_ret;
167 }
168
184 public function get($id, $includepermissions = 0)
185 {
186 if ($id == 0) {
187 throw new RestException(400, 'No user with id=0 can exist');
188 }
189
190 if (!DolibarrApiAccess::$user->hasRight('user', 'user', 'lire') && empty(DolibarrApiAccess::$user->admin) && DolibarrApiAccess::$user->id != $id) {
191 throw new RestException(403, 'Not allowed');
192 }
193
194 if ($id == 0) {
195 $result = $this->useraccount->initAsSpecimen();
196 } else {
197 $result = $this->useraccount->fetch($id);
198 }
199 if (!$result) {
200 throw new RestException(404, 'User not found');
201 }
202
203 if ($id > 0 && !DolibarrApi::_checkAccessToResource('user', $this->useraccount->id, 'user')) {
204 throw new RestException(403, 'Access on this object not allowed for login '.DolibarrApiAccess::$user->login);
205 }
206
207 if ($includepermissions) {
208 $this->useraccount->loadRights();
209 }
210
211 return $this->_cleanObjectDatas($this->useraccount);
212 }
213
231 public function getByLogin($login, $includepermissions = 0)
232 {
233 if (empty($login)) {
234 throw new RestException(400, 'Bad parameters');
235 }
236
237 if (!DolibarrApiAccess::$user->hasRight('user', 'user', 'lire') && empty(DolibarrApiAccess::$user->admin) && DolibarrApiAccess::$user->login != $login) {
238 throw new RestException(403, 'Not allowed');
239 }
240
241 $result = $this->useraccount->fetch(0, $login);
242 if (!$result) {
243 throw new RestException(404, 'User not found');
244 }
245
246 if (!DolibarrApi::_checkAccessToResource('user', $this->useraccount->id, 'user')) {
247 throw new RestException(403, 'Access on this object not allowed for login '.DolibarrApiAccess::$user->login);
248 }
249
250 if ($includepermissions) {
251 $this->useraccount->loadRights();
252 }
253
254 return $this->_cleanObjectDatas($this->useraccount);
255 }
256
274 public function getByEmail($email, $includepermissions = 0)
275 {
276 if (empty($email)) {
277 throw new RestException(400, 'Bad parameters');
278 }
279
280 if (!DolibarrApiAccess::$user->hasRight('user', 'user', 'lire') && empty(DolibarrApiAccess::$user->admin) && DolibarrApiAccess::$user->email != $email) {
281 throw new RestException(403, 'Not allowed');
282 }
283
284 $result = $this->useraccount->fetch(0, '', '', 0, -1, $email);
285 if (!$result) {
286 throw new RestException(404, 'User not found');
287 }
288
289 if (!DolibarrApi::_checkAccessToResource('user', $this->useraccount->id, 'user')) {
290 throw new RestException(403, 'Access on this object not allowed for login '.DolibarrApiAccess::$user->login);
291 }
292
293 if ($includepermissions) {
294 $this->useraccount->loadRights();
295 }
296
297 return $this->_cleanObjectDatas($this->useraccount);
298 }
299
315 public function getInfo($includepermissions = 0)
316 {
317 if (!DolibarrApiAccess::$user->hasRight('user', 'self', 'creer') && !DolibarrApiAccess::$user->hasRight('user', 'user', 'lire') && empty(DolibarrApiAccess::$user->admin)) {
318 throw new RestException(403, 'Not allowed');
319 }
320
321 $apiUser = DolibarrApiAccess::$user;
322
323 $result = $this->useraccount->fetch($apiUser->id);
324 if (!$result) {
325 throw new RestException(404, 'User not found');
326 }
327
328 if (!DolibarrApi::_checkAccessToResource('user', $this->useraccount->id, 'user')) {
329 throw new RestException(403, 'Access on this object not allowed to current logged user');
330 }
331
332 if ($includepermissions) {
333 $this->useraccount->loadRights();
334 }
335
336 $usergroup = new UserGroup($this->db);
337 $userGroupList = $usergroup->listGroupsForUser($apiUser->id, false);
338 if (!is_array($userGroupList)) {
339 throw new RestException(404, 'User group not found');
340 }
341
342 $this->useraccount->user_group_list = $this->_cleanUserGroupListDatas($userGroupList);
343
344 return $this->_cleanObjectDatas($this->useraccount);
345 }
346
359 public function post($request_data = null)
360 {
361 // Check user authorization
362 if (!DolibarrApiAccess::$user->hasRight('user', 'user', 'creer') && empty(DolibarrApiAccess::$user->admin)) {
363 throw new RestException(403, "User creation not allowed for login ".DolibarrApiAccess::$user->login);
364 }
365
366 // check mandatory fields
367 if (!isset($request_data["login"]))
368 throw new RestException(500, "login field missing");
369 /*if (!isset($request_data["password"]))
370 throw new RestException(400, "password field missing");
371 if (!isset($request_data["lastname"]))
372 throw new RestException(400, "lastname field missing");*/
373
374 //assign field values
375 foreach ($request_data as $field => $value) {
376 if (in_array($field, array('pass_crypted', 'pass_indatabase', 'pass_indatabase_crypted', 'pass_temp', 'api_key', 'openid'))) {
377 // This properties can't be set/modified with API
378 throw new RestException(405, 'The property '.$field." can't be set/modified using the APIs");
379 }
380 if ($field == 'pass') {
381 if (!DolibarrApiAccess::$user->hasRight('user', 'user', 'password')) { // In creation, users is always a different user than the one who create it.
382 throw new RestException(403, 'You are not allowed to modify/set password of other users');
383 }
384 if (!DolibarrApiAccess::$user->admin) { // Only admin can set a password and knowing it. Others can reset with correct rights user->self->password but without knowing it.
385 throw new RestException(403, 'As a non admin user, you are not allowed to set a password from this API. Use the /setPassword endpoint for this.');
386 }
387 }
388
389 $canreadsalary = ((isModEnabled('salaries') && DolibarrApiAccess::$user->hasRight('salaries', 'read')) || !isModEnabled('salaries'));
390 if (!$canreadsalary) {
391 if (in_array($field, array('salary', 'salaryextra', 'thm', 'tjm'))) {
392 // This properties can't be set/modified with API
393 throw new RestException(405, 'The property '.$field." can't be set/modified using the APIs with permission on salaries");
394 }
395 }
396
397 if ($field === 'caller') {
398 // Add a mention of caller so on trigger called after action, we can filter to avoid a loop if we try to sync back again with the caller
399 $this->useraccount->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
400 continue;
401 }
402
403 if (DolibarrApiAccess::$user->admin) { // If user for API is admin
404 if ($field == 'admin' && $value != $this->useraccount->admin && empty($value)) {
405 throw new RestException(403, 'Reseting the admin status of a user is not possible using the API');
406 }
407 } else {
408 if ($field == 'admin' && $value != $this->useraccount->admin) {
409 throw new RestException(403, 'Only an admin user can modify the admin status of another user');
410 }
411 }
412
413 $this->useraccount->$field = $this->_checkValForAPI($field, $value, $this->useraccount);
414 }
415
416 if ($this->useraccount->create(DolibarrApiAccess::$user) < 0) {
417 throw new RestException(500, 'Error creating', array_merge(array($this->useraccount->error), $this->useraccount->errors));
418 }
419 return $this->useraccount->id;
420 }
421
422
438 public function put($id, $request_data = null)
439 {
440 $isSelfUpdate = ((int) $id === (int) DolibarrApiAccess::$user->id);
441
442 // Check user authorization
443 if (
444 !DolibarrApiAccess::$user->hasRight('user', 'user', 'creer')
445 && !DolibarrApiAccess::$user->hasRight('user', 'user', 'write')
446 && !(
447 $isSelfUpdate
448 && (
449 DolibarrApiAccess::$user->hasRight('user', 'self', 'creer')
450 || DolibarrApiAccess::$user->hasRight('user', 'self', 'write')
451 )
452 )
453 && empty(DolibarrApiAccess::$user->admin)
454 ) {
455 throw new RestException(403, "User update not allowed");
456 }
457
458 $result = $this->useraccount->fetch($id);
459 if (!$result) {
460 throw new RestException(404, 'Account not found');
461 }
462
463 if (!DolibarrApi::_checkAccessToResource('user', $this->useraccount->id, 'user')) {
464 throw new RestException(403, 'Access on this object not allowed for login '.DolibarrApiAccess::$user->login);
465 }
466
467 foreach ($request_data as $field => $value) {
468 if (in_array($field, array('pass_crypted', 'pass_indatabase', 'pass_indatabase_crypted', 'pass_temp', 'api_key', 'openid'))) {
469 // This properties can't be set/modified with API
470 throw new RestException(405, 'The property '.$field." can't be set/modified using the APIs");
471 }
472
473 $canreadsalary = ((isModEnabled('salaries') && DolibarrApiAccess::$user->hasRight('salaries', 'read')) || !isModEnabled('salaries'));
474 if (!$canreadsalary) {
475 if (in_array($field, array('salary', 'salaryextra', 'thm', 'tjm'))) {
476 // This properties can't be set/modified with API
477 throw new RestException(405, 'The property '.$field." can't be set/modified using the APIs with permission on salaries");
478 }
479 }
480
481 if ($field == 'id') {
482 continue;
483 }
484 if ($field == 'pass') {
485 if ($this->useraccount->id != DolibarrApiAccess::$user->id && !DolibarrApiAccess::$user->hasRight('user', 'user', 'password')) {
486 throw new RestException(403, 'You are not allowed to modify password of other users');
487 }
488 if ($this->useraccount->id == DolibarrApiAccess::$user->id && !DolibarrApiAccess::$user->hasRight('user', 'self', 'password')) {
489 throw new RestException(403, 'You are not allowed to modify your own password');
490 }
491 if (!DolibarrApiAccess::$user->admin) { // Only admin can set a password and knowing it. Others can reset with correct rights user->self->password but without knowing it.
492 throw new RestException(403, 'As a non admin user, you are not allowed to set a password from this API. Use the /setPassword endpoint for this.');
493 }
494 }
495 if ($field === 'caller') {
496 // Add a mention of caller so on trigger called after action, we can filter to avoid a loop if we try to sync back again with the caller
497 $this->useraccount->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
498 continue;
499 }
500 if ($field == 'array_options' && is_array($value)) {
501 foreach ($value as $index => $val) {
502 $this->useraccount->array_options[$index] = $this->_checkValExtrafieldsForAPI($index, $val, $this->useraccount);
503 }
504 continue;
505 }
506
507 if (DolibarrApiAccess::$user->admin) { // If user for API is admin
508 if ($field == 'admin' && $value != $this->useraccount->admin && empty($value)) {
509 throw new RestException(403, 'Reseting the admin status of a user is not possible using the API');
510 }
511 } else {
512 if ($field == 'admin' && $value != $this->useraccount->admin) {
513 throw new RestException(403, 'Only an admin user can modify the admin status of another user');
514 }
515 }
516 if ($field == 'entity' && $value != $this->useraccount->entity) {
517 throw new RestException(403, 'Changing entity of a user using the APIs is not possible');
518 }
519
520 // The status must be updated using setstatus() because it
521 // is not handled by the update() method.
522 if ($field == 'statut' || $field == 'status') {
523 $result = $this->useraccount->setstatus($value);
524 if ($result < 0) {
525 throw new RestException(500, 'Error when updating status of user: '.$this->useraccount->error);
526 }
527 } else {
528 $this->useraccount->$field = $this->_checkValForAPI($field, $value, $this->useraccount);
529 }
530 }
531
532 // If there is no error, update() returns the number of affected
533 // rows so if the update is a no op, the return value is zezo.
534 if ($this->useraccount->update(DolibarrApiAccess::$user) >= 0) {
535 return $this->get($id);
536 } else {
537 throw new RestException(500, $this->useraccount->error);
538 }
539 }
540
556 public function setPassword($id, $send_password = false)
557 {
558 if (!getDolGlobalInt('API_ENABLE_LOGIN_API')) {
559 throw new RestException(403, "Error: login and password reset APIs are disabled. You can get access token from the backoffice to get access permission but permission and password manipulation from APIs are forbidden.");
560 }
561
562 if (!getDolGlobalString('API_ALLOW_PASSWORD_RESET')) {
563 throw new RestException(403, "Error: password reset APIs are disabled by default. To allow this, the option API_ALLOW_PASSWORD_RESET must be set.");
564 }
565
566 if ($id != DolibarrApiAccess::$user->id && !DolibarrApiAccess::$user->hasRight('user', 'user', 'password')) {
567 throw new RestException(403, 'You are not allowed to modify password of other users');
568 }
569 if ($id == DolibarrApiAccess::$user->id && !DolibarrApiAccess::$user->hasRight('user', 'self', 'password')) {
570 throw new RestException(403, 'You are not allowed to modify your own password');
571 }
572
573 $result = $this->useraccount->fetch($id);
574 if (!$result) {
575 throw new RestException(404, 'User not found, no password changed');
576 }
577
578 if (!DolibarrApi::_checkAccessToResource('user', $this->useraccount->id, 'user')) {
579 throw new RestException(403, 'Access on this object not allowed for login '.DolibarrApiAccess::$user->login);
580 }
581
582 $newpassword = $this->useraccount->setPassword($this->useraccount, ''); // This will generate a new password
583 if (is_int($newpassword) && $newpassword < 0) {
584 throw new RestException(500, 'ErrorFailedToSetNewPassword'.$this->useraccount->error);
585 } else {
586 // Success
587 if ($send_password) {
588 if ($this->useraccount->send_password($this->useraccount, $newpassword) > 0) {
589 return 2;
590 } else {
591 throw new RestException(500, 'ErrorFailedSendingNewPassword - '.$this->useraccount->error);
592 }
593 } else {
594 return 1;
595 }
596 }
597 }
598
615 public function getGroups($id)
616 {
617 if ($id == 0) {
618 throw new RestException(400, 'No user with id=0 can exist');
619 }
620
621 if (!DolibarrApiAccess::$user->hasRight('user', 'user', 'lire') && empty(DolibarrApiAccess::$user->admin)) {
622 throw new RestException(403);
623 }
624
625 $user = new User($this->db);
626 $result = $user->fetch($id);
627 if (!$result) {
628 throw new RestException(404, 'User not found');
629 }
630 if (!DolibarrApi::_checkAccessToResource('user', $user->id, 'user')) {
631 throw new RestException(403, 'Access on this object not allowed for login '.DolibarrApiAccess::$user->login);
632 }
633
634 $usergroup = new UserGroup($this->db);
635 $groups = $usergroup->listGroupsForUser($id, false);
636 $obj_ret = array();
637 foreach ($groups as $group) {
638 $obj_ret[] = $this->_cleanObjectDatas($group);
639 }
640 return $obj_ret;
641 }
642
643
660 public function setGroup($id, $group, $entity = 1)
661 {
662 global $conf;
663
664 if (!DolibarrApiAccess::$user->hasRight('user', 'user', 'creer') && empty(DolibarrApiAccess::$user->admin)) {
665 throw new RestException(403, 'setGroup on users not allowed for login '.DolibarrApiAccess::$user->login);
666 }
667
668 $result = $this->useraccount->fetch($id);
669 if (!$result) {
670 throw new RestException(404, 'User not found');
671 }
672
673 if (!DolibarrApi::_checkAccessToResource('user', $this->useraccount->id, 'user')) {
674 throw new RestException(403, 'Access on this object not allowed for login '.DolibarrApiAccess::$user->login);
675 }
676
677 if (isModEnabled('multicompany') && getDolGlobalString('MULTICOMPANY_TRANSVERSE_MODE') && !empty(DolibarrApiAccess::$user->admin) && empty(DolibarrApiAccess::$user->entity)) {
678 $entity = (!empty($entity) ? (int) $entity : $conf->entity);
679 } else {
680 // When using API, action is done on entity of logged user because a user of entity X with permission to create user should not be able to
681 // hack the security by giving himself permissions on another entity.
682 $entity = (((int) DolibarrApiAccess::$user->entity) > 0 ? (int) DolibarrApiAccess::$user->entity : $conf->entity);
683 }
684
685 $result = $this->useraccount->SetInGroup($group, $entity);
686 if (!($result > 0)) {
687 throw new RestException(500, $this->useraccount->error);
688 }
689
690 return 1;
691 }
692
706 public function postGroups($request_data = null)
707 {
708 // Check user authorization
709 if (!DolibarrApiAccess::$user->hasRight('user', 'group_advance', 'write') && empty(DolibarrApiAccess::$user->admin)) {
710 throw new RestException(403, "Usergroup creation not allowed for login ".DolibarrApiAccess::$user->login);
711 }
712 $usergroup = new UserGroup($this->db);
713 foreach ($request_data as $field => $value) {
714 if ($field === 'caller') {
715 // Add a mention of caller so on trigger called after action, we can filter to avoid a loop if we try to sync back again with the caller
716 $usergroup->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
717 continue;
718 }
719 if ($field == 'id') {
720 throw new RestException(400, 'Creating with id field is forbidden');
721 }
722
723 $usergroup->$field = $this->_checkValForAPI($field, $value, $usergroup);
724 }
725
726 if ($usergroup->create(1) < 0) {
727 throw new RestException(500, 'Error creating', array_merge(array($usergroup->error), $usergroup->errors));
728 }
729 return $usergroup->id;
730 }
731
749 public function putGroups($group, $request_data = null)
750 {
751 // Check user authorization
752 if (!DolibarrApiAccess::$user->hasRight('user', 'group_advance', 'write') && empty(DolibarrApiAccess::$user->admin)) {
753 throw new RestException(403, "Usergroup update not allowed");
754 }
755
756 $usergroup = new UserGroup($this->db);
757
758 $result = $usergroup->fetch($group);
759 if ($result < 1) {
760 throw new RestException(404, 'Usergroup not found');
761 }
762
763 foreach ($request_data as $field => $value) {
764 if ($field == 'id') {
765 throw new RestException(400, 'Updating with id field is forbidden');
766 }
767 if ($field === 'caller') {
768 // Add a mention of caller so on trigger called after action, we can filter to avoid a loop if we try to sync back again with the caller
769 $usergroup->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
770 continue;
771 }
772
773 if ($field == 'entity' && $value != $usergroup->entity) {
774 throw new RestException(403, 'Changing entity of a user using the APIs is not possible');
775 }
776
777 $usergroup->$field = $this->_checkValForAPI($field, $value, $usergroup);
778 }
779
780 // If there is no error, update() returns the number of affected
781 // rows so if the update is a no op, the return value is zezo.
782 if ($usergroup->update() >= 0) {
783 return $this->infoGroups($group);
784 } else {
785 throw new RestException(500, $usergroup->error);
786 }
787 }
788
804 public function removeUserFromGroup($id, $group)
805 {
806 if (!DolibarrApiAccess::$user->admin) {
807 throw new RestException(403, 'Only admin can remove users from groups');
808 }
809
810 $sql = "DELETE FROM " . MAIN_DB_PREFIX . "usergroup_user";
811 $sql .= " WHERE fk_user = " . ((int) $id);
812 $sql .= " AND fk_usergroup = " . ((int) $group);
813
814 $resql = $this->db->query($sql);
815
816 if (!$resql) {
817 throw new RestException(503, 'DB error: ' . $this->db->lasterror());
818 }
819
820 return [
821 'success' => true,
822 'message' => "User $id removed from group $group"
823 ];
824 }
825
850 public function listGroups($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $group_ids = '0', $sqlfilters = '', $properties = '')
851 {
852 $obj_ret = array();
853
854 if ((!getDolGlobalString('MAIN_USE_ADVANCED_PERMS') && !DolibarrApiAccess::$user->hasRight('user', 'user', 'lire') && empty(DolibarrApiAccess::$user->admin)) ||
855 getDolGlobalString('MAIN_USE_ADVANCED_PERMS') && !DolibarrApiAccess::$user->hasRight('user', 'group_advance', 'read') && empty(DolibarrApiAccess::$user->admin)) {
856 throw new RestException(403, "You are not allowed to read groups");
857 }
858
859 // case of external user, $societe param is ignored and replaced by user's socid
860 //$socid = DolibarrApiAccess::$user->socid ?: $societe;
861
862 $sql = "SELECT t.rowid";
863 $sql .= " FROM ".MAIN_DB_PREFIX."usergroup AS t LEFT JOIN ".MAIN_DB_PREFIX."usergroup_extrafields AS ef ON (ef.fk_object = t.rowid)"; // Modification VMR Global Solutions to include extrafields as search parameters in the API GET call, so we will be able to filter on extrafields
864 $sql .= ' WHERE t.entity IN ('.getEntity('user').')';
865 if ($group_ids) {
866 $sql .= " AND t.rowid IN (".$this->db->sanitize($group_ids).")";
867 }
868 // Add sql filters
869 if ($sqlfilters) {
870 $errormessage = '';
871 $sql .= forgeSQLFromUniversalSearchCriteria($sqlfilters, $errormessage);
872 if ($errormessage) {
873 throw new RestException(400, 'Error when validating parameter sqlfilters -> '.$errormessage);
874 }
875 }
876
877 $sql .= $this->db->order($sortfield, $sortorder);
878 if ($limit) {
879 if ($page < 0) {
880 $page = 0;
881 }
882 $offset = $limit * $page;
883
884 $sql .= $this->db->plimit($limit + 1, $offset);
885 }
886
887 $result = $this->db->query($sql);
888
889 if ($result) {
890 $i = 0;
891 $num = $this->db->num_rows($result);
892 $min = min($num, ($limit <= 0 ? $num : $limit));
893 while ($i < $min) {
894 $obj = $this->db->fetch_object($result);
895 $group_static = new UserGroup($this->db);
896 if ($group_static->fetch($obj->rowid)) {
897 $obj_ret[] = $this->_filterObjectProperties($this->_cleanObjectDatas($group_static), $properties);
898 }
899 $i++;
900 }
901 } else {
902 throw new RestException(503, 'Error when retrieve Group list : '.$this->db->lasterror());
903 }
904
905 return $obj_ret;
906 }
907
926 public function infoGroups($group, $load_members = 0, $includepermissions = 0)
927 {
928 if ($group == 0) {
929 throw new RestException(400, 'No usergroup with id=0 can exist');
930 }
931
932 if ((!getDolGlobalString('MAIN_USE_ADVANCED_PERMS') && !DolibarrApiAccess::$user->hasRight('user', 'user', 'lire') && empty(DolibarrApiAccess::$user->admin)) ||
933 getDolGlobalString('MAIN_USE_ADVANCED_PERMS') && !DolibarrApiAccess::$user->hasRight('user', 'group_advance', 'read') && empty(DolibarrApiAccess::$user->admin)) {
934 throw new RestException(403, "You are not allowed to read groups");
935 }
936
937 $group_static = new UserGroup($this->db);
938 $result = $group_static->fetch($group, '', (bool) $load_members);
939
940 if ($result < 1) {
941 throw new RestException(404, 'Usergroup not found');
942 }
943
944 if ($includepermissions) {
945 $group_static->loadRights();
946 }
947
948 if ($load_members > 0 && is_array($group_static->members) && count($group_static->members) > 0) {
949 foreach ($group_static->members as &$member) {
950 $member = $this->_cleanObjectDatas($member);
951 }
952 }
953
954 return $this->_cleanUserGroup($group_static);
955 }
956
970 public function delete($id)
971 {
972 if (!DolibarrApiAccess::$user->hasRight('user', 'user', 'supprimer') && empty(DolibarrApiAccess::$user->admin)) {
973 throw new RestException(403, 'Not allowed');
974 }
975 $result = $this->useraccount->fetch($id);
976 if (!$result) {
977 throw new RestException(404, 'User not found');
978 }
979
980 if (!DolibarrApi::_checkAccessToResource('user', $this->useraccount->id, 'user')) {
981 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
982 }
983
984 if ($this->useraccount->admin && empty(DolibarrApiAccess::$user->admin)) {
985 throw new RestException(403, 'Only admin users can delete admin users');
986 }
987 if ($this->useraccount->admin && empty($this->useraccount->entity) && !empty(DolibarrApiAccess::$user->entity)) {
988 throw new RestException(403, 'Only superadmin users can delete superadmin users');
989 }
990
991 $this->useraccount->oldcopy = clone $this->useraccount; // @phan-suppress-current-line PhanTypeMismatchProperty
992
993 if (!$this->useraccount->delete(DolibarrApiAccess::$user)) {
994 throw new RestException(500);
995 }
996
997 return array(
998 'success' => array(
999 'code' => 200,
1000 'message' => 'User deleted'
1001 )
1002 );
1003 }
1004
1020 public function deleteGroups($group)
1021 {
1022 if (!DolibarrApiAccess::$user->hasRight('user', 'group_advance', 'delete') && empty(DolibarrApiAccess::$user->admin)) {
1023 throw new RestException(403, 'Not allowed');
1024 }
1025
1026 $usergroup = new UserGroup($this->db);
1027
1028 $result = $usergroup->fetch($group);
1029 if ($result < 0) {
1030 throw new RestException(404, 'Usergroup not found');
1031 }
1032
1033 if (!$usergroup->delete(DolibarrApiAccess::$user)) {
1034 throw new RestException(500);
1035 }
1036
1037 return array(
1038 'success' => array(
1039 'code' => 200,
1040 'message' => 'Usergroup deleted'
1041 )
1042 );
1043 }
1044
1062 public function getUserNotification($id)
1063 {
1064 if (empty($id)) {
1065 throw new RestException(400, 'No user with id=0 can exist');
1066 }
1067 if (!DolibarrApiAccess::$user->hasRight('user', 'user', 'lire') && empty(DolibarrApiAccess::$user->admin)) {
1068 throw new RestException(403);
1069 }
1071 throw new RestException(403, 'Access on this object not allowed for login '.DolibarrApiAccess::$user->login);
1072 }
1073
1078 $sql = "SELECT rowid as id, fk_action as event, fk_user, type, datec, tms";
1079 $sql .= " FROM ".MAIN_DB_PREFIX."notify_def";
1080 $sql .= " WHERE fk_user = ".((int) $id);
1081
1082 $result = $this->db->query($sql);
1083 if ($this->db->num_rows($result) == 0) {
1084 throw new RestException(404, 'Notification not found');
1085 }
1086
1087 $i = 0;
1088
1089 $notifications = array();
1090
1091 if ($result) {
1092 $num = $this->db->num_rows($result);
1093 //$min = min($num, ($limit <= 0 ? $num : $limit));
1094 $min = $num;
1095 while ($i < $min) {
1096 $obj = $this->db->fetch_object($result);
1097 $notifications[] = $obj;
1098 $i++;
1099 }
1100 } else {
1101 throw new RestException(404, 'No notifications found');
1102 }
1103
1104 $fields = array('id', 'fk_user', 'event', 'datec', 'tms', 'type');
1105
1106 $returnNotifications = array();
1107
1108 foreach ($notifications as $notification) {
1109 $object = array();
1110 foreach ($notification as $key => $value) {
1111 if (in_array($key, $fields)) {
1112 $object[$key] = $value;
1113 }
1114 }
1115 $returnNotifications[] = $object;
1116 }
1117
1118 // Too complex for phan ?: @phan-suppress-next-line PhanTypeMismatchReturn
1119 return $returnNotifications;
1120 }
1121
1138 public function createUserNotification($id, $request_data = null)
1139 {
1140 if (!DolibarrApiAccess::$user->hasRight('user', 'user', 'creer')) {
1141 throw new RestException(403, "User has no right to update users");
1142 }
1143 if ($this->useraccount->fetch($id) <= 0) {
1144 throw new RestException(404, 'Error creating User Notification, User doesn\'t exists');
1145 }
1146 $notification = new Notify($this->db);
1147
1148 $notification->fk_user = $id;
1149
1150 foreach ($request_data as $field => $value) {
1151 $notification->$field = $this->_checkValForAPI($field, $value, $notification);
1152 }
1153
1154 $event = $notification->event;
1155 if (!$event) {
1156 throw new RestException(500, 'Error creating User Notification, request_data missing event');
1157 }
1158 $fk_user = $notification->fk_user;
1159
1160 $exists_sql = "SELECT rowid, fk_action as event, fk_user, type, datec, tms as datem";
1161 $exists_sql .= " FROM ".MAIN_DB_PREFIX."notify_def";
1162 $exists_sql .= " WHERE fk_action = '".$this->db->escape((string) $event)."'";
1163 $exists_sql .= " AND fk_user = '".$this->db->escape((string) $fk_user)."'";
1164
1165 $exists_result = $this->db->query($exists_sql);
1166 if ($this->db->num_rows($exists_result) > 0) {
1167 throw new RestException(403, 'Notification already exists');
1168 }
1169
1170 if ($notification->create(DolibarrApiAccess::$user) < 0) {
1171 throw new RestException(500, 'Error creating User Notification');
1172 }
1173
1174 if ($notification->update(DolibarrApiAccess::$user) < 0) {
1175 throw new RestException(500, 'Error updating values');
1176 }
1177
1178 return $this->_cleanObjectDatas($notification);
1179 }
1180
1199 public function createUserNotificationByCode($id, $code, $request_data = null)
1200 {
1201 if (!DolibarrApiAccess::$user->hasRight('user', 'user', 'creer')) {
1202 throw new RestException(403, "User has no right to update users");
1203 }
1204 if ($this->useraccount->fetch($id) <= 0) {
1205 throw new RestException(404, 'Error creating User Notification, User doesn\'t exists');
1206 }
1207 $notification = new Notify($this->db);
1208 $notification->fk_user = $id;
1209
1210 $sql = "SELECT t.rowid as id FROM ".MAIN_DB_PREFIX."c_action_trigger as t";
1211 $sql .= " WHERE t.code = '".$this->db->escape($code)."'";
1212
1213 $result = $this->db->query($sql);
1214 if ($this->db->num_rows($result) == 0) {
1215 throw new RestException(404, 'Action Trigger code not found');
1216 }
1217
1218 $notification->event = $this->db->fetch_row($result)[0];
1219 foreach ($request_data as $field => $value) {
1220 if ($field === 'event') {
1221 throw new RestException(500, 'Error creating User Notification, request_data contains event key');
1222 }
1223 if ($field === 'fk_action') {
1224 throw new RestException(500, 'Error creating User Notification, request_data contains fk_action key');
1225 }
1226 $notification->$field = $this->_checkValForAPI($field, $value, $notification);
1227 }
1228
1229 $event = $notification->event;
1230 $fk_user = $notification->fk_user;
1231
1232 $exists_sql = "SELECT rowid, fk_action as event, fk_user, type, datec, tms as datem";
1233 $exists_sql .= " FROM ".MAIN_DB_PREFIX."notify_def";
1234 $exists_sql .= " WHERE fk_action = '".$this->db->escape((string) $event)."'";
1235 $exists_sql .= " AND fk_user = '".$this->db->escape((string) $fk_user)."'";
1236
1237 $exists_result = $this->db->query($exists_sql);
1238 if ($this->db->num_rows($exists_result) > 0) {
1239 throw new RestException(403, 'Notification already exists');
1240 }
1241
1242 if ($notification->create(DolibarrApiAccess::$user) < 0) {
1243 throw new RestException(500, 'Error creating User Notification, are request_data well formed?');
1244 }
1245
1246 if ($notification->update(DolibarrApiAccess::$user) < 0) {
1247 throw new RestException(500, 'Error updating values');
1248 }
1249
1250 return $this->_cleanObjectDatas($notification);
1251 }
1252
1267 public function deleteUserNotification($id, $notification_id)
1268 {
1269 if (!DolibarrApiAccess::$user->hasRight('user', 'user', 'creer')) {
1270 throw new RestException(403, "User has no right to update users");
1271 }
1272
1273 $notification = new Notify($this->db);
1274
1275 $notification->fetch($notification_id);
1276
1277 $fk_user = (int) $notification->fk_user;
1278
1279 if ($fk_user == $id) {
1280 return $notification->delete(DolibarrApiAccess::$user);
1281 } else {
1282 throw new RestException(403, "Not allowed due to bad consistency of input data");
1283 }
1284 }
1285
1303 public function updateUserNotification($id, $notification_id, $request_data = null)
1304 {
1305 if (!DolibarrApiAccess::$user->hasRight('user', 'user', 'creer')) {
1306 throw new RestException(403, "User has no right to update users");
1307 }
1308 if ($this->useraccount->fetch($id) <= 0) {
1309 throw new RestException(404, 'Error creating Notification, User doesn\'t exists');
1310 }
1311 $notification = new Notify($this->db);
1312
1313 // @phan-suppress-next-line PhanPluginSuspiciousParamPosition
1314 $notification->fetch($notification_id, $id);
1315
1316 if ($notification->fk_user != $id) {
1317 throw new RestException(403, "Not allowed due to bad consistency of input data");
1318 }
1319
1320 foreach ($request_data as $field => $value) {
1321 $notification->$field = $this->_checkValForAPI($field, $value, $notification);
1322 }
1323
1324 if ($notification->update(DolibarrApiAccess::$user) < 0) {
1325 throw new RestException(500, 'Error updating values');
1326 }
1327
1328 return $this->_cleanObjectDatas($notification);
1329 }
1330
1331 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
1341 protected function _cleanObjectDatas($object)
1342 {
1343 // phpcs:enable
1344 $object = parent::_cleanObjectDatas($object);
1345
1346 unset($object->default_values);
1347 unset($object->lastsearch_values);
1348 unset($object->lastsearch_values_tmp);
1349
1350 unset($object->total_ht);
1351 unset($object->total_tva);
1352 unset($object->total_localtax1);
1353 unset($object->total_localtax2);
1354 unset($object->total_ttc);
1355
1356 unset($object->label_incoterms);
1357 unset($object->location_incoterms);
1358
1359 unset($object->fk_delivery_address);
1360 unset($object->fk_incoterms);
1361 unset($object->all_permissions_are_loaded);
1362 unset($object->shipping_method_id);
1363 unset($object->nb_rights);
1364 unset($object->search_sid);
1365 unset($object->ldap_sid);
1366 unset($object->clicktodial_loaded);
1367
1368 unset($object->lines);
1369 unset($object->model_pdf);
1370
1371 // List of properties never returned by API, whatever are permissions
1372 unset($object->pass);
1373 unset($object->pass_indatabase);
1374 unset($object->pass_indatabase_crypted);
1375 unset($object->pass_temp);
1376 unset($object->api_key);
1377 unset($object->clicktodial_password);
1378 unset($object->openid);
1379
1380 $canreadsalary = ((isModEnabled('salaries') && DolibarrApiAccess::$user->hasRight('salaries', 'read')) || !isModEnabled('salaries'));
1381 if (!$canreadsalary) {
1382 unset($object->salary);
1383 unset($object->salaryextra);
1384 unset($object->thm);
1385 unset($object->tjm);
1386 }
1387
1388 return $object;
1389 }
1390
1391 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
1398 private function _cleanUserGroup($object)
1399 {
1400 // phpcs:enable
1401 $object = parent::_cleanObjectDatas($object);
1402
1403 unset($object->actiontypecode);
1404 unset($object->all_permissions_are_loaded);
1405 unset($object->barcode_type_coder);
1406 unset($object->barcode_type);
1407 unset($object->canvas);
1408 unset($object->civility_code);
1409 unset($object->civility_id);
1410 unset($object->clicktodial_loaded);
1411 unset($object->cond_reglement_id);
1412 unset($object->cond_reglement_supplier_id);
1413 unset($object->contact_id);
1414 unset($object->contacts_ids_internal);
1415 unset($object->contacts_ids);
1416 unset($object->country_code);
1417 unset($object->country_id);
1418 unset($object->date_cloture);
1419 unset($object->date_creation);
1420 unset($object->date_modification);
1421 unset($object->date_validation);
1422 unset($object->default_values);
1423 unset($object->demand_reason_id);
1424 unset($object->deposit_percent);
1425 unset($object->extraparams);
1426 unset($object->firstname);
1427 unset($object->fk_account);
1428 unset($object->fk_delivery_address);
1429 unset($object->fk_incoterms);
1430 unset($object->fk_multicurrency);
1431 unset($object->fk_project);
1432 unset($object->fk_user_creat);
1433 unset($object->fk_user_modif);
1434 unset($object->globalgroup);
1435 unset($object->import_key);
1436 unset($object->last_main_doc);
1437 unset($object->lastname);
1438 unset($object->lastsearch_values_tmp);
1439 unset($object->lastsearch_values);
1440 unset($object->ldap_sid);
1441 unset($object->libelle_incoterms);
1442 unset($object->lines);
1443 unset($object->linkedObjectsIds);
1444 unset($object->location_incoterms);
1445 unset($object->members);
1446 unset($object->mode_reglement_id);
1447 unset($object->module);
1448 unset($object->multicurrency_code);
1449 unset($object->multicurrency_total_ht);
1450 unset($object->multicurrency_total_localtax1);
1451 unset($object->multicurrency_total_localtax2);
1452 unset($object->multicurrency_total_ttc);
1453 unset($object->multicurrency_total_tva);
1454 unset($object->multicurrency_tx);
1455 unset($object->nb_rights);
1456 unset($object->nb_users);
1457 unset($object->note_public);
1458 unset($object->origin_id);
1459 unset($object->origin_type);
1460 unset($object->product);
1461 unset($object->ref_ext);
1462 unset($object->ref);
1463 unset($object->region_id);
1464 unset($object->retained_warranty_fk_cond_reglement);
1465 unset($object->rights);
1466 unset($object->search_sid);
1467 unset($object->shipping_method_id);
1468 unset($object->shipping_method);
1469 unset($object->specimen);
1470 unset($object->state_id);
1471 unset($object->status);
1472 unset($object->statut);
1473 unset($object->total_ht);
1474 unset($object->total_localtax1);
1475 unset($object->total_localtax2);
1476 unset($object->total_ttc);
1477 unset($object->total_tva);
1478 unset($object->totalpaid_multicurrency);
1479 unset($object->totalpaid);
1480 unset($object->transport_mode_id);
1481 unset($object->TRIGGER_PREFIX);
1482 unset($object->user_closing_id);
1483 unset($object->user_creation_id);
1484 unset($object->user_modification_id);
1485 unset($object->user_validation_id);
1486 unset($object->user);
1487 unset($object->usergroup_entity);
1488 unset($object->warehouse_id);
1489
1490 return $object;
1491 }
1492
1499 private function _cleanUserGroupListDatas($objectList)
1500 {
1501 $cleanObjectList = array();
1502
1503 foreach ($objectList as $object) {
1504 $cleanObject = parent::_cleanObjectDatas($object);
1505
1506 unset($cleanObject->default_values);
1507 unset($cleanObject->lastsearch_values);
1508 unset($cleanObject->lastsearch_values_tmp);
1509
1510 unset($cleanObject->total_ht);
1511 unset($cleanObject->total_tva);
1512 unset($cleanObject->total_localtax1);
1513 unset($cleanObject->total_localtax2);
1514 unset($cleanObject->total_ttc);
1515
1516 unset($cleanObject->libelle_incoterms);
1517 unset($cleanObject->location_incoterms);
1518
1519 unset($cleanObject->fk_delivery_address);
1520 unset($cleanObject->fk_incoterms);
1521 unset($cleanObject->all_permissions_are_loaded);
1522 unset($cleanObject->shipping_method_id);
1523 unset($cleanObject->nb_rights);
1524 unset($cleanObject->search_sid);
1525 unset($cleanObject->ldap_sid);
1526 unset($cleanObject->clicktodial_loaded);
1527
1528 unset($cleanObject->datec);
1529 unset($cleanObject->tms);
1530 unset($cleanObject->members);
1531 unset($cleanObject->note);
1532 unset($cleanObject->note_private);
1533
1534 $cleanObjectList[] = $cleanObject;
1535 }
1536
1537 return $cleanObjectList;
1538 }
1539
1547 private function _validate($data) // @phpstan-ignore-line
1548 {
1549 $account = array();
1550 foreach (Users::$FIELDS as $field) {
1551 if (!isset($data[$field])) {
1552 throw new RestException(400, "$field field missing");
1553 }
1554 $account[$field] = $data[$field];
1555 }
1556 return $account;
1557 }
1558}
$id
Support class for third parties, contacts, members, users or resources.
Definition account.php:47
if(! $sortfield) if(! $sortorder) $object
Definition account.php:100
Class for API REST v1.
Definition api.class.php:35
_checkValExtrafieldsForAPI($field, $value, $object)
Check and convert a string depending on its type/name.
_filterObjectProperties($object, $properties)
Filter properties that will be returned on object.
_checkValForAPI($field, $value, $object)
Check and convert a string depending on its type/name.
static _checkAccessToResource($resource, $resource_id=0, $dbtablename='', $feature2='', $dbt_keyfield='fk_soc', $dbt_select='rowid', $parenttableforentity='')
Check access by user to a given resource.
Class to manage the table of subscription to notifications.
Class to manage user groups.
Class to manage Dolibarr users.
put($id, $request_data=null)
Update a user.
listGroups($sortfield="t.rowid", $sortorder='ASC', $limit=100, $page=0, $group_ids='0', $sqlfilters='', $properties='')
List groups of the current user (so user of API token)
index($sortfield="t.rowid", $sortorder='ASC', $limit=100, $page=0, $user_ids='0', $category=0, $sqlfilters='', $properties='')
List users.
deleteGroups($group)
Delete a usergroup.
_cleanObjectDatas($object)
Clean sensible object datas @phpstan-template T.
getInfo($includepermissions=0)
Get more properties of the current user (so user of API token).
_cleanUserGroupListDatas($objectList)
Clean sensible user group list datas.
updateUserNotification($id, $notification_id, $request_data=null)
Update a notification for a user.
setGroup($id, $group, $entity=1)
Add a user to a group.
setPassword($id, $send_password=false)
Update a user password.
postGroups($request_data=null)
Create user group.
deleteUserNotification($id, $notification_id)
Delete a notification attached to a user.
_validate($data)
Validate fields before create or update object.
infoGroups($group, $load_members=0, $includepermissions=0)
Get properties of a user group.
getByEmail($email, $includepermissions=0)
Get a user by email.
getGroups($id)
List the groups of a user.
putGroups($group, $request_data=null)
Update user group.
createUserNotificationByCode($id, $code, $request_data=null)
Create a notification for a user using action trigger code.
post($request_data=null)
Create a user.
createUserNotification($id, $request_data=null)
Create a notification for a user.
getByLogin($login, $includepermissions=0)
Get a user by login.
removeUserFromGroup($id, $group)
Remove user from group (only admin)
getUserNotification($id)
Get notifications for a user.
__construct()
Constructor.
_cleanUserGroup($object)
Clean sensible usergroup object datas.
print $script_file $mode $langs defaultlang(is_numeric($duration_value) ? " delay=". $duration_value :"").(is_numeric($duration_value2) ? " after cd cd cd description as p label as s rowid as s nom as s email
Sender: Who sends the email ("Sender" has sent emails on behalf of "From").
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $conf
The main.inc.php has been included so the following variable are now defined:
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $db
API class for accounts.
getDolGlobalInt($key, $default=0)
Return a Dolibarr global constant int value.
forgeSQLFromUniversalSearchCriteria($filter, &$errorstr='', $noand=0, $nopar=0, $noerror=0, $forbiddenfields=array())
forgeSQLFromUniversalSearchCriteria
getDolGlobalString($key, $default='')
Return a Dolibarr global constant string value.
sanitizeVal($out='', $check='alphanohtml', $filter=null, $options=null)
Return a sanitized or empty value after checking value against a rule.
isModEnabled($module)
Is Dolibarr module enabled.