dolibarr 23.0.3
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 *
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 3 of the License, or
12 * (at your option) any later version.
13 *
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
18 *
19 * You should have received a copy of the GNU General Public License
20 * along with this program. If not, see <https://www.gnu.org/licenses/>.
21 */
22
23use Luracast\Restler\RestException;
24
25require_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php';
26require_once DOL_DOCUMENT_ROOT.'/user/class/usergroup.class.php';
27require_once DOL_DOCUMENT_ROOT.'/core/class/notify.class.php';
28
29
38class Users extends DolibarrApi
39{
43 public static $FIELDS = array(
44 'login',
45 );
46
50 public $useraccount;
51
55 public function __construct()
56 {
57 global $db;
58
59 $this->db = $db;
60 $this->useraccount = new User($this->db);
61 }
62
63
85 public function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $user_ids = '0', $category = 0, $sqlfilters = '', $properties = '')
86 {
87 if (!DolibarrApiAccess::$user->hasRight('user', 'user', 'lire') && empty(DolibarrApiAccess::$user->admin)) {
88 throw new RestException(403, "You are not allowed to read list of users");
89 }
90
91 $obj_ret = array();
92
93 // case of external user, $societe param is ignored and replaced by user's socid
94 //$socid = DolibarrApiAccess::$user->socid ?: $societe;
95
96 $sql = "SELECT t.rowid";
97 $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
98 if ($category > 0) {
99 $sql .= ", ".$this->db->prefix()."categorie_user as c";
100 }
101 $sql .= ' WHERE t.entity IN ('.getEntity('user').')';
102 if ($user_ids) {
103 $sql .= " AND t.rowid IN (".$this->db->sanitize($user_ids).")";
104 }
105
106 // Select products of given category
107 if ($category > 0) {
108 $sql .= " AND c.fk_categorie = ".((int) $category);
109 $sql .= " AND c.fk_user = t.rowid";
110 }
111
112 // Add sql filters
113 if ($sqlfilters) {
114 $errormessage = '';
115 $sql .= forgeSQLFromUniversalSearchCriteria($sqlfilters, $errormessage);
116 if ($errormessage) {
117 throw new RestException(400, 'Error when validating parameter sqlfilters -> '.$errormessage);
118 }
119 }
120
121 $sql .= $this->db->order($sortfield, $sortorder);
122 if ($limit) {
123 if ($page < 0) {
124 $page = 0;
125 }
126 $offset = $limit * $page;
127
128 $sql .= $this->db->plimit($limit + 1, $offset);
129 }
130
131 $result = $this->db->query($sql);
132
133 if ($result) {
134 $i = 0;
135 $num = $this->db->num_rows($result);
136 $min = min($num, ($limit <= 0 ? $num : $limit));
137 while ($i < $min) {
138 $obj = $this->db->fetch_object($result);
139 $user_static = new User($this->db);
140 if ($user_static->fetch($obj->rowid)) {
141 $obj_ret[] = $this->_filterObjectProperties($this->_cleanObjectDatas($user_static), $properties);
142 }
143 $i++;
144 }
145 } else {
146 throw new RestException(503, 'Error when retrieve User list : '.$this->db->lasterror());
147 }
148
149 return $obj_ret;
150 }
151
167 public function get($id, $includepermissions = 0)
168 {
169 if ($id == 0) {
170 throw new RestException(400, 'No user with id=0 can exist');
171 }
172
173 if (!DolibarrApiAccess::$user->hasRight('user', 'user', 'lire') && empty(DolibarrApiAccess::$user->admin) && $id != 0 && DolibarrApiAccess::$user->id != $id) {
174 throw new RestException(403, 'Not allowed');
175 }
176
177 if ($id == 0) {
178 $result = $this->useraccount->initAsSpecimen();
179 } else {
180 $result = $this->useraccount->fetch($id);
181 }
182 if (!$result) {
183 throw new RestException(404, 'User not found');
184 }
185
186 if ($id > 0 && !DolibarrApi::_checkAccessToResource('user', $this->useraccount->id, 'user')) {
187 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
188 }
189
190 if ($includepermissions) {
191 $this->useraccount->loadRights();
192 }
193
194 return $this->_cleanObjectDatas($this->useraccount);
195 }
196
214 public function getByLogin($login, $includepermissions = 0)
215 {
216 if (empty($login)) {
217 throw new RestException(400, 'Bad parameters');
218 }
219
220 if (!DolibarrApiAccess::$user->hasRight('user', 'user', 'lire') && empty(DolibarrApiAccess::$user->admin) && DolibarrApiAccess::$user->login != $login) {
221 throw new RestException(403, 'Not allowed');
222 }
223
224 $result = $this->useraccount->fetch(0, $login);
225 if (!$result) {
226 throw new RestException(404, 'User not found');
227 }
228
229 if (!DolibarrApi::_checkAccessToResource('user', $this->useraccount->id, 'user')) {
230 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
231 }
232
233 if ($includepermissions) {
234 $this->useraccount->loadRights();
235 }
236
237 return $this->_cleanObjectDatas($this->useraccount);
238 }
239
257 public function getByEmail($email, $includepermissions = 0)
258 {
259 if (empty($email)) {
260 throw new RestException(400, 'Bad parameters');
261 }
262
263 if (!DolibarrApiAccess::$user->hasRight('user', 'user', 'lire') && empty(DolibarrApiAccess::$user->admin) && DolibarrApiAccess::$user->email != $email) {
264 throw new RestException(403, 'Not allowed');
265 }
266
267 $result = $this->useraccount->fetch(0, '', '', 0, -1, $email);
268 if (!$result) {
269 throw new RestException(404, 'User not found');
270 }
271
272 if (!DolibarrApi::_checkAccessToResource('user', $this->useraccount->id, 'user')) {
273 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
274 }
275
276 if ($includepermissions) {
277 $this->useraccount->loadRights();
278 }
279
280 return $this->_cleanObjectDatas($this->useraccount);
281 }
282
298 public function getInfo($includepermissions = 0)
299 {
300 if (!DolibarrApiAccess::$user->hasRight('user', 'self', 'creer') && !DolibarrApiAccess::$user->hasRight('user', 'user', 'lire') && empty(DolibarrApiAccess::$user->admin)) {
301 throw new RestException(403, 'Not allowed');
302 }
303
304 $apiUser = DolibarrApiAccess::$user;
305
306 $result = $this->useraccount->fetch($apiUser->id);
307 if (!$result) {
308 throw new RestException(404, 'User not found');
309 }
310
311 if (!DolibarrApi::_checkAccessToResource('user', $this->useraccount->id, 'user')) {
312 throw new RestException(403, 'Access not allowed to current logged user');
313 }
314
315 if ($includepermissions) {
316 $this->useraccount->loadRights();
317 }
318
319 $usergroup = new UserGroup($this->db);
320 $userGroupList = $usergroup->listGroupsForUser($apiUser->id, false);
321 if (!is_array($userGroupList)) {
322 throw new RestException(404, 'User group not found');
323 }
324
325 $this->useraccount->user_group_list = $this->_cleanUserGroupListDatas($userGroupList);
326
327 return $this->_cleanObjectDatas($this->useraccount);
328 }
329
342 public function post($request_data = null)
343 {
344 // Check user authorization
345 if (!DolibarrApiAccess::$user->hasRight('user', 'user', 'creer') && empty(DolibarrApiAccess::$user->admin)) {
346 throw new RestException(403, "User creation not allowed for login ".DolibarrApiAccess::$user->login);
347 }
348
349 // check mandatory fields
350 if (!isset($request_data["login"]))
351 throw new RestException(500, "login field missing");
352 /*if (!isset($request_data["password"]))
353 throw new RestException(400, "password field missing");
354 if (!isset($request_data["lastname"]))
355 throw new RestException(400, "lastname field missing");*/
356
357 //assign field values
358 foreach ($request_data as $field => $value) {
359 if (in_array($field, array('pass_crypted', 'pass_indatabase', 'pass_indatabase_crypted', 'pass_temp', 'api_key'))) {
360 // This properties can't be set/modified with API
361 throw new RestException(405, 'The property '.$field." can't be set/modified using the APIs");
362 }
363 /*if ($field == 'pass') {
364 if (!DolibarrApiAccess::$user->hasRight('user', 'user', 'password')) {
365 throw new RestException(403, 'You are not allowed to modify/set password of other users');
366 continue;
367 }
368 }
369 */
370 if ($field === 'caller') {
371 // 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
372 $this->useraccount->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
373 continue;
374 }
375
376 if (DolibarrApiAccess::$user->admin) { // If user for API is admin
377 if ($field == 'admin' && $value != $this->useraccount->admin && empty($value)) {
378 throw new RestException(403, 'Reseting the admin status of a user is not possible using the API');
379 }
380 } else {
381 if ($field == 'admin' && $value != $this->useraccount->admin) {
382 throw new RestException(403, 'Only an admin user can modify the admin status of another user');
383 }
384 }
385
386 $this->useraccount->$field = $this->_checkValForAPI($field, $value, $this->useraccount);
387 }
388
389 if ($this->useraccount->create(DolibarrApiAccess::$user) < 0) {
390 throw new RestException(500, 'Error creating', array_merge(array($this->useraccount->error), $this->useraccount->errors));
391 }
392 return $this->useraccount->id;
393 }
394
395
411 public function put($id, $request_data = null)
412 {
413 // Check user authorization
414 if (!DolibarrApiAccess::$user->hasRight('user', 'user', 'creer') && empty(DolibarrApiAccess::$user->admin)) {
415 throw new RestException(403, "User update not allowed");
416 }
417
418 $result = $this->useraccount->fetch($id);
419 if (!$result) {
420 throw new RestException(404, 'Account not found');
421 }
422
423 if (!DolibarrApi::_checkAccessToResource('user', $this->useraccount->id, 'user')) {
424 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
425 }
426
427 foreach ($request_data as $field => $value) {
428 if (in_array($field, array('pass_crypted', 'pass_indatabase', 'pass_indatabase_crypted', 'pass_temp', 'api_key'))) {
429 // This properties can't be set/modified with API
430 throw new RestException(405, 'The property '.$field." can't be set/modified using the APIs");
431 }
432 if ($field == 'id') {
433 continue;
434 }
435 if ($field == 'pass') {
436 if ($this->useraccount->id != DolibarrApiAccess::$user->id && !DolibarrApiAccess::$user->hasRight('user', 'user', 'password')) {
437 throw new RestException(403, 'You are not allowed to modify password of other users');
438 }
439 if ($this->useraccount->id == DolibarrApiAccess::$user->id && !DolibarrApiAccess::$user->hasRight('user', 'self', 'password')) {
440 throw new RestException(403, 'You are not allowed to modify your own password');
441 }
442 }
443 if ($field === 'caller') {
444 // 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
445 $this->useraccount->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
446 continue;
447 }
448 if ($field == 'array_options' && is_array($value)) {
449 foreach ($value as $index => $val) {
450 $this->useraccount->array_options[$index] = $this->_checkValForAPI($field, $val, $this->useraccount);
451 }
452 continue;
453 }
454
455 if (DolibarrApiAccess::$user->admin) { // If user for API is admin
456 if ($field == 'admin' && $value != $this->useraccount->admin && empty($value)) {
457 throw new RestException(403, 'Reseting the admin status of a user is not possible using the API');
458 }
459 } else {
460 if ($field == 'admin' && $value != $this->useraccount->admin) {
461 throw new RestException(403, 'Only an admin user can modify the admin status of another user');
462 }
463 }
464 if ($field == 'entity' && $value != $this->useraccount->entity) {
465 throw new RestException(403, 'Changing entity of a user using the APIs is not possible');
466 }
467
468 // The status must be updated using setstatus() because it
469 // is not handled by the update() method.
470 if ($field == 'statut' || $field == 'status') {
471 $result = $this->useraccount->setstatus($value);
472 if ($result < 0) {
473 throw new RestException(500, 'Error when updating status of user: '.$this->useraccount->error);
474 }
475 } else {
476 $this->useraccount->$field = $this->_checkValForAPI($field, $value, $this->useraccount);
477 }
478 }
479
480 // If there is no error, update() returns the number of affected
481 // rows so if the update is a no op, the return value is zezo.
482 if ($this->useraccount->update(DolibarrApiAccess::$user) >= 0) {
483 return $this->get($id);
484 } else {
485 throw new RestException(500, $this->useraccount->error);
486 }
487 }
488
504 public function setPassword($id, $send_password = false)
505 {
506 //$conf->global->API_DISABLE_LOGIN_API = 1;
507 if (getDolGlobalString('API_DISABLE_LOGIN_API')) {
508 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.");
509 }
510
511 //$conf->global->API_ALLOW_PASSWORD_RESET = 1;
512 if (!getDolGlobalString('API_ALLOW_PASSWORD_RESET')) {
513 throw new RestException(403, "Error: password reset APIs are disabled by default. To allow this, the option API_ALLOW_PASSWORD_RESET must be set.");
514 }
515
516 if (!DolibarrApiAccess::$user->hasRight('user', 'user', 'creer') && empty(DolibarrApiAccess::$user->admin)) {
517 throw new RestException(403, "setPassword on user not allowed for login ".DolibarrApiAccess::$user->login);
518 }
519
520 $result = $this->useraccount->fetch($id);
521 if (!$result) {
522 throw new RestException(404, 'User not found, no password changed');
523 }
524
525 if (!DolibarrApi::_checkAccessToResource('user', $this->useraccount->id, 'user')) {
526 throw new RestException(403, 'Access on this object not allowed for login '.DolibarrApiAccess::$user->login);
527 }
528
529 $newpassword = $this->useraccount->setPassword($this->useraccount, ''); // This will generate a new password
530 if (is_int($newpassword) && $newpassword < 0) {
531 throw new RestException(500, 'ErrorFailedToSetNewPassword'.$this->useraccount->error);
532 } else {
533 // Success
534 if ($send_password) {
535 if ($this->useraccount->send_password($this->useraccount, $newpassword) > 0) {
536 return 2;
537 } else {
538 throw new RestException(500, 'ErrorFailedSendingNewPassword - '.$this->useraccount->error);
539 }
540 } else {
541 return 1;
542 }
543 }
544 }
545
562 public function getGroups($id)
563 {
564 if ($id == 0) {
565 throw new RestException(400, 'No user with id=0 can exist');
566 }
567
568 if (!DolibarrApiAccess::$user->hasRight('user', 'user', 'lire') && empty(DolibarrApiAccess::$user->admin)) {
569 throw new RestException(403);
570 }
571
572 $user = new User($this->db);
573 $result = $user->fetch($id);
574 if (!$result) {
575 throw new RestException(404, 'user not found');
576 }
577
578 $usergroup = new UserGroup($this->db);
579 $groups = $usergroup->listGroupsForUser($id, false);
580 $obj_ret = array();
581 foreach ($groups as $group) {
582 $obj_ret[] = $this->_cleanObjectDatas($group);
583 }
584 return $obj_ret;
585 }
586
587
604 public function setGroup($id, $group, $entity = 1)
605 {
606 global $conf;
607
608 if (!DolibarrApiAccess::$user->hasRight('user', 'user', 'creer') && empty(DolibarrApiAccess::$user->admin)) {
609 throw new RestException(403, 'setGroup on users not allowed for login '.DolibarrApiAccess::$user->login);
610 }
611
612 $result = $this->useraccount->fetch($id);
613 if (!$result) {
614 throw new RestException(404, 'User not found');
615 }
616
617 if (!DolibarrApi::_checkAccessToResource('user', $this->useraccount->id, 'user')) {
618 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
619 }
620
621 if (isModEnabled('multicompany') && getDolGlobalString('MULTICOMPANY_TRANSVERSE_MODE') && !empty(DolibarrApiAccess::$user->admin) && empty(DolibarrApiAccess::$user->entity)) {
622 $entity = (!empty($entity) ? (int) $entity : $conf->entity);
623 } else {
624 // 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
625 // hack the security by giving himself permissions on another entity.
626 $entity = (((int) DolibarrApiAccess::$user->entity) > 0 ? (int) DolibarrApiAccess::$user->entity : $conf->entity);
627 }
628
629 $result = $this->useraccount->SetInGroup($group, $entity);
630 if (!($result > 0)) {
631 throw new RestException(500, $this->useraccount->error);
632 }
633
634 return 1;
635 }
636
650 public function postGroups($request_data = null)
651 {
652 // Check user authorization
653 if (!DolibarrApiAccess::$user->hasRight('user', 'group_advance', 'write') && empty(DolibarrApiAccess::$user->admin)) {
654 throw new RestException(403, "Usergroup creation not allowed for login ".DolibarrApiAccess::$user->login);
655 }
656 $usergroup = new UserGroup($this->db);
657 foreach ($request_data as $field => $value) {
658 if ($field === 'caller') {
659 // 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
660 $usergroup->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
661 continue;
662 }
663 if ($field == 'id') {
664 throw new RestException(400, 'Creating with id field is forbidden');
665 }
666
667 $usergroup->$field = $this->_checkValForAPI($field, $value, $usergroup);
668 }
669
670 if ($usergroup->create(1) < 0) {
671 throw new RestException(500, 'Error creating', array_merge(array($usergroup->error), $usergroup->errors));
672 }
673 return $usergroup->id;
674 }
675
693 public function putGroups($group, $request_data = null)
694 {
695 // Check user authorization
696 if (!DolibarrApiAccess::$user->hasRight('user', 'group_advance', 'write') && empty(DolibarrApiAccess::$user->admin)) {
697 throw new RestException(403, "Usergroup update not allowed");
698 }
699
700 $usergroup = new UserGroup($this->db);
701
702 $result = $usergroup->fetch($group);
703 if ($result < 1) {
704 throw new RestException(404, 'Usergroup not found');
705 }
706
707 foreach ($request_data as $field => $value) {
708 if ($field == 'id') {
709 throw new RestException(400, 'Updating with id field is forbidden');
710 }
711 if ($field === 'caller') {
712 // 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
713 $usergroup->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
714 continue;
715 }
716
717 if ($field == 'entity' && $value != $usergroup->entity) {
718 throw new RestException(403, 'Changing entity of a user using the APIs is not possible');
719 }
720
721 $usergroup->$field = $this->_checkValForAPI($field, $value, $usergroup);
722 }
723
724 // If there is no error, update() returns the number of affected
725 // rows so if the update is a no op, the return value is zezo.
726 if ($usergroup->update() >= 0) {
727 return $this->infoGroups($group);
728 } else {
729 throw new RestException(500, $usergroup->error);
730 }
731 }
732
748 public function removeUserFromGroup($id, $group)
749 {
750 if (!DolibarrApiAccess::$user->admin) {
751 throw new RestException(403, 'Only admin can remove users from groups');
752 }
753
754 $sql = "DELETE FROM " . MAIN_DB_PREFIX . "usergroup_user";
755 $sql .= " WHERE fk_user = " . ((int) $id);
756 $sql .= " AND fk_usergroup = " . ((int) $group);
757
758 $resql = $this->db->query($sql);
759
760 if (!$resql) {
761 throw new RestException(503, 'DB error: ' . $this->db->lasterror());
762 }
763
764 return [
765 'success' => true,
766 'message' => "User $id removed from group $group"
767 ];
768 }
769
794 public function listGroups($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $group_ids = '0', $sqlfilters = '', $properties = '')
795 {
796 $obj_ret = array();
797
798 if ((!getDolGlobalString('MAIN_USE_ADVANCED_PERMS') && !DolibarrApiAccess::$user->hasRight('user', 'user', 'lire') && empty(DolibarrApiAccess::$user->admin)) ||
799 getDolGlobalString('MAIN_USE_ADVANCED_PERMS') && !DolibarrApiAccess::$user->hasRight('user', 'group_advance', 'read') && empty(DolibarrApiAccess::$user->admin)) {
800 throw new RestException(403, "You are not allowed to read groups");
801 }
802
803 // case of external user, $societe param is ignored and replaced by user's socid
804 //$socid = DolibarrApiAccess::$user->socid ?: $societe;
805
806 $sql = "SELECT t.rowid";
807 $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
808 $sql .= ' WHERE t.entity IN ('.getEntity('user').')';
809 if ($group_ids) {
810 $sql .= " AND t.rowid IN (".$this->db->sanitize($group_ids).")";
811 }
812 // Add sql filters
813 if ($sqlfilters) {
814 $errormessage = '';
815 $sql .= forgeSQLFromUniversalSearchCriteria($sqlfilters, $errormessage);
816 if ($errormessage) {
817 throw new RestException(400, 'Error when validating parameter sqlfilters -> '.$errormessage);
818 }
819 }
820
821 $sql .= $this->db->order($sortfield, $sortorder);
822 if ($limit) {
823 if ($page < 0) {
824 $page = 0;
825 }
826 $offset = $limit * $page;
827
828 $sql .= $this->db->plimit($limit + 1, $offset);
829 }
830
831 $result = $this->db->query($sql);
832
833 if ($result) {
834 $i = 0;
835 $num = $this->db->num_rows($result);
836 $min = min($num, ($limit <= 0 ? $num : $limit));
837 while ($i < $min) {
838 $obj = $this->db->fetch_object($result);
839 $group_static = new UserGroup($this->db);
840 if ($group_static->fetch($obj->rowid)) {
841 $obj_ret[] = $this->_filterObjectProperties($this->_cleanObjectDatas($group_static), $properties);
842 }
843 $i++;
844 }
845 } else {
846 throw new RestException(503, 'Error when retrieve Group list : '.$this->db->lasterror());
847 }
848
849 return $obj_ret;
850 }
851
869 public function infoGroups($group, $load_members = 0)
870 {
871 if ($group == 0) {
872 throw new RestException(400, 'No usergroup with id=0 can exist');
873 }
874
875 if ((!getDolGlobalString('MAIN_USE_ADVANCED_PERMS') && !DolibarrApiAccess::$user->hasRight('user', 'user', 'lire') && empty(DolibarrApiAccess::$user->admin)) ||
876 getDolGlobalString('MAIN_USE_ADVANCED_PERMS') && !DolibarrApiAccess::$user->hasRight('user', 'group_advance', 'read') && empty(DolibarrApiAccess::$user->admin)) {
877 throw new RestException(403, "You are not allowed to read groups");
878 }
879
880 $group_static = new UserGroup($this->db);
881 $result = $group_static->fetch($group, '', (bool) $load_members);
882
883 if ($result < 1) {
884 throw new RestException(404, 'Usergroup not found');
885 }
886
887 if ($load_members > 0 && is_array($group_static->members) && count($group_static->members) > 0) {
888 foreach ($group_static->members as &$member) {
889 $member = $this->_cleanObjectDatas($member);
890 }
891 }
892
893 return $this->_cleanUserGroup($group_static);
894 }
895
909 public function delete($id)
910 {
911 if (!DolibarrApiAccess::$user->hasRight('user', 'user', 'supprimer') && empty(DolibarrApiAccess::$user->admin)) {
912 throw new RestException(403, 'Not allowed');
913 }
914 $result = $this->useraccount->fetch($id);
915 if (!$result) {
916 throw new RestException(404, 'User not found');
917 }
918
919 if (!DolibarrApi::_checkAccessToResource('user', $this->useraccount->id, 'user')) {
920 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
921 }
922 $this->useraccount->oldcopy = clone $this->useraccount; // @phan-suppress-current-line PhanTypeMismatchProperty
923
924 if (!$this->useraccount->delete(DolibarrApiAccess::$user)) {
925 throw new RestException(500);
926 }
927
928 return array(
929 'success' => array(
930 'code' => 200,
931 'message' => 'User deleted'
932 )
933 );
934 }
935
951 public function deleteGroups($group)
952 {
953 if (!DolibarrApiAccess::$user->hasRight('user', 'group_advance', 'delete') && empty(DolibarrApiAccess::$user->admin)) {
954 throw new RestException(403, 'Not allowed');
955 }
956
957 $usergroup = new UserGroup($this->db);
958
959 $result = $usergroup->fetch($group);
960 if ($result < 0) {
961 throw new RestException(404, 'Usergroup not found');
962 }
963
964 if (!$usergroup->delete(DolibarrApiAccess::$user)) {
965 throw new RestException(500);
966 }
967
968 return array(
969 'success' => array(
970 'code' => 200,
971 'message' => 'Usergroup deleted'
972 )
973 );
974 }
975
993 public function getUserNotification($id)
994 {
995 if (empty($id)) {
996 throw new RestException(400, 'No user with id=0 can exist');
997 }
998 if (!DolibarrApiAccess::$user->hasRight('user', 'user', 'lire') && empty(DolibarrApiAccess::$user->admin)) {
999 throw new RestException(403);
1000 }
1002 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1003 }
1004
1009 $sql = "SELECT rowid as id, fk_action as event, fk_user, type, datec, tms";
1010 $sql .= " FROM ".MAIN_DB_PREFIX."notify_def";
1011 $sql .= " WHERE fk_user = ".((int) $id);
1012
1013 $result = $this->db->query($sql);
1014 if ($this->db->num_rows($result) == 0) {
1015 throw new RestException(404, 'Notification not found');
1016 }
1017
1018 $i = 0;
1019
1020 $notifications = array();
1021
1022 if ($result) {
1023 $num = $this->db->num_rows($result);
1024 //$min = min($num, ($limit <= 0 ? $num : $limit));
1025 $min = $num;
1026 while ($i < $min) {
1027 $obj = $this->db->fetch_object($result);
1028 $notifications[] = $obj;
1029 $i++;
1030 }
1031 } else {
1032 throw new RestException(404, 'No notifications found');
1033 }
1034
1035 $fields = array('id', 'fk_user', 'event', 'datec', 'tms', 'type');
1036
1037 $returnNotifications = array();
1038
1039 foreach ($notifications as $notification) {
1040 $object = array();
1041 foreach ($notification as $key => $value) {
1042 if (in_array($key, $fields)) {
1043 $object[$key] = $value;
1044 }
1045 }
1046 $returnNotifications[] = $object;
1047 }
1048
1049 // Too complex for phan ?: @phan-suppress-next-line PhanTypeMismatchReturn
1050 return $returnNotifications;
1051 }
1052
1069 public function createUserNotification($id, $request_data = null)
1070 {
1071 if (!DolibarrApiAccess::$user->hasRight('user', 'user', 'creer')) {
1072 throw new RestException(403, "User has no right to update users");
1073 }
1074 if ($this->useraccount->fetch($id) <= 0) {
1075 throw new RestException(404, 'Error creating User Notification, User doesn\'t exists');
1076 }
1077 $notification = new Notify($this->db);
1078
1079 $notification->fk_user = $id;
1080
1081 foreach ($request_data as $field => $value) {
1082 $notification->$field = $value;
1083 }
1084
1085 $event = $notification->event;
1086 if (!$event) {
1087 throw new RestException(500, 'Error creating User Notification, request_data missing event');
1088 }
1089 $fk_user = $notification->fk_user;
1090
1091 $exists_sql = "SELECT rowid, fk_action as event, fk_user, type, datec, tms as datem";
1092 $exists_sql .= " FROM ".MAIN_DB_PREFIX."notify_def";
1093 $exists_sql .= " WHERE fk_action = '".$this->db->escape((string) $event)."'";
1094 $exists_sql .= " AND fk_user = '".$this->db->escape((string) $fk_user)."'";
1095
1096 $exists_result = $this->db->query($exists_sql);
1097 if ($this->db->num_rows($exists_result) > 0) {
1098 throw new RestException(403, 'Notification already exists');
1099 }
1100
1101 if ($notification->create(DolibarrApiAccess::$user) < 0) {
1102 throw new RestException(500, 'Error creating User Notification');
1103 }
1104
1105 if ($notification->update(DolibarrApiAccess::$user) < 0) {
1106 throw new RestException(500, 'Error updating values');
1107 }
1108
1109 return $this->_cleanObjectDatas($notification);
1110 }
1111
1130 public function createUserNotificationByCode($id, $code, $request_data = null)
1131 {
1132 if (!DolibarrApiAccess::$user->hasRight('user', 'user', 'creer')) {
1133 throw new RestException(403, "User has no right to update users");
1134 }
1135 if ($this->useraccount->fetch($id) <= 0) {
1136 throw new RestException(404, 'Error creating User Notification, User doesn\'t exists');
1137 }
1138 $notification = new Notify($this->db);
1139 $notification->fk_user = $id;
1140
1141 $sql = "SELECT t.rowid as id FROM ".MAIN_DB_PREFIX."c_action_trigger as t";
1142 $sql .= " WHERE t.code = '".$this->db->escape($code)."'";
1143
1144 $result = $this->db->query($sql);
1145 if ($this->db->num_rows($result) == 0) {
1146 throw new RestException(404, 'Action Trigger code not found');
1147 }
1148
1149 $notification->event = $this->db->fetch_row($result)[0];
1150 foreach ($request_data as $field => $value) {
1151 if ($field === 'event') {
1152 throw new RestException(500, 'Error creating User Notification, request_data contains event key');
1153 }
1154 if ($field === 'fk_action') {
1155 throw new RestException(500, 'Error creating User Notification, request_data contains fk_action key');
1156 }
1157 $notification->$field = $value;
1158 }
1159
1160 $event = $notification->event;
1161 $fk_user = $notification->fk_user;
1162
1163 $exists_sql = "SELECT rowid, fk_action as event, fk_user, type, datec, tms as datem";
1164 $exists_sql .= " FROM ".MAIN_DB_PREFIX."notify_def";
1165 $exists_sql .= " WHERE fk_action = '".$this->db->escape((string) $event)."'";
1166 $exists_sql .= " AND fk_user = '".$this->db->escape((string) $fk_user)."'";
1167
1168 $exists_result = $this->db->query($exists_sql);
1169 if ($this->db->num_rows($exists_result) > 0) {
1170 throw new RestException(403, 'Notification already exists');
1171 }
1172
1173 if ($notification->create(DolibarrApiAccess::$user) < 0) {
1174 throw new RestException(500, 'Error creating User Notification, are request_data well formed?');
1175 }
1176
1177 if ($notification->update(DolibarrApiAccess::$user) < 0) {
1178 throw new RestException(500, 'Error updating values');
1179 }
1180
1181 return $this->_cleanObjectDatas($notification);
1182 }
1183
1198 public function deleteUserNotification($id, $notification_id)
1199 {
1200 if (!DolibarrApiAccess::$user->hasRight('user', 'user', 'creer')) {
1201 throw new RestException(403, "User has no right to update users");
1202 }
1203
1204 $notification = new Notify($this->db);
1205
1206 $notification->fetch($notification_id);
1207
1208 $fk_user = (int) $notification->fk_user;
1209
1210 if ($fk_user == $id) {
1211 return $notification->delete(DolibarrApiAccess::$user);
1212 } else {
1213 throw new RestException(403, "Not allowed due to bad consistency of input data");
1214 }
1215 }
1216
1234 public function updateUserNotification($id, $notification_id, $request_data = null)
1235 {
1236 if (!DolibarrApiAccess::$user->hasRight('user', 'user', 'creer')) {
1237 throw new RestException(403, "User has no right to update users");
1238 }
1239 if ($this->useraccount->fetch($id) <= 0) {
1240 throw new RestException(404, 'Error creating Notification, User doesn\'t exists');
1241 }
1242 $notification = new Notify($this->db);
1243
1244 // @phan-suppress-next-line PhanPluginSuspiciousParamPosition
1245 $notification->fetch($notification_id, $id);
1246
1247 if ($notification->fk_user != $id) {
1248 throw new RestException(403, "Not allowed due to bad consistency of input data");
1249 }
1250
1251 foreach ($request_data as $field => $value) {
1252 $notification->$field = $value;
1253 }
1254
1255 if ($notification->update(DolibarrApiAccess::$user) < 0) {
1256 throw new RestException(500, 'Error updating values');
1257 }
1258
1259 return $this->_cleanObjectDatas($notification);
1260 }
1261
1262 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
1272 protected function _cleanObjectDatas($object)
1273 {
1274 // phpcs:enable
1275 $object = parent::_cleanObjectDatas($object);
1276
1277 unset($object->default_values);
1278 unset($object->lastsearch_values);
1279 unset($object->lastsearch_values_tmp);
1280
1281 unset($object->total_ht);
1282 unset($object->total_tva);
1283 unset($object->total_localtax1);
1284 unset($object->total_localtax2);
1285 unset($object->total_ttc);
1286
1287 unset($object->label_incoterms);
1288 unset($object->location_incoterms);
1289
1290 unset($object->fk_delivery_address);
1291 unset($object->fk_incoterms);
1292 unset($object->all_permissions_are_loaded);
1293 unset($object->shipping_method_id);
1294 unset($object->nb_rights);
1295 unset($object->search_sid);
1296 unset($object->ldap_sid);
1297 unset($object->clicktodial_loaded);
1298
1299 // List of properties never returned by API, whatever are permissions
1300 unset($object->pass);
1301 unset($object->pass_indatabase);
1302 unset($object->pass_indatabase_crypted);
1303 unset($object->pass_temp);
1304 unset($object->api_key);
1305 unset($object->clicktodial_password);
1306 unset($object->openid);
1307
1308 unset($object->lines);
1309 unset($object->model_pdf);
1310
1311 $canreadsalary = ((isModEnabled('salaries') && DolibarrApiAccess::$user->hasRight('salaries', 'read')) || !isModEnabled('salaries'));
1312
1313 if (!$canreadsalary) {
1314 unset($object->salary);
1315 unset($object->salaryextra);
1316 unset($object->thm);
1317 unset($object->tjm);
1318 }
1319
1320 return $object;
1321 }
1322
1323 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
1330 private function _cleanUserGroup($object)
1331 {
1332 // phpcs:enable
1333 $object = parent::_cleanObjectDatas($object);
1334
1335 unset($object->actiontypecode);
1336 unset($object->all_permissions_are_loaded);
1337 unset($object->barcode_type_coder);
1338 unset($object->barcode_type);
1339 unset($object->canvas);
1340 unset($object->civility_code);
1341 unset($object->civility_id);
1342 unset($object->clicktodial_loaded);
1343 unset($object->cond_reglement_id);
1344 unset($object->cond_reglement_supplier_id);
1345 unset($object->contact_id);
1346 unset($object->contacts_ids_internal);
1347 unset($object->contacts_ids);
1348 unset($object->country_code);
1349 unset($object->country_id);
1350 unset($object->date_cloture);
1351 unset($object->date_creation);
1352 unset($object->date_modification);
1353 unset($object->date_validation);
1354 unset($object->default_values);
1355 unset($object->demand_reason_id);
1356 unset($object->deposit_percent);
1357 unset($object->extraparams);
1358 unset($object->firstname);
1359 unset($object->fk_account);
1360 unset($object->fk_delivery_address);
1361 unset($object->fk_incoterms);
1362 unset($object->fk_multicurrency);
1363 unset($object->fk_project);
1364 unset($object->fk_user_creat);
1365 unset($object->fk_user_modif);
1366 unset($object->globalgroup);
1367 unset($object->import_key);
1368 unset($object->last_main_doc);
1369 unset($object->lastname);
1370 unset($object->lastsearch_values_tmp);
1371 unset($object->lastsearch_values);
1372 unset($object->ldap_sid);
1373 unset($object->libelle_incoterms);
1374 unset($object->lines);
1375 unset($object->linkedObjectsIds);
1376 unset($object->location_incoterms);
1377 unset($object->members);
1378 unset($object->mode_reglement_id);
1379 unset($object->module);
1380 unset($object->multicurrency_code);
1381 unset($object->multicurrency_total_ht);
1382 unset($object->multicurrency_total_localtax1);
1383 unset($object->multicurrency_total_localtax2);
1384 unset($object->multicurrency_total_ttc);
1385 unset($object->multicurrency_total_tva);
1386 unset($object->multicurrency_tx);
1387 unset($object->nb_rights);
1388 unset($object->nb_users);
1389 unset($object->note_public);
1390 unset($object->origin_id);
1391 unset($object->origin_type);
1392 unset($object->product);
1393 unset($object->ref_ext);
1394 unset($object->ref);
1395 unset($object->region_id);
1396 unset($object->retained_warranty_fk_cond_reglement);
1397 unset($object->rights);
1398 unset($object->search_sid);
1399 unset($object->shipping_method_id);
1400 unset($object->shipping_method);
1401 unset($object->specimen);
1402 unset($object->state_id);
1403 unset($object->status);
1404 unset($object->statut);
1405 unset($object->total_ht);
1406 unset($object->total_localtax1);
1407 unset($object->total_localtax2);
1408 unset($object->total_ttc);
1409 unset($object->total_tva);
1410 unset($object->totalpaid_multicurrency);
1411 unset($object->totalpaid);
1412 unset($object->transport_mode_id);
1413 unset($object->TRIGGER_PREFIX);
1414 unset($object->user_closing_id);
1415 unset($object->user_creation_id);
1416 unset($object->user_modification_id);
1417 unset($object->user_validation_id);
1418 unset($object->user);
1419 unset($object->usergroup_entity);
1420 unset($object->warehouse_id);
1421
1422 return $object;
1423 }
1424
1431 private function _cleanUserGroupListDatas($objectList)
1432 {
1433 $cleanObjectList = array();
1434
1435 foreach ($objectList as $object) {
1436 $cleanObject = parent::_cleanObjectDatas($object);
1437
1438 unset($cleanObject->default_values);
1439 unset($cleanObject->lastsearch_values);
1440 unset($cleanObject->lastsearch_values_tmp);
1441
1442 unset($cleanObject->total_ht);
1443 unset($cleanObject->total_tva);
1444 unset($cleanObject->total_localtax1);
1445 unset($cleanObject->total_localtax2);
1446 unset($cleanObject->total_ttc);
1447
1448 unset($cleanObject->libelle_incoterms);
1449 unset($cleanObject->location_incoterms);
1450
1451 unset($cleanObject->fk_delivery_address);
1452 unset($cleanObject->fk_incoterms);
1453 unset($cleanObject->all_permissions_are_loaded);
1454 unset($cleanObject->shipping_method_id);
1455 unset($cleanObject->nb_rights);
1456 unset($cleanObject->search_sid);
1457 unset($cleanObject->ldap_sid);
1458 unset($cleanObject->clicktodial_loaded);
1459
1460 unset($cleanObject->datec);
1461 unset($cleanObject->tms);
1462 unset($cleanObject->members);
1463 unset($cleanObject->note);
1464 unset($cleanObject->note_private);
1465
1466 $cleanObjectList[] = $cleanObject;
1467 }
1468
1469 return $cleanObjectList;
1470 }
1471
1479 private function _validate($data) // @phpstan-ignore-line
1480 {
1481 $account = array();
1482 foreach (Users::$FIELDS as $field) {
1483 if (!isset($data[$field])) {
1484 throw new RestException(400, "$field field missing");
1485 }
1486 $account[$field] = $data[$field];
1487 }
1488 return $account;
1489 }
1490}
$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:33
_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.
Definition api.class.php:98
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.
infoGroups($group, $load_members=0)
Get properties of a user group.
_validate($data)
Validate fields before create or update object.
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").
forgeSQLFromUniversalSearchCriteria($filter, &$errorstr='', $noand=0, $nopar=0, $noerror=0)
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.