dolibarr 22.0.5
api_contacts.class.php
1<?php
2/* Copyright (C) 2015 Jean-François Ferry <jfefe@aternatik.fr>
3 * Copyright (C) 2019-2024 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';
25
26
35class Contacts extends DolibarrApi
36{
41 public static $FIELDS = array(
42 'lastname',
43 );
44
48 public $contact;
49
53 public function __construct()
54 {
55 global $db, $conf;
56 $this->db = $db;
57
58 require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
59 require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
60
61 $this->contact = new Contact($this->db);
62 }
63
78 public function get($id, $includecount = 0, $includeroles = 0)
79 {
80 if (!DolibarrApiAccess::$user->hasRight('societe', 'contact', 'lire')) {
81 throw new RestException(403, 'No permission to read contacts');
82 }
83
84 if ($id === 0) {
85 $result = $this->contact->initAsSpecimen();
86 } else {
87 $result = $this->contact->fetch($id);
88 }
89
90 if (!$result) {
91 throw new RestException(404, 'Contact not found');
92 }
93
94 if (!DolibarrApi::_checkAccessToResource('contact', $this->contact->id, 'socpeople&societe')) {
95 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
96 }
97
98 if ($includecount) {
99 $this->contact->load_ref_elements();
100 }
101
102 if ($includeroles) {
103 $this->contact->fetchRoles();
104 }
105
106 if (isModEnabled('mailing')) {
107 $this->contact->getNoEmail();
108 }
109
110 return $this->_cleanObjectDatas($this->contact);
111 }
112
128 public function getByEmail($email, $includecount = 0, $includeroles = 0)
129 {
130 if (!DolibarrApiAccess::$user->hasRight('societe', 'contact', 'lire')) {
131 throw new RestException(403, 'No permission to read contacts');
132 }
133
134 if (empty($email)) {
135 $result = $this->contact->initAsSpecimen();
136 } else {
137 $result = $this->contact->fetch(0, null, '', $email);
138 }
139
140 if (!$result) {
141 throw new RestException(404, 'Contact not found');
142 }
143
144 if (!DolibarrApi::_checkAccessToResource('contact', $this->contact->id, 'socpeople&societe')) {
145 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
146 }
147
148 if ($includecount) {
149 $this->contact->load_ref_elements();
150 }
151
152 if ($includeroles) {
153 $this->contact->fetchRoles();
154 }
155
156 if (isModEnabled('mailing')) {
157 $this->contact->getNoEmail();
158 }
159
160 return $this->_cleanObjectDatas($this->contact);
161 }
162
185 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)
186 {
187 global $db, $conf;
188
189 $obj_ret = array();
190
191 if (!DolibarrApiAccess::$user->hasRight('societe', 'contact', 'lire')) {
192 throw new RestException(403, 'No permission to read contacts');
193 }
194
195 // case of external user, $thirdparty_ids param is ignored and replaced by user's socid
196 $socids = DolibarrApiAccess::$user->socid ?: $thirdparty_ids;
197
198 // If the internal user must only see his customers, force searching by him
199 $search_sale = 0;
200 if (!DolibarrApiAccess::$user->hasRight('societe', 'client', 'voir') && !$socids) {
201 $search_sale = DolibarrApiAccess::$user->id;
202 }
203
204 $sql = "SELECT t.rowid";
205 $sql .= " FROM ".MAIN_DB_PREFIX."socpeople as t";
206 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."socpeople_extrafields as te ON te.fk_object = t.rowid";
207 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON t.fk_soc = s.rowid";
208 $sql .= ' WHERE t.entity IN ('.getEntity('contact').')';
209 if ($socids) {
210 $sql .= " AND t.fk_soc IN (".$this->db->sanitize($socids).")";
211 }
212 // Search on sale representative
213 if ($search_sale && $search_sale != '-1') {
214 if ($search_sale == -2) {
215 $sql .= " AND NOT EXISTS (SELECT sc.fk_soc FROM ".MAIN_DB_PREFIX."societe_commerciaux as sc WHERE sc.fk_soc = t.fk_soc)";
216 } elseif ($search_sale > 0) {
217 $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).")";
218 }
219 }
220 // Select contacts of given category
221 if ($category > 0) {
222 // Search Contact Categories
223 $searchCategoryContactList = $category ? array($category) : array();
224 // $searchCategoryContactOperator = 0;
225 // Search for tag/category ($searchCategoryContactList is an array of ID)
226 if (!empty($searchCategoryContactList)) {
227 $searchCategoryContactSqlList = array();
228 // $listofcategoryid = '';
229 foreach ($searchCategoryContactList as $searchCategoryContact) {
230 if (intval($searchCategoryContact) == -2) {
231 $searchCategoryContactSqlList[] = "NOT EXISTS (SELECT ck.fk_socpeople FROM ".MAIN_DB_PREFIX."categorie_contact as ck WHERE t.rowid = ck.fk_socpeople)";
232 } elseif (intval($searchCategoryContact) > 0) {
233 // if ($searchCategoryContactOperator == 0) {
234 $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).")";
235 // } else {
236 // $listofcategoryid .= ($listofcategoryid ? ', ' : '') .((int) $searchCategoryContact);
237 // }
238 }
239 }
240 // if ($listofcategoryid) {
241 // $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)."))";
242 // }
243 // if ($searchCategoryContactOperator == 1) {
244 // if (!empty($searchCategoryContactSqlList)) {
245 // $sql .= " AND (".implode(' OR ', $searchCategoryContactSqlList).")";
246 // }
247 // } else {
248 if (!empty($searchCategoryContactSqlList)) {
249 $sql .= " AND (".implode(' AND ', $searchCategoryContactSqlList).")";
250 }
251 // }
252 }
253 }
254
255 // Add sql filters
256 if ($sqlfilters) {
257 $errormessage = '';
258 $sql .= forgeSQLFromUniversalSearchCriteria($sqlfilters, $errormessage);
259 if ($errormessage) {
260 throw new RestException(400, 'Error when validating parameter sqlfilters -> '.$errormessage);
261 }
262 }
263
264 //this query will return total orders with the filters given
265 $sqlTotals = str_replace('SELECT t.rowid', 'SELECT count(t.rowid) as total', $sql);
266
267 $sql .= $this->db->order($sortfield, $sortorder);
268
269 if ($limit) {
270 if ($page < 0) {
271 $page = 0;
272 }
273 $offset = $limit * $page;
274
275 $sql .= $this->db->plimit($limit + 1, $offset);
276 }
277 $result = $this->db->query($sql);
278 if ($result) {
279 $num = $this->db->num_rows($result);
280 $min = min($num, ($limit <= 0 ? $num : $limit));
281 $i = 0;
282 while ($i < $min) {
283 $obj = $this->db->fetch_object($result);
284 $contact_static = new Contact($this->db);
285 if ($contact_static->fetch($obj->rowid)) {
286 $contact_static->fetchRoles();
287 if ($includecount) {
288 $contact_static->load_ref_elements();
289 }
290 if ($includeroles) {
291 $contact_static->fetchRoles();
292 }
293 if (isModEnabled('mailing')) {
294 $contact_static->getNoEmail();
295 }
296
297 $obj_ret[] = $this->_filterObjectProperties($this->_cleanObjectDatas($contact_static), $properties);
298 }
299
300 $i++;
301 }
302 } else {
303 throw new RestException(503, 'Error when retrieve contacts : '.$sql);
304 }
305
306 //if $pagination_data is true the response will contain element data with all values and element pagination with pagination data(total,page,limit)
307 if ($pagination_data) {
308 $totalsResult = $this->db->query($sqlTotals);
309 $total = $this->db->fetch_object($totalsResult)->total;
310
311 $tmp = $obj_ret;
312 $obj_ret = [];
313
314 $obj_ret['data'] = $tmp;
315 $obj_ret['pagination'] = [
316 'total' => (int) $total,
317 'page' => $page, //count starts from 0
318 'page_count' => ceil((int) $total / $limit),
319 'limit' => $limit
320 ];
321 }
322
323 return $obj_ret;
324 }
325
338 public function post($request_data = null)
339 {
340 if (!DolibarrApiAccess::$user->hasRight('societe', 'contact', 'creer')) {
341 throw new RestException(403, 'No permission to create/update contacts');
342 }
343 // Check mandatory fields
344 $result = $this->_validate($request_data);
345
346 foreach ($request_data as $field => $value) {
347 if ($field === 'caller') {
348 // 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
349 $this->contact->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
350 continue;
351 }
352 if ($field == 'array_options' && is_array($value)) {
353 foreach ($value as $index => $val) {
354 $this->contact->array_options[$index] = $this->_checkValForAPI('extrafields', $val, $this->contact);
355 }
356 continue;
357 }
358
359 $this->contact->$field = $this->_checkValForAPI($field, $value, $this->contact);
360 }
361 if ($this->contact->create(DolibarrApiAccess::$user) < 0) {
362 throw new RestException(500, "Error creating contact", array_merge(array($this->contact->error), $this->contact->errors));
363 }
364 if (isModEnabled('mailing') && !empty($this->contact->email) && isset($this->contact->no_email)) {
365 $this->contact->setNoEmail($this->contact->no_email);
366 }
367 return $this->contact->id;
368 }
369
385 public function put($id, $request_data = null)
386 {
387 if (!DolibarrApiAccess::$user->hasRight('societe', 'contact', 'creer')) {
388 throw new RestException(403, 'No permission to create/update contacts');
389 }
390
391 $result = $this->contact->fetch($id);
392 if (!$result) {
393 throw new RestException(404, 'Contact not found');
394 }
395
396 if (!DolibarrApi::_checkAccessToResource('contact', $this->contact->id, 'socpeople&societe')) {
397 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
398 }
399
400 foreach ($request_data as $field => $value) {
401 if ($field == 'id') {
402 continue;
403 }
404 if ($field === 'caller') {
405 // 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
406 $this->contact->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
407 continue;
408 }
409 if ($field == 'array_options' && is_array($value)) {
410 foreach ($value as $index => $val) {
411 $this->contact->array_options[$index] = $this->_checkValForAPI($field, $val, $this->contact);
412 }
413 continue;
414 }
415
416 $this->contact->$field = $this->_checkValForAPI($field, $value, $this->contact);
417 }
418
419 if (isModEnabled('mailing') && !empty($this->contact->email) && isset($this->contact->no_email)) {
420 $this->contact->setNoEmail($this->contact->no_email);
421 }
422
423 if ($this->contact->update($id, DolibarrApiAccess::$user, 0, 'update') > 0) {
424 return $this->get($id);
425 } else {
426 throw new RestException(500, $this->contact->error);
427 }
428 }
429
440 public function delete($id)
441 {
442 if (!DolibarrApiAccess::$user->hasRight('societe', 'contact', 'supprimer')) {
443 throw new RestException(403, 'No permission to delete contacts');
444 }
445 $result = $this->contact->fetch($id);
446 if (!$result) {
447 throw new RestException(404, 'Contact not found');
448 }
449
450 if (!DolibarrApi::_checkAccessToResource('contact', $this->contact->id, 'socpeople&societe')) {
451 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
452 }
453 $this->contact->oldcopy = clone $this->contact; // @phan-suppress-current-line PhanTypeMismatchProperty
454
455 if ($this->contact->delete(DolibarrApiAccess::$user) <= 0) {
456 throw new RestException(500, 'Error when delete contact ' . $this->contact->error);
457 }
458
459 return array(
460 'success' => array(
461 'code' => 200,
462 'message' => 'Contact deleted'
463 )
464 );
465 }
466
481 public function createUser($id, $request_data = null)
482 {
483 //if (!DolibarrApiAccess::$user->hasRight('user', 'user', 'creer')) {
484 //throw new RestException(403);
485 //}
486
487 if (!isset($request_data["login"])) {
488 throw new RestException(400, "login field missing");
489 }
490 if (!isset($request_data["password"])) {
491 throw new RestException(400, "password field missing");
492 }
493
494 if (!DolibarrApiAccess::$user->hasRight('societe', 'contact', 'lire')) {
495 throw new RestException(403, 'No permission to read contacts');
496 }
497 if (!DolibarrApiAccess::$user->hasRight('user', 'user', 'creer')) {
498 throw new RestException(403, 'No permission to create user');
499 }
500
501 $contact = new Contact($this->db);
502 $contact->fetch($id);
503 if ($contact->id <= 0) {
504 throw new RestException(404, 'Contact not found');
505 }
506
507 if (!DolibarrApi::_checkAccessToResource('contact', $contact->id, 'socpeople&societe')) {
508 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
509 }
510
511 // Check mandatory fields
512 $login = $request_data["login"];
513 $password = $request_data["password"];
514 $useraccount = new User($this->db);
515 $result = $useraccount->create_from_contact($contact, $login, $password);
516 if ($result <= 0) {
517 throw new RestException(500, "User not created");
518 }
519 // password parameter not used in create_from_contact
520 $useraccount->setPassword($useraccount, $password);
521
522 return $result;
523 }
524
540 public function getCategories($id, $sortfield = "s.rowid", $sortorder = 'ASC', $limit = 0, $page = 0)
541 {
542 if (!DolibarrApiAccess::$user->hasRight('categorie', 'lire')) {
543 throw new RestException(403);
544 }
545
546 $categories = new Categorie($this->db);
547
548 $result = $categories->getListForItem($id, 'contact', $sortfield, $sortorder, $limit, $page);
549
550 if ($result < 0) {
551 throw new RestException(503, 'Error when retrieve category list : '.$categories->error);
552 }
553
554 return $result;
555 }
556
572 public function addCategory($id, $category_id)
573 {
574 if (!DolibarrApiAccess::$user->hasRight('societe', 'contact', 'creer')) {
575 throw new RestException(403, 'Insufficient rights');
576 }
577
578 $result = $this->contact->fetch($id);
579 if (!$result) {
580 throw new RestException(404, 'Contact not found');
581 }
582 $category = new Categorie($this->db);
583 $result = $category->fetch($category_id);
584 if (!$result) {
585 throw new RestException(404, 'category not found');
586 }
587
588 if (!DolibarrApi::_checkAccessToResource('contact', $this->contact->id)) {
589 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
590 }
591 if (!DolibarrApi::_checkAccessToResource('category', $category->id)) {
592 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
593 }
594
595 $category->add_type($this->contact, 'contact');
596
597 return $this->_cleanObjectDatas($this->contact);
598 }
599
614 public function deleteCategory($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)) {
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->del_type($this->contact, 'contact');
638
639 return $this->_cleanObjectDatas($this->contact);
640 }
641
642 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
649 protected function _cleanObjectDatas($object)
650 {
651 // phpcs:enable
652 $object = parent::_cleanObjectDatas($object);
653
654 unset($object->total_ht);
655 unset($object->total_tva);
656 unset($object->total_localtax1);
657 unset($object->total_localtax2);
658 unset($object->total_ttc);
659
660 unset($object->note);
661 unset($object->lines);
662 unset($object->thirdparty);
663
664 return $object;
665 }
666
674 private function _validate($data)
675 {
676 $contact = array();
677 foreach (Contacts::$FIELDS as $field) {
678 if (!isset($data[$field])) {
679 throw new RestException(400, "$field field missing");
680 }
681 $contact[$field] = $data[$field];
682 }
683
684 return $contact;
685 }
686}
$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 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.
__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: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 Dolibarr users.
forgeSQLFromUniversalSearchCriteria($filter, &$errorstr='', $noand=0, $nopar=0, $noerror=0)
forgeSQLFromUniversalSearchCriteria
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