dolibarr 25.0.0-alpha
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';
26require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
27
28
37class Contacts extends DolibarrApi
38{
43 public static $FIELDS = array(
44 'lastname',
45 );
46
50 public $contact;
51
55 public function __construct()
56 {
57 global $db, $conf;
58 $this->db = $db;
59
60 require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
61 require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
62
63 $this->contact = new Contact($this->db);
64 }
65
80 public function get($id, $includecount = 0, $includeroles = 0)
81 {
82 if (!DolibarrApiAccess::$user->hasRight('societe', 'contact', 'lire')) {
83 throw new RestException(403, 'No permission to read contacts');
84 }
85
86 if ($id === 0) {
87 $result = $this->contact->initAsSpecimen();
88 } else {
89 $result = $this->contact->fetch($id);
90 }
91
92 if (!$result) {
93 throw new RestException(404, 'Contact not found');
94 }
95
96 if (!DolibarrApi::_checkAccessToResource('contact', $this->contact->id, 'socpeople&societe')) {
97 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
98 }
99
100 if ($includecount) {
101 $this->contact->load_ref_elements();
102 }
103
104 if ($includeroles) {
105 $this->contact->fetchRoles();
106 }
107
108 if (isModEnabled('mailing')) {
109 $this->contact->getNoEmail();
110 }
111
112 return $this->_cleanObjectDatas($this->contact);
113 }
114
130 public function getByEmail($email, $includecount = 0, $includeroles = 0)
131 {
132 if (!DolibarrApiAccess::$user->hasRight('societe', 'contact', 'lire')) {
133 throw new RestException(403, 'No permission to read contacts');
134 }
135
136 if (empty($email)) {
137 $result = $this->contact->initAsSpecimen();
138 } else {
139 $result = $this->contact->fetch(0, null, '', $email);
140 }
141
142 if (!$result) {
143 throw new RestException(404, 'Contact not found');
144 }
145
146 if (!DolibarrApi::_checkAccessToResource('contact', $this->contact->id, 'socpeople&societe')) {
147 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
148 }
149
150 if ($includecount) {
151 $this->contact->load_ref_elements();
152 }
153
154 if ($includeroles) {
155 $this->contact->fetchRoles();
156 }
157
158 if (isModEnabled('mailing')) {
159 $this->contact->getNoEmail();
160 }
161
162 return $this->_cleanObjectDatas($this->contact);
163 }
164
187 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)
188 {
189 global $db, $conf;
190
191 $obj_ret = array();
192
193 if (!DolibarrApiAccess::$user->hasRight('societe', 'contact', 'lire')) {
194 throw new RestException(403, 'No permission to read contacts');
195 }
196
197 // case of external user, $thirdparty_ids param is ignored and replaced by user's socid
198 $socids = DolibarrApiAccess::$user->socid ?: $thirdparty_ids;
199
200 // If the internal user must only see his customers, force searching by him
201 $search_sale = 0;
202 if (!DolibarrApiAccess::$user->hasRight('societe', 'client', 'voir') && !$socids) {
203 $search_sale = DolibarrApiAccess::$user->id;
204 }
205
206 $sql = "SELECT t.rowid";
207 $sql .= " FROM ".MAIN_DB_PREFIX."socpeople as t";
208 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."socpeople_extrafields as te ON te.fk_object = t.rowid";
209 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON t.fk_soc = s.rowid";
210 $sql .= ' WHERE t.entity IN ('.getEntity('contact').')';
211 // A private contact is only visible by the user that created it
212 $sql .= " AND (t.priv = 0 OR t.fk_user_creat = ".((int) DolibarrApiAccess::$user->id).")";
213 if ($socids) {
214 $sql .= " AND t.fk_soc IN (".$this->db->sanitize($socids).")";
215 }
216 // Search on sale representative
217 if ($search_sale && $search_sale != '-1') {
218 if ($search_sale == -2) {
219 $sql .= " AND ".getSalesRepresentativeSqlFilter('t.fk_soc', 0, 1);
220 } elseif ($search_sale > 0) {
221 $sql .= " AND ".getSalesRepresentativeSqlFilter('t.fk_soc', (int) $search_sale);
222 }
223 }
224 // Select contacts of given category
225 if ($category > 0) {
226 // Search Contact Categories
227 $searchCategoryContactList = $category ? array($category) : array();
228 // $searchCategoryContactOperator = 0;
229 // Search for tag/category ($searchCategoryContactList is an array of ID)
230 if (!empty($searchCategoryContactList)) {
231 $searchCategoryContactSqlList = array();
232 // $listofcategoryid = '';
233 foreach ($searchCategoryContactList as $searchCategoryContact) {
234 if (intval($searchCategoryContact) == -2) {
235 $searchCategoryContactSqlList[] = "NOT EXISTS (SELECT ck.fk_socpeople FROM ".MAIN_DB_PREFIX."categorie_contact as ck WHERE t.rowid = ck.fk_socpeople)";
236 } elseif (intval($searchCategoryContact) > 0) {
237 // if ($searchCategoryContactOperator == 0) {
238 $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).")";
239 // } else {
240 // $listofcategoryid .= ($listofcategoryid ? ', ' : '') .((int) $searchCategoryContact);
241 // }
242 }
243 }
244 // if ($listofcategoryid) {
245 // $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)."))";
246 // }
247 // if ($searchCategoryContactOperator == 1) {
248 // if (!empty($searchCategoryContactSqlList)) {
249 // $sql .= " AND (".implode(' OR ', $searchCategoryContactSqlList).")";
250 // }
251 // } else {
252 if (!empty($searchCategoryContactSqlList)) {
253 $sql .= " AND (".implode(' AND ', $searchCategoryContactSqlList).")";
254 }
255 // }
256 }
257 }
258
259 // Add sql filters
260 if ($sqlfilters) {
261 $errormessage = '';
262 $sql .= forgeSQLFromUniversalSearchCriteria($sqlfilters, $errormessage);
263 if ($errormessage) {
264 throw new RestException(400, 'Error when validating parameter sqlfilters -> '.$errormessage);
265 }
266 }
267
268 //this query will return total orders with the filters given
269 $sqlTotals = str_replace('SELECT t.rowid', 'SELECT count(t.rowid) as total', $sql);
270
271 $sql .= $this->db->order($sortfield, $sortorder);
272
273 if ($limit) {
274 if ($page < 0) {
275 $page = 0;
276 }
277 $offset = $limit * $page;
278
279 $sql .= $this->db->plimit($limit + 1, $offset);
280 }
281 $result = $this->db->query($sql);
282 if ($result) {
283 $num = $this->db->num_rows($result);
284 $min = min($num, ($limit <= 0 ? $num : $limit));
285 $i = 0;
286 while ($i < $min) {
287 $obj = $this->db->fetch_object($result);
288 $contact_static = new Contact($this->db);
289 if ($contact_static->fetch($obj->rowid)) {
290 $contact_static->fetchRoles();
291 if ($includecount) {
292 $contact_static->load_ref_elements();
293 }
294 if ($includeroles) {
295 $contact_static->fetchRoles();
296 }
297 if (isModEnabled('mailing')) {
298 $contact_static->getNoEmail();
299 }
300
301 $obj_ret[] = $this->_filterObjectProperties($this->_cleanObjectDatas($contact_static), $properties);
302 }
303
304 $i++;
305 }
306 } else {
307 throw new RestException(503, 'Error when retrieve contacts : '.$sql);
308 }
309
310 //if $pagination_data is true the response will contain element data with all values and element pagination with pagination data(total,page,limit)
311 if ($pagination_data) {
312 $totalsResult = $this->db->query($sqlTotals);
313 $total = $this->db->fetch_object($totalsResult)->total;
314
315 $tmp = $obj_ret;
316 $obj_ret = [];
317
318 $obj_ret['data'] = $tmp;
319 $obj_ret['pagination'] = [
320 'total' => (int) $total,
321 'page' => $page, //count starts from 0
322 'page_count' => ceil((int) $total / $limit),
323 'limit' => $limit
324 ];
325 }
326
327 return $obj_ret;
328 }
329
342 public function post($request_data = null)
343 {
344 if (!DolibarrApiAccess::$user->hasRight('societe', 'contact', 'creer')) {
345 throw new RestException(403, 'No permission to create/update contacts');
346 }
347 // Check mandatory fields
348 $result = $this->_validate($request_data);
349
350 // External api user does not know internal country ID
351 if (!isset($request_data['country_id']) && isset($request_data['country_code'])) {
352 $field = strlen($request_data['country_code']) > 2 ? 'code_iso' : 'code';
353 $id = dol_getIdFromCode($this->db, $request_data['country_code'], "c_country", $field, "rowid");
354 if ($id < 0) {
355 throw new RestException(404, 'Country code not found in database: ' . $this->db->lasterror());
356 }
357 $request_data['country_id'] = $id;
358 }
359
360 foreach ($request_data as $field => $value) {
361 if ($field === 'caller') {
362 // 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
363 $this->contact->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
364 continue;
365 }
366 if ($field == 'array_options' && is_array($value)) {
367 $this->contact->fetch_optionals(); // To force the load of the extrafields definition by fetch_name_optionals_label()
368
369 foreach ($value as $index => $val) {
370 $this->contact->array_options[$index] = $this->_checkValExtrafieldsForAPI($index, $val, $this->contact);
371 }
372 continue;
373 }
374 if ($field == 'socid') {
375 $new_socid = (int) $value;
376 $loopthirdpartytmp = new Societe($this->db);
377 $new_thirdparty_result = $loopthirdpartytmp->fetch($new_socid);
378 if ($new_thirdparty_result < 1) {
379 throw new RestException(404, 'Thirdparty with id='.$new_socid.' not found or not allowed');
380 }
381 if (!DolibarrApi::_checkAccessToResource('societe', $new_socid)) {
382 throw new RestException(403, 'Access to socid/thirdparty='.$new_socid.' is not allowed for login '.DolibarrApiAccess::$user->login);
383 }
384 }
385
386 $this->contact->$field = $this->_checkValForAPI($field, $value, $this->contact);
387 }
388 if ($this->contact->create(DolibarrApiAccess::$user) < 0) {
389 throw new RestException(500, "Error creating contact", array_merge(array($this->contact->error), $this->contact->errors));
390 }
391 if (isModEnabled('mailing') && !empty($this->contact->email) && isset($this->contact->no_email)) {
392 $this->contact->setNoEmail($this->contact->no_email);
393 }
394 return $this->contact->id;
395 }
396
412 public function put($id, $request_data = null)
413 {
414 if (!DolibarrApiAccess::$user->hasRight('societe', 'contact', 'creer')) {
415 throw new RestException(403, 'No permission to create/update contacts');
416 }
417
418 $result = $this->contact->fetch($id);
419 if (!$result) {
420 throw new RestException(404, 'Contact not found');
421 }
422
423 if (!DolibarrApi::_checkAccessToResource('contact', $this->contact->id, 'socpeople&societe')) {
424 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
425 }
426
427 foreach ($request_data as $field => $value) {
428 if ($field == 'id') {
429 continue;
430 }
431 if ($field === 'caller') {
432 // 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
433 $this->contact->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
434 continue;
435 }
436 if ($field == 'array_options' && is_array($value)) {
437 foreach ($value as $index => $val) {
438 $this->contact->array_options[$index] = $this->_checkValExtrafieldsForAPI($index, $val, $this->contact);
439 }
440 continue;
441 }
442 if ($field == 'socid') {
443 $new_socid = (int) $value;
444 $loopthirdpartytmp = new Societe($this->db);
445 $new_thirdparty_result = $loopthirdpartytmp->fetch($new_socid);
446 if ($new_thirdparty_result < 1) {
447 throw new RestException(404, 'Thirdparty with id='.$new_socid.' not found or not allowed');
448 }
449 if (!DolibarrApi::_checkAccessToResource('societe', $new_socid)) {
450 throw new RestException(403, 'Access to socid/thirdparty='.$new_socid.' is not allowed for login '.DolibarrApiAccess::$user->login);
451 }
452 }
453
454 $this->contact->$field = $this->_checkValForAPI($field, $value, $this->contact);
455 }
456
457 if (isModEnabled('mailing') && !empty($this->contact->email) && isset($this->contact->no_email)) {
458 $this->contact->setNoEmail($this->contact->no_email);
459 }
460
461 if ($this->contact->update($id, DolibarrApiAccess::$user, 0, 'update') > 0) {
462 return $this->get($id);
463 } else {
464 throw new RestException(500, $this->contact->errorsToString());
465 }
466 }
467
478 public function delete($id)
479 {
480 if (!DolibarrApiAccess::$user->hasRight('societe', 'contact', 'supprimer')) {
481 throw new RestException(403, 'No permission to delete contacts');
482 }
483 $result = $this->contact->fetch($id);
484 if (!$result) {
485 throw new RestException(404, 'Contact not found');
486 }
487
488 if (!DolibarrApi::_checkAccessToResource('contact', $this->contact->id, 'socpeople&societe')) {
489 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
490 }
491 $this->contact->oldcopy = clone $this->contact; // @phan-suppress-current-line PhanTypeMismatchProperty
492
493 if ($this->contact->delete(DolibarrApiAccess::$user) <= 0) {
494 throw new RestException(500, 'Error when delete contact ' . $this->contact->errorsToString());
495 }
496
497 return array(
498 'success' => array(
499 'code' => 200,
500 'message' => 'Contact deleted'
501 )
502 );
503 }
504
519 public function createUser($id, $request_data = null)
520 {
521 //if (!DolibarrApiAccess::$user->hasRight('user', 'user', 'creer')) {
522 //throw new RestException(403);
523 //}
524
525 if (!isset($request_data["login"])) {
526 throw new RestException(400, "login field missing");
527 }
528 if (!isset($request_data["password"])) {
529 throw new RestException(400, "password field missing");
530 }
531
532 if (!DolibarrApiAccess::$user->hasRight('societe', 'contact', 'lire')) {
533 throw new RestException(403, 'No permission to read contacts');
534 }
535 if (!DolibarrApiAccess::$user->hasRight('user', 'user', 'creer')) {
536 throw new RestException(403, 'No permission to create user');
537 }
538
539 $contact = new Contact($this->db);
540 $contact->fetch($id);
541 if ($contact->id <= 0) {
542 throw new RestException(404, 'Contact not found');
543 }
544
545 if (!DolibarrApi::_checkAccessToResource('contact', $contact->id, 'socpeople&societe')) {
546 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
547 }
548
549 // Check mandatory fields
550 $login = $request_data["login"];
551 $password = $request_data["password"];
552 $useraccount = new User($this->db);
553 $result = $useraccount->create_from_contact($contact, $login, $password);
554 if ($result <= 0) {
555 throw new RestException(500, "User not created");
556 }
557 // password parameter not used in create_from_contact
558 $useraccount->setPassword($useraccount, $password);
559
560 return $result;
561 }
562
578 public function getCategories($id, $sortfield = "s.rowid", $sortorder = 'ASC', $limit = 0, $page = 0)
579 {
580 if (!DolibarrApiAccess::$user->hasRight('categorie', 'lire')) {
581 throw new RestException(403);
582 }
583
584 if (!DolibarrApi::_checkAccessToResource('contact', $id, 'socpeople&societe')) {
585 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
586 }
587
588 $categories = new Categorie($this->db);
589
590 $result = $categories->getListForItem($id, 'contact', $sortfield, $sortorder, $limit, $page);
591
592 if ($result < 0) {
593 throw new RestException(503, 'Error when retrieve category list : '.$categories->errorsToString());
594 }
595
596 return $result;
597 }
598
614 public function addCategory($id, $category_id)
615 {
616 if (!DolibarrApiAccess::$user->hasRight('societe', 'contact', 'creer')) {
617 throw new RestException(403, 'Insufficient rights');
618 }
619
620 $result = $this->contact->fetch($id);
621 if (!$result) {
622 throw new RestException(404, 'Contact not found');
623 }
624 $category = new Categorie($this->db);
625 $result = $category->fetch($category_id);
626 if (!$result) {
627 throw new RestException(404, 'category not found');
628 }
629
630 if (!DolibarrApi::_checkAccessToResource('contact', $this->contact->id, 'socpeople&societe')) {
631 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
632 }
633 if (!DolibarrApi::_checkAccessToResource('category', $category->id)) {
634 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
635 }
636
637 $category->add_type($this->contact, 'contact');
638
639 return $this->_cleanObjectDatas($this->contact);
640 }
641
656 public function deleteCategory($id, $category_id)
657 {
658 if (!DolibarrApiAccess::$user->hasRight('societe', 'contact', 'creer')) {
659 throw new RestException(403, 'Insufficient rights');
660 }
661
662 $result = $this->contact->fetch($id);
663 if (!$result) {
664 throw new RestException(404, 'Contact not found');
665 }
666 $category = new Categorie($this->db);
667 $result = $category->fetch($category_id);
668 if (!$result) {
669 throw new RestException(404, 'category not found');
670 }
671
672 if (!DolibarrApi::_checkAccessToResource('contact', $this->contact->id, 'socpeople&societe')) {
673 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
674 }
675 if (!DolibarrApi::_checkAccessToResource('category', $category->id)) {
676 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
677 }
678
679 $category->del_type($this->contact, 'contact');
680
681 return $this->_cleanObjectDatas($this->contact);
682 }
683
684 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
694 protected function _cleanObjectDatas($object)
695 {
696 // phpcs:enable
697 $object = parent::_cleanObjectDatas($object);
698
699 unset($object->total_ht);
700 unset($object->total_tva);
701 unset($object->total_localtax1);
702 unset($object->total_localtax2);
703 unset($object->total_ttc);
704
705 unset($object->note);
706 unset($object->lines);
707 unset($object->thirdparty);
708
709 return $object;
710 }
711
719 private function _validate($data)
720 {
721 $contact = array();
722 foreach (Contacts::$FIELDS as $field) {
723 if (!isset($data[$field])) {
724 throw new RestException(400, "$field field missing");
725 }
726 $contact[$field] = $data[$field];
727 }
728
729 return $contact;
730 }
731}
$id
Support class for third parties, contacts, members, users or resources.
Definition account.php:47
if(! $sortfield) if(! $sortorder) $object
Definition account.php:100
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $conf
The main.inc.php has been included so the following variable are now defined:
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.
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.