dolibarr 22.0.5
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 Frédéric France <frederic.france@free.fr>
6 * COpyright (C) 2025 William Mead <william@m34d.com>
7 *
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 3 of the License, or
11 * (at your option) any later version.
12 *
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
17 *
18 * You should have received a copy of the GNU General Public License
19 * along with this program. If not, see <https://www.gnu.org/licenses/>.
20 */
21
22use Luracast\Restler\RestException;
23
24require_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php';
25require_once DOL_DOCUMENT_ROOT.'/user/class/usergroup.class.php';
26require_once DOL_DOCUMENT_ROOT.'/core/class/notify.class.php';
27
28
37class Users extends DolibarrApi
38{
42 public static $FIELDS = array(
43 'login',
44 );
45
49 public $useraccount;
50
54 public function __construct()
55 {
56 global $db;
57
58 $this->db = $db;
59 $this->useraccount = new User($this->db);
60 }
61
62
84 public function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $user_ids = '0', $category = 0, $sqlfilters = '', $properties = '')
85 {
86 if (!DolibarrApiAccess::$user->hasRight('user', 'user', 'lire') && empty(DolibarrApiAccess::$user->admin)) {
87 throw new RestException(403, "You are not allowed to read list of users");
88 }
89
90 $obj_ret = array();
91
92 // case of external user, $societe param is ignored and replaced by user's socid
93 //$socid = DolibarrApiAccess::$user->socid ?: $societe;
94
95 $sql = "SELECT t.rowid";
96 $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
97 if ($category > 0) {
98 $sql .= ", ".$this->db->prefix()."categorie_user as c";
99 }
100 $sql .= ' WHERE t.entity IN ('.getEntity('user').')';
101 if ($user_ids) {
102 $sql .= " AND t.rowid IN (".$this->db->sanitize($user_ids).")";
103 }
104
105 // Select products of given category
106 if ($category > 0) {
107 $sql .= " AND c.fk_categorie = ".((int) $category);
108 $sql .= " AND c.fk_user = t.rowid";
109 }
110
111 // Add sql filters
112 if ($sqlfilters) {
113 $errormessage = '';
114 $sql .= forgeSQLFromUniversalSearchCriteria($sqlfilters, $errormessage);
115 if ($errormessage) {
116 throw new RestException(400, 'Error when validating parameter sqlfilters -> '.$errormessage);
117 }
118 }
119
120 $sql .= $this->db->order($sortfield, $sortorder);
121 if ($limit) {
122 if ($page < 0) {
123 $page = 0;
124 }
125 $offset = $limit * $page;
126
127 $sql .= $this->db->plimit($limit + 1, $offset);
128 }
129
130 $result = $this->db->query($sql);
131
132 if ($result) {
133 $i = 0;
134 $num = $this->db->num_rows($result);
135 $min = min($num, ($limit <= 0 ? $num : $limit));
136 while ($i < $min) {
137 $obj = $this->db->fetch_object($result);
138 $user_static = new User($this->db);
139 if ($user_static->fetch($obj->rowid)) {
140 $obj_ret[] = $this->_filterObjectProperties($this->_cleanObjectDatas($user_static), $properties);
141 }
142 $i++;
143 }
144 } else {
145 throw new RestException(503, 'Error when retrieve User list : '.$this->db->lasterror());
146 }
147
148 return $obj_ret;
149 }
150
165 public function get($id, $includepermissions = 0)
166 {
167 if (!DolibarrApiAccess::$user->hasRight('user', 'user', 'lire') && empty(DolibarrApiAccess::$user->admin) && $id != 0 && DolibarrApiAccess::$user->id != $id) {
168 throw new RestException(403, 'Not allowed');
169 }
170
171 if ($id == 0) {
172 $result = $this->useraccount->initAsSpecimen();
173 } else {
174 $result = $this->useraccount->fetch($id);
175 }
176 if (!$result) {
177 throw new RestException(404, 'User not found');
178 }
179
180 if ($id > 0 && !DolibarrApi::_checkAccessToResource('user', $this->useraccount->id, 'user')) {
181 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
182 }
183
184 if ($includepermissions) {
185 $this->useraccount->loadRights();
186 }
187
188 return $this->_cleanObjectDatas($this->useraccount);
189 }
190
208 public function getByLogin($login, $includepermissions = 0)
209 {
210 if (empty($login)) {
211 throw new RestException(400, 'Bad parameters');
212 }
213
214 if (!DolibarrApiAccess::$user->hasRight('user', 'user', 'lire') && empty(DolibarrApiAccess::$user->admin) && DolibarrApiAccess::$user->login != $login) {
215 throw new RestException(403, 'Not allowed');
216 }
217
218 $result = $this->useraccount->fetch(0, $login);
219 if (!$result) {
220 throw new RestException(404, 'User not found');
221 }
222
223 if (!DolibarrApi::_checkAccessToResource('user', $this->useraccount->id, 'user')) {
224 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
225 }
226
227 if ($includepermissions) {
228 $this->useraccount->loadRights();
229 }
230
231 return $this->_cleanObjectDatas($this->useraccount);
232 }
233
251 public function getByEmail($email, $includepermissions = 0)
252 {
253 if (empty($email)) {
254 throw new RestException(400, 'Bad parameters');
255 }
256
257 if (!DolibarrApiAccess::$user->hasRight('user', 'user', 'lire') && empty(DolibarrApiAccess::$user->admin) && DolibarrApiAccess::$user->email != $email) {
258 throw new RestException(403, 'Not allowed');
259 }
260
261 $result = $this->useraccount->fetch(0, '', '', 0, -1, $email);
262 if (!$result) {
263 throw new RestException(404, 'User not found');
264 }
265
266 if (!DolibarrApi::_checkAccessToResource('user', $this->useraccount->id, 'user')) {
267 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
268 }
269
270 if ($includepermissions) {
271 $this->useraccount->loadRights();
272 }
273
274 return $this->_cleanObjectDatas($this->useraccount);
275 }
276
290 public function getInfo($includepermissions = 0)
291 {
292 if (!DolibarrApiAccess::$user->hasRight('user', 'self', 'creer') && !DolibarrApiAccess::$user->hasRight('user', 'user', 'lire') && empty(DolibarrApiAccess::$user->admin)) {
293 throw new RestException(403, 'Not allowed');
294 }
295
296 $apiUser = DolibarrApiAccess::$user;
297
298 $result = $this->useraccount->fetch($apiUser->id);
299 if (!$result) {
300 throw new RestException(404, 'User not found');
301 }
302
303 if (!DolibarrApi::_checkAccessToResource('user', $this->useraccount->id, 'user')) {
304 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
305 }
306
307 if ($includepermissions) {
308 $this->useraccount->loadRights();
309 }
310
311 $usergroup = new UserGroup($this->db);
312 $userGroupList = $usergroup->listGroupsForUser($apiUser->id, false);
313 if (!is_array($userGroupList)) {
314 throw new RestException(404, 'User group not found');
315 }
316
317 $this->useraccount->user_group_list = $this->_cleanUserGroupListDatas($userGroupList);
318
319 return $this->_cleanObjectDatas($this->useraccount);
320 }
321
334 public function post($request_data = null)
335 {
336 // Check user authorization
337 if (!DolibarrApiAccess::$user->hasRight('user', 'user', 'creer') && empty(DolibarrApiAccess::$user->admin)) {
338 throw new RestException(403, "User creation not allowed for login ".DolibarrApiAccess::$user->login);
339 }
340
341 // check mandatory fields
342 /*if (!isset($request_data["login"]))
343 throw new RestException(400, "login field missing");
344 if (!isset($request_data["password"]))
345 throw new RestException(400, "password field missing");
346 if (!isset($request_data["lastname"]))
347 throw new RestException(400, "lastname field missing");*/
348
349 //assign field values
350 foreach ($request_data as $field => $value) {
351 if (in_array($field, array('pass_crypted', 'pass_indatabase', 'pass_indatabase_crypted', 'pass_temp', 'api_key'))) {
352 // This properties can't be set/modified with API
353 throw new RestException(405, 'The property '.$field." can't be set/modified using the APIs");
354 }
355 if ($field === 'caller') {
356 // 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
357 $this->useraccount->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
358 continue;
359 }
360 /*if ($field == 'pass') {
361 if (!DolibarrApiAccess::$user->hasRight('user', 'user', 'password')) {
362 throw new RestException(403, 'You are not allowed to modify/set password of other users');
363 continue;
364 }
365 }
366 */
367
368 $this->useraccount->$field = $this->_checkValForAPI($field, $value, $this->useraccount);
369 }
370
371 if ($this->useraccount->create(DolibarrApiAccess::$user) < 0) {
372 throw new RestException(500, 'Error creating', array_merge(array($this->useraccount->error), $this->useraccount->errors));
373 }
374 return $this->useraccount->id;
375 }
376
377
393 public function put($id, $request_data = null)
394 {
395 // Check user authorization
396 if (!DolibarrApiAccess::$user->hasRight('user', 'user', 'creer') && empty(DolibarrApiAccess::$user->admin)) {
397 throw new RestException(403, "User update not allowed");
398 }
399
400 $result = $this->useraccount->fetch($id);
401 if (!$result) {
402 throw new RestException(404, 'Account not found');
403 }
404
405 if (!DolibarrApi::_checkAccessToResource('user', $this->useraccount->id, 'user')) {
406 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
407 }
408
409 foreach ($request_data as $field => $value) {
410 if (in_array($field, array('pass_crypted', 'pass_indatabase', 'pass_indatabase_crypted', 'pass_temp', 'api_key'))) {
411 // This properties can't be set/modified with API
412 throw new RestException(405, 'The property '.$field." can't be set/modified using the APIs");
413 }
414 if ($field == 'id') {
415 continue;
416 }
417 if ($field == 'pass') {
418 if ($this->useraccount->id != DolibarrApiAccess::$user->id && !DolibarrApiAccess::$user->hasRight('user', 'user', 'password')) {
419 throw new RestException(403, 'You are not allowed to modify password of other users');
420 }
421 if ($this->useraccount->id == DolibarrApiAccess::$user->id && !DolibarrApiAccess::$user->hasRight('user', 'self', 'password')) {
422 throw new RestException(403, 'You are not allowed to modify your own password');
423 }
424 }
425 if ($field === 'caller') {
426 // 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
427 $this->useraccount->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
428 continue;
429 }
430 if ($field == 'array_options' && is_array($value)) {
431 foreach ($value as $index => $val) {
432 $this->useraccount->array_options[$index] = $this->_checkValForAPI($field, $val, $this->useraccount);
433 }
434 continue;
435 }
436
437 if (DolibarrApiAccess::$user->admin) { // If user for API is admin
438 if ($field == 'admin' && $value != $this->useraccount->admin && empty($value)) {
439 throw new RestException(403, 'Reseting the admin status of a user is not possible using the API');
440 }
441 } else {
442 if ($field == 'admin' && $value != $this->useraccount->admin) {
443 throw new RestException(403, 'Only an admin user can modify the admin status of another user');
444 }
445 }
446 if ($field == 'entity' && $value != $this->useraccount->entity) {
447 throw new RestException(403, 'Changing entity of a user using the APIs is not possible');
448 }
449
450 // The status must be updated using setstatus() because it
451 // is not handled by the update() method.
452 if ($field == 'statut' || $field == 'status') {
453 $result = $this->useraccount->setstatus($value);
454 if ($result < 0) {
455 throw new RestException(500, 'Error when updating status of user: '.$this->useraccount->error);
456 }
457 } else {
458 $this->useraccount->$field = $this->_checkValForAPI($field, $value, $this->useraccount);
459 }
460 }
461
462 // If there is no error, update() returns the number of affected
463 // rows so if the update is a no op, the return value is zezo.
464 if ($this->useraccount->update(DolibarrApiAccess::$user) >= 0) {
465 return $this->get($id);
466 } else {
467 throw new RestException(500, $this->useraccount->error);
468 }
469 }
470
486 public function setPassword($id, $send_password = false)
487 {
488 //$conf->global->API_DISABLE_LOGIN_API = 1;
489 if (getDolGlobalString('API_DISABLE_LOGIN_API')) {
490 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.");
491 }
492
493 //$conf->global->API_ALLOW_PASSWORD_RESET = 1;
494 if (!getDolGlobalString('API_ALLOW_PASSWORD_RESET')) {
495 throw new RestException(403, "Error: password reset APIs are disabled by default. To allow this, the option API_ALLOW_PASSWORD_RESET must be set.");
496 }
497
498 if (!DolibarrApiAccess::$user->hasRight('user', 'user', 'creer') && empty(DolibarrApiAccess::$user->admin)) {
499 throw new RestException(403, "setPassword on user not allowed for login ".DolibarrApiAccess::$user->login);
500 }
501
502 $result = $this->useraccount->fetch($id);
503 if (!$result) {
504 throw new RestException(404, 'User not found, no password changed');
505 }
506
507 if (!DolibarrApi::_checkAccessToResource('user', $this->useraccount->id, 'user')) {
508 throw new RestException(403, 'Access on this object not allowed for login '.DolibarrApiAccess::$user->login);
509 }
510
511 $newpassword = $this->useraccount->setPassword($this->useraccount, ''); // This will generate a new password
512 if (is_int($newpassword) && $newpassword < 0) {
513 throw new RestException(500, 'ErrorFailedToSetNewPassword'.$this->useraccount->error);
514 } else {
515 // Success
516 if ($send_password) {
517 if ($this->useraccount->send_password($this->useraccount, $newpassword) > 0) {
518 return 2;
519 } else {
520 throw new RestException(500, 'ErrorFailedSendingNewPassword - '.$this->useraccount->error);
521 }
522 } else {
523 return 1;
524 }
525 }
526 }
527
543 public function getGroups($id)
544 {
545 if (!DolibarrApiAccess::$user->hasRight('user', 'user', 'lire') && empty(DolibarrApiAccess::$user->admin)) {
546 throw new RestException(403);
547 }
548
549 $user = new User($this->db);
550 $result = $user->fetch($id);
551 if (!$result) {
552 throw new RestException(404, 'user not found');
553 }
554
555 $usergroup = new UserGroup($this->db);
556 $groups = $usergroup->listGroupsForUser($id, false);
557 $obj_ret = array();
558 foreach ($groups as $group) {
559 $obj_ret[] = $this->_cleanObjectDatas($group);
560 }
561 return $obj_ret;
562 }
563
564
581 public function setGroup($id, $group, $entity = 1)
582 {
583 global $conf;
584
585 if (!DolibarrApiAccess::$user->hasRight('user', 'user', 'creer') && empty(DolibarrApiAccess::$user->admin)) {
586 throw new RestException(403, 'setGroup on users not allowed for login '.DolibarrApiAccess::$user->login);
587 }
588
589 $result = $this->useraccount->fetch($id);
590 if (!$result) {
591 throw new RestException(404, 'User not found');
592 }
593
594 if (!DolibarrApi::_checkAccessToResource('user', $this->useraccount->id, 'user')) {
595 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
596 }
597
598 if (isModEnabled('multicompany') && getDolGlobalString('MULTICOMPANY_TRANSVERSE_MODE') && !empty(DolibarrApiAccess::$user->admin) && empty(DolibarrApiAccess::$user->entity)) {
599 $entity = (!empty($entity) ? $entity : $conf->entity);
600 } else {
601 // 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
602 // hack the security by giving himself permissions on another entity.
603 $entity = (DolibarrApiAccess::$user->entity > 0 ? DolibarrApiAccess::$user->entity : $conf->entity);
604 }
605
606 $result = $this->useraccount->SetInGroup($group, $entity);
607 if (!($result > 0)) {
608 throw new RestException(500, $this->useraccount->error);
609 }
610
611 return 1;
612 }
613
638 public function listGroups($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $group_ids = '0', $sqlfilters = '', $properties = '')
639 {
640 $obj_ret = array();
641
642 if ((!getDolGlobalString('MAIN_USE_ADVANCED_PERMS') && !DolibarrApiAccess::$user->hasRight('user', 'user', 'lire') && empty(DolibarrApiAccess::$user->admin)) ||
643 getDolGlobalString('MAIN_USE_ADVANCED_PERMS') && !DolibarrApiAccess::$user->hasRight('user', 'group_advance', 'read') && empty(DolibarrApiAccess::$user->admin)) {
644 throw new RestException(403, "You are not allowed to read groups");
645 }
646
647 // case of external user, $societe param is ignored and replaced by user's socid
648 //$socid = DolibarrApiAccess::$user->socid ?: $societe;
649
650 $sql = "SELECT t.rowid";
651 $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
652 $sql .= ' WHERE t.entity IN ('.getEntity('user').')';
653 if ($group_ids) {
654 $sql .= " AND t.rowid IN (".$this->db->sanitize($group_ids).")";
655 }
656 // Add sql filters
657 if ($sqlfilters) {
658 $errormessage = '';
659 $sql .= forgeSQLFromUniversalSearchCriteria($sqlfilters, $errormessage);
660 if ($errormessage) {
661 throw new RestException(400, 'Error when validating parameter sqlfilters -> '.$errormessage);
662 }
663 }
664
665 $sql .= $this->db->order($sortfield, $sortorder);
666 if ($limit) {
667 if ($page < 0) {
668 $page = 0;
669 }
670 $offset = $limit * $page;
671
672 $sql .= $this->db->plimit($limit + 1, $offset);
673 }
674
675 $result = $this->db->query($sql);
676
677 if ($result) {
678 $i = 0;
679 $num = $this->db->num_rows($result);
680 $min = min($num, ($limit <= 0 ? $num : $limit));
681 while ($i < $min) {
682 $obj = $this->db->fetch_object($result);
683 $group_static = new UserGroup($this->db);
684 if ($group_static->fetch($obj->rowid)) {
685 $obj_ret[] = $this->_filterObjectProperties($this->_cleanObjectDatas($group_static), $properties);
686 }
687 $i++;
688 }
689 } else {
690 throw new RestException(503, 'Error when retrieve Group list : '.$this->db->lasterror());
691 }
692
693 return $obj_ret;
694 }
695
712 public function infoGroups($group, $load_members = 0)
713 {
714 if ((!getDolGlobalString('MAIN_USE_ADVANCED_PERMS') && !DolibarrApiAccess::$user->hasRight('user', 'user', 'lire') && empty(DolibarrApiAccess::$user->admin)) ||
715 getDolGlobalString('MAIN_USE_ADVANCED_PERMS') && !DolibarrApiAccess::$user->hasRight('user', 'group_advance', 'read') && empty(DolibarrApiAccess::$user->admin)) {
716 throw new RestException(403, "You are not allowed to read groups");
717 }
718
719 $group_static = new UserGroup($this->db);
720 $result = $group_static->fetch($group, '', (bool) $load_members);
721
722 if (!$result) {
723 throw new RestException(404, 'Group not found');
724 }
725
726 return $this->_cleanObjectDatas($group_static);
727 }
728
742 public function delete($id)
743 {
744 if (!DolibarrApiAccess::$user->hasRight('user', 'user', 'supprimer') && empty(DolibarrApiAccess::$user->admin)) {
745 throw new RestException(403, 'Not allowed');
746 }
747 $result = $this->useraccount->fetch($id);
748 if (!$result) {
749 throw new RestException(404, 'User not found');
750 }
751
752 if (!DolibarrApi::_checkAccessToResource('user', $this->useraccount->id, 'user')) {
753 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
754 }
755 $this->useraccount->oldcopy = clone $this->useraccount; // @phan-suppress-current-line PhanTypeMismatchProperty
756
757 if (!$this->useraccount->delete(DolibarrApiAccess::$user)) {
758 throw new RestException(500);
759 }
760
761 return array(
762 'success' => array(
763 'code' => 200,
764 'message' => 'Ticket deleted'
765 )
766 );
767 }
768
784 public function getUserNotification($id)
785 {
786 if (empty($id)) {
787 throw new RestException(400, 'user ID is mandatory');
788 }
789 if (!DolibarrApiAccess::$user->hasRight('user', 'user', 'lire') && empty(DolibarrApiAccess::$user->admin)) {
790 throw new RestException(403);
791 }
793 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
794 }
795
800 $sql = "SELECT rowid as id, fk_action as event, fk_user, type, datec, tms";
801 $sql .= " FROM ".MAIN_DB_PREFIX."notify_def";
802 $sql .= " WHERE fk_user = ".((int) $id);
803
804 $result = $this->db->query($sql);
805 if ($this->db->num_rows($result) == 0) {
806 throw new RestException(404, 'Notification not found');
807 }
808
809 $i = 0;
810
811 $notifications = array();
812
813 if ($result) {
814 $num = $this->db->num_rows($result);
815 while ($i < $num) {
816 $obj = $this->db->fetch_object($result);
817 $notifications[] = $obj;
818 $i++;
819 }
820 } else {
821 throw new RestException(404, 'No notifications found');
822 }
823
824 $fields = array('id', 'fk_user', 'event', 'datec', 'tms', 'type');
825
826 $returnNotifications = array();
827
828 foreach ($notifications as $notification) {
829 $object = array();
830 foreach ($notification as $key => $value) {
831 if (in_array($key, $fields)) {
832 $object[$key] = $value;
833 }
834 }
835 $returnNotifications[] = $object;
836 }
837
838 // Too complex for phan ?: @phan-suppress-next-line PhanTypeMismatchReturn
839 return $returnNotifications;
840 }
841
858 public function createUserNotification($id, $request_data = null)
859 {
860 if (!DolibarrApiAccess::$user->hasRight('user', 'user', 'creer')) {
861 throw new RestException(403, "User has no right to update users");
862 }
863 if ($this->useraccount->fetch($id) <= 0) {
864 throw new RestException(404, 'Error creating User Notification, User doesn\'t exists');
865 }
866 $notification = new Notify($this->db);
867
868 $notification->fk_user = $id;
869
870 foreach ($request_data as $field => $value) {
871 $notification->$field = $value;
872 }
873
874 $event = $notification->event;
875 if (!$event) {
876 throw new RestException(500, 'Error creating User Notification, request_data missing event');
877 }
878 $fk_user = $notification->fk_user;
879
880 $exists_sql = "SELECT rowid, fk_action as event, fk_user, type, datec, tms as datem";
881 $exists_sql .= " FROM ".MAIN_DB_PREFIX."notify_def";
882 $exists_sql .= " WHERE fk_action = '".$this->db->escape((string) $event)."'";
883 $exists_sql .= " AND fk_user = '".$this->db->escape((string) $fk_user)."'";
884
885 $exists_result = $this->db->query($exists_sql);
886 if ($this->db->num_rows($exists_result) > 0) {
887 throw new RestException(403, 'Notification already exists');
888 }
889
890 if ($notification->create(DolibarrApiAccess::$user) < 0) {
891 throw new RestException(500, 'Error creating User Notification');
892 }
893
894 if ($notification->update(DolibarrApiAccess::$user) < 0) {
895 throw new RestException(500, 'Error updating values');
896 }
897
898 return $this->_cleanObjectDatas($notification);
899 }
900
919 public function createUserNotificationByCode($id, $code, $request_data = null)
920 {
921 if (!DolibarrApiAccess::$user->hasRight('user', 'user', 'creer')) {
922 throw new RestException(403, "User has no right to update users");
923 }
924 if ($this->useraccount->fetch($id) <= 0) {
925 throw new RestException(404, 'Error creating User Notification, User doesn\'t exists');
926 }
927 $notification = new Notify($this->db);
928 $notification->fk_user = $id;
929
930 $sql = "SELECT t.rowid as id FROM ".MAIN_DB_PREFIX."c_action_trigger as t";
931 $sql .= " WHERE t.code = '".$this->db->escape($code)."'";
932
933 $result = $this->db->query($sql);
934 if ($this->db->num_rows($result) == 0) {
935 throw new RestException(404, 'Action Trigger code not found');
936 }
937
938 $notification->event = $this->db->fetch_row($result)[0];
939 foreach ($request_data as $field => $value) {
940 if ($field === 'event') {
941 throw new RestException(500, 'Error creating User Notification, request_data contains event key');
942 }
943 if ($field === 'fk_action') {
944 throw new RestException(500, 'Error creating User Notification, request_data contains fk_action key');
945 }
946 $notification->$field = $value;
947 }
948
949 $event = $notification->event;
950 $fk_user = $notification->fk_user;
951
952 $exists_sql = "SELECT rowid, fk_action as event, fk_user, type, datec, tms as datem";
953 $exists_sql .= " FROM ".MAIN_DB_PREFIX."notify_def";
954 $exists_sql .= " WHERE fk_action = '".$this->db->escape((string) $event)."'";
955 $exists_sql .= " AND fk_user = '".$this->db->escape((string) $fk_user)."'";
956
957 $exists_result = $this->db->query($exists_sql);
958 if ($this->db->num_rows($exists_result) > 0) {
959 throw new RestException(403, 'Notification already exists');
960 }
961
962 if ($notification->create(DolibarrApiAccess::$user) < 0) {
963 throw new RestException(500, 'Error creating User Notification, are request_data well formed?');
964 }
965
966 if ($notification->update(DolibarrApiAccess::$user) < 0) {
967 throw new RestException(500, 'Error updating values');
968 }
969
970 return $this->_cleanObjectDatas($notification);
971 }
972
987 public function deleteUserNotification($id, $notification_id)
988 {
989 if (!DolibarrApiAccess::$user->hasRight('user', 'user', 'creer')) {
990 throw new RestException(403, "User has no right to update users");
991 }
992
993 $notification = new Notify($this->db);
994
995 $notification->fetch($notification_id);
996
997 $fk_user = (int) $notification->fk_user;
998
999 if ($fk_user == $id) {
1000 return $notification->delete(DolibarrApiAccess::$user);
1001 } else {
1002 throw new RestException(403, "Not allowed due to bad consistency of input data");
1003 }
1004 }
1005
1023 public function updateUserNotification($id, $notification_id, $request_data = null)
1024 {
1025 if (!DolibarrApiAccess::$user->hasRight('user', 'user', 'creer')) {
1026 throw new RestException(403, "User has no right to update users");
1027 }
1028 if ($this->useraccount->fetch($id) <= 0) {
1029 throw new RestException(404, 'Error creating Notification, User doesn\'t exists');
1030 }
1031 $notification = new Notify($this->db);
1032
1033 // @phan-suppress-next-line PhanPluginSuspiciousParamPosition
1034 $notification->fetch($notification_id, $id);
1035
1036 if ($notification->fk_user != $id) {
1037 throw new RestException(403, "Not allowed due to bad consistency of input data");
1038 }
1039
1040 foreach ($request_data as $field => $value) {
1041 $notification->$field = $value;
1042 }
1043
1044 if ($notification->update(DolibarrApiAccess::$user) < 0) {
1045 throw new RestException(500, 'Error updating values');
1046 }
1047
1048 return $this->_cleanObjectDatas($notification);
1049 }
1050
1051 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
1058 protected function _cleanObjectDatas($object)
1059 {
1060 // phpcs:enable
1061 $object = parent::_cleanObjectDatas($object);
1062
1063 unset($object->default_values);
1064 unset($object->lastsearch_values);
1065 unset($object->lastsearch_values_tmp);
1066
1067 unset($object->total_ht);
1068 unset($object->total_tva);
1069 unset($object->total_localtax1);
1070 unset($object->total_localtax2);
1071 unset($object->total_ttc);
1072
1073 unset($object->label_incoterms);
1074 unset($object->location_incoterms);
1075
1076 unset($object->fk_delivery_address);
1077 unset($object->fk_incoterms);
1078 unset($object->all_permissions_are_loaded);
1079 unset($object->shipping_method_id);
1080 unset($object->nb_rights);
1081 unset($object->search_sid);
1082 unset($object->ldap_sid);
1083 unset($object->clicktodial_loaded);
1084
1085 // List of properties never returned by API, whatever are permissions
1086 unset($object->pass);
1087 unset($object->pass_indatabase);
1088 unset($object->pass_indatabase_crypted);
1089 unset($object->pass_temp);
1090 unset($object->api_key);
1091 unset($object->clicktodial_password);
1092 unset($object->openid);
1093
1094 unset($object->lines);
1095 unset($object->model_pdf);
1096
1097 $canreadsalary = ((isModEnabled('salaries') && DolibarrApiAccess::$user->hasRight('salaries', 'read')) || !isModEnabled('salaries'));
1098
1099 if (!$canreadsalary) {
1100 unset($object->salary);
1101 unset($object->salaryextra);
1102 unset($object->thm);
1103 unset($object->tjm);
1104 }
1105
1106 return $object;
1107 }
1108
1115 private function _cleanUserGroupListDatas($objectList)
1116 {
1117 $cleanObjectList = array();
1118
1119 foreach ($objectList as $object) {
1120 $cleanObject = parent::_cleanObjectDatas($object);
1121
1122 unset($cleanObject->default_values);
1123 unset($cleanObject->lastsearch_values);
1124 unset($cleanObject->lastsearch_values_tmp);
1125
1126 unset($cleanObject->total_ht);
1127 unset($cleanObject->total_tva);
1128 unset($cleanObject->total_localtax1);
1129 unset($cleanObject->total_localtax2);
1130 unset($cleanObject->total_ttc);
1131
1132 unset($cleanObject->libelle_incoterms);
1133 unset($cleanObject->location_incoterms);
1134
1135 unset($cleanObject->fk_delivery_address);
1136 unset($cleanObject->fk_incoterms);
1137 unset($cleanObject->all_permissions_are_loaded);
1138 unset($cleanObject->shipping_method_id);
1139 unset($cleanObject->nb_rights);
1140 unset($cleanObject->search_sid);
1141 unset($cleanObject->ldap_sid);
1142 unset($cleanObject->clicktodial_loaded);
1143
1144 unset($cleanObject->datec);
1145 unset($cleanObject->tms);
1146 unset($cleanObject->members);
1147 unset($cleanObject->note);
1148 unset($cleanObject->note_private);
1149
1150 $cleanObjectList[] = $cleanObject;
1151 }
1152
1153 return $cleanObjectList;
1154 }
1155
1163 private function _validate($data) // @phpstan-ignore-line
1164 {
1165 $account = array();
1166 foreach (Users::$FIELDS as $field) {
1167 if (!isset($data[$field])) {
1168 throw new RestException(400, "$field field missing");
1169 }
1170 $account[$field] = $data[$field];
1171 }
1172 return $account;
1173 }
1174}
$id
Support class for third parties, contacts, members, users or resources.
Definition account.php:48
if( $user->socid > 0) if(! $user->hasRight('accounting', 'chartofaccount')) $object
Definition card.php:67
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.
index($sortfield="t.rowid", $sortorder='ASC', $limit=100, $page=0, $user_ids='0', $category=0, $sqlfilters='', $properties='')
List users.
_cleanObjectDatas($object)
Clean sensible object datas.
getInfo($includepermissions=0)
Get more properties of a user.
_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.
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.
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.
getUserNotification($id)
Get notifications for a user.
__construct()
Constructor.
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.
global $conf
The following vars must be defined: $type2label $form $conf, $lang, The following vars may also be de...
Definition member.php:79