dolibarr 25.0.0-alpha
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')) {
382 throw new RestException(403, 'You are not allowed to modify/set password of other users');
383 continue;
384 }
385 }
386 */
387 $canreadsalary = ((isModEnabled('salaries') && DolibarrApiAccess::$user->hasRight('salaries', 'read')) || !isModEnabled('salaries'));
388 if (!$canreadsalary) {
389 if (in_array($field, array('salary', 'salaryextra', 'thm', 'tjm'))) {
390 // This properties can't be set/modified with API
391 throw new RestException(405, 'The property '.$field." can't be set/modified using the APIs with permission on salaries");
392 }
393 }
394
395 if ($field === 'caller') {
396 // 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
397 $this->useraccount->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
398 continue;
399 }
400
401 if (DolibarrApiAccess::$user->admin) { // If user for API is admin
402 if ($field == 'admin' && $value != $this->useraccount->admin && empty($value)) {
403 throw new RestException(403, 'Reseting the admin status of a user is not possible using the API');
404 }
405 } else {
406 if ($field == 'admin' && $value != $this->useraccount->admin) {
407 throw new RestException(403, 'Only an admin user can modify the admin status of another user');
408 }
409 }
410
411 $this->useraccount->$field = $this->_checkValForAPI($field, $value, $this->useraccount);
412 }
413
414 if ($this->useraccount->create(DolibarrApiAccess::$user) < 0) {
415 throw new RestException(500, 'Error creating', array_merge(array($this->useraccount->error), $this->useraccount->errors));
416 }
417 return $this->useraccount->id;
418 }
419
420
436 public function put($id, $request_data = null)
437 {
438 $isSelfUpdate = ((int) $id === (int) DolibarrApiAccess::$user->id);
439
440 // Check user authorization
441 if (
442 !DolibarrApiAccess::$user->hasRight('user', 'user', 'creer')
443 && !DolibarrApiAccess::$user->hasRight('user', 'user', 'write')
444 && !(
445 $isSelfUpdate
446 && (
447 DolibarrApiAccess::$user->hasRight('user', 'self', 'creer')
448 || DolibarrApiAccess::$user->hasRight('user', 'self', 'write')
449 )
450 )
451 && empty(DolibarrApiAccess::$user->admin)
452 ) {
453 throw new RestException(403, "User update not allowed");
454 }
455
456 $result = $this->useraccount->fetch($id);
457 if (!$result) {
458 throw new RestException(404, 'Account not found');
459 }
460
461 if (!DolibarrApi::_checkAccessToResource('user', $this->useraccount->id, 'user')) {
462 throw new RestException(403, 'Access on this object not allowed for login '.DolibarrApiAccess::$user->login);
463 }
464
465 foreach ($request_data as $field => $value) {
466 if (in_array($field, array('pass_crypted', 'pass_indatabase', 'pass_indatabase_crypted', 'pass_temp', 'api_key', 'openid'))) {
467 // This properties can't be set/modified with API
468 throw new RestException(405, 'The property '.$field." can't be set/modified using the APIs");
469 }
470
471 $canreadsalary = ((isModEnabled('salaries') && DolibarrApiAccess::$user->hasRight('salaries', 'read')) || !isModEnabled('salaries'));
472 if (!$canreadsalary) {
473 if (in_array($field, array('salary', 'salaryextra', 'thm', 'tjm'))) {
474 // This properties can't be set/modified with API
475 throw new RestException(405, 'The property '.$field." can't be set/modified using the APIs with permission on salaries");
476 }
477 }
478
479 if ($field == 'id') {
480 continue;
481 }
482 if ($field == 'pass') {
483 if ($this->useraccount->id != DolibarrApiAccess::$user->id && !DolibarrApiAccess::$user->hasRight('user', 'user', 'password')) {
484 throw new RestException(403, 'You are not allowed to modify password of other users');
485 }
486 if ($this->useraccount->id == DolibarrApiAccess::$user->id && !DolibarrApiAccess::$user->hasRight('user', 'self', 'password')) {
487 throw new RestException(403, 'You are not allowed to modify your own password');
488 }
489 }
490 if ($field === 'caller') {
491 // 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
492 $this->useraccount->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
493 continue;
494 }
495 if ($field == 'array_options' && is_array($value)) {
496 foreach ($value as $index => $val) {
497 $this->useraccount->array_options[$index] = $this->_checkValExtrafieldsForAPI($index, $val, $this->useraccount);
498 }
499 continue;
500 }
501
502 if (DolibarrApiAccess::$user->admin) { // If user for API is admin
503 if ($field == 'admin' && $value != $this->useraccount->admin && empty($value)) {
504 throw new RestException(403, 'Reseting the admin status of a user is not possible using the API');
505 }
506 } else {
507 if ($field == 'admin' && $value != $this->useraccount->admin) {
508 throw new RestException(403, 'Only an admin user can modify the admin status of another user');
509 }
510 }
511 if ($field == 'entity' && $value != $this->useraccount->entity) {
512 throw new RestException(403, 'Changing entity of a user using the APIs is not possible');
513 }
514
515 // The status must be updated using setstatus() because it
516 // is not handled by the update() method.
517 if ($field == 'statut' || $field == 'status') {
518 $result = $this->useraccount->setstatus($value);
519 if ($result < 0) {
520 throw new RestException(500, 'Error when updating status of user: '.$this->useraccount->error);
521 }
522 } else {
523 $this->useraccount->$field = $this->_checkValForAPI($field, $value, $this->useraccount);
524 }
525 }
526
527 // If there is no error, update() returns the number of affected
528 // rows so if the update is a no op, the return value is zezo.
529 if ($this->useraccount->update(DolibarrApiAccess::$user) >= 0) {
530 return $this->get($id);
531 } else {
532 throw new RestException(500, $this->useraccount->error);
533 }
534 }
535
551 public function setPassword($id, $send_password = false)
552 {
553 if (!getDolGlobalInt('API_ENABLE_LOGIN_API')) {
554 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.");
555 }
556
557 if (!getDolGlobalString('API_ALLOW_PASSWORD_RESET')) {
558 throw new RestException(403, "Error: password reset APIs are disabled by default. To allow this, the option API_ALLOW_PASSWORD_RESET must be set.");
559 }
560
561 if (!DolibarrApiAccess::$user->hasRight('user', 'user', 'creer') && empty(DolibarrApiAccess::$user->admin)) {
562 throw new RestException(403, "setPassword on user not allowed for login ".DolibarrApiAccess::$user->login);
563 }
564
565 $result = $this->useraccount->fetch($id);
566 if (!$result) {
567 throw new RestException(404, 'User not found, no password changed');
568 }
569
570 if (!DolibarrApi::_checkAccessToResource('user', $this->useraccount->id, 'user')) {
571 throw new RestException(403, 'Access on this object not allowed for login '.DolibarrApiAccess::$user->login);
572 }
573
574 $newpassword = $this->useraccount->setPassword($this->useraccount, ''); // This will generate a new password
575 if (is_int($newpassword) && $newpassword < 0) {
576 throw new RestException(500, 'ErrorFailedToSetNewPassword'.$this->useraccount->error);
577 } else {
578 // Success
579 if ($send_password) {
580 if ($this->useraccount->send_password($this->useraccount, $newpassword) > 0) {
581 return 2;
582 } else {
583 throw new RestException(500, 'ErrorFailedSendingNewPassword - '.$this->useraccount->error);
584 }
585 } else {
586 return 1;
587 }
588 }
589 }
590
607 public function getGroups($id)
608 {
609 if ($id == 0) {
610 throw new RestException(400, 'No user with id=0 can exist');
611 }
612
613 if (!DolibarrApiAccess::$user->hasRight('user', 'user', 'lire') && empty(DolibarrApiAccess::$user->admin)) {
614 throw new RestException(403);
615 }
616
617 $user = new User($this->db);
618 $result = $user->fetch($id);
619 if (!$result) {
620 throw new RestException(404, 'User not found');
621 }
622 if (!DolibarrApi::_checkAccessToResource('user', $user->id, 'user')) {
623 throw new RestException(403, 'Access on this object not allowed for login '.DolibarrApiAccess::$user->login);
624 }
625
626 $usergroup = new UserGroup($this->db);
627 $groups = $usergroup->listGroupsForUser($id, false);
628 $obj_ret = array();
629 foreach ($groups as $group) {
630 $obj_ret[] = $this->_cleanObjectDatas($group);
631 }
632 return $obj_ret;
633 }
634
635
652 public function setGroup($id, $group, $entity = 1)
653 {
654 global $conf;
655
656 if (!DolibarrApiAccess::$user->hasRight('user', 'user', 'creer') && empty(DolibarrApiAccess::$user->admin)) {
657 throw new RestException(403, 'setGroup on users not allowed for login '.DolibarrApiAccess::$user->login);
658 }
659
660 $result = $this->useraccount->fetch($id);
661 if (!$result) {
662 throw new RestException(404, 'User not found');
663 }
664
665 if (!DolibarrApi::_checkAccessToResource('user', $this->useraccount->id, 'user')) {
666 throw new RestException(403, 'Access on this object not allowed for login '.DolibarrApiAccess::$user->login);
667 }
668
669 if (isModEnabled('multicompany') && getDolGlobalString('MULTICOMPANY_TRANSVERSE_MODE') && !empty(DolibarrApiAccess::$user->admin) && empty(DolibarrApiAccess::$user->entity)) {
670 $entity = (!empty($entity) ? (int) $entity : $conf->entity);
671 } else {
672 // 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
673 // hack the security by giving himself permissions on another entity.
674 $entity = (((int) DolibarrApiAccess::$user->entity) > 0 ? (int) DolibarrApiAccess::$user->entity : $conf->entity);
675 }
676
677 $result = $this->useraccount->SetInGroup($group, $entity);
678 if (!($result > 0)) {
679 throw new RestException(500, $this->useraccount->error);
680 }
681
682 return 1;
683 }
684
698 public function postGroups($request_data = null)
699 {
700 // Check user authorization
701 if (!DolibarrApiAccess::$user->hasRight('user', 'group_advance', 'write') && empty(DolibarrApiAccess::$user->admin)) {
702 throw new RestException(403, "Usergroup creation not allowed for login ".DolibarrApiAccess::$user->login);
703 }
704 $usergroup = new UserGroup($this->db);
705 foreach ($request_data as $field => $value) {
706 if ($field === 'caller') {
707 // 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
708 $usergroup->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
709 continue;
710 }
711 if ($field == 'id') {
712 throw new RestException(400, 'Creating with id field is forbidden');
713 }
714
715 $usergroup->$field = $this->_checkValForAPI($field, $value, $usergroup);
716 }
717
718 if ($usergroup->create(1) < 0) {
719 throw new RestException(500, 'Error creating', array_merge(array($usergroup->error), $usergroup->errors));
720 }
721 return $usergroup->id;
722 }
723
741 public function putGroups($group, $request_data = null)
742 {
743 // Check user authorization
744 if (!DolibarrApiAccess::$user->hasRight('user', 'group_advance', 'write') && empty(DolibarrApiAccess::$user->admin)) {
745 throw new RestException(403, "Usergroup update not allowed");
746 }
747
748 $usergroup = new UserGroup($this->db);
749
750 $result = $usergroup->fetch($group);
751 if ($result < 1) {
752 throw new RestException(404, 'Usergroup not found');
753 }
754
755 foreach ($request_data as $field => $value) {
756 if ($field == 'id') {
757 throw new RestException(400, 'Updating with id field is forbidden');
758 }
759 if ($field === 'caller') {
760 // 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
761 $usergroup->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
762 continue;
763 }
764
765 if ($field == 'entity' && $value != $usergroup->entity) {
766 throw new RestException(403, 'Changing entity of a user using the APIs is not possible');
767 }
768
769 $usergroup->$field = $this->_checkValForAPI($field, $value, $usergroup);
770 }
771
772 // If there is no error, update() returns the number of affected
773 // rows so if the update is a no op, the return value is zezo.
774 if ($usergroup->update() >= 0) {
775 return $this->infoGroups($group);
776 } else {
777 throw new RestException(500, $usergroup->error);
778 }
779 }
780
796 public function removeUserFromGroup($id, $group)
797 {
798 if (!DolibarrApiAccess::$user->admin) {
799 throw new RestException(403, 'Only admin can remove users from groups');
800 }
801
802 $sql = "DELETE FROM " . MAIN_DB_PREFIX . "usergroup_user";
803 $sql .= " WHERE fk_user = " . ((int) $id);
804 $sql .= " AND fk_usergroup = " . ((int) $group);
805
806 $resql = $this->db->query($sql);
807
808 if (!$resql) {
809 throw new RestException(503, 'DB error: ' . $this->db->lasterror());
810 }
811
812 return [
813 'success' => true,
814 'message' => "User $id removed from group $group"
815 ];
816 }
817
842 public function listGroups($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $group_ids = '0', $sqlfilters = '', $properties = '')
843 {
844 $obj_ret = array();
845
846 if ((!getDolGlobalString('MAIN_USE_ADVANCED_PERMS') && !DolibarrApiAccess::$user->hasRight('user', 'user', 'lire') && empty(DolibarrApiAccess::$user->admin)) ||
847 getDolGlobalString('MAIN_USE_ADVANCED_PERMS') && !DolibarrApiAccess::$user->hasRight('user', 'group_advance', 'read') && empty(DolibarrApiAccess::$user->admin)) {
848 throw new RestException(403, "You are not allowed to read groups");
849 }
850
851 // case of external user, $societe param is ignored and replaced by user's socid
852 //$socid = DolibarrApiAccess::$user->socid ?: $societe;
853
854 $sql = "SELECT t.rowid";
855 $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
856 $sql .= ' WHERE t.entity IN ('.getEntity('user').')';
857 if ($group_ids) {
858 $sql .= " AND t.rowid IN (".$this->db->sanitize($group_ids).")";
859 }
860 // Add sql filters
861 if ($sqlfilters) {
862 $errormessage = '';
863 $sql .= forgeSQLFromUniversalSearchCriteria($sqlfilters, $errormessage);
864 if ($errormessage) {
865 throw new RestException(400, 'Error when validating parameter sqlfilters -> '.$errormessage);
866 }
867 }
868
869 $sql .= $this->db->order($sortfield, $sortorder);
870 if ($limit) {
871 if ($page < 0) {
872 $page = 0;
873 }
874 $offset = $limit * $page;
875
876 $sql .= $this->db->plimit($limit + 1, $offset);
877 }
878
879 $result = $this->db->query($sql);
880
881 if ($result) {
882 $i = 0;
883 $num = $this->db->num_rows($result);
884 $min = min($num, ($limit <= 0 ? $num : $limit));
885 while ($i < $min) {
886 $obj = $this->db->fetch_object($result);
887 $group_static = new UserGroup($this->db);
888 if ($group_static->fetch($obj->rowid)) {
889 $obj_ret[] = $this->_filterObjectProperties($this->_cleanObjectDatas($group_static), $properties);
890 }
891 $i++;
892 }
893 } else {
894 throw new RestException(503, 'Error when retrieve Group list : '.$this->db->lasterror());
895 }
896
897 return $obj_ret;
898 }
899
918 public function infoGroups($group, $load_members = 0, $includepermissions = 0)
919 {
920 if ($group == 0) {
921 throw new RestException(400, 'No usergroup with id=0 can exist');
922 }
923
924 if ((!getDolGlobalString('MAIN_USE_ADVANCED_PERMS') && !DolibarrApiAccess::$user->hasRight('user', 'user', 'lire') && empty(DolibarrApiAccess::$user->admin)) ||
925 getDolGlobalString('MAIN_USE_ADVANCED_PERMS') && !DolibarrApiAccess::$user->hasRight('user', 'group_advance', 'read') && empty(DolibarrApiAccess::$user->admin)) {
926 throw new RestException(403, "You are not allowed to read groups");
927 }
928
929 $group_static = new UserGroup($this->db);
930 $result = $group_static->fetch($group, '', (bool) $load_members);
931
932 if ($result < 1) {
933 throw new RestException(404, 'Usergroup not found');
934 }
935
936 if ($includepermissions) {
937 $group_static->loadRights();
938 }
939
940 if ($load_members > 0 && is_array($group_static->members) && count($group_static->members) > 0) {
941 foreach ($group_static->members as &$member) {
942 $member = $this->_cleanObjectDatas($member);
943 }
944 }
945
946 return $this->_cleanUserGroup($group_static);
947 }
948
962 public function delete($id)
963 {
964 if (!DolibarrApiAccess::$user->hasRight('user', 'user', 'supprimer') && empty(DolibarrApiAccess::$user->admin)) {
965 throw new RestException(403, 'Not allowed');
966 }
967 $result = $this->useraccount->fetch($id);
968 if (!$result) {
969 throw new RestException(404, 'User not found');
970 }
971
972 if (!DolibarrApi::_checkAccessToResource('user', $this->useraccount->id, 'user')) {
973 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
974 }
975 $this->useraccount->oldcopy = clone $this->useraccount; // @phan-suppress-current-line PhanTypeMismatchProperty
976
977 if (!$this->useraccount->delete(DolibarrApiAccess::$user)) {
978 throw new RestException(500);
979 }
980
981 return array(
982 'success' => array(
983 'code' => 200,
984 'message' => 'User deleted'
985 )
986 );
987 }
988
1004 public function deleteGroups($group)
1005 {
1006 if (!DolibarrApiAccess::$user->hasRight('user', 'group_advance', 'delete') && empty(DolibarrApiAccess::$user->admin)) {
1007 throw new RestException(403, 'Not allowed');
1008 }
1009
1010 $usergroup = new UserGroup($this->db);
1011
1012 $result = $usergroup->fetch($group);
1013 if ($result < 0) {
1014 throw new RestException(404, 'Usergroup not found');
1015 }
1016
1017 if (!$usergroup->delete(DolibarrApiAccess::$user)) {
1018 throw new RestException(500);
1019 }
1020
1021 return array(
1022 'success' => array(
1023 'code' => 200,
1024 'message' => 'Usergroup deleted'
1025 )
1026 );
1027 }
1028
1046 public function getUserNotification($id)
1047 {
1048 if (empty($id)) {
1049 throw new RestException(400, 'No user with id=0 can exist');
1050 }
1051 if (!DolibarrApiAccess::$user->hasRight('user', 'user', 'lire') && empty(DolibarrApiAccess::$user->admin)) {
1052 throw new RestException(403);
1053 }
1055 throw new RestException(403, 'Access on this object not allowed for login '.DolibarrApiAccess::$user->login);
1056 }
1057
1062 $sql = "SELECT rowid as id, fk_action as event, fk_user, type, datec, tms";
1063 $sql .= " FROM ".MAIN_DB_PREFIX."notify_def";
1064 $sql .= " WHERE fk_user = ".((int) $id);
1065
1066 $result = $this->db->query($sql);
1067 if ($this->db->num_rows($result) == 0) {
1068 throw new RestException(404, 'Notification not found');
1069 }
1070
1071 $i = 0;
1072
1073 $notifications = array();
1074
1075 if ($result) {
1076 $num = $this->db->num_rows($result);
1077 //$min = min($num, ($limit <= 0 ? $num : $limit));
1078 $min = $num;
1079 while ($i < $min) {
1080 $obj = $this->db->fetch_object($result);
1081 $notifications[] = $obj;
1082 $i++;
1083 }
1084 } else {
1085 throw new RestException(404, 'No notifications found');
1086 }
1087
1088 $fields = array('id', 'fk_user', 'event', 'datec', 'tms', 'type');
1089
1090 $returnNotifications = array();
1091
1092 foreach ($notifications as $notification) {
1093 $object = array();
1094 foreach ($notification as $key => $value) {
1095 if (in_array($key, $fields)) {
1096 $object[$key] = $value;
1097 }
1098 }
1099 $returnNotifications[] = $object;
1100 }
1101
1102 // Too complex for phan ?: @phan-suppress-next-line PhanTypeMismatchReturn
1103 return $returnNotifications;
1104 }
1105
1122 public function createUserNotification($id, $request_data = null)
1123 {
1124 if (!DolibarrApiAccess::$user->hasRight('user', 'user', 'creer')) {
1125 throw new RestException(403, "User has no right to update users");
1126 }
1127 if ($this->useraccount->fetch($id) <= 0) {
1128 throw new RestException(404, 'Error creating User Notification, User doesn\'t exists');
1129 }
1130 $notification = new Notify($this->db);
1131
1132 $notification->fk_user = $id;
1133
1134 foreach ($request_data as $field => $value) {
1135 $notification->$field = $this->_checkValForAPI($field, $value, $notification);
1136 }
1137
1138 $event = $notification->event;
1139 if (!$event) {
1140 throw new RestException(500, 'Error creating User Notification, request_data missing event');
1141 }
1142 $fk_user = $notification->fk_user;
1143
1144 $exists_sql = "SELECT rowid, fk_action as event, fk_user, type, datec, tms as datem";
1145 $exists_sql .= " FROM ".MAIN_DB_PREFIX."notify_def";
1146 $exists_sql .= " WHERE fk_action = '".$this->db->escape((string) $event)."'";
1147 $exists_sql .= " AND fk_user = '".$this->db->escape((string) $fk_user)."'";
1148
1149 $exists_result = $this->db->query($exists_sql);
1150 if ($this->db->num_rows($exists_result) > 0) {
1151 throw new RestException(403, 'Notification already exists');
1152 }
1153
1154 if ($notification->create(DolibarrApiAccess::$user) < 0) {
1155 throw new RestException(500, 'Error creating User Notification');
1156 }
1157
1158 if ($notification->update(DolibarrApiAccess::$user) < 0) {
1159 throw new RestException(500, 'Error updating values');
1160 }
1161
1162 return $this->_cleanObjectDatas($notification);
1163 }
1164
1183 public function createUserNotificationByCode($id, $code, $request_data = null)
1184 {
1185 if (!DolibarrApiAccess::$user->hasRight('user', 'user', 'creer')) {
1186 throw new RestException(403, "User has no right to update users");
1187 }
1188 if ($this->useraccount->fetch($id) <= 0) {
1189 throw new RestException(404, 'Error creating User Notification, User doesn\'t exists');
1190 }
1191 $notification = new Notify($this->db);
1192 $notification->fk_user = $id;
1193
1194 $sql = "SELECT t.rowid as id FROM ".MAIN_DB_PREFIX."c_action_trigger as t";
1195 $sql .= " WHERE t.code = '".$this->db->escape($code)."'";
1196
1197 $result = $this->db->query($sql);
1198 if ($this->db->num_rows($result) == 0) {
1199 throw new RestException(404, 'Action Trigger code not found');
1200 }
1201
1202 $notification->event = $this->db->fetch_row($result)[0];
1203 foreach ($request_data as $field => $value) {
1204 if ($field === 'event') {
1205 throw new RestException(500, 'Error creating User Notification, request_data contains event key');
1206 }
1207 if ($field === 'fk_action') {
1208 throw new RestException(500, 'Error creating User Notification, request_data contains fk_action key');
1209 }
1210 $notification->$field = $this->_checkValForAPI($field, $value, $notification);
1211 }
1212
1213 $event = $notification->event;
1214 $fk_user = $notification->fk_user;
1215
1216 $exists_sql = "SELECT rowid, fk_action as event, fk_user, type, datec, tms as datem";
1217 $exists_sql .= " FROM ".MAIN_DB_PREFIX."notify_def";
1218 $exists_sql .= " WHERE fk_action = '".$this->db->escape((string) $event)."'";
1219 $exists_sql .= " AND fk_user = '".$this->db->escape((string) $fk_user)."'";
1220
1221 $exists_result = $this->db->query($exists_sql);
1222 if ($this->db->num_rows($exists_result) > 0) {
1223 throw new RestException(403, 'Notification already exists');
1224 }
1225
1226 if ($notification->create(DolibarrApiAccess::$user) < 0) {
1227 throw new RestException(500, 'Error creating User Notification, are request_data well formed?');
1228 }
1229
1230 if ($notification->update(DolibarrApiAccess::$user) < 0) {
1231 throw new RestException(500, 'Error updating values');
1232 }
1233
1234 return $this->_cleanObjectDatas($notification);
1235 }
1236
1251 public function deleteUserNotification($id, $notification_id)
1252 {
1253 if (!DolibarrApiAccess::$user->hasRight('user', 'user', 'creer')) {
1254 throw new RestException(403, "User has no right to update users");
1255 }
1256
1257 $notification = new Notify($this->db);
1258
1259 $notification->fetch($notification_id);
1260
1261 $fk_user = (int) $notification->fk_user;
1262
1263 if ($fk_user == $id) {
1264 return $notification->delete(DolibarrApiAccess::$user);
1265 } else {
1266 throw new RestException(403, "Not allowed due to bad consistency of input data");
1267 }
1268 }
1269
1287 public function updateUserNotification($id, $notification_id, $request_data = null)
1288 {
1289 if (!DolibarrApiAccess::$user->hasRight('user', 'user', 'creer')) {
1290 throw new RestException(403, "User has no right to update users");
1291 }
1292 if ($this->useraccount->fetch($id) <= 0) {
1293 throw new RestException(404, 'Error creating Notification, User doesn\'t exists');
1294 }
1295 $notification = new Notify($this->db);
1296
1297 // @phan-suppress-next-line PhanPluginSuspiciousParamPosition
1298 $notification->fetch($notification_id, $id);
1299
1300 if ($notification->fk_user != $id) {
1301 throw new RestException(403, "Not allowed due to bad consistency of input data");
1302 }
1303
1304 foreach ($request_data as $field => $value) {
1305 $notification->$field = $this->_checkValForAPI($field, $value, $notification);
1306 }
1307
1308 if ($notification->update(DolibarrApiAccess::$user) < 0) {
1309 throw new RestException(500, 'Error updating values');
1310 }
1311
1312 return $this->_cleanObjectDatas($notification);
1313 }
1314
1315 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
1325 protected function _cleanObjectDatas($object)
1326 {
1327 // phpcs:enable
1328 $object = parent::_cleanObjectDatas($object);
1329
1330 unset($object->default_values);
1331 unset($object->lastsearch_values);
1332 unset($object->lastsearch_values_tmp);
1333
1334 unset($object->total_ht);
1335 unset($object->total_tva);
1336 unset($object->total_localtax1);
1337 unset($object->total_localtax2);
1338 unset($object->total_ttc);
1339
1340 unset($object->label_incoterms);
1341 unset($object->location_incoterms);
1342
1343 unset($object->fk_delivery_address);
1344 unset($object->fk_incoterms);
1345 unset($object->all_permissions_are_loaded);
1346 unset($object->shipping_method_id);
1347 unset($object->nb_rights);
1348 unset($object->search_sid);
1349 unset($object->ldap_sid);
1350 unset($object->clicktodial_loaded);
1351
1352 unset($object->lines);
1353 unset($object->model_pdf);
1354
1355 // List of properties never returned by API, whatever are permissions
1356 unset($object->pass);
1357 unset($object->pass_indatabase);
1358 unset($object->pass_indatabase_crypted);
1359 unset($object->pass_temp);
1360 unset($object->api_key);
1361 unset($object->clicktodial_password);
1362 unset($object->openid);
1363
1364 $canreadsalary = ((isModEnabled('salaries') && DolibarrApiAccess::$user->hasRight('salaries', 'read')) || !isModEnabled('salaries'));
1365 if (!$canreadsalary) {
1366 unset($object->salary);
1367 unset($object->salaryextra);
1368 unset($object->thm);
1369 unset($object->tjm);
1370 }
1371
1372 return $object;
1373 }
1374
1375 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
1382 private function _cleanUserGroup($object)
1383 {
1384 // phpcs:enable
1385 $object = parent::_cleanObjectDatas($object);
1386
1387 unset($object->actiontypecode);
1388 unset($object->all_permissions_are_loaded);
1389 unset($object->barcode_type_coder);
1390 unset($object->barcode_type);
1391 unset($object->canvas);
1392 unset($object->civility_code);
1393 unset($object->civility_id);
1394 unset($object->clicktodial_loaded);
1395 unset($object->cond_reglement_id);
1396 unset($object->cond_reglement_supplier_id);
1397 unset($object->contact_id);
1398 unset($object->contacts_ids_internal);
1399 unset($object->contacts_ids);
1400 unset($object->country_code);
1401 unset($object->country_id);
1402 unset($object->date_cloture);
1403 unset($object->date_creation);
1404 unset($object->date_modification);
1405 unset($object->date_validation);
1406 unset($object->default_values);
1407 unset($object->demand_reason_id);
1408 unset($object->deposit_percent);
1409 unset($object->extraparams);
1410 unset($object->firstname);
1411 unset($object->fk_account);
1412 unset($object->fk_delivery_address);
1413 unset($object->fk_incoterms);
1414 unset($object->fk_multicurrency);
1415 unset($object->fk_project);
1416 unset($object->fk_user_creat);
1417 unset($object->fk_user_modif);
1418 unset($object->globalgroup);
1419 unset($object->import_key);
1420 unset($object->last_main_doc);
1421 unset($object->lastname);
1422 unset($object->lastsearch_values_tmp);
1423 unset($object->lastsearch_values);
1424 unset($object->ldap_sid);
1425 unset($object->libelle_incoterms);
1426 unset($object->lines);
1427 unset($object->linkedObjectsIds);
1428 unset($object->location_incoterms);
1429 unset($object->members);
1430 unset($object->mode_reglement_id);
1431 unset($object->module);
1432 unset($object->multicurrency_code);
1433 unset($object->multicurrency_total_ht);
1434 unset($object->multicurrency_total_localtax1);
1435 unset($object->multicurrency_total_localtax2);
1436 unset($object->multicurrency_total_ttc);
1437 unset($object->multicurrency_total_tva);
1438 unset($object->multicurrency_tx);
1439 unset($object->nb_rights);
1440 unset($object->nb_users);
1441 unset($object->note_public);
1442 unset($object->origin_id);
1443 unset($object->origin_type);
1444 unset($object->product);
1445 unset($object->ref_ext);
1446 unset($object->ref);
1447 unset($object->region_id);
1448 unset($object->retained_warranty_fk_cond_reglement);
1449 unset($object->rights);
1450 unset($object->search_sid);
1451 unset($object->shipping_method_id);
1452 unset($object->shipping_method);
1453 unset($object->specimen);
1454 unset($object->state_id);
1455 unset($object->status);
1456 unset($object->statut);
1457 unset($object->total_ht);
1458 unset($object->total_localtax1);
1459 unset($object->total_localtax2);
1460 unset($object->total_ttc);
1461 unset($object->total_tva);
1462 unset($object->totalpaid_multicurrency);
1463 unset($object->totalpaid);
1464 unset($object->transport_mode_id);
1465 unset($object->TRIGGER_PREFIX);
1466 unset($object->user_closing_id);
1467 unset($object->user_creation_id);
1468 unset($object->user_modification_id);
1469 unset($object->user_validation_id);
1470 unset($object->user);
1471 unset($object->usergroup_entity);
1472 unset($object->warehouse_id);
1473
1474 return $object;
1475 }
1476
1483 private function _cleanUserGroupListDatas($objectList)
1484 {
1485 $cleanObjectList = array();
1486
1487 foreach ($objectList as $object) {
1488 $cleanObject = parent::_cleanObjectDatas($object);
1489
1490 unset($cleanObject->default_values);
1491 unset($cleanObject->lastsearch_values);
1492 unset($cleanObject->lastsearch_values_tmp);
1493
1494 unset($cleanObject->total_ht);
1495 unset($cleanObject->total_tva);
1496 unset($cleanObject->total_localtax1);
1497 unset($cleanObject->total_localtax2);
1498 unset($cleanObject->total_ttc);
1499
1500 unset($cleanObject->libelle_incoterms);
1501 unset($cleanObject->location_incoterms);
1502
1503 unset($cleanObject->fk_delivery_address);
1504 unset($cleanObject->fk_incoterms);
1505 unset($cleanObject->all_permissions_are_loaded);
1506 unset($cleanObject->shipping_method_id);
1507 unset($cleanObject->nb_rights);
1508 unset($cleanObject->search_sid);
1509 unset($cleanObject->ldap_sid);
1510 unset($cleanObject->clicktodial_loaded);
1511
1512 unset($cleanObject->datec);
1513 unset($cleanObject->tms);
1514 unset($cleanObject->members);
1515 unset($cleanObject->note);
1516 unset($cleanObject->note_private);
1517
1518 $cleanObjectList[] = $cleanObject;
1519 }
1520
1521 return $cleanObjectList;
1522 }
1523
1531 private function _validate($data) // @phpstan-ignore-line
1532 {
1533 $account = array();
1534 foreach (Users::$FIELDS as $field) {
1535 if (!isset($data[$field])) {
1536 throw new RestException(400, "$field field missing");
1537 }
1538 $account[$field] = $data[$field];
1539 }
1540 return $account;
1541 }
1542}
$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.