dolibarr 20.0.2
api_contacts.class.php
1<?php
2/* Copyright (C) 2015 Jean-François Ferry <jfefe@aternatik.fr>
3 * Copyright (C) 2019 Frédéric France <frederic.france@netlogic.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('', '', '', $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
175 public function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $thirdparty_ids = '', $category = 0, $sqlfilters = '', $includecount = 0, $includeroles = 0, $properties = '')
176 {
177 global $db, $conf;
178
179 $obj_ret = array();
180
181 if (!DolibarrApiAccess::$user->hasRight('societe', 'contact', 'lire')) {
182 throw new RestException(403, 'No permission to read contacts');
183 }
184
185 // case of external user, $thirdparty_ids param is ignored and replaced by user's socid
186 $socids = DolibarrApiAccess::$user->socid ? DolibarrApiAccess::$user->socid : $thirdparty_ids;
187
188 // If the internal user must only see his customers, force searching by him
189 $search_sale = 0;
190 if (!DolibarrApiAccess::$user->hasRight('societe', 'client', 'voir') && !$socids) {
191 $search_sale = DolibarrApiAccess::$user->id;
192 }
193
194 $sql = "SELECT t.rowid";
195 $sql .= " FROM ".MAIN_DB_PREFIX."socpeople as t";
196 if ($category > 0) {
197 $sql .= ", ".MAIN_DB_PREFIX."categorie_contact as c";
198 }
199 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."socpeople_extrafields as te ON te.fk_object = t.rowid";
200 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON t.fk_soc = s.rowid";
201 $sql .= ' WHERE t.entity IN ('.getEntity('contact').')';
202 if ($socids) {
203 $sql .= " AND t.fk_soc IN (".$this->db->sanitize($socids).")";
204 }
205 // Search on sale representative
206 if ($search_sale && $search_sale != '-1') {
207 if ($search_sale == -2) {
208 $sql .= " AND NOT EXISTS (SELECT sc.fk_soc FROM ".MAIN_DB_PREFIX."societe_commerciaux as sc WHERE sc.fk_soc = t.fk_soc)";
209 } elseif ($search_sale > 0) {
210 $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).")";
211 }
212 }
213 // Select contacts of given category
214 if ($category > 0) {
215 $sql .= " AND c.fk_categorie = ".((int) $category);
216 $sql .= " AND c.fk_socpeople = t.rowid ";
217 }
218
219 // Add sql filters
220 if ($sqlfilters) {
221 $errormessage = '';
222 $sql .= forgeSQLFromUniversalSearchCriteria($sqlfilters, $errormessage);
223 if ($errormessage) {
224 throw new RestException(400, 'Error when validating parameter sqlfilters -> '.$errormessage);
225 }
226 }
227
228 $sql .= $this->db->order($sortfield, $sortorder);
229
230 if ($limit) {
231 if ($page < 0) {
232 $page = 0;
233 }
234 $offset = $limit * $page;
235
236 $sql .= $this->db->plimit($limit + 1, $offset);
237 }
238 $result = $this->db->query($sql);
239 if ($result) {
240 $num = $this->db->num_rows($result);
241 $min = min($num, ($limit <= 0 ? $num : $limit));
242 $i = 0;
243 while ($i < $min) {
244 $obj = $this->db->fetch_object($result);
245 $contact_static = new Contact($this->db);
246 if ($contact_static->fetch($obj->rowid)) {
247 $contact_static->fetchRoles();
248 if ($includecount) {
249 $contact_static->load_ref_elements();
250 }
251 if ($includeroles) {
252 $contact_static->fetchRoles();
253 }
254 if (isModEnabled('mailing')) {
255 $contact_static->getNoEmail();
256 }
257
258 $obj_ret[] = $this->_filterObjectProperties($this->_cleanObjectDatas($contact_static), $properties);
259 }
260
261 $i++;
262 }
263 } else {
264 throw new RestException(503, 'Error when retrieve contacts : '.$sql);
265 }
266 if (!count($obj_ret)) {
267 throw new RestException(404, 'Contacts not found');
268 }
269 return $obj_ret;
270 }
271
280 public function post($request_data = null)
281 {
282 if (!DolibarrApiAccess::$user->hasRight('societe', 'contact', 'creer')) {
283 throw new RestException(403, 'No permission to create/update contacts');
284 }
285 // Check mandatory fields
286 $result = $this->_validate($request_data);
287
288 foreach ($request_data as $field => $value) {
289 if ($field === 'caller') {
290 // 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
291 $this->contact->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
292 continue;
293 }
294 if ($field == 'array_options' && is_array($value)) {
295 foreach ($value as $index => $val) {
296 $this->contact->array_options[$index] = $this->_checkValForAPI('extrafields', $val, $this->contact);
297 }
298 continue;
299 }
300
301 $this->contact->$field = $this->_checkValForAPI($field, $value, $this->contact);
302 }
303 if ($this->contact->create(DolibarrApiAccess::$user) < 0) {
304 throw new RestException(500, "Error creating contact", array_merge(array($this->contact->error), $this->contact->errors));
305 }
306 if (isModEnabled('mailing') && !empty($this->contact->email) && isset($this->contact->no_email)) {
307 $this->contact->setNoEmail($this->contact->no_email);
308 }
309 return $this->contact->id;
310 }
311
323 public function put($id, $request_data = null)
324 {
325 if (!DolibarrApiAccess::$user->hasRight('societe', 'contact', 'creer')) {
326 throw new RestException(403, 'No permission to create/update contacts');
327 }
328
329 $result = $this->contact->fetch($id);
330 if (!$result) {
331 throw new RestException(404, 'Contact not found');
332 }
333
334 if (!DolibarrApi::_checkAccessToResource('contact', $this->contact->id, 'socpeople&societe')) {
335 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
336 }
337
338 foreach ($request_data as $field => $value) {
339 if ($field == 'id') {
340 continue;
341 }
342 if ($field === 'caller') {
343 // 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
344 $this->contact->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
345 continue;
346 }
347 if ($field == 'array_options' && is_array($value)) {
348 foreach ($value as $index => $val) {
349 $this->contact->array_options[$index] = $this->_checkValForAPI('extrafields', $val, $this->contact);
350 }
351 continue;
352 }
353
354 $this->contact->$field = $this->_checkValForAPI($field, $value, $this->contact);
355 }
356
357 if (isModEnabled('mailing') && !empty($this->contact->email) && isset($this->contact->no_email)) {
358 $this->contact->setNoEmail($this->contact->no_email);
359 }
360
361 if ($this->contact->update($id, DolibarrApiAccess::$user, 0, 'update') > 0) {
362 return $this->get($id);
363 } else {
364 throw new RestException(500, $this->contact->error);
365 }
366 }
367
374 public function delete($id)
375 {
376 if (!DolibarrApiAccess::$user->hasRight('societe', 'contact', 'supprimer')) {
377 throw new RestException(403, 'No permission to delete contacts');
378 }
379 $result = $this->contact->fetch($id);
380 if (!$result) {
381 throw new RestException(404, 'Contact not found');
382 }
383
384 if (!DolibarrApi::_checkAccessToResource('contact', $this->contact->id, 'socpeople&societe')) {
385 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
386 }
387 $this->contact->oldcopy = clone $this->contact;
388
389 if ($this->contact->delete(DolibarrApiAccess::$user) <= 0) {
390 throw new RestException(500, 'Error when delete contact ' . $this->contact->error);
391 }
392
393 return array(
394 'success' => array(
395 'code' => 200,
396 'message' => 'Contact deleted'
397 )
398 );
399 }
400
411 public function createUser($id, $request_data = null)
412 {
413 //if (!DolibarrApiAccess::$user->hasRight('user', 'user', 'creer')) {
414 //throw new RestException(403);
415 //}
416
417 if (!isset($request_data["login"])) {
418 throw new RestException(400, "login field missing");
419 }
420 if (!isset($request_data["password"])) {
421 throw new RestException(400, "password field missing");
422 }
423
424 if (!DolibarrApiAccess::$user->hasRight('societe', 'contact', 'lire')) {
425 throw new RestException(403, 'No permission to read contacts');
426 }
427 if (!DolibarrApiAccess::$user->hasRight('user', 'user', 'creer')) {
428 throw new RestException(403, 'No permission to create user');
429 }
430
431 $contact = new Contact($this->db);
432 $contact->fetch($id);
433 if ($contact->id <= 0) {
434 throw new RestException(404, 'Contact not found');
435 }
436
437 if (!DolibarrApi::_checkAccessToResource('contact', $contact->id, 'socpeople&societe')) {
438 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
439 }
440
441 // Check mandatory fields
442 $login = $request_data["login"];
443 $password = $request_data["password"];
444 $useraccount = new User($this->db);
445 $result = $useraccount->create_from_contact($contact, $login, $password);
446 if ($result <= 0) {
447 throw new RestException(500, "User not created");
448 }
449 // password parameter not used in create_from_contact
450 $useraccount->setPassword($useraccount, $password);
451
452 return $result;
453 }
454
468 public function getCategories($id, $sortfield = "s.rowid", $sortorder = 'ASC', $limit = 0, $page = 0)
469 {
470 if (!DolibarrApiAccess::$user->hasRight('categorie', 'lire')) {
471 throw new RestException(403);
472 }
473
474 $categories = new Categorie($this->db);
475
476 $result = $categories->getListForItem($id, 'contact', $sortfield, $sortorder, $limit, $page);
477
478 if ($result < 0) {
479 throw new RestException(503, 'Error when retrieve category list : '.$categories->error);
480 }
481
482 return $result;
483 }
484
498 public function addCategory($id, $category_id)
499 {
500 if (!DolibarrApiAccess::$user->hasRight('societe', 'contact', 'creer')) {
501 throw new RestException(403, 'Insufficient rights');
502 }
503
504 $result = $this->contact->fetch($id);
505 if (!$result) {
506 throw new RestException(404, 'Contact not found');
507 }
508 $category = new Categorie($this->db);
509 $result = $category->fetch($category_id);
510 if (!$result) {
511 throw new RestException(404, 'category not found');
512 }
513
514 if (!DolibarrApi::_checkAccessToResource('contact', $this->contact->id)) {
515 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
516 }
517 if (!DolibarrApi::_checkAccessToResource('category', $category->id)) {
518 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
519 }
520
521 $category->add_type($this->contact, 'contact');
522
523 return $this->_cleanObjectDatas($this->contact);
524 }
525
538 public function deleteCategory($id, $category_id)
539 {
540 if (!DolibarrApiAccess::$user->hasRight('societe', 'contact', 'creer')) {
541 throw new RestException(403, 'Insufficient rights');
542 }
543
544 $result = $this->contact->fetch($id);
545 if (!$result) {
546 throw new RestException(404, 'Contact not found');
547 }
548 $category = new Categorie($this->db);
549 $result = $category->fetch($category_id);
550 if (!$result) {
551 throw new RestException(404, 'category not found');
552 }
553
554 if (!DolibarrApi::_checkAccessToResource('contact', $this->contact->id)) {
555 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
556 }
557 if (!DolibarrApi::_checkAccessToResource('category', $category->id)) {
558 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
559 }
560
561 $category->del_type($this->contact, 'contact');
562
563 return $this->_cleanObjectDatas($this->contact);
564 }
565
566 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
573 protected function _cleanObjectDatas($object)
574 {
575 // phpcs:enable
576 $object = parent::_cleanObjectDatas($object);
577
578 unset($object->total_ht);
579 unset($object->total_tva);
580 unset($object->total_localtax1);
581 unset($object->total_localtax2);
582 unset($object->total_ttc);
583
584 unset($object->note);
585 unset($object->lines);
586 unset($object->thirdparty);
587
588 return $object;
589 }
590
598 private function _validate($data)
599 {
600 $contact = array();
601 foreach (Contacts::$FIELDS as $field) {
602 if (!isset($data[$field])) {
603 throw new RestException(400, "$field field missing");
604 }
605 $contact[$field] = $data[$field];
606 }
607
608 return $contact;
609 }
610}
if( $user->socid > 0) if(! $user->hasRight('accounting', 'chartofaccount')) $object
Definition card.php:58
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.
index($sortfield="t.rowid", $sortorder='ASC', $limit=100, $page=0, $thirdparty_ids='', $category=0, $sqlfilters='', $includecount=0, $includeroles=0, $properties='')
List contacts.
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.
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.