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 if ($socids) {
212 $sql .= " AND t.fk_soc IN (".$this->db->sanitize($socids).")";
213 }
214 // Search on sale representative
215 if ($search_sale && $search_sale != '-1') {
216 if ($search_sale == -2) {
217 $sql .= " AND ".getSalesRepresentativeSqlFilter('t.fk_soc', 0, 1);
218 } elseif ($search_sale > 0) {
219 $sql .= " AND ".getSalesRepresentativeSqlFilter('t.fk_soc', (int) $search_sale);
220 }
221 }
222 // Select contacts of given category
223 if ($category > 0) {
224 // Search Contact Categories
225 $searchCategoryContactList = $category ? array($category) : array();
226 // $searchCategoryContactOperator = 0;
227 // Search for tag/category ($searchCategoryContactList is an array of ID)
228 if (!empty($searchCategoryContactList)) {
229 $searchCategoryContactSqlList = array();
230 // $listofcategoryid = '';
231 foreach ($searchCategoryContactList as $searchCategoryContact) {
232 if (intval($searchCategoryContact) == -2) {
233 $searchCategoryContactSqlList[] = "NOT EXISTS (SELECT ck.fk_socpeople FROM ".MAIN_DB_PREFIX."categorie_contact as ck WHERE t.rowid = ck.fk_socpeople)";
234 } elseif (intval($searchCategoryContact) > 0) {
235 // if ($searchCategoryContactOperator == 0) {
236 $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).")";
237 // } else {
238 // $listofcategoryid .= ($listofcategoryid ? ', ' : '') .((int) $searchCategoryContact);
239 // }
240 }
241 }
242 // if ($listofcategoryid) {
243 // $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)."))";
244 // }
245 // if ($searchCategoryContactOperator == 1) {
246 // if (!empty($searchCategoryContactSqlList)) {
247 // $sql .= " AND (".implode(' OR ', $searchCategoryContactSqlList).")";
248 // }
249 // } else {
250 if (!empty($searchCategoryContactSqlList)) {
251 $sql .= " AND (".implode(' AND ', $searchCategoryContactSqlList).")";
252 }
253 // }
254 }
255 }
256
257 // Add sql filters
258 if ($sqlfilters) {
259 $errormessage = '';
260 $sql .= forgeSQLFromUniversalSearchCriteria($sqlfilters, $errormessage);
261 if ($errormessage) {
262 throw new RestException(400, 'Error when validating parameter sqlfilters -> '.$errormessage);
263 }
264 }
265
266 //this query will return total orders with the filters given
267 $sqlTotals = str_replace('SELECT t.rowid', 'SELECT count(t.rowid) as total', $sql);
268
269 $sql .= $this->db->order($sortfield, $sortorder);
270
271 if ($limit) {
272 if ($page < 0) {
273 $page = 0;
274 }
275 $offset = $limit * $page;
276
277 $sql .= $this->db->plimit($limit + 1, $offset);
278 }
279 $result = $this->db->query($sql);
280 if ($result) {
281 $num = $this->db->num_rows($result);
282 $min = min($num, ($limit <= 0 ? $num : $limit));
283 $i = 0;
284 while ($i < $min) {
285 $obj = $this->db->fetch_object($result);
286 $contact_static = new Contact($this->db);
287 if ($contact_static->fetch($obj->rowid)) {
288 $contact_static->fetchRoles();
289 if ($includecount) {
290 $contact_static->load_ref_elements();
291 }
292 if ($includeroles) {
293 $contact_static->fetchRoles();
294 }
295 if (isModEnabled('mailing')) {
296 $contact_static->getNoEmail();
297 }
298
299 $obj_ret[] = $this->_filterObjectProperties($this->_cleanObjectDatas($contact_static), $properties);
300 }
301
302 $i++;
303 }
304 } else {
305 throw new RestException(503, 'Error when retrieve contacts : '.$sql);
306 }
307
308 //if $pagination_data is true the response will contain element data with all values and element pagination with pagination data(total,page,limit)
309 if ($pagination_data) {
310 $totalsResult = $this->db->query($sqlTotals);
311 $total = $this->db->fetch_object($totalsResult)->total;
312
313 $tmp = $obj_ret;
314 $obj_ret = [];
315
316 $obj_ret['data'] = $tmp;
317 $obj_ret['pagination'] = [
318 'total' => (int) $total,
319 'page' => $page, //count starts from 0
320 'page_count' => ceil((int) $total / $limit),
321 'limit' => $limit
322 ];
323 }
324
325 return $obj_ret;
326 }
327
340 public function post($request_data = null)
341 {
342 if (!DolibarrApiAccess::$user->hasRight('societe', 'contact', 'creer')) {
343 throw new RestException(403, 'No permission to create/update contacts');
344 }
345 // Check mandatory fields
346 $result = $this->_validate($request_data);
347
348 // External api user does not know internal country ID
349 if (!isset($request_data['country_id']) && isset($request_data['country_code'])) {
350 $field = strlen($request_data['country_code']) > 2 ? 'code_iso' : 'code';
351 $id = dol_getIdFromCode($this->db, $request_data['country_code'], "c_country", $field, "rowid");
352 if ($id < 0) {
353 throw new RestException(404, 'Country code not found in database: ' . $this->db->error);
354 }
355 $request_data['country_id'] = $id;
356 }
357
358 foreach ($request_data as $field => $value) {
359 if ($field === 'caller') {
360 // 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
361 $this->contact->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
362 continue;
363 }
364 if ($field == 'array_options' && is_array($value)) {
365 $this->contact->fetch_optionals(); // To force the load of the extrafields definition by fetch_name_optionals_label()
366
367 foreach ($value as $index => $val) {
368 $this->contact->array_options[$index] = $this->_checkValExtrafieldsForAPI($index, $val, $this->contact);
369 }
370 continue;
371 }
372 if ($field == 'socid') {
373 $new_socid = (int) $value;
374 $loopthirdpartytmp = new Societe($this->db);
375 $new_thirdparty_result = $loopthirdpartytmp->fetch($new_socid);
376 if ($new_thirdparty_result < 1) {
377 throw new RestException(404, 'Thirdparty with id='.$new_socid.' not found or not allowed');
378 }
379 if (!DolibarrApi::_checkAccessToResource('societe', $new_socid)) {
380 throw new RestException(403, 'Access to socid/thirdparty='.$new_socid.' is not allowed for login '.DolibarrApiAccess::$user->login);
381 }
382 }
383
384 $this->contact->$field = $this->_checkValForAPI($field, $value, $this->contact);
385 }
386 if ($this->contact->create(DolibarrApiAccess::$user) < 0) {
387 throw new RestException(500, "Error creating contact", array_merge(array($this->contact->error), $this->contact->errors));
388 }
389 if (isModEnabled('mailing') && !empty($this->contact->email) && isset($this->contact->no_email)) {
390 $this->contact->setNoEmail($this->contact->no_email);
391 }
392 return $this->contact->id;
393 }
394
410 public function put($id, $request_data = null)
411 {
412 if (!DolibarrApiAccess::$user->hasRight('societe', 'contact', 'creer')) {
413 throw new RestException(403, 'No permission to create/update contacts');
414 }
415
416 $result = $this->contact->fetch($id);
417 if (!$result) {
418 throw new RestException(404, 'Contact not found');
419 }
420
421 if (!DolibarrApi::_checkAccessToResource('contact', $this->contact->id, 'socpeople&societe')) {
422 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
423 }
424
425 foreach ($request_data as $field => $value) {
426 if ($field == 'id') {
427 continue;
428 }
429 if ($field === 'caller') {
430 // 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
431 $this->contact->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
432 continue;
433 }
434 if ($field == 'array_options' && is_array($value)) {
435 foreach ($value as $index => $val) {
436 $this->contact->array_options[$index] = $this->_checkValExtrafieldsForAPI($index, $val, $this->contact);
437 }
438 continue;
439 }
440 if ($field == 'socid') {
441 $new_socid = (int) $value;
442 $loopthirdpartytmp = new Societe($this->db);
443 $new_thirdparty_result = $loopthirdpartytmp->fetch($new_socid);
444 if ($new_thirdparty_result < 1) {
445 throw new RestException(404, 'Thirdparty with id='.$new_socid.' not found or not allowed');
446 }
447 if (!DolibarrApi::_checkAccessToResource('societe', $new_socid)) {
448 throw new RestException(403, 'Access to socid/thirdparty='.$new_socid.' is not allowed for login '.DolibarrApiAccess::$user->login);
449 }
450 }
451
452 $this->contact->$field = $this->_checkValForAPI($field, $value, $this->contact);
453 }
454
455 if (isModEnabled('mailing') && !empty($this->contact->email) && isset($this->contact->no_email)) {
456 $this->contact->setNoEmail($this->contact->no_email);
457 }
458
459 if ($this->contact->update($id, DolibarrApiAccess::$user, 0, 'update') > 0) {
460 return $this->get($id);
461 } else {
462 throw new RestException(500, $this->contact->error);
463 }
464 }
465
476 public function delete($id)
477 {
478 if (!DolibarrApiAccess::$user->hasRight('societe', 'contact', 'supprimer')) {
479 throw new RestException(403, 'No permission to delete contacts');
480 }
481 $result = $this->contact->fetch($id);
482 if (!$result) {
483 throw new RestException(404, 'Contact not found');
484 }
485
486 if (!DolibarrApi::_checkAccessToResource('contact', $this->contact->id, 'socpeople&societe')) {
487 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
488 }
489 $this->contact->oldcopy = clone $this->contact; // @phan-suppress-current-line PhanTypeMismatchProperty
490
491 if ($this->contact->delete(DolibarrApiAccess::$user) <= 0) {
492 throw new RestException(500, 'Error when delete contact ' . $this->contact->error);
493 }
494
495 return array(
496 'success' => array(
497 'code' => 200,
498 'message' => 'Contact deleted'
499 )
500 );
501 }
502
517 public function createUser($id, $request_data = null)
518 {
519 //if (!DolibarrApiAccess::$user->hasRight('user', 'user', 'creer')) {
520 //throw new RestException(403);
521 //}
522
523 if (!isset($request_data["login"])) {
524 throw new RestException(400, "login field missing");
525 }
526 if (!isset($request_data["password"])) {
527 throw new RestException(400, "password field missing");
528 }
529
530 if (!DolibarrApiAccess::$user->hasRight('societe', 'contact', 'lire')) {
531 throw new RestException(403, 'No permission to read contacts');
532 }
533 if (!DolibarrApiAccess::$user->hasRight('user', 'user', 'creer')) {
534 throw new RestException(403, 'No permission to create user');
535 }
536
537 $contact = new Contact($this->db);
538 $contact->fetch($id);
539 if ($contact->id <= 0) {
540 throw new RestException(404, 'Contact not found');
541 }
542
543 if (!DolibarrApi::_checkAccessToResource('contact', $contact->id, 'socpeople&societe')) {
544 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
545 }
546
547 // Check mandatory fields
548 $login = $request_data["login"];
549 $password = $request_data["password"];
550 $useraccount = new User($this->db);
551 $result = $useraccount->create_from_contact($contact, $login, $password);
552 if ($result <= 0) {
553 throw new RestException(500, "User not created");
554 }
555 // password parameter not used in create_from_contact
556 $useraccount->setPassword($useraccount, $password);
557
558 return $result;
559 }
560
576 public function getCategories($id, $sortfield = "s.rowid", $sortorder = 'ASC', $limit = 0, $page = 0)
577 {
578 if (!DolibarrApiAccess::$user->hasRight('categorie', 'lire')) {
579 throw new RestException(403);
580 }
581
582 $categories = new Categorie($this->db);
583
584 $result = $categories->getListForItem($id, 'contact', $sortfield, $sortorder, $limit, $page);
585
586 if ($result < 0) {
587 throw new RestException(503, 'Error when retrieve category list : '.$categories->error);
588 }
589
590 return $result;
591 }
592
608 public function addCategory($id, $category_id)
609 {
610 if (!DolibarrApiAccess::$user->hasRight('societe', 'contact', 'creer')) {
611 throw new RestException(403, 'Insufficient rights');
612 }
613
614 $result = $this->contact->fetch($id);
615 if (!$result) {
616 throw new RestException(404, 'Contact not found');
617 }
618 $category = new Categorie($this->db);
619 $result = $category->fetch($category_id);
620 if (!$result) {
621 throw new RestException(404, 'category not found');
622 }
623
624 if (!DolibarrApi::_checkAccessToResource('contact', $this->contact->id)) {
625 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
626 }
627 if (!DolibarrApi::_checkAccessToResource('category', $category->id)) {
628 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
629 }
630
631 $category->add_type($this->contact, 'contact');
632
633 return $this->_cleanObjectDatas($this->contact);
634 }
635
650 public function deleteCategory($id, $category_id)
651 {
652 if (!DolibarrApiAccess::$user->hasRight('societe', 'contact', 'creer')) {
653 throw new RestException(403, 'Insufficient rights');
654 }
655
656 $result = $this->contact->fetch($id);
657 if (!$result) {
658 throw new RestException(404, 'Contact not found');
659 }
660 $category = new Categorie($this->db);
661 $result = $category->fetch($category_id);
662 if (!$result) {
663 throw new RestException(404, 'category not found');
664 }
665
666 if (!DolibarrApi::_checkAccessToResource('contact', $this->contact->id)) {
667 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
668 }
669 if (!DolibarrApi::_checkAccessToResource('category', $category->id)) {
670 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
671 }
672
673 $category->del_type($this->contact, 'contact');
674
675 return $this->_cleanObjectDatas($this->contact);
676 }
677
678 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
688 protected function _cleanObjectDatas($object)
689 {
690 // phpcs:enable
691 $object = parent::_cleanObjectDatas($object);
692
693 unset($object->total_ht);
694 unset($object->total_tva);
695 unset($object->total_localtax1);
696 unset($object->total_localtax2);
697 unset($object->total_ttc);
698
699 unset($object->note);
700 unset($object->lines);
701 unset($object->thirdparty);
702
703 return $object;
704 }
705
713 private function _validate($data)
714 {
715 $contact = array();
716 foreach (Contacts::$FIELDS as $field) {
717 if (!isset($data[$field])) {
718 throw new RestException(400, "$field field missing");
719 }
720 $contact[$field] = $data[$field];
721 }
722
723 return $contact;
724 }
725}
$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.