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 // A private contact is only visible by the user that created it
210 $sql .= " AND (t.priv = 0 OR t.fk_user_creat = ".((int) DolibarrApiAccess::$user->id).")";
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 NOT EXISTS (SELECT sc.fk_soc FROM ".MAIN_DB_PREFIX."societe_commerciaux as sc WHERE sc.fk_soc = t.fk_soc)";
218 } elseif ($search_sale > 0) {
219 $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).")";
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 foreach ($request_data as $field => $value) {
349 if ($field === 'caller') {
350 // 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
351 $this->contact->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
352 continue;
353 }
354 if ($field == 'array_options' && is_array($value)) {
355 foreach ($value as $index => $val) {
356 $this->contact->array_options[$index] = $this->_checkValForAPI('extrafields', $val, $this->contact);
357 }
358 continue;
359 }
360
361 $this->contact->$field = $this->_checkValForAPI($field, $value, $this->contact);
362 }
363 if ($this->contact->create(DolibarrApiAccess::$user) < 0) {
364 throw new RestException(500, "Error creating contact", array_merge(array($this->contact->error), $this->contact->errors));
365 }
366 if (isModEnabled('mailing') && !empty($this->contact->email) && isset($this->contact->no_email)) {
367 $this->contact->setNoEmail($this->contact->no_email);
368 }
369 return $this->contact->id;
370 }
371
387 public function put($id, $request_data = null)
388 {
389 if (!DolibarrApiAccess::$user->hasRight('societe', 'contact', 'creer')) {
390 throw new RestException(403, 'No permission to create/update contacts');
391 }
392
393 $result = $this->contact->fetch($id);
394 if (!$result) {
395 throw new RestException(404, 'Contact not found');
396 }
397
398 if (!DolibarrApi::_checkAccessToResource('contact', $this->contact->id, 'socpeople&societe')) {
399 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
400 }
401
402 foreach ($request_data as $field => $value) {
403 if ($field == 'id') {
404 continue;
405 }
406 if ($field === 'caller') {
407 // 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
408 $this->contact->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
409 continue;
410 }
411 if ($field == 'array_options' && is_array($value)) {
412 foreach ($value as $index => $val) {
413 $this->contact->array_options[$index] = $this->_checkValForAPI($field, $val, $this->contact);
414 }
415 continue;
416 }
417
418 $this->contact->$field = $this->_checkValForAPI($field, $value, $this->contact);
419 }
420
421 if (isModEnabled('mailing') && !empty($this->contact->email) && isset($this->contact->no_email)) {
422 $this->contact->setNoEmail($this->contact->no_email);
423 }
424
425 if ($this->contact->update($id, DolibarrApiAccess::$user, 0, 'update') > 0) {
426 return $this->get($id);
427 } else {
428 throw new RestException(500, $this->contact->error);
429 }
430 }
431
442 public function delete($id)
443 {
444 if (!DolibarrApiAccess::$user->hasRight('societe', 'contact', 'supprimer')) {
445 throw new RestException(403, 'No permission to delete contacts');
446 }
447 $result = $this->contact->fetch($id);
448 if (!$result) {
449 throw new RestException(404, 'Contact not found');
450 }
451
452 if (!DolibarrApi::_checkAccessToResource('contact', $this->contact->id, 'socpeople&societe')) {
453 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
454 }
455 $this->contact->oldcopy = clone $this->contact; // @phan-suppress-current-line PhanTypeMismatchProperty
456
457 if ($this->contact->delete(DolibarrApiAccess::$user) <= 0) {
458 throw new RestException(500, 'Error when delete contact ' . $this->contact->error);
459 }
460
461 return array(
462 'success' => array(
463 'code' => 200,
464 'message' => 'Contact deleted'
465 )
466 );
467 }
468
483 public function createUser($id, $request_data = null)
484 {
485 //if (!DolibarrApiAccess::$user->hasRight('user', 'user', 'creer')) {
486 //throw new RestException(403);
487 //}
488
489 if (!isset($request_data["login"])) {
490 throw new RestException(400, "login field missing");
491 }
492 if (!isset($request_data["password"])) {
493 throw new RestException(400, "password field missing");
494 }
495
496 if (!DolibarrApiAccess::$user->hasRight('societe', 'contact', 'lire')) {
497 throw new RestException(403, 'No permission to read contacts');
498 }
499 if (!DolibarrApiAccess::$user->hasRight('user', 'user', 'creer')) {
500 throw new RestException(403, 'No permission to create user');
501 }
502
503 $contact = new Contact($this->db);
504 $contact->fetch($id);
505 if ($contact->id <= 0) {
506 throw new RestException(404, 'Contact not found');
507 }
508
509 if (!DolibarrApi::_checkAccessToResource('contact', $contact->id, 'socpeople&societe')) {
510 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
511 }
512
513 // Check mandatory fields
514 $login = $request_data["login"];
515 $password = $request_data["password"];
516 $useraccount = new User($this->db);
517 $result = $useraccount->create_from_contact($contact, $login, $password);
518 if ($result <= 0) {
519 throw new RestException(500, "User not created");
520 }
521 // password parameter not used in create_from_contact
522 $useraccount->setPassword($useraccount, $password);
523
524 return $result;
525 }
526
542 public function getCategories($id, $sortfield = "s.rowid", $sortorder = 'ASC', $limit = 0, $page = 0)
543 {
544 if (!DolibarrApiAccess::$user->hasRight('categorie', 'lire')) {
545 throw new RestException(403);
546 }
547
548 if (!DolibarrApi::_checkAccessToResource('contact', $id, 'socpeople&societe')) {
549 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
550 }
551
552 $categories = new Categorie($this->db);
553
554 $result = $categories->getListForItem($id, 'contact', $sortfield, $sortorder, $limit, $page);
555
556 if ($result < 0) {
557 throw new RestException(503, 'Error when retrieve category list : '.$categories->error);
558 }
559
560 return $result;
561 }
562
578 public function addCategory($id, $category_id)
579 {
580 if (!DolibarrApiAccess::$user->hasRight('societe', 'contact', 'creer')) {
581 throw new RestException(403, 'Insufficient rights');
582 }
583
584 $result = $this->contact->fetch($id);
585 if (!$result) {
586 throw new RestException(404, 'Contact not found');
587 }
588 $category = new Categorie($this->db);
589 $result = $category->fetch($category_id);
590 if (!$result) {
591 throw new RestException(404, 'category not found');
592 }
593
594 if (!DolibarrApi::_checkAccessToResource('contact', $this->contact->id, 'socpeople&societe')) {
595 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
596 }
597 if (!DolibarrApi::_checkAccessToResource('category', $category->id)) {
598 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
599 }
600
601 $category->add_type($this->contact, 'contact');
602
603 return $this->_cleanObjectDatas($this->contact);
604 }
605
620 public function deleteCategory($id, $category_id)
621 {
622 if (!DolibarrApiAccess::$user->hasRight('societe', 'contact', 'creer')) {
623 throw new RestException(403, 'Insufficient rights');
624 }
625
626 $result = $this->contact->fetch($id);
627 if (!$result) {
628 throw new RestException(404, 'Contact not found');
629 }
630 $category = new Categorie($this->db);
631 $result = $category->fetch($category_id);
632 if (!$result) {
633 throw new RestException(404, 'category not found');
634 }
635
636 if (!DolibarrApi::_checkAccessToResource('contact', $this->contact->id, 'socpeople&societe')) {
637 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
638 }
639 if (!DolibarrApi::_checkAccessToResource('category', $category->id)) {
640 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
641 }
642
643 $category->del_type($this->contact, 'contact');
644
645 return $this->_cleanObjectDatas($this->contact);
646 }
647
648 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
655 protected function _cleanObjectDatas($object)
656 {
657 // phpcs:enable
658 $object = parent::_cleanObjectDatas($object);
659
660 unset($object->total_ht);
661 unset($object->total_tva);
662 unset($object->total_localtax1);
663 unset($object->total_localtax2);
664 unset($object->total_ttc);
665
666 unset($object->note);
667 unset($object->lines);
668 unset($object->thirdparty);
669
670 return $object;
671 }
672
680 private function _validate($data)
681 {
682 $contact = array();
683 foreach (Contacts::$FIELDS as $field) {
684 if (!isset($data[$field])) {
685 throw new RestException(400, "$field field missing");
686 }
687 $contact[$field] = $data[$field];
688 }
689
690 return $contact;
691 }
692}
$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