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
393 if ($this->contact->delete(DolibarrApiAccess::$user) <= 0) {
394 throw new RestException(500, 'Error when delete contact ' . $this->contact->error);
395 }
396
397 return array(
398 'success' => array(
399 'code' => 200,
400 'message' => 'Contact deleted'
401 )
402 );
403 }
404
414 public function createUser($id, $request_data = null)
415 {
416 //if (!DolibarrApiAccess::$user->hasRight('user', 'user', 'creer')) {
417 //throw new RestException(401);
418 //}
419
420 if (!isset($request_data["login"])) {
421 throw new RestException(400, "login field missing");
422 }
423 if (!isset($request_data["password"])) {
424 throw new RestException(400, "password field missing");
425 }
426
427 if (!DolibarrApiAccess::$user->rights->societe->contact->lire) {
428 throw new RestException(401, 'No permission to read contacts');
429 }
430 if (!DolibarrApiAccess::$user->hasRight('user', 'user', 'creer')) {
431 throw new RestException(401, 'No permission to create user');
432 }
433
434 $contact = new Contact($this->db);
435 $contact->fetch($id);
436 if ($contact->id <= 0) {
437 throw new RestException(404, 'Contact not found');
438 }
439
440 if (!DolibarrApi::_checkAccessToResource('contact', $contact->id, 'socpeople&societe')) {
441 throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
442 }
443
444 // Check mandatory fields
445 $login = $request_data["login"];
446 $password = $request_data["password"];
447 $useraccount = new User($this->db);
448 $result = $useraccount->create_from_contact($contact, $login, $password);
449 if ($result <= 0) {
450 throw new RestException(500, "User not created");
451 }
452 // password parameter not used in create_from_contact
453 $useraccount->setPassword($useraccount, $password);
454
455 return $result;
456 }
457
471 public function getCategories($id, $sortfield = "s.rowid", $sortorder = 'ASC', $limit = 0, $page = 0)
472 {
473 if (!DolibarrApiAccess::$user->rights->categorie->lire) {
474 throw new RestException(401);
475 }
476
477 $categories = new Categorie($this->db);
478
479 $result = $categories->getListForItem($id, 'contact', $sortfield, $sortorder, $limit, $page);
480
481 if ($result < 0) {
482 throw new RestException(503, 'Error when retrieve category list : '.$categories->error);
483 }
484
485 return $result;
486 }
487
501 public function addCategory($id, $category_id)
502 {
503 if (!DolibarrApiAccess::$user->rights->societe->contact->creer) {
504 throw new RestException(401, 'Insufficient rights');
505 }
506
507 $result = $this->contact->fetch($id);
508 if (!$result) {
509 throw new RestException(404, 'Contact not found');
510 }
511 $category = new Categorie($this->db);
512 $result = $category->fetch($category_id);
513 if (!$result) {
514 throw new RestException(404, 'category not found');
515 }
516
517 if (!DolibarrApi::_checkAccessToResource('contact', $this->contact->id)) {
518 throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
519 }
520 if (!DolibarrApi::_checkAccessToResource('category', $category->id)) {
521 throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
522 }
523
524 $category->add_type($this->contact, 'contact');
525
526 return $this->_cleanObjectDatas($this->contact);
527 }
528
541 public function deleteCategory($id, $category_id)
542 {
543 if (!DolibarrApiAccess::$user->rights->societe->contact->creer) {
544 throw new RestException(401, 'Insufficient rights');
545 }
546
547 $result = $this->contact->fetch($id);
548 if (!$result) {
549 throw new RestException(404, 'Contact not found');
550 }
551 $category = new Categorie($this->db);
552 $result = $category->fetch($category_id);
553 if (!$result) {
554 throw new RestException(404, 'category not found');
555 }
556
557 if (!DolibarrApi::_checkAccessToResource('contact', $this->contact->id)) {
558 throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
559 }
560 if (!DolibarrApi::_checkAccessToResource('category', $category->id)) {
561 throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
562 }
563
564 $category->del_type($this->contact, 'contact');
565
566 return $this->_cleanObjectDatas($this->contact);
567 }
568
569 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
576 protected function _cleanObjectDatas($object)
577 {
578 // phpcs:enable
579 $object = parent::_cleanObjectDatas($object);
580
581 unset($object->total_ht);
582 unset($object->total_tva);
583 unset($object->total_localtax1);
584 unset($object->total_localtax2);
585 unset($object->total_ttc);
586
587 unset($object->note);
588 unset($object->lines);
589 unset($object->thirdparty);
590
591 return $object;
592 }
593
601 private function _validate($data)
602 {
603 $contact = array();
604 foreach (Contacts::$FIELDS as $field) {
605 if (!isset($data[$field])) {
606 throw new RestException(400, "$field field missing");
607 }
608 $contact[$field] = $data[$field];
609 }
610
611 return $contact;
612 }
613}
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