dolibarr 21.0.0-beta
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 *
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 3 of the License, or
9 * (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with this program. If not, see <https://www.gnu.org/licenses/>.
18 */
19
20use Luracast\Restler\RestException;
21
22//require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
23//require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
24
25
32class Contacts extends DolibarrApi
33{
38 public static $FIELDS = array(
39 'lastname',
40 );
41
45 public $contact;
46
50 public function __construct()
51 {
52 global $db, $conf;
53 $this->db = $db;
54
55 require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
56 require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
57
58 $this->contact = new Contact($this->db);
59 }
60
73 public function get($id, $includecount = 0, $includeroles = 0)
74 {
75 if (!DolibarrApiAccess::$user->hasRight('societe', 'contact', 'lire')) {
76 throw new RestException(403, 'No permission to read contacts');
77 }
78
79 if ($id === 0) {
80 $result = $this->contact->initAsSpecimen();
81 } else {
82 $result = $this->contact->fetch($id);
83 }
84
85 if (!$result) {
86 throw new RestException(404, 'Contact not found');
87 }
88
89 if (!DolibarrApi::_checkAccessToResource('contact', $this->contact->id, 'socpeople&societe')) {
90 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
91 }
92
93 if ($includecount) {
94 $this->contact->load_ref_elements();
95 }
96
97 if ($includeroles) {
98 $this->contact->fetchRoles();
99 }
100
101 if (isModEnabled('mailing')) {
102 $this->contact->getNoEmail();
103 }
104
105 return $this->_cleanObjectDatas($this->contact);
106 }
107
121 public function getByEmail($email, $includecount = 0, $includeroles = 0)
122 {
123 if (!DolibarrApiAccess::$user->hasRight('societe', 'contact', 'lire')) {
124 throw new RestException(403, 'No permission to read contacts');
125 }
126
127 if (empty($email)) {
128 $result = $this->contact->initAsSpecimen();
129 } else {
130 $result = $this->contact->fetch(0, null, '', $email);
131 }
132
133 if (!$result) {
134 throw new RestException(404, 'Contact not found');
135 }
136
137 if (!DolibarrApi::_checkAccessToResource('contact', $this->contact->id, 'socpeople&societe')) {
138 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
139 }
140
141 if ($includecount) {
142 $this->contact->load_ref_elements();
143 }
144
145 if ($includeroles) {
146 $this->contact->fetchRoles();
147 }
148
149 if (isModEnabled('mailing')) {
150 $this->contact->getNoEmail();
151 }
152
153 return $this->_cleanObjectDatas($this->contact);
154 }
155
176 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)
177 {
178 global $db, $conf;
179
180 $obj_ret = array();
181
182 if (!DolibarrApiAccess::$user->hasRight('societe', 'contact', 'lire')) {
183 throw new RestException(403, 'No permission to read contacts');
184 }
185
186 // case of external user, $thirdparty_ids param is ignored and replaced by user's socid
187 $socids = DolibarrApiAccess::$user->socid ? DolibarrApiAccess::$user->socid : $thirdparty_ids;
188
189 // If the internal user must only see his customers, force searching by him
190 $search_sale = 0;
191 if (!DolibarrApiAccess::$user->hasRight('societe', 'client', 'voir') && !$socids) {
192 $search_sale = DolibarrApiAccess::$user->id;
193 }
194
195 $sql = "SELECT t.rowid";
196 $sql .= " FROM ".MAIN_DB_PREFIX."socpeople as t";
197 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."socpeople_extrafields as te ON te.fk_object = t.rowid";
198 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON t.fk_soc = s.rowid";
199 $sql .= ' WHERE t.entity IN ('.getEntity('contact').')';
200 if ($socids) {
201 $sql .= " AND t.fk_soc IN (".$this->db->sanitize($socids).")";
202 }
203 // Search on sale representative
204 if ($search_sale && $search_sale != '-1') {
205 if ($search_sale == -2) {
206 $sql .= " AND NOT EXISTS (SELECT sc.fk_soc FROM ".MAIN_DB_PREFIX."societe_commerciaux as sc WHERE sc.fk_soc = t.fk_soc)";
207 } elseif ($search_sale > 0) {
208 $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).")";
209 }
210 }
211 // Select contacts of given category
212 if ($category > 0) {
213 // Search Contact Categories
214 $searchCategoryContactList = $category ? array($category) : array();
215 // $searchCategoryContactOperator = 0;
216 // Search for tag/category ($searchCategoryContactList is an array of ID)
217 if (!empty($searchCategoryContactList)) {
218 $searchCategoryContactSqlList = array();
219 // $listofcategoryid = '';
220 foreach ($searchCategoryContactList as $searchCategoryContact) {
221 if (intval($searchCategoryContact) == -2) {
222 $searchCategoryContactSqlList[] = "NOT EXISTS (SELECT ck.fk_socpeople FROM ".MAIN_DB_PREFIX."categorie_contact as ck WHERE t.rowid = ck.fk_socpeople)";
223 } elseif (intval($searchCategoryContact) > 0) {
224 // if ($searchCategoryContactOperator == 0) {
225 $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).")";
226 // } else {
227 // $listofcategoryid .= ($listofcategoryid ? ', ' : '') .((int) $searchCategoryContact);
228 // }
229 }
230 }
231 // if ($listofcategoryid) {
232 // $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)."))";
233 // }
234 // if ($searchCategoryContactOperator == 1) {
235 // if (!empty($searchCategoryContactSqlList)) {
236 // $sql .= " AND (".implode(' OR ', $searchCategoryContactSqlList).")";
237 // }
238 // } else {
239 if (!empty($searchCategoryContactSqlList)) {
240 $sql .= " AND (".implode(' AND ', $searchCategoryContactSqlList).")";
241 }
242 // }
243 }
244 }
245
246 // Add sql filters
247 if ($sqlfilters) {
248 $errormessage = '';
249 $sql .= forgeSQLFromUniversalSearchCriteria($sqlfilters, $errormessage);
250 if ($errormessage) {
251 throw new RestException(400, 'Error when validating parameter sqlfilters -> '.$errormessage);
252 }
253 }
254
255 //this query will return total orders with the filters given
256 $sqlTotals = str_replace('SELECT t.rowid', 'SELECT count(t.rowid) as total', $sql);
257
258 $sql .= $this->db->order($sortfield, $sortorder);
259
260 if ($limit) {
261 if ($page < 0) {
262 $page = 0;
263 }
264 $offset = $limit * $page;
265
266 $sql .= $this->db->plimit($limit + 1, $offset);
267 }
268 $result = $this->db->query($sql);
269 if ($result) {
270 $num = $this->db->num_rows($result);
271 $min = min($num, ($limit <= 0 ? $num : $limit));
272 $i = 0;
273 while ($i < $min) {
274 $obj = $this->db->fetch_object($result);
275 $contact_static = new Contact($this->db);
276 if ($contact_static->fetch($obj->rowid)) {
277 $contact_static->fetchRoles();
278 if ($includecount) {
279 $contact_static->load_ref_elements();
280 }
281 if ($includeroles) {
282 $contact_static->fetchRoles();
283 }
284 if (isModEnabled('mailing')) {
285 $contact_static->getNoEmail();
286 }
287
288 $obj_ret[] = $this->_filterObjectProperties($this->_cleanObjectDatas($contact_static), $properties);
289 }
290
291 $i++;
292 }
293 } else {
294 throw new RestException(503, 'Error when retrieve contacts : '.$sql);
295 }
296
297 //if $pagination_data is true the response will contain element data with all values and element pagination with pagination data(total,page,limit)
298 if ($pagination_data) {
299 $totalsResult = $this->db->query($sqlTotals);
300 $total = $this->db->fetch_object($totalsResult)->total;
301
302 $tmp = $obj_ret;
303 $obj_ret = [];
304
305 $obj_ret['data'] = $tmp;
306 $obj_ret['pagination'] = [
307 'total' => (int) $total,
308 'page' => $page, //count starts from 0
309 'page_count' => ceil((int) $total / $limit),
310 'limit' => $limit
311 ];
312 }
313
314 return $obj_ret;
315 }
316
327 public function post($request_data = null)
328 {
329 if (!DolibarrApiAccess::$user->hasRight('societe', 'contact', 'creer')) {
330 throw new RestException(403, 'No permission to create/update contacts');
331 }
332 // Check mandatory fields
333 $result = $this->_validate($request_data);
334
335 foreach ($request_data as $field => $value) {
336 if ($field === 'caller') {
337 // 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
338 $this->contact->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
339 continue;
340 }
341 if ($field == 'array_options' && is_array($value)) {
342 foreach ($value as $index => $val) {
343 $this->contact->array_options[$index] = $this->_checkValForAPI('extrafields', $val, $this->contact);
344 }
345 continue;
346 }
347
348 $this->contact->$field = $this->_checkValForAPI($field, $value, $this->contact);
349 }
350 if ($this->contact->create(DolibarrApiAccess::$user) < 0) {
351 throw new RestException(500, "Error creating contact", array_merge(array($this->contact->error), $this->contact->errors));
352 }
353 if (isModEnabled('mailing') && !empty($this->contact->email) && isset($this->contact->no_email)) {
354 $this->contact->setNoEmail($this->contact->no_email);
355 }
356 return $this->contact->id;
357 }
358
372 public function put($id, $request_data = null)
373 {
374 if (!DolibarrApiAccess::$user->hasRight('societe', 'contact', 'creer')) {
375 throw new RestException(403, 'No permission to create/update contacts');
376 }
377
378 $result = $this->contact->fetch($id);
379 if (!$result) {
380 throw new RestException(404, 'Contact not found');
381 }
382
383 if (!DolibarrApi::_checkAccessToResource('contact', $this->contact->id, 'socpeople&societe')) {
384 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
385 }
386
387 foreach ($request_data as $field => $value) {
388 if ($field == 'id') {
389 continue;
390 }
391 if ($field === 'caller') {
392 // 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
393 $this->contact->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
394 continue;
395 }
396 if ($field == 'array_options' && is_array($value)) {
397 foreach ($value as $index => $val) {
398 $this->contact->array_options[$index] = $this->_checkValForAPI('extrafields', $val, $this->contact);
399 }
400 continue;
401 }
402
403 $this->contact->$field = $this->_checkValForAPI($field, $value, $this->contact);
404 }
405
406 if (isModEnabled('mailing') && !empty($this->contact->email) && isset($this->contact->no_email)) {
407 $this->contact->setNoEmail($this->contact->no_email);
408 }
409
410 if ($this->contact->update($id, DolibarrApiAccess::$user, 0, 'update') > 0) {
411 return $this->get($id);
412 } else {
413 throw new RestException(500, $this->contact->error);
414 }
415 }
416
425 public function delete($id)
426 {
427 if (!DolibarrApiAccess::$user->hasRight('societe', 'contact', 'supprimer')) {
428 throw new RestException(403, 'No permission to delete contacts');
429 }
430 $result = $this->contact->fetch($id);
431 if (!$result) {
432 throw new RestException(404, 'Contact not found');
433 }
434
435 if (!DolibarrApi::_checkAccessToResource('contact', $this->contact->id, 'socpeople&societe')) {
436 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
437 }
438 $this->contact->oldcopy = clone $this->contact; // @phan-suppress-current-line PhanTypeMismatchProperty
439
440 if ($this->contact->delete(DolibarrApiAccess::$user) <= 0) {
441 throw new RestException(500, 'Error when delete contact ' . $this->contact->error);
442 }
443
444 return array(
445 'success' => array(
446 'code' => 200,
447 'message' => 'Contact deleted'
448 )
449 );
450 }
451
464 public function createUser($id, $request_data = null)
465 {
466 //if (!DolibarrApiAccess::$user->hasRight('user', 'user', 'creer')) {
467 //throw new RestException(403);
468 //}
469
470 if (!isset($request_data["login"])) {
471 throw new RestException(400, "login field missing");
472 }
473 if (!isset($request_data["password"])) {
474 throw new RestException(400, "password field missing");
475 }
476
477 if (!DolibarrApiAccess::$user->hasRight('societe', 'contact', 'lire')) {
478 throw new RestException(403, 'No permission to read contacts');
479 }
480 if (!DolibarrApiAccess::$user->hasRight('user', 'user', 'creer')) {
481 throw new RestException(403, 'No permission to create user');
482 }
483
484 $contact = new Contact($this->db);
485 $contact->fetch($id);
486 if ($contact->id <= 0) {
487 throw new RestException(404, 'Contact not found');
488 }
489
490 if (!DolibarrApi::_checkAccessToResource('contact', $contact->id, 'socpeople&societe')) {
491 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
492 }
493
494 // Check mandatory fields
495 $login = $request_data["login"];
496 $password = $request_data["password"];
497 $useraccount = new User($this->db);
498 $result = $useraccount->create_from_contact($contact, $login, $password);
499 if ($result <= 0) {
500 throw new RestException(500, "User not created");
501 }
502 // password parameter not used in create_from_contact
503 $useraccount->setPassword($useraccount, $password);
504
505 return $result;
506 }
507
521 public function getCategories($id, $sortfield = "s.rowid", $sortorder = 'ASC', $limit = 0, $page = 0)
522 {
523 if (!DolibarrApiAccess::$user->hasRight('categorie', 'lire')) {
524 throw new RestException(403);
525 }
526
527 $categories = new Categorie($this->db);
528
529 $result = $categories->getListForItem($id, 'contact', $sortfield, $sortorder, $limit, $page);
530
531 if ($result < 0) {
532 throw new RestException(503, 'Error when retrieve category list : '.$categories->error);
533 }
534
535 return $result;
536 }
537
551 public function addCategory($id, $category_id)
552 {
553 if (!DolibarrApiAccess::$user->hasRight('societe', 'contact', 'creer')) {
554 throw new RestException(403, 'Insufficient rights');
555 }
556
557 $result = $this->contact->fetch($id);
558 if (!$result) {
559 throw new RestException(404, 'Contact not found');
560 }
561 $category = new Categorie($this->db);
562 $result = $category->fetch($category_id);
563 if (!$result) {
564 throw new RestException(404, 'category not found');
565 }
566
567 if (!DolibarrApi::_checkAccessToResource('contact', $this->contact->id)) {
568 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
569 }
570 if (!DolibarrApi::_checkAccessToResource('category', $category->id)) {
571 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
572 }
573
574 $category->add_type($this->contact, 'contact');
575
576 return $this->_cleanObjectDatas($this->contact);
577 }
578
591 public function deleteCategory($id, $category_id)
592 {
593 if (!DolibarrApiAccess::$user->hasRight('societe', 'contact', 'creer')) {
594 throw new RestException(403, 'Insufficient rights');
595 }
596
597 $result = $this->contact->fetch($id);
598 if (!$result) {
599 throw new RestException(404, 'Contact not found');
600 }
601 $category = new Categorie($this->db);
602 $result = $category->fetch($category_id);
603 if (!$result) {
604 throw new RestException(404, 'category not found');
605 }
606
607 if (!DolibarrApi::_checkAccessToResource('contact', $this->contact->id)) {
608 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
609 }
610 if (!DolibarrApi::_checkAccessToResource('category', $category->id)) {
611 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
612 }
613
614 $category->del_type($this->contact, 'contact');
615
616 return $this->_cleanObjectDatas($this->contact);
617 }
618
619 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
626 protected function _cleanObjectDatas($object)
627 {
628 // phpcs:enable
629 $object = parent::_cleanObjectDatas($object);
630
631 unset($object->total_ht);
632 unset($object->total_tva);
633 unset($object->total_localtax1);
634 unset($object->total_localtax2);
635 unset($object->total_ttc);
636
637 unset($object->note);
638 unset($object->lines);
639 unset($object->thirdparty);
640
641 return $object;
642 }
643
651 private function _validate($data)
652 {
653 $contact = array();
654 foreach (Contacts::$FIELDS as $field) {
655 if (!isset($data[$field])) {
656 throw new RestException(400, "$field field missing");
657 }
658 $contact[$field] = $data[$field];
659 }
660
661 return $contact;
662 }
663}
$id
Definition account.php:48
if( $user->socid > 0) if(! $user->hasRight('accounting', 'chartofaccount')) $object
Definition card.php:66
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 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 an user account object from contact (external user)
post($request_data=null)
Create contact object.
getByEmail($email, $includecount=0, $includeroles=0)
Get properties of a contact object by Email.
getCategories($id, $sortfield="s.rowid", $sortorder='ASC', $limit=0, $page=0)
Get categories for a contact.
_cleanObjectDatas($object)
Clean sensible object datas.
__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:30
_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:82
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