dolibarr 19.0.3
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 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 3 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License
16 * along with this program. If not, see <https://www.gnu.org/licenses/>.
17 */
18
19use Luracast\Restler\RestException;
20
21//require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
22//require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
23
24
31class Contacts extends DolibarrApi
32{
37 public static $FIELDS = array(
38 'lastname',
39 );
40
44 public $contact;
45
49 public function __construct()
50 {
51 global $db, $conf;
52 $this->db = $db;
53
54 require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
55 require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
56
57 $this->contact = new Contact($this->db);
58 }
59
72 public function get($id, $includecount = 0, $includeroles = 0)
73 {
74 if (!DolibarrApiAccess::$user->rights->societe->contact->lire) {
75 throw new RestException(401, 'No permission to read contacts');
76 }
77
78 if ($id === 0) {
79 $result = $this->contact->initAsSpecimen();
80 } else {
81 $result = $this->contact->fetch($id);
82 }
83
84 if (!$result) {
85 throw new RestException(404, 'Contact not found');
86 }
87
88 if (!DolibarrApi::_checkAccessToResource('contact', $this->contact->id, 'socpeople&societe')) {
89 throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
90 }
91
92 if ($includecount) {
93 $this->contact->load_ref_elements();
94 }
95
96 if ($includeroles) {
97 $this->contact->fetchRoles();
98 }
99
100 if (isModEnabled('mailing')) {
101 $this->contact->getNoEmail();
102 }
103
104 return $this->_cleanObjectDatas($this->contact);
105 }
106
120 public function getByEmail($email, $includecount = 0, $includeroles = 0)
121 {
122 if (!DolibarrApiAccess::$user->rights->societe->contact->lire) {
123 throw new RestException(401, 'No permission to read contacts');
124 }
125
126 if (empty($email)) {
127 $result = $this->contact->initAsSpecimen();
128 } else {
129 $result = $this->contact->fetch('', '', '', $email);
130 }
131
132 if (!$result) {
133 throw new RestException(404, 'Contact not found');
134 }
135
136 if (!DolibarrApi::_checkAccessToResource('contact', $this->contact->id, 'socpeople&societe')) {
137 throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
138 }
139
140 if ($includecount) {
141 $this->contact->load_ref_elements();
142 }
143
144 if ($includeroles) {
145 $this->contact->fetchRoles();
146 }
147
148 if (isModEnabled('mailing')) {
149 $this->contact->getNoEmail();
150 }
151
152 return $this->_cleanObjectDatas($this->contact);
153 }
154
174 public function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $thirdparty_ids = '', $category = 0, $sqlfilters = '', $includecount = 0, $includeroles = 0, $properties = '')
175 {
176 global $db, $conf;
177
178 $obj_ret = array();
179
180 if (!DolibarrApiAccess::$user->rights->societe->contact->lire) {
181 throw new RestException(401, 'No permission to read contacts');
182 }
183
184 // case of external user, $thirdparty_ids param is ignored and replaced by user's socid
185 $socids = DolibarrApiAccess::$user->socid ? DolibarrApiAccess::$user->socid : $thirdparty_ids;
186
187 // If the internal user must only see his customers, force searching by him
188 $search_sale = 0;
189 if (!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) {
190 $search_sale = DolibarrApiAccess::$user->id;
191 }
192
193 $sql = "SELECT t.rowid";
194 $sql .= " FROM ".MAIN_DB_PREFIX."socpeople as t";
195 if ($category > 0) {
196 $sql .= ", ".MAIN_DB_PREFIX."categorie_contact as c";
197 }
198 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."socpeople_extrafields as te ON te.fk_object = t.rowid";
199 if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) {
200 // We need this table joined to the select in order to filter by sale
201 $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
202 }
203 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON t.fk_soc = s.rowid";
204 $sql .= ' WHERE t.entity IN ('.getEntity('contact').')';
205 if ($socids) {
206 $sql .= " AND t.fk_soc IN (".$this->db->sanitize($socids).")";
207 }
208
209 if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) {
210 $sql .= " AND t.fk_soc = sc.fk_soc";
211 }
212 if ($search_sale > 0) {
213 $sql .= " AND s.rowid = sc.fk_soc"; // Join for the needed table to filter by sale
214 }
215 // Insert sale filter
216 if ($search_sale > 0) {
217 $sql .= " AND sc.fk_user = ".((int) $search_sale);
218 }
219
220 // Select contacts of given category
221 if ($category > 0) {
222 $sql .= " AND c.fk_categorie = ".((int) $category);
223 $sql .= " AND c.fk_socpeople = t.rowid ";
224 }
225
226 // Add sql filters
227 if ($sqlfilters) {
228 $errormessage = '';
229 $sql .= forgeSQLFromUniversalSearchCriteria($sqlfilters, $errormessage);
230 if ($errormessage) {
231 throw new RestException(400, 'Error when validating parameter sqlfilters -> '.$errormessage);
232 }
233 }
234
235 $sql .= $this->db->order($sortfield, $sortorder);
236
237 if ($limit) {
238 if ($page < 0) {
239 $page = 0;
240 }
241 $offset = $limit * $page;
242
243 $sql .= $this->db->plimit($limit + 1, $offset);
244 }
245 $result = $this->db->query($sql);
246 if ($result) {
247 $num = $this->db->num_rows($result);
248 $min = min($num, ($limit <= 0 ? $num : $limit));
249 $i = 0;
250 while ($i < $min) {
251 $obj = $this->db->fetch_object($result);
252 $contact_static = new Contact($this->db);
253 if ($contact_static->fetch($obj->rowid)) {
254 $contact_static->fetchRoles();
255 if ($includecount) {
256 $contact_static->load_ref_elements();
257 }
258 if ($includeroles) {
259 $contact_static->fetchRoles();
260 }
261 if (isModEnabled('mailing')) {
262 $contact_static->getNoEmail();
263 }
264
265 $obj_ret[] = $this->_filterObjectProperties($this->_cleanObjectDatas($contact_static), $properties);
266 }
267
268 $i++;
269 }
270 } else {
271 throw new RestException(503, 'Error when retrieve contacts : '.$sql);
272 }
273 if (!count($obj_ret)) {
274 throw new RestException(404, 'Contacts not found');
275 }
276 return $obj_ret;
277 }
278
285 public function post($request_data = null)
286 {
287 if (!DolibarrApiAccess::$user->rights->societe->contact->creer) {
288 throw new RestException(401, 'No permission to create/update contacts');
289 }
290 // Check mandatory fields
291 $result = $this->_validate($request_data);
292
293 foreach ($request_data as $field => $value) {
294 if ($field === 'caller') {
295 // 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 whith the caller
296 $this->contact->context['caller'] = $request_data['caller'];
297 continue;
298 }
299 if ($field == 'array_options' && is_array($value)) {
300 foreach ($value as $index => $val) {
301 $this->contact->array_options[$index] = $val;
302 }
303 continue;
304 }
305
306 $this->contact->$field = $this->_checkValForAPI($field, $value, $this->contact);
307 }
308 if ($this->contact->create(DolibarrApiAccess::$user) < 0) {
309 throw new RestException(500, "Error creating contact", array_merge(array($this->contact->error), $this->contact->errors));
310 }
311 if (isModEnabled('mailing') && !empty($this->contact->email) && isset($this->contact->no_email)) {
312 $this->contact->setNoEmail($this->contact->no_email);
313 }
314 return $this->contact->id;
315 }
316
327 public function put($id, $request_data = null)
328 {
329 if (!DolibarrApiAccess::$user->rights->societe->contact->creer) {
330 throw new RestException(401, 'No permission to create/update contacts');
331 }
332
333 $result = $this->contact->fetch($id);
334 if (!$result) {
335 throw new RestException(404, 'Contact not found');
336 }
337
338 if (!DolibarrApi::_checkAccessToResource('contact', $this->contact->id, 'socpeople&societe')) {
339 throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
340 }
341
342 foreach ($request_data as $field => $value) {
343 if ($field == 'id') {
344 continue;
345 }
346 if ($field === 'caller') {
347 // 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 whith the caller
348 $this->contact->context['caller'] = $request_data['caller'];
349 continue;
350 }
351 if ($field == 'array_options' && is_array($value)) {
352 foreach ($value as $index => $val) {
353 $this->contact->array_options[$index] = $val;
354 }
355 continue;
356 }
357
358 $this->contact->$field = $this->_checkValForAPI($field, $value, $this->contact);
359 }
360
361 if (isModEnabled('mailing') && !empty($this->contact->email) && isset($this->contact->no_email)) {
362 $this->contact->setNoEmail($this->contact->no_email);
363 }
364
365 if ($this->contact->update($id, DolibarrApiAccess::$user, 0, 'update') > 0) {
366 return $this->get($id);
367 } else {
368 throw new RestException(500, $this->contact->error);
369 }
370 }
371
378 public function delete($id)
379 {
380 if (!DolibarrApiAccess::$user->rights->societe->contact->supprimer) {
381 throw new RestException(401, 'No permission to delete contacts');
382 }
383 $result = $this->contact->fetch($id);
384 if (!$result) {
385 throw new RestException(404, 'Contact not found');
386 }
387
388 if (!DolibarrApi::_checkAccessToResource('contact', $this->contact->id, 'socpeople&societe')) {
389 throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
390 }
391 $this->contact->oldcopy = clone $this->contact;
392 return $this->contact->delete(DolibarrApiAccess::$user);
393 }
394
404 public function createUser($id, $request_data = null)
405 {
406 //if (!DolibarrApiAccess::$user->hasRight('user', 'user', 'creer')) {
407 //throw new RestException(401);
408 //}
409
410 if (!isset($request_data["login"])) {
411 throw new RestException(400, "login field missing");
412 }
413 if (!isset($request_data["password"])) {
414 throw new RestException(400, "password field missing");
415 }
416
417 if (!DolibarrApiAccess::$user->rights->societe->contact->lire) {
418 throw new RestException(401, 'No permission to read contacts');
419 }
420 if (!DolibarrApiAccess::$user->hasRight('user', 'user', 'creer')) {
421 throw new RestException(401, 'No permission to create user');
422 }
423
424 $contact = new Contact($this->db);
425 $contact->fetch($id);
426 if ($contact->id <= 0) {
427 throw new RestException(404, 'Contact not found');
428 }
429
430 if (!DolibarrApi::_checkAccessToResource('contact', $contact->id, 'socpeople&societe')) {
431 throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
432 }
433
434 // Check mandatory fields
435 $login = $request_data["login"];
436 $password = $request_data["password"];
437 $useraccount = new User($this->db);
438 $result = $useraccount->create_from_contact($contact, $login, $password);
439 if ($result <= 0) {
440 throw new RestException(500, "User not created");
441 }
442 // password parameter not used in create_from_contact
443 $useraccount->setPassword($useraccount, $password);
444
445 return $result;
446 }
447
461 public function getCategories($id, $sortfield = "s.rowid", $sortorder = 'ASC', $limit = 0, $page = 0)
462 {
463 if (!DolibarrApiAccess::$user->rights->categorie->lire) {
464 throw new RestException(401);
465 }
466
467 $categories = new Categorie($this->db);
468
469 $result = $categories->getListForItem($id, 'contact', $sortfield, $sortorder, $limit, $page);
470
471 if ($result < 0) {
472 throw new RestException(503, 'Error when retrieve category list : '.$categories->error);
473 }
474
475 return $result;
476 }
477
491 public function addCategory($id, $category_id)
492 {
493 if (!DolibarrApiAccess::$user->rights->societe->contact->creer) {
494 throw new RestException(401, 'Insufficient rights');
495 }
496
497 $result = $this->contact->fetch($id);
498 if (!$result) {
499 throw new RestException(404, 'Contact not found');
500 }
501 $category = new Categorie($this->db);
502 $result = $category->fetch($category_id);
503 if (!$result) {
504 throw new RestException(404, 'category not found');
505 }
506
507 if (!DolibarrApi::_checkAccessToResource('contact', $this->contact->id)) {
508 throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
509 }
510 if (!DolibarrApi::_checkAccessToResource('category', $category->id)) {
511 throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
512 }
513
514 $category->add_type($this->contact, 'contact');
515
516 return $this->_cleanObjectDatas($this->contact);
517 }
518
531 public function deleteCategory($id, $category_id)
532 {
533 if (!DolibarrApiAccess::$user->rights->societe->contact->creer) {
534 throw new RestException(401, 'Insufficient rights');
535 }
536
537 $result = $this->contact->fetch($id);
538 if (!$result) {
539 throw new RestException(404, 'Contact not found');
540 }
541 $category = new Categorie($this->db);
542 $result = $category->fetch($category_id);
543 if (!$result) {
544 throw new RestException(404, 'category not found');
545 }
546
547 if (!DolibarrApi::_checkAccessToResource('contact', $this->contact->id)) {
548 throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
549 }
550 if (!DolibarrApi::_checkAccessToResource('category', $category->id)) {
551 throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
552 }
553
554 $category->del_type($this->contact, 'contact');
555
556 return $this->_cleanObjectDatas($this->contact);
557 }
558
559 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
566 protected function _cleanObjectDatas($object)
567 {
568 // phpcs:enable
569 $object = parent::_cleanObjectDatas($object);
570
571 unset($object->total_ht);
572 unset($object->total_tva);
573 unset($object->total_localtax1);
574 unset($object->total_localtax2);
575 unset($object->total_ttc);
576
577 unset($object->note);
578 unset($object->lines);
579 unset($object->thirdparty);
580
581 return $object;
582 }
583
591 private function _validate($data)
592 {
593 $contact = array();
594 foreach (Contacts::$FIELDS as $field) {
595 if (!isset($data[$field])) {
596 throw new RestException(400, "$field field missing");
597 }
598 $contact[$field] = $data[$field];
599 }
600
601 return $contact;
602 }
603}
Class to manage categories.
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:31
_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:85
Class to manage Dolibarr users.
forgeSQLFromUniversalSearchCriteria($filter, &$errorstr='', $noand=0, $nopar=0, $noerror=0)
forgeSQLFromUniversalSearchCriteria
Contact()
Old copy.
Definition index.php:572