dolibarr 24.0.2
api_contacts.class.php
1<?php
2/* Copyright (C) 2015 Jean-François Ferry <jfefe@aternatik.fr>
3 * Copyright (C) 2019-2025 Frédéric France <frederic.france@free.fr>
4 * Copyright (C) 2024 MDW <mdeweerd@users.noreply.github.com>
5 * Copyright (C) 2025 William Mead <william@m34d.com>
6 *
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 3 of the License, or
10 * (at your option) any later version.
11 *
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
19 */
20
21use Luracast\Restler\RestException;
22
23//require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
24//require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
25require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';
26
27
36class Contacts extends DolibarrApi
37{
42 public static $FIELDS = array(
43 'lastname',
44 );
45
49 public $contact;
50
54 public function __construct()
55 {
56 global $db, $conf;
57 $this->db = $db;
58
59 require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
60 require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
61
62 $this->contact = new Contact($this->db);
63 }
64
79 public function get($id, $includecount = 0, $includeroles = 0)
80 {
81 if (!DolibarrApiAccess::$user->hasRight('societe', 'contact', 'lire')) {
82 throw new RestException(403, 'No permission to read contacts');
83 }
84
85 if ($id === 0) {
86 $result = $this->contact->initAsSpecimen();
87 } else {
88 $result = $this->contact->fetch($id);
89 }
90
91 if (!$result) {
92 throw new RestException(404, 'Contact not found');
93 }
94
95 if (!DolibarrApi::_checkAccessToResource('contact', $this->contact->id, 'socpeople&societe')) {
96 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
97 }
98
99 if ($includecount) {
100 $this->contact->load_ref_elements();
101 }
102
103 if ($includeroles) {
104 $this->contact->fetchRoles();
105 }
106
107 if (isModEnabled('mailing')) {
108 $this->contact->getNoEmail();
109 }
110
111 return $this->_cleanObjectDatas($this->contact);
112 }
113
129 public function getByEmail($email, $includecount = 0, $includeroles = 0)
130 {
131 if (!DolibarrApiAccess::$user->hasRight('societe', 'contact', 'lire')) {
132 throw new RestException(403, 'No permission to read contacts');
133 }
134
135 if (empty($email)) {
136 $result = $this->contact->initAsSpecimen();
137 } else {
138 $result = $this->contact->fetch(0, null, '', $email);
139 }
140
141 if (!$result) {
142 throw new RestException(404, 'Contact not found');
143 }
144
145 if (!DolibarrApi::_checkAccessToResource('contact', $this->contact->id, 'socpeople&societe')) {
146 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
147 }
148
149 if ($includecount) {
150 $this->contact->load_ref_elements();
151 }
152
153 if ($includeroles) {
154 $this->contact->fetchRoles();
155 }
156
157 if (isModEnabled('mailing')) {
158 $this->contact->getNoEmail();
159 }
160
161 return $this->_cleanObjectDatas($this->contact);
162 }
163
186 public function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $thirdparty_ids = '', $category = 0, $sqlfilters = '', $includecount = 0, $includeroles = 0, $properties = '', $pagination_data = false)
187 {
188 global $db, $conf;
189
190 $obj_ret = array();
191
192 if (!DolibarrApiAccess::$user->hasRight('societe', 'contact', 'lire')) {
193 throw new RestException(403, 'No permission to read contacts');
194 }
195
196 // case of external user, $thirdparty_ids param is ignored and replaced by user's socid
197 $socids = DolibarrApiAccess::$user->socid ?: $thirdparty_ids;
198
199 // If the internal user must only see his customers, force searching by him
200 $search_sale = 0;
201 if (!DolibarrApiAccess::$user->hasRight('societe', 'client', 'voir') && !$socids) {
202 $search_sale = DolibarrApiAccess::$user->id;
203 }
204
205 $sql = "SELECT t.rowid";
206 $sql .= " FROM ".MAIN_DB_PREFIX."socpeople as t";
207 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."socpeople_extrafields as te ON te.fk_object = t.rowid";
208 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON t.fk_soc = s.rowid";
209 $sql .= ' WHERE t.entity IN ('.getEntity('contact').')';
210 // A private contact is only visible by the user that created it
211 $sql .= " AND (t.priv = 0 OR t.fk_user_creat = ".((int) DolibarrApiAccess::$user->id).")";
212 if ($socids) {
213 $sql .= " AND t.fk_soc IN (".$this->db->sanitize($socids).")";
214 }
215 // Search on sale representative
216 if ($search_sale && $search_sale != '-1') {
217 if ($search_sale == -2) {
218 $sql .= " AND NOT EXISTS (SELECT sc.fk_soc FROM ".MAIN_DB_PREFIX."societe_commerciaux as sc WHERE sc.fk_soc = t.fk_soc)";
219 } elseif ($search_sale > 0) {
220 $sql .= " AND EXISTS (SELECT sc.fk_soc FROM ".MAIN_DB_PREFIX."societe_commerciaux as sc WHERE sc.fk_soc = t.fk_soc AND sc.fk_user = ".((int) $search_sale).")";
221 }
222 }
223 // Select contacts of given category
224 if ($category > 0) {
225 // Search Contact Categories
226 $searchCategoryContactList = $category ? array($category) : array();
227 // $searchCategoryContactOperator = 0;
228 // Search for tag/category ($searchCategoryContactList is an array of ID)
229 if (!empty($searchCategoryContactList)) {
230 $searchCategoryContactSqlList = array();
231 // $listofcategoryid = '';
232 foreach ($searchCategoryContactList as $searchCategoryContact) {
233 if (intval($searchCategoryContact) == -2) {
234 $searchCategoryContactSqlList[] = "NOT EXISTS (SELECT ck.fk_socpeople FROM ".MAIN_DB_PREFIX."categorie_contact as ck WHERE t.rowid = ck.fk_socpeople)";
235 } elseif (intval($searchCategoryContact) > 0) {
236 // if ($searchCategoryContactOperator == 0) {
237 $searchCategoryContactSqlList[] = " EXISTS (SELECT ck.fk_socpeople FROM ".MAIN_DB_PREFIX."categorie_contact as ck WHERE t.rowid = ck.fk_socpeople AND ck.fk_categorie = ".((int) $searchCategoryContact).")";
238 // } else {
239 // $listofcategoryid .= ($listofcategoryid ? ', ' : '') .((int) $searchCategoryContact);
240 // }
241 }
242 }
243 // if ($listofcategoryid) {
244 // $searchCategoryContactSqlList[] = " EXISTS (SELECT ck.fk_socpeople FROM ".MAIN_DB_PREFIX."categorie_contact as ck WHERE t.rowid = ck.fk_socpeople AND ck.fk_categorie IN (".$this->db->sanitize($listofcategoryid)."))";
245 // }
246 // if ($searchCategoryContactOperator == 1) {
247 // if (!empty($searchCategoryContactSqlList)) {
248 // $sql .= " AND (".implode(' OR ', $searchCategoryContactSqlList).")";
249 // }
250 // } else {
251 if (!empty($searchCategoryContactSqlList)) {
252 $sql .= " AND (".implode(' AND ', $searchCategoryContactSqlList).")";
253 }
254 // }
255 }
256 }
257
258 // Add sql filters
259 if ($sqlfilters) {
260 $errormessage = '';
261 $sql .= forgeSQLFromUniversalSearchCriteria($sqlfilters, $errormessage);
262 if ($errormessage) {
263 throw new RestException(400, 'Error when validating parameter sqlfilters -> '.$errormessage);
264 }
265 }
266
267 //this query will return total orders with the filters given
268 $sqlTotals = str_replace('SELECT t.rowid', 'SELECT count(t.rowid) as total', $sql);
269
270 $sql .= $this->db->order($sortfield, $sortorder);
271
272 if ($limit) {
273 if ($page < 0) {
274 $page = 0;
275 }
276 $offset = $limit * $page;
277
278 $sql .= $this->db->plimit($limit + 1, $offset);
279 }
280 $result = $this->db->query($sql);
281 if ($result) {
282 $num = $this->db->num_rows($result);
283 $min = min($num, ($limit <= 0 ? $num : $limit));
284 $i = 0;
285 while ($i < $min) {
286 $obj = $this->db->fetch_object($result);
287 $contact_static = new Contact($this->db);
288 if ($contact_static->fetch($obj->rowid)) {
289 $contact_static->fetchRoles();
290 if ($includecount) {
291 $contact_static->load_ref_elements();
292 }
293 if ($includeroles) {
294 $contact_static->fetchRoles();
295 }
296 if (isModEnabled('mailing')) {
297 $contact_static->getNoEmail();
298 }
299
300 $obj_ret[] = $this->_filterObjectProperties($this->_cleanObjectDatas($contact_static), $properties);
301 }
302
303 $i++;
304 }
305 } else {
306 throw new RestException(503, 'Error when retrieve contacts : '.$sql);
307 }
308
309 //if $pagination_data is true the response will contain element data with all values and element pagination with pagination data(total,page,limit)
310 if ($pagination_data) {
311 $totalsResult = $this->db->query($sqlTotals);
312 $total = $this->db->fetch_object($totalsResult)->total;
313
314 $tmp = $obj_ret;
315 $obj_ret = [];
316
317 $obj_ret['data'] = $tmp;
318 $obj_ret['pagination'] = [
319 'total' => (int) $total,
320 'page' => $page, //count starts from 0
321 'page_count' => ceil((int) $total / $limit),
322 'limit' => $limit
323 ];
324 }
325
326 return $obj_ret;
327 }
328
341 public function post($request_data = null)
342 {
343 if (!DolibarrApiAccess::$user->hasRight('societe', 'contact', 'creer')) {
344 throw new RestException(403, 'No permission to create/update contacts');
345 }
346 // Check mandatory fields
347 $result = $this->_validate($request_data);
348
349 // External api user does not know internal country ID
350 if (!isset($request_data['country_id']) && isset($request_data['country_code'])) {
351 $field = strlen($request_data['country_code']) > 2 ? 'code_iso' : 'code';
352 $id = dol_getIdFromCode($this->db, $request_data['country_code'], "c_country", $field, "rowid");
353 if ($id < 0) {
354 throw new RestException(404, 'Country code not found in database: ' . $this->db->error);
355 }
356 $request_data['country_id'] = $id;
357 }
358
359 foreach ($request_data as $field => $value) {
360 if ($field === 'caller') {
361 // 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
362 $this->contact->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
363 continue;
364 }
365 if ($field == 'array_options' && is_array($value)) {
366 $this->contact->fetch_optionals(); // To force the load of the extrafields definition by fetch_name_optionals_label()
367
368 foreach ($value as $index => $val) {
369 $this->contact->array_options[$index] = $this->_checkValExtrafieldsForAPI($index, $val, $this->contact);
370 }
371 continue;
372 }
373 if ($field == 'socid') {
374 $new_socid = (int) $value;
375 $loopthirdpartytmp = new Societe($this->db);
376 $new_thirdparty_result = $loopthirdpartytmp->fetch($new_socid);
377 if ($new_thirdparty_result < 1) {
378 throw new RestException(404, 'Thirdparty with id='.$new_socid.' not found or not allowed');
379 }
380 if (!DolibarrApi::_checkAccessToResource('societe', $new_socid)) {
381 throw new RestException(403, 'Access to socid/thirdparty='.$new_socid.' is not allowed for login '.DolibarrApiAccess::$user->login);
382 }
383 }
384
385 $this->contact->$field = $this->_checkValForAPI($field, $value, $this->contact);
386 }
387 if ($this->contact->create(DolibarrApiAccess::$user) < 0) {
388 throw new RestException(500, "Error creating contact", array_merge(array($this->contact->error), $this->contact->errors));
389 }
390 if (isModEnabled('mailing') && !empty($this->contact->email) && isset($this->contact->no_email)) {
391 $this->contact->setNoEmail($this->contact->no_email);
392 }
393 return $this->contact->id;
394 }
395
411 public function put($id, $request_data = null)
412 {
413 if (!DolibarrApiAccess::$user->hasRight('societe', 'contact', 'creer')) {
414 throw new RestException(403, 'No permission to create/update contacts');
415 }
416
417 $result = $this->contact->fetch($id);
418 if (!$result) {
419 throw new RestException(404, 'Contact not found');
420 }
421
422 if (!DolibarrApi::_checkAccessToResource('contact', $this->contact->id, 'socpeople&societe')) {
423 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
424 }
425
426 foreach ($request_data as $field => $value) {
427 if ($field == 'id') {
428 continue;
429 }
430 if ($field === 'caller') {
431 // 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
432 $this->contact->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
433 continue;
434 }
435 if ($field == 'array_options' && is_array($value)) {
436 foreach ($value as $index => $val) {
437 $this->contact->array_options[$index] = $this->_checkValExtrafieldsForAPI($index, $val, $this->contact);
438 }
439 continue;
440 }
441 if ($field == 'socid') {
442 $new_socid = (int) $value;
443 $loopthirdpartytmp = new Societe($this->db);
444 $new_thirdparty_result = $loopthirdpartytmp->fetch($new_socid);
445 if ($new_thirdparty_result < 1) {
446 throw new RestException(404, 'Thirdparty with id='.$new_socid.' not found or not allowed');
447 }
448 if (!DolibarrApi::_checkAccessToResource('societe', $new_socid)) {
449 throw new RestException(403, 'Access to socid/thirdparty='.$new_socid.' is not allowed for login '.DolibarrApiAccess::$user->login);
450 }
451 }
452
453 $this->contact->$field = $this->_checkValForAPI($field, $value, $this->contact);
454 }
455
456 if (isModEnabled('mailing') && !empty($this->contact->email) && isset($this->contact->no_email)) {
457 $this->contact->setNoEmail($this->contact->no_email);
458 }
459
460 if ($this->contact->update($id, DolibarrApiAccess::$user, 0, 'update') > 0) {
461 return $this->get($id);
462 } else {
463 throw new RestException(500, $this->contact->error);
464 }
465 }
466
477 public function delete($id)
478 {
479 if (!DolibarrApiAccess::$user->hasRight('societe', 'contact', 'supprimer')) {
480 throw new RestException(403, 'No permission to delete contacts');
481 }
482 $result = $this->contact->fetch($id);
483 if (!$result) {
484 throw new RestException(404, 'Contact not found');
485 }
486
487 if (!DolibarrApi::_checkAccessToResource('contact', $this->contact->id, 'socpeople&societe')) {
488 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
489 }
490 $this->contact->oldcopy = clone $this->contact; // @phan-suppress-current-line PhanTypeMismatchProperty
491
492 if ($this->contact->delete(DolibarrApiAccess::$user) <= 0) {
493 throw new RestException(500, 'Error when delete contact ' . $this->contact->error);
494 }
495
496 return array(
497 'success' => array(
498 'code' => 200,
499 'message' => 'Contact deleted'
500 )
501 );
502 }
503
518 public function createUser($id, $request_data = null)
519 {
520 //if (!DolibarrApiAccess::$user->hasRight('user', 'user', 'creer')) {
521 //throw new RestException(403);
522 //}
523
524 if (!isset($request_data["login"])) {
525 throw new RestException(400, "login field missing");
526 }
527 if (!isset($request_data["password"])) {
528 throw new RestException(400, "password field missing");
529 }
530
531 if (!DolibarrApiAccess::$user->hasRight('societe', 'contact', 'lire')) {
532 throw new RestException(403, 'No permission to read contacts');
533 }
534 if (!DolibarrApiAccess::$user->hasRight('user', 'user', 'creer')) {
535 throw new RestException(403, 'No permission to create user');
536 }
537
538 $contact = new Contact($this->db);
539 $contact->fetch($id);
540 if ($contact->id <= 0) {
541 throw new RestException(404, 'Contact not found');
542 }
543
544 if (!DolibarrApi::_checkAccessToResource('contact', $contact->id, 'socpeople&societe')) {
545 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
546 }
547
548 // Check mandatory fields
549 $login = $request_data["login"];
550 $password = $request_data["password"];
551 $useraccount = new User($this->db);
552 $result = $useraccount->create_from_contact($contact, $login, $password);
553 if ($result <= 0) {
554 throw new RestException(500, "User not created");
555 }
556 // password parameter not used in create_from_contact
557 $useraccount->setPassword($useraccount, $password);
558
559 return $result;
560 }
561
577 public function getCategories($id, $sortfield = "s.rowid", $sortorder = 'ASC', $limit = 0, $page = 0)
578 {
579 if (!DolibarrApiAccess::$user->hasRight('categorie', 'lire')) {
580 throw new RestException(403);
581 }
582
583 if (!DolibarrApi::_checkAccessToResource('contact', $id, 'socpeople&societe')) {
584 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
585 }
586
587 $categories = new Categorie($this->db);
588
589 $result = $categories->getListForItem($id, 'contact', $sortfield, $sortorder, $limit, $page);
590
591 if ($result < 0) {
592 throw new RestException(503, 'Error when retrieve category list : '.$categories->error);
593 }
594
595 return $result;
596 }
597
613 public function addCategory($id, $category_id)
614 {
615 if (!DolibarrApiAccess::$user->hasRight('societe', 'contact', 'creer')) {
616 throw new RestException(403, 'Insufficient rights');
617 }
618
619 $result = $this->contact->fetch($id);
620 if (!$result) {
621 throw new RestException(404, 'Contact not found');
622 }
623 $category = new Categorie($this->db);
624 $result = $category->fetch($category_id);
625 if (!$result) {
626 throw new RestException(404, 'category not found');
627 }
628
629 if (!DolibarrApi::_checkAccessToResource('contact', $this->contact->id, 'socpeople&societe')) {
630 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
631 }
632 if (!DolibarrApi::_checkAccessToResource('category', $category->id)) {
633 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
634 }
635
636 $category->add_type($this->contact, 'contact');
637
638 return $this->_cleanObjectDatas($this->contact);
639 }
640
655 public function deleteCategory($id, $category_id)
656 {
657 if (!DolibarrApiAccess::$user->hasRight('societe', 'contact', 'creer')) {
658 throw new RestException(403, 'Insufficient rights');
659 }
660
661 $result = $this->contact->fetch($id);
662 if (!$result) {
663 throw new RestException(404, 'Contact not found');
664 }
665 $category = new Categorie($this->db);
666 $result = $category->fetch($category_id);
667 if (!$result) {
668 throw new RestException(404, 'category not found');
669 }
670
671 if (!DolibarrApi::_checkAccessToResource('contact', $this->contact->id, 'socpeople&societe')) {
672 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
673 }
674 if (!DolibarrApi::_checkAccessToResource('category', $category->id)) {
675 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
676 }
677
678 $category->del_type($this->contact, 'contact');
679
680 return $this->_cleanObjectDatas($this->contact);
681 }
682
683 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
693 protected function _cleanObjectDatas($object)
694 {
695 // phpcs:enable
696 $object = parent::_cleanObjectDatas($object);
697
698 unset($object->total_ht);
699 unset($object->total_tva);
700 unset($object->total_localtax1);
701 unset($object->total_localtax2);
702 unset($object->total_ttc);
703
704 unset($object->note);
705 unset($object->lines);
706 unset($object->thirdparty);
707
708 return $object;
709 }
710
718 private function _validate($data)
719 {
720 $contact = array();
721 foreach (Contacts::$FIELDS as $field) {
722 if (!isset($data[$field])) {
723 throw new RestException(400, "$field field missing");
724 }
725 $contact[$field] = $data[$field];
726 }
727
728 return $contact;
729 }
730}
$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 to manage categories.
Class to manage contact/addresses.
addCategory($id, $category_id)
Add a category to a contact.
put($id, $request_data=null)
Update a contact.
_validate($data)
Validate fields before create or update object.
deleteCategory($id, $category_id)
Remove the link between a category and a contact.
createUser($id, $request_data=null)
Create a user account object from contact (external user)
post($request_data=null)
Create a contact.
getByEmail($email, $includecount=0, $includeroles=0)
Get a contact by Email.
getCategories($id, $sortfield="s.rowid", $sortorder='ASC', $limit=0, $page=0)
Get categories of a contact.
_cleanObjectDatas($object)
Clean sensible object data @phpstan-template T.
__construct()
Constructor.
index($sortfield="t.rowid", $sortorder='ASC', $limit=100, $page=0, $thirdparty_ids='', $category=0, $sqlfilters='', $includecount=0, $includeroles=0, $properties='', $pagination_data=false)
List contacts.
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 third parties objects (customers, suppliers, prospects...)
Class to manage Dolibarr users.
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.
dol_getIdFromCode($db, $key, $tablename, $fieldkey='code', $fieldid='id', $entityfilter=0, $filters='', $useCache=true)
Return an id or code from a code or id.
forgeSQLFromUniversalSearchCriteria($filter, &$errorstr='', $noand=0, $nopar=0, $noerror=0, $forbiddenfields=array())
forgeSQLFromUniversalSearchCriteria
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.