dolibarr 24.0.0-beta
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 $errormessage = '';
116 $sql .= forgeSQLFromUniversalSearchCriteria($sqlfilters, $errormessage);
117 if ($errormessage) {
118 throw new RestException(400, 'Error when validating parameter sqlfilters -> '.$errormessage);
119 }
120 }
121
122 $sql .= $this->db->order($sortfield, $sortorder);
123 if ($limit) {
124 if ($page < 0) {
125 $page = 0;
126 }
127 $offset = $limit * $page;
128
129 $sql .= $this->db->plimit($limit + 1, $offset);
130 }
131
132 $result = $this->db->query($sql);
133
134 if ($result) {
135 $i = 0;
136 $num = $this->db->num_rows($result);
137 $min = min($num, ($limit <= 0 ? $num : $limit));
138 while ($i < $min) {
139 $obj = $this->db->fetch_object($result);
140 $user_static = new User($this->db);
141 if ($user_static->fetch($obj->rowid)) {
142 $obj_ret[] = $this->_filterObjectProperties($this->_cleanObjectDatas($user_static), $properties);
143 }
144 $i++;
145 }
146 } else {
147 throw new RestException(503, 'Error when retrieve User list : '.$this->db->lasterror());
148 }
149
150 return $obj_ret;
151 }
152
168 public function get($id, $includepermissions = 0)
169 {
170 if ($id == 0) {
171 throw new RestException(400, 'No user with id=0 can exist');
172 }
173
174 if (!DolibarrApiAccess::$user->hasRight('user', 'user', 'lire') && empty(DolibarrApiAccess::$user->admin) && $id != 0 && DolibarrApiAccess::$user->id != $id) {
175 throw new RestException(403, 'Not allowed');
176 }
177
178 if ($id == 0) {
179 $result = $this->useraccount->initAsSpecimen();
180 } else {
181 $result = $this->useraccount->fetch($id);
182 }
183 if (!$result) {
184 throw new RestException(404, 'User not found');
185 }
186
187 if ($id > 0 && !DolibarrApi::_checkAccessToResource('user', $this->useraccount->id, 'user')) {
188 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
189 }
190
191 if ($includepermissions) {
192 $this->useraccount->loadRights();
193 }
194
195 return $this->_cleanObjectDatas($this->useraccount);
196 }
197
215 public function getByLogin($login, $includepermissions = 0)
216 {
217 if (empty($login)) {
218 throw new RestException(400, 'Bad parameters');
219 }
220
221 if (!DolibarrApiAccess::$user->hasRight('user', 'user', 'lire') && empty(DolibarrApiAccess::$user->admin) && DolibarrApiAccess::$user->login != $login) {
222 throw new RestException(403, 'Not allowed');
223 }
224
225 $result = $this->useraccount->fetch(0, $login);
226 if (!$result) {
227 throw new RestException(404, 'User not found');
228 }
229
230 if (!DolibarrApi::_checkAccessToResource('user', $this->useraccount->id, 'user')) {
231 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
232 }
233
234 if ($includepermissions) {
235 $this->useraccount->loadRights();
236 }
237
238 return $this->_cleanObjectDatas($this->useraccount);
239 }
240
258 public function getByEmail($email, $includepermissions = 0)
259 {
260 if (empty($email)) {
261 throw new RestException(400, 'Bad parameters');
262 }
263
264 if (!DolibarrApiAccess::$user->hasRight('user', 'user', 'lire') && empty(DolibarrApiAccess::$user->admin) && DolibarrApiAccess::$user->email != $email) {
265 throw new RestException(403, 'Not allowed');
266 }
267
268 $result = $this->useraccount->fetch(0, '', '', 0, -1, $email);
269 if (!$result) {
270 throw new RestException(404, 'User not found');
271 }
272
273 if (!DolibarrApi::_checkAccessToResource('user', $this->useraccount->id, 'user')) {
274 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
275 }
276
277 if ($includepermissions) {
278 $this->useraccount->loadRights();
279 }
280
281 return $this->_cleanObjectDatas($this->useraccount);
282 }
283
299 public function getInfo($includepermissions = 0)
300 {
301 if (!DolibarrApiAccess::$user->hasRight('user', 'self', 'creer') && !DolibarrApiAccess::$user->hasRight('user', 'user', 'lire') && empty(DolibarrApiAccess::$user->admin)) {
302 throw new RestException(403, 'Not allowed');
303 }
304
305 $apiUser = DolibarrApiAccess::$user;
306
307 $result = $this->useraccount->fetch($apiUser->id);
308 if (!$result) {
309 throw new RestException(404, 'User not found');
310 }
311
312 if (!DolibarrApi::_checkAccessToResource('user', $this->useraccount->id, 'user')) {
313 throw new RestException(403, 'Access not allowed to current logged user');
314 }
315
316 if ($includepermissions) {
317 $this->useraccount->loadRights();
318 }
319
320 $usergroup = new UserGroup($this->db);
321 $userGroupList = $usergroup->listGroupsForUser($apiUser->id, false);
322 if (!is_array($userGroupList)) {
323 throw new RestException(404, 'User group not found');
324 }
325
326 $this->useraccount->user_group_list = $this->_cleanUserGroupListDatas($userGroupList);
327
328 return $this->_cleanObjectDatas($this->useraccount);
329 }
330
343 public function post($request_data = null)
344 {
345 // Check user authorization
346 if (!DolibarrApiAccess::$user->hasRight('user', 'user', 'creer') && empty(DolibarrApiAccess::$user->admin)) {
347 throw new RestException(403, "User creation not allowed for login ".DolibarrApiAccess::$user->login);
348 }
349
350 // check mandatory fields
351 if (!isset($request_data["login"]))
352 throw new RestException(500, "login field missing");
353 /*if (!isset($request_data["password"]))
354 throw new RestException(400, "password field missing");
355 if (!isset($request_data["lastname"]))
356 throw new RestException(400, "lastname field missing");*/
357
358 //assign field values
359 foreach ($request_data as $field => $value) {
360 if (in_array($field, array('pass_crypted', 'pass_indatabase', 'pass_indatabase_crypted', 'pass_temp', 'api_key'))) {
361 // This properties can't be set/modified with API
362 throw new RestException(405, 'The property '.$field." can't be set/modified using the APIs");
363 }
364 /*if ($field == 'pass') {
365 if (!DolibarrApiAccess::$user->hasRight('user', 'user', 'password')) {
366 throw new RestException(403, 'You are not allowed to modify/set password of other users');
367 continue;
368 }
369 }
370 */
371 if ($field === 'caller') {
372 // 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
373 $this->useraccount->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
374 continue;
375 }
376
377 if (DolibarrApiAccess::$user->admin) { // If user for API is admin
378 if ($field == 'admin' && $value != $this->useraccount->admin && empty($value)) {
379 throw new RestException(403, 'Reseting the admin status of a user is not possible using the API');
380 }
381 } else {
382 if ($field == 'admin' && $value != $this->useraccount->admin) {
383 throw new RestException(403, 'Only an admin user can modify the admin status of another user');
384 }
385 }
386
387 $this->useraccount->$field = $this->_checkValForAPI($field, $value, $this->useraccount);
388 }
389
390 if ($this->useraccount->create(DolibarrApiAccess::$user) < 0) {
391 throw new RestException(500, 'Error creating', array_merge(array($this->useraccount->error), $this->useraccount->errors));
392 }
393 return $this->useraccount->id;
394 }
395
396
412 public function put($id, $request_data = null)
413 {
414 $isSelfUpdate = ((int) $id === (int) DolibarrApiAccess::$user->id);
415
416 // Check user authorization
417 if (
418 !DolibarrApiAccess::$user->hasRight('user', 'user', 'creer')
419 && !DolibarrApiAccess::$user->hasRight('user', 'user', 'write')
420 && !(
421 $isSelfUpdate
422 && (
423 DolibarrApiAccess::$user->hasRight('user', 'self', 'creer')
424 || DolibarrApiAccess::$user->hasRight('user', 'self', 'write')
425 )
426 )
427 && empty(DolibarrApiAccess::$user->admin)
428 ) {
429 throw new RestException(403, "User update not allowed");
430 }
431
432 $result = $this->useraccount->fetch($id);
433 if (!$result) {
434 throw new RestException(404, 'Account not found');
435 }
436
437 if (!DolibarrApi::_checkAccessToResource('user', $this->useraccount->id, 'user')) {
438 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
439 }
440
441 foreach ($request_data as $field => $value) {
442 if (in_array($field, array('pass_crypted', 'pass_indatabase', 'pass_indatabase_crypted', 'pass_temp', 'api_key'))) {
443 // This properties can't be set/modified with API
444 throw new RestException(405, 'The property '.$field." can't be set/modified using the APIs");
445 }
446 if ($field == 'id') {
447 continue;
448 }
449 if ($field == 'pass') {
450 if ($this->useraccount->id != DolibarrApiAccess::$user->id && !DolibarrApiAccess::$user->hasRight('user', 'user', 'password')) {
451 throw new RestException(403, 'You are not allowed to modify password of other users');
452 }
453 if ($this->useraccount->id == DolibarrApiAccess::$user->id && !DolibarrApiAccess::$user->hasRight('user', 'self', 'password')) {
454 throw new RestException(403, 'You are not allowed to modify your own password');
455 }
456 }
457 if ($field === 'caller') {
458 // 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
459 $this->useraccount->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
460 continue;
461 }
462 if ($field == 'array_options' && is_array($value)) {
463 foreach ($value as $index => $val) {
464 $this->useraccount->array_options[$index] = $this->_checkValExtrafieldsForAPI($index, $val, $this->useraccount);
465 }
466 continue;
467 }
468
469 if (DolibarrApiAccess::$user->admin) { // If user for API is admin
470 if ($field == 'admin' && $value != $this->useraccount->admin && empty($value)) {
471 throw new RestException(403, 'Reseting the admin status of a user is not possible using the API');
472 }
473 } else {
474 if ($field == 'admin' && $value != $this->useraccount->admin) {
475 throw new RestException(403, 'Only an admin user can modify the admin status of another user');
476 }
477 }
478 if ($field == 'entity' && $value != $this->useraccount->entity) {
479 throw new RestException(403, 'Changing entity of a user using the APIs is not possible');
480 }
481
482 // The status must be updated using setstatus() because it
483 // is not handled by the update() method.
484 if ($field == 'statut' || $field == 'status') {
485 $result = $this->useraccount->setstatus($value);
486 if ($result < 0) {
487 throw new RestException(500, 'Error when updating status of user: '.$this->useraccount->error);
488 }
489 } else {
490 $this->useraccount->$field = $this->_checkValForAPI($field, $value, $this->useraccount);
491 }
492 }
493
494 // If there is no error, update() returns the number of affected
495 // rows so if the update is a no op, the return value is zezo.
496 if ($this->useraccount->update(DolibarrApiAccess::$user) >= 0) {
497 return $this->get($id);
498 } else {
499 throw new RestException(500, $this->useraccount->error);
500 }
501 }
502
518 public function setPassword($id, $send_password = false)
519 {
520 if (!getDolGlobalInt('API_ENABLE_LOGIN_API')) {
521 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.");
522 }
523
524 if (!getDolGlobalString('API_ALLOW_PASSWORD_RESET')) {
525 throw new RestException(403, "Error: password reset APIs are disabled by default. To allow this, the option API_ALLOW_PASSWORD_RESET must be set.");
526 }
527
528 if (!DolibarrApiAccess::$user->hasRight('user', 'user', 'creer') && empty(DolibarrApiAccess::$user->admin)) {
529 throw new RestException(403, "setPassword on user not allowed for login ".DolibarrApiAccess::$user->login);
530 }
531
532 $result = $this->useraccount->fetch($id);
533 if (!$result) {
534 throw new RestException(404, 'User not found, no password changed');
535 }
536
537 if (!DolibarrApi::_checkAccessToResource('user', $this->useraccount->id, 'user')) {
538 throw new RestException(403, 'Access on this object not allowed for login '.DolibarrApiAccess::$user->login);
539 }
540
541 $newpassword = $this->useraccount->setPassword($this->useraccount, ''); // This will generate a new password
542 if (is_int($newpassword) && $newpassword < 0) {
543 throw new RestException(500, 'ErrorFailedToSetNewPassword'.$this->useraccount->error);
544 } else {
545 // Success
546 if ($send_password) {
547 if ($this->useraccount->send_password($this->useraccount, $newpassword) > 0) {
548 return 2;
549 } else {
550 throw new RestException(500, 'ErrorFailedSendingNewPassword - '.$this->useraccount->error);
551 }
552 } else {
553 return 1;
554 }
555 }
556 }
557
574 public function getGroups($id)
575 {
576 if ($id == 0) {
577 throw new RestException(400, 'No user with id=0 can exist');
578 }
579
580 if (!DolibarrApiAccess::$user->hasRight('user', 'user', 'lire') && empty(DolibarrApiAccess::$user->admin)) {
581 throw new RestException(403);
582 }
583
584 $user = new User($this->db);
585 $result = $user->fetch($id);
586 if (!$result) {
587 throw new RestException(404, 'user not found');
588 }
589
590 $usergroup = new UserGroup($this->db);
591 $groups = $usergroup->listGroupsForUser($id, false);
592 $obj_ret = array();
593 foreach ($groups as $group) {
594 $obj_ret[] = $this->_cleanObjectDatas($group);
595 }
596 return $obj_ret;
597 }
598
599
616 public function setGroup($id, $group, $entity = 1)
617 {
618 global $conf;
619
620 if (!DolibarrApiAccess::$user->hasRight('user', 'user', 'creer') && empty(DolibarrApiAccess::$user->admin)) {
621 throw new RestException(403, 'setGroup on users not allowed for login '.DolibarrApiAccess::$user->login);
622 }
623
624 $result = $this->useraccount->fetch($id);
625 if (!$result) {
626 throw new RestException(404, 'User not found');
627 }
628
629 if (!DolibarrApi::_checkAccessToResource('user', $this->useraccount->id, 'user')) {
630 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
631 }
632
633 if (isModEnabled('multicompany') && getDolGlobalString('MULTICOMPANY_TRANSVERSE_MODE') && !empty(DolibarrApiAccess::$user->admin) && empty(DolibarrApiAccess::$user->entity)) {
634 $entity = (!empty($entity) ? (int) $entity : $conf->entity);
635 } else {
636 // 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
637 // hack the security by giving himself permissions on another entity.
638 $entity = (((int) DolibarrApiAccess::$user->entity) > 0 ? (int) DolibarrApiAccess::$user->entity : $conf->entity);
639 }
640
641 $result = $this->useraccount->SetInGroup($group, $entity);
642 if (!($result > 0)) {
643 throw new RestException(500, $this->useraccount->error);
644 }
645
646 return 1;
647 }
648
662 public function postGroups($request_data = null)
663 {
664 // Check user authorization
665 if (!DolibarrApiAccess::$user->hasRight('user', 'group_advance', 'write') && empty(DolibarrApiAccess::$user->admin)) {
666 throw new RestException(403, "Usergroup creation not allowed for login ".DolibarrApiAccess::$user->login);
667 }
668 $usergroup = new UserGroup($this->db);
669 foreach ($request_data as $field => $value) {
670 if ($field === 'caller') {
671 // 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
672 $usergroup->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
673 continue;
674 }
675 if ($field == 'id') {
676 throw new RestException(400, 'Creating with id field is forbidden');
677 }
678
679 $usergroup->$field = $this->_checkValForAPI($field, $value, $usergroup);
680 }
681
682 if ($usergroup->create(1) < 0) {
683 throw new RestException(500, 'Error creating', array_merge(array($usergroup->error), $usergroup->errors));
684 }
685 return $usergroup->id;
686 }
687
705 public function putGroups($group, $request_data = null)
706 {
707 // Check user authorization
708 if (!DolibarrApiAccess::$user->hasRight('user', 'group_advance', 'write') && empty(DolibarrApiAccess::$user->admin)) {
709 throw new RestException(403, "Usergroup update not allowed");
710 }
711
712 $usergroup = new UserGroup($this->db);
713
714 $result = $usergroup->fetch($group);
715 if ($result < 1) {
716 throw new RestException(404, 'Usergroup not found');
717 }
718
719 foreach ($request_data as $field => $value) {
720 if ($field == 'id') {
721 throw new RestException(400, 'Updating with id field is forbidden');
722 }
723 if ($field === 'caller') {
724 // 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
725 $usergroup->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
726 continue;
727 }
728
729 if ($field == 'entity' && $value != $usergroup->entity) {
730 throw new RestException(403, 'Changing entity of a user using the APIs is not possible');
731 }
732
733 $usergroup->$field = $this->_checkValForAPI($field, $value, $usergroup);
734 }
735
736 // If there is no error, update() returns the number of affected
737 // rows so if the update is a no op, the return value is zezo.
738 if ($usergroup->update() >= 0) {
739 return $this->infoGroups($group);
740 } else {
741 throw new RestException(500, $usergroup->error);
742 }
743 }
744
760 public function removeUserFromGroup($id, $group)
761 {
762 if (!DolibarrApiAccess::$user->admin) {
763 throw new RestException(403, 'Only admin can remove users from groups');
764 }
765
766 $sql = "DELETE FROM " . MAIN_DB_PREFIX . "usergroup_user";
767 $sql .= " WHERE fk_user = " . ((int) $id);
768 $sql .= " AND fk_usergroup = " . ((int) $group);
769
770 $resql = $this->db->query($sql);
771
772 if (!$resql) {
773 throw new RestException(503, 'DB error: ' . $this->db->lasterror());
774 }
775
776 return [
777 'success' => true,
778 'message' => "User $id removed from group $group"
779 ];
780 }
781
806 public function listGroups($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $group_ids = '0', $sqlfilters = '', $properties = '')
807 {
808 $obj_ret = array();
809
810 if ((!getDolGlobalString('MAIN_USE_ADVANCED_PERMS') && !DolibarrApiAccess::$user->hasRight('user', 'user', 'lire') && empty(DolibarrApiAccess::$user->admin)) ||
811 getDolGlobalString('MAIN_USE_ADVANCED_PERMS') && !DolibarrApiAccess::$user->hasRight('user', 'group_advance', 'read') && empty(DolibarrApiAccess::$user->admin)) {
812 throw new RestException(403, "You are not allowed to read groups");
813 }
814
815 // case of external user, $societe param is ignored and replaced by user's socid
816 //$socid = DolibarrApiAccess::$user->socid ?: $societe;
817
818 $sql = "SELECT t.rowid";
819 $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
820 $sql .= ' WHERE t.entity IN ('.getEntity('user').')';
821 if ($group_ids) {
822 $sql .= " AND t.rowid IN (".$this->db->sanitize($group_ids).")";
823 }
824 // Add sql filters
825 if ($sqlfilters) {
826 $errormessage = '';
827 $sql .= forgeSQLFromUniversalSearchCriteria($sqlfilters, $errormessage);
828 if ($errormessage) {
829 throw new RestException(400, 'Error when validating parameter sqlfilters -> '.$errormessage);
830 }
831 }
832
833 $sql .= $this->db->order($sortfield, $sortorder);
834 if ($limit) {
835 if ($page < 0) {
836 $page = 0;
837 }
838 $offset = $limit * $page;
839
840 $sql .= $this->db->plimit($limit + 1, $offset);
841 }
842
843 $result = $this->db->query($sql);
844
845 if ($result) {
846 $i = 0;
847 $num = $this->db->num_rows($result);
848 $min = min($num, ($limit <= 0 ? $num : $limit));
849 while ($i < $min) {
850 $obj = $this->db->fetch_object($result);
851 $group_static = new UserGroup($this->db);
852 if ($group_static->fetch($obj->rowid)) {
853 $obj_ret[] = $this->_filterObjectProperties($this->_cleanObjectDatas($group_static), $properties);
854 }
855 $i++;
856 }
857 } else {
858 throw new RestException(503, 'Error when retrieve Group list : '.$this->db->lasterror());
859 }
860
861 return $obj_ret;
862 }
863
882 public function infoGroups($group, $load_members = 0, $includepermissions = 0)
883 {
884 if ($group == 0) {
885 throw new RestException(400, 'No usergroup with id=0 can exist');
886 }
887
888 if ((!getDolGlobalString('MAIN_USE_ADVANCED_PERMS') && !DolibarrApiAccess::$user->hasRight('user', 'user', 'lire') && empty(DolibarrApiAccess::$user->admin)) ||
889 getDolGlobalString('MAIN_USE_ADVANCED_PERMS') && !DolibarrApiAccess::$user->hasRight('user', 'group_advance', 'read') && empty(DolibarrApiAccess::$user->admin)) {
890 throw new RestException(403, "You are not allowed to read groups");
891 }
892
893 $group_static = new UserGroup($this->db);
894 $result = $group_static->fetch($group, '', (bool) $load_members);
895
896 if ($result < 1) {
897 throw new RestException(404, 'Usergroup not found');
898 }
899
900 if ($includepermissions) {
901 $group_static->loadRights();
902 }
903
904 if ($load_members > 0 && is_array($group_static->members) && count($group_static->members) > 0) {
905 foreach ($group_static->members as &$member) {
906 $member = $this->_cleanObjectDatas($member);
907 }
908 }
909
910 return $this->_cleanUserGroup($group_static);
911 }
912
926 public function delete($id)
927 {
928 if (!DolibarrApiAccess::$user->hasRight('user', 'user', 'supprimer') && empty(DolibarrApiAccess::$user->admin)) {
929 throw new RestException(403, 'Not allowed');
930 }
931 $result = $this->useraccount->fetch($id);
932 if (!$result) {
933 throw new RestException(404, 'User not found');
934 }
935
936 if (!DolibarrApi::_checkAccessToResource('user', $this->useraccount->id, 'user')) {
937 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
938 }
939 $this->useraccount->oldcopy = clone $this->useraccount; // @phan-suppress-current-line PhanTypeMismatchProperty
940
941 if (!$this->useraccount->delete(DolibarrApiAccess::$user)) {
942 throw new RestException(500);
943 }
944
945 return array(
946 'success' => array(
947 'code' => 200,
948 'message' => 'User deleted'
949 )
950 );
951 }
952
968 public function deleteGroups($group)
969 {
970 if (!DolibarrApiAccess::$user->hasRight('user', 'group_advance', 'delete') && empty(DolibarrApiAccess::$user->admin)) {
971 throw new RestException(403, 'Not allowed');
972 }
973
974 $usergroup = new UserGroup($this->db);
975
976 $result = $usergroup->fetch($group);
977 if ($result < 0) {
978 throw new RestException(404, 'Usergroup not found');
979 }
980
981 if (!$usergroup->delete(DolibarrApiAccess::$user)) {
982 throw new RestException(500);
983 }
984
985 return array(
986 'success' => array(
987 'code' => 200,
988 'message' => 'Usergroup deleted'
989 )
990 );
991 }
992
1010 public function getUserNotification($id)
1011 {
1012 if (empty($id)) {
1013 throw new RestException(400, 'No user with id=0 can exist');
1014 }
1015 if (!DolibarrApiAccess::$user->hasRight('user', 'user', 'lire') && empty(DolibarrApiAccess::$user->admin)) {
1016 throw new RestException(403);
1017 }
1019 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1020 }
1021
1026 $sql = "SELECT rowid as id, fk_action as event, fk_user, type, datec, tms";
1027 $sql .= " FROM ".MAIN_DB_PREFIX."notify_def";
1028 $sql .= " WHERE fk_user = ".((int) $id);
1029
1030 $result = $this->db->query($sql);
1031 if ($this->db->num_rows($result) == 0) {
1032 throw new RestException(404, 'Notification not found');
1033 }
1034
1035 $i = 0;
1036
1037 $notifications = array();
1038
1039 if ($result) {
1040 $num = $this->db->num_rows($result);
1041 //$min = min($num, ($limit <= 0 ? $num : $limit));
1042 $min = $num;
1043 while ($i < $min) {
1044 $obj = $this->db->fetch_object($result);
1045 $notifications[] = $obj;
1046 $i++;
1047 }
1048 } else {
1049 throw new RestException(404, 'No notifications found');
1050 }
1051
1052 $fields = array('id', 'fk_user', 'event', 'datec', 'tms', 'type');
1053
1054 $returnNotifications = array();
1055
1056 foreach ($notifications as $notification) {
1057 $object = array();
1058 foreach ($notification as $key => $value) {
1059 if (in_array($key, $fields)) {
1060 $object[$key] = $value;
1061 }
1062 }
1063 $returnNotifications[] = $object;
1064 }
1065
1066 // Too complex for phan ?: @phan-suppress-next-line PhanTypeMismatchReturn
1067 return $returnNotifications;
1068 }
1069
1086 public function createUserNotification($id, $request_data = null)
1087 {
1088 if (!DolibarrApiAccess::$user->hasRight('user', 'user', 'creer')) {
1089 throw new RestException(403, "User has no right to update users");
1090 }
1091 if ($this->useraccount->fetch($id) <= 0) {
1092 throw new RestException(404, 'Error creating User Notification, User doesn\'t exists');
1093 }
1094 $notification = new Notify($this->db);
1095
1096 $notification->fk_user = $id;
1097
1098 foreach ($request_data as $field => $value) {
1099 $notification->$field = $this->_checkValForAPI($field, $value, $notification);
1100 }
1101
1102 $event = $notification->event;
1103 if (!$event) {
1104 throw new RestException(500, 'Error creating User Notification, request_data missing event');
1105 }
1106 $fk_user = $notification->fk_user;
1107
1108 $exists_sql = "SELECT rowid, fk_action as event, fk_user, type, datec, tms as datem";
1109 $exists_sql .= " FROM ".MAIN_DB_PREFIX."notify_def";
1110 $exists_sql .= " WHERE fk_action = '".$this->db->escape((string) $event)."'";
1111 $exists_sql .= " AND fk_user = '".$this->db->escape((string) $fk_user)."'";
1112
1113 $exists_result = $this->db->query($exists_sql);
1114 if ($this->db->num_rows($exists_result) > 0) {
1115 throw new RestException(403, 'Notification already exists');
1116 }
1117
1118 if ($notification->create(DolibarrApiAccess::$user) < 0) {
1119 throw new RestException(500, 'Error creating User Notification');
1120 }
1121
1122 if ($notification->update(DolibarrApiAccess::$user) < 0) {
1123 throw new RestException(500, 'Error updating values');
1124 }
1125
1126 return $this->_cleanObjectDatas($notification);
1127 }
1128
1147 public function createUserNotificationByCode($id, $code, $request_data = null)
1148 {
1149 if (!DolibarrApiAccess::$user->hasRight('user', 'user', 'creer')) {
1150 throw new RestException(403, "User has no right to update users");
1151 }
1152 if ($this->useraccount->fetch($id) <= 0) {
1153 throw new RestException(404, 'Error creating User Notification, User doesn\'t exists');
1154 }
1155 $notification = new Notify($this->db);
1156 $notification->fk_user = $id;
1157
1158 $sql = "SELECT t.rowid as id FROM ".MAIN_DB_PREFIX."c_action_trigger as t";
1159 $sql .= " WHERE t.code = '".$this->db->escape($code)."'";
1160
1161 $result = $this->db->query($sql);
1162 if ($this->db->num_rows($result) == 0) {
1163 throw new RestException(404, 'Action Trigger code not found');
1164 }
1165
1166 $notification->event = $this->db->fetch_row($result)[0];
1167 foreach ($request_data as $field => $value) {
1168 if ($field === 'event') {
1169 throw new RestException(500, 'Error creating User Notification, request_data contains event key');
1170 }
1171 if ($field === 'fk_action') {
1172 throw new RestException(500, 'Error creating User Notification, request_data contains fk_action key');
1173 }
1174 $notification->$field = $this->_checkValForAPI($field, $value, $notification);
1175 }
1176
1177 $event = $notification->event;
1178 $fk_user = $notification->fk_user;
1179
1180 $exists_sql = "SELECT rowid, fk_action as event, fk_user, type, datec, tms as datem";
1181 $exists_sql .= " FROM ".MAIN_DB_PREFIX."notify_def";
1182 $exists_sql .= " WHERE fk_action = '".$this->db->escape((string) $event)."'";
1183 $exists_sql .= " AND fk_user = '".$this->db->escape((string) $fk_user)."'";
1184
1185 $exists_result = $this->db->query($exists_sql);
1186 if ($this->db->num_rows($exists_result) > 0) {
1187 throw new RestException(403, 'Notification already exists');
1188 }
1189
1190 if ($notification->create(DolibarrApiAccess::$user) < 0) {
1191 throw new RestException(500, 'Error creating User Notification, are request_data well formed?');
1192 }
1193
1194 if ($notification->update(DolibarrApiAccess::$user) < 0) {
1195 throw new RestException(500, 'Error updating values');
1196 }
1197
1198 return $this->_cleanObjectDatas($notification);
1199 }
1200
1215 public function deleteUserNotification($id, $notification_id)
1216 {
1217 if (!DolibarrApiAccess::$user->hasRight('user', 'user', 'creer')) {
1218 throw new RestException(403, "User has no right to update users");
1219 }
1220
1221 $notification = new Notify($this->db);
1222
1223 $notification->fetch($notification_id);
1224
1225 $fk_user = (int) $notification->fk_user;
1226
1227 if ($fk_user == $id) {
1228 return $notification->delete(DolibarrApiAccess::$user);
1229 } else {
1230 throw new RestException(403, "Not allowed due to bad consistency of input data");
1231 }
1232 }
1233
1251 public function updateUserNotification($id, $notification_id, $request_data = null)
1252 {
1253 if (!DolibarrApiAccess::$user->hasRight('user', 'user', 'creer')) {
1254 throw new RestException(403, "User has no right to update users");
1255 }
1256 if ($this->useraccount->fetch($id) <= 0) {
1257 throw new RestException(404, 'Error creating Notification, User doesn\'t exists');
1258 }
1259 $notification = new Notify($this->db);
1260
1261 // @phan-suppress-next-line PhanPluginSuspiciousParamPosition
1262 $notification->fetch($notification_id, $id);
1263
1264 if ($notification->fk_user != $id) {
1265 throw new RestException(403, "Not allowed due to bad consistency of input data");
1266 }
1267
1268 foreach ($request_data as $field => $value) {
1269 $notification->$field = $this->_checkValForAPI($field, $value, $notification);
1270 }
1271
1272 if ($notification->update(DolibarrApiAccess::$user) < 0) {
1273 throw new RestException(500, 'Error updating values');
1274 }
1275
1276 return $this->_cleanObjectDatas($notification);
1277 }
1278
1279 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
1289 protected function _cleanObjectDatas($object)
1290 {
1291 // phpcs:enable
1292 $object = parent::_cleanObjectDatas($object);
1293
1294 unset($object->default_values);
1295 unset($object->lastsearch_values);
1296 unset($object->lastsearch_values_tmp);
1297
1298 unset($object->total_ht);
1299 unset($object->total_tva);
1300 unset($object->total_localtax1);
1301 unset($object->total_localtax2);
1302 unset($object->total_ttc);
1303
1304 unset($object->label_incoterms);
1305 unset($object->location_incoterms);
1306
1307 unset($object->fk_delivery_address);
1308 unset($object->fk_incoterms);
1309 unset($object->all_permissions_are_loaded);
1310 unset($object->shipping_method_id);
1311 unset($object->nb_rights);
1312 unset($object->search_sid);
1313 unset($object->ldap_sid);
1314 unset($object->clicktodial_loaded);
1315
1316 // List of properties never returned by API, whatever are permissions
1317 unset($object->pass);
1318 unset($object->pass_indatabase);
1319 unset($object->pass_indatabase_crypted);
1320 unset($object->pass_temp);
1321 unset($object->api_key);
1322 unset($object->clicktodial_password);
1323 unset($object->openid);
1324
1325 unset($object->lines);
1326 unset($object->model_pdf);
1327
1328 $canreadsalary = ((isModEnabled('salaries') && DolibarrApiAccess::$user->hasRight('salaries', 'read')) || !isModEnabled('salaries'));
1329
1330 if (!$canreadsalary) {
1331 unset($object->salary);
1332 unset($object->salaryextra);
1333 unset($object->thm);
1334 unset($object->tjm);
1335 }
1336
1337 return $object;
1338 }
1339
1340 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
1347 private function _cleanUserGroup($object)
1348 {
1349 // phpcs:enable
1350 $object = parent::_cleanObjectDatas($object);
1351
1352 unset($object->actiontypecode);
1353 unset($object->all_permissions_are_loaded);
1354 unset($object->barcode_type_coder);
1355 unset($object->barcode_type);
1356 unset($object->canvas);
1357 unset($object->civility_code);
1358 unset($object->civility_id);
1359 unset($object->clicktodial_loaded);
1360 unset($object->cond_reglement_id);
1361 unset($object->cond_reglement_supplier_id);
1362 unset($object->contact_id);
1363 unset($object->contacts_ids_internal);
1364 unset($object->contacts_ids);
1365 unset($object->country_code);
1366 unset($object->country_id);
1367 unset($object->date_cloture);
1368 unset($object->date_creation);
1369 unset($object->date_modification);
1370 unset($object->date_validation);
1371 unset($object->default_values);
1372 unset($object->demand_reason_id);
1373 unset($object->deposit_percent);
1374 unset($object->extraparams);
1375 unset($object->firstname);
1376 unset($object->fk_account);
1377 unset($object->fk_delivery_address);
1378 unset($object->fk_incoterms);
1379 unset($object->fk_multicurrency);
1380 unset($object->fk_project);
1381 unset($object->fk_user_creat);
1382 unset($object->fk_user_modif);
1383 unset($object->globalgroup);
1384 unset($object->import_key);
1385 unset($object->last_main_doc);
1386 unset($object->lastname);
1387 unset($object->lastsearch_values_tmp);
1388 unset($object->lastsearch_values);
1389 unset($object->ldap_sid);
1390 unset($object->libelle_incoterms);
1391 unset($object->lines);
1392 unset($object->linkedObjectsIds);
1393 unset($object->location_incoterms);
1394 unset($object->members);
1395 unset($object->mode_reglement_id);
1396 unset($object->module);
1397 unset($object->multicurrency_code);
1398 unset($object->multicurrency_total_ht);
1399 unset($object->multicurrency_total_localtax1);
1400 unset($object->multicurrency_total_localtax2);
1401 unset($object->multicurrency_total_ttc);
1402 unset($object->multicurrency_total_tva);
1403 unset($object->multicurrency_tx);
1404 unset($object->nb_rights);
1405 unset($object->nb_users);
1406 unset($object->note_public);
1407 unset($object->origin_id);
1408 unset($object->origin_type);
1409 unset($object->product);
1410 unset($object->ref_ext);
1411 unset($object->ref);
1412 unset($object->region_id);
1413 unset($object->retained_warranty_fk_cond_reglement);
1414 unset($object->rights);
1415 unset($object->search_sid);
1416 unset($object->shipping_method_id);
1417 unset($object->shipping_method);
1418 unset($object->specimen);
1419 unset($object->state_id);
1420 unset($object->status);
1421 unset($object->statut);
1422 unset($object->total_ht);
1423 unset($object->total_localtax1);
1424 unset($object->total_localtax2);
1425 unset($object->total_ttc);
1426 unset($object->total_tva);
1427 unset($object->totalpaid_multicurrency);
1428 unset($object->totalpaid);
1429 unset($object->transport_mode_id);
1430 unset($object->TRIGGER_PREFIX);
1431 unset($object->user_closing_id);
1432 unset($object->user_creation_id);
1433 unset($object->user_modification_id);
1434 unset($object->user_validation_id);
1435 unset($object->user);
1436 unset($object->usergroup_entity);
1437 unset($object->warehouse_id);
1438
1439 return $object;
1440 }
1441
1448 private function _cleanUserGroupListDatas($objectList)
1449 {
1450 $cleanObjectList = array();
1451
1452 foreach ($objectList as $object) {
1453 $cleanObject = parent::_cleanObjectDatas($object);
1454
1455 unset($cleanObject->default_values);
1456 unset($cleanObject->lastsearch_values);
1457 unset($cleanObject->lastsearch_values_tmp);
1458
1459 unset($cleanObject->total_ht);
1460 unset($cleanObject->total_tva);
1461 unset($cleanObject->total_localtax1);
1462 unset($cleanObject->total_localtax2);
1463 unset($cleanObject->total_ttc);
1464
1465 unset($cleanObject->libelle_incoterms);
1466 unset($cleanObject->location_incoterms);
1467
1468 unset($cleanObject->fk_delivery_address);
1469 unset($cleanObject->fk_incoterms);
1470 unset($cleanObject->all_permissions_are_loaded);
1471 unset($cleanObject->shipping_method_id);
1472 unset($cleanObject->nb_rights);
1473 unset($cleanObject->search_sid);
1474 unset($cleanObject->ldap_sid);
1475 unset($cleanObject->clicktodial_loaded);
1476
1477 unset($cleanObject->datec);
1478 unset($cleanObject->tms);
1479 unset($cleanObject->members);
1480 unset($cleanObject->note);
1481 unset($cleanObject->note_private);
1482
1483 $cleanObjectList[] = $cleanObject;
1484 }
1485
1486 return $cleanObjectList;
1487 }
1488
1496 private function _validate($data) // @phpstan-ignore-line
1497 {
1498 $account = array();
1499 foreach (Users::$FIELDS as $field) {
1500 if (!isset($data[$field])) {
1501 throw new RestException(400, "$field field missing");
1502 }
1503 $account[$field] = $data[$field];
1504 }
1505 return $account;
1506 }
1507}
$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.
static _checkAccessToResource($resource, $resource_id=0, $dbtablename='', $feature2='', $dbt_keyfield='fk_soc', $dbt_select='rowid')
Check access by user to a given resource.
_checkValForAPI($field, $value, $object)
Check and convert a string depending on its type/name.
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.
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.