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