dolibarr 18.0.6
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
173 public function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $thirdparty_ids = '', $category = 0, $sqlfilters = '', $includecount = 0, $includeroles = 0)
174 {
175 global $db, $conf;
176
177 $obj_ret = array();
178
179 if (!DolibarrApiAccess::$user->rights->societe->contact->lire) {
180 throw new RestException(401, 'No permission to read contacts');
181 }
182
183 // case of external user, $thirdparty_ids param is ignored and replaced by user's socid
184 $socids = DolibarrApiAccess::$user->socid ? DolibarrApiAccess::$user->socid : $thirdparty_ids;
185
186 // If the internal user must only see his customers, force searching by him
187 $search_sale = 0;
188 if (!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) {
189 $search_sale = DolibarrApiAccess::$user->id;
190 }
191
192 $sql = "SELECT t.rowid";
193 $sql .= " FROM ".MAIN_DB_PREFIX."socpeople as t";
194 if ($category > 0) {
195 $sql .= ", ".MAIN_DB_PREFIX."categorie_contact as c";
196 }
197 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."socpeople_extrafields as te ON te.fk_object = t.rowid";
198 if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) {
199 // We need this table joined to the select in order to filter by sale
200 $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
201 }
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
208 if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) {
209 $sql .= " AND t.fk_soc = sc.fk_soc";
210 }
211 if ($search_sale > 0) {
212 $sql .= " AND s.rowid = sc.fk_soc"; // Join for the needed table to filter by sale
213 }
214 // Insert sale filter
215 if ($search_sale > 0) {
216 $sql .= " AND sc.fk_user = ".((int) $search_sale);
217 }
218
219 // Select contacts of given category
220 if ($category > 0) {
221 $sql .= " AND c.fk_categorie = ".((int) $category);
222 $sql .= " AND c.fk_socpeople = t.rowid ";
223 }
224
225 // Add sql filters
226 if ($sqlfilters) {
227 $errormessage = '';
228 $sql .= forgeSQLFromUniversalSearchCriteria($sqlfilters, $errormessage);
229 if ($errormessage) {
230 throw new RestException(400, 'Error when validating parameter sqlfilters -> '.$errormessage);
231 }
232 }
233
234 $sql .= $this->db->order($sortfield, $sortorder);
235
236 if ($limit) {
237 if ($page < 0) {
238 $page = 0;
239 }
240 $offset = $limit * $page;
241
242 $sql .= $this->db->plimit($limit + 1, $offset);
243 }
244 $result = $this->db->query($sql);
245 if ($result) {
246 $num = $this->db->num_rows($result);
247 $min = min($num, ($limit <= 0 ? $num : $limit));
248 $i = 0;
249 while ($i < $min) {
250 $obj = $this->db->fetch_object($result);
251 $contact_static = new Contact($this->db);
252 if ($contact_static->fetch($obj->rowid)) {
253 $contact_static->fetchRoles();
254 if ($includecount) {
255 $contact_static->load_ref_elements();
256 }
257 if ($includeroles) {
258 $contact_static->fetchRoles();
259 }
260 if (isModEnabled('mailing')) {
261 $contact_static->getNoEmail();
262 }
263
264 $obj_ret[] = $this->_cleanObjectDatas($contact_static);
265 }
266
267 $i++;
268 }
269 } else {
270 throw new RestException(503, 'Error when retrieve contacts : '.$sql);
271 }
272 if (!count($obj_ret)) {
273 throw new RestException(404, 'Contacts not found');
274 }
275 return $obj_ret;
276 }
277
284 public function post($request_data = null)
285 {
286 if (!DolibarrApiAccess::$user->rights->societe->contact->creer) {
287 throw new RestException(401, 'No permission to create/update contacts');
288 }
289 // Check mandatory fields
290 $result = $this->_validate($request_data);
291
292 foreach ($request_data as $field => $value) {
293 $this->contact->$field = $value;
294 }
295 if ($this->contact->create(DolibarrApiAccess::$user) < 0) {
296 throw new RestException(500, "Error creating contact", array_merge(array($this->contact->error), $this->contact->errors));
297 }
298 if (isModEnabled('mailing') && !empty($this->contact->email) && isset($this->contact->no_email)) {
299 $this->contact->setNoEmail($this->contact->no_email);
300 }
301 return $this->contact->id;
302 }
303
314 public function put($id, $request_data = null)
315 {
316 if (!DolibarrApiAccess::$user->rights->societe->contact->creer) {
317 throw new RestException(401, 'No permission to create/update contacts');
318 }
319
320 $result = $this->contact->fetch($id);
321 if (!$result) {
322 throw new RestException(404, 'Contact not found');
323 }
324
325 if (!DolibarrApi::_checkAccessToResource('contact', $this->contact->id, 'socpeople&societe')) {
326 throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
327 }
328
329 foreach ($request_data as $field => $value) {
330 if ($field == 'id') {
331 continue;
332 } elseif ($field == 'array_options' && is_array($value)) {
333 foreach ($value as $index => $val) {
334 $this->contact->array_options[$index] = $val;
335 }
336 } else {
337 $this->contact->$field = $value;
338 }
339 }
340
341 if (isModEnabled('mailing') && !empty($this->contact->email) && isset($this->contact->no_email)) {
342 $this->contact->setNoEmail($this->contact->no_email);
343 }
344
345 if ($this->contact->update($id, DolibarrApiAccess::$user, 0, 'update') > 0) {
346 return $this->get($id);
347 } else {
348 throw new RestException(500, $this->contact->error);
349 }
350 }
351
358 public function delete($id)
359 {
360 if (!DolibarrApiAccess::$user->rights->societe->contact->supprimer) {
361 throw new RestException(401, 'No permission to delete contacts');
362 }
363 $result = $this->contact->fetch($id);
364 if (!$result) {
365 throw new RestException(404, 'Contact not found');
366 }
367
368 if (!DolibarrApi::_checkAccessToResource('contact', $this->contact->id, 'socpeople&societe')) {
369 throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
370 }
371 $this->contact->oldcopy = clone $this->contact;
372
373 if ($this->contact->delete() <= 0) {
374 throw new RestException(500, 'Error when delete contact ' . $this->contact->error);
375 }
376
377 return array(
378 'success' => array(
379 'code' => 200,
380 'message' => 'Contact deleted'
381 )
382 );
383 }
384
394 public function createUser($id, $request_data = null)
395 {
396 //if (!DolibarrApiAccess::$user->hasRight('user', 'user', 'creer')) {
397 //throw new RestException(401);
398 //}
399
400 if (!isset($request_data["login"])) {
401 throw new RestException(400, "login field missing");
402 }
403 if (!isset($request_data["password"])) {
404 throw new RestException(400, "password field missing");
405 }
406
407 if (!DolibarrApiAccess::$user->rights->societe->contact->lire) {
408 throw new RestException(401, 'No permission to read contacts');
409 }
410 if (!DolibarrApiAccess::$user->hasRight('user', 'user', 'creer')) {
411 throw new RestException(401, 'No permission to create user');
412 }
413
414 $contact = new Contact($this->db);
415 $contact->fetch($id);
416 if ($contact->id <= 0) {
417 throw new RestException(404, 'Contact not found');
418 }
419
420 if (!DolibarrApi::_checkAccessToResource('contact', $contact->id, 'socpeople&societe')) {
421 throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
422 }
423
424 // Check mandatory fields
425 $login = $request_data["login"];
426 $password = $request_data["password"];
427 $useraccount = new User($this->db);
428 $result = $useraccount->create_from_contact($contact, $login, $password);
429 if ($result <= 0) {
430 throw new RestException(500, "User not created");
431 }
432 // password parameter not used in create_from_contact
433 $useraccount->setPassword($useraccount, $password);
434
435 return $result;
436 }
437
451 public function getCategories($id, $sortfield = "s.rowid", $sortorder = 'ASC', $limit = 0, $page = 0)
452 {
453 if (!DolibarrApiAccess::$user->rights->categorie->lire) {
454 throw new RestException(401);
455 }
456
457 $categories = new Categorie($this->db);
458
459 $result = $categories->getListForItem($id, 'contact', $sortfield, $sortorder, $limit, $page);
460
461 if (empty($result)) {
462 throw new RestException(404, 'No category found');
463 }
464
465 if ($result < 0) {
466 throw new RestException(503, 'Error when retrieve category list : '.$categories->error);
467 }
468
469 return $result;
470 }
471
485 public function addCategory($id, $category_id)
486 {
487 if (!DolibarrApiAccess::$user->rights->societe->contact->creer) {
488 throw new RestException(401, 'Insufficient rights');
489 }
490
491 $result = $this->contact->fetch($id);
492 if (!$result) {
493 throw new RestException(404, 'Contact not found');
494 }
495 $category = new Categorie($this->db);
496 $result = $category->fetch($category_id);
497 if (!$result) {
498 throw new RestException(404, 'category not found');
499 }
500
501 if (!DolibarrApi::_checkAccessToResource('contact', $this->contact->id)) {
502 throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
503 }
504 if (!DolibarrApi::_checkAccessToResource('category', $category->id)) {
505 throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
506 }
507
508 $category->add_type($this->contact, 'contact');
509
510 return $this->_cleanObjectDatas($this->contact);
511 }
512
525 public function deleteCategory($id, $category_id)
526 {
527 if (!DolibarrApiAccess::$user->rights->societe->contact->creer) {
528 throw new RestException(401, 'Insufficient rights');
529 }
530
531 $result = $this->contact->fetch($id);
532 if (!$result) {
533 throw new RestException(404, 'Contact not found');
534 }
535 $category = new Categorie($this->db);
536 $result = $category->fetch($category_id);
537 if (!$result) {
538 throw new RestException(404, 'category not found');
539 }
540
541 if (!DolibarrApi::_checkAccessToResource('contact', $this->contact->id)) {
542 throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
543 }
544 if (!DolibarrApi::_checkAccessToResource('category', $category->id)) {
545 throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
546 }
547
548 $category->del_type($this->contact, 'contact');
549
550 return $this->_cleanObjectDatas($this->contact);
551 }
552
553 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
560 protected function _cleanObjectDatas($object)
561 {
562 // phpcs:enable
563 $object = parent::_cleanObjectDatas($object);
564
565 unset($object->total_ht);
566 unset($object->total_tva);
567 unset($object->total_localtax1);
568 unset($object->total_localtax2);
569 unset($object->total_ttc);
570
571 unset($object->note);
572 unset($object->lines);
573 unset($object->thirdparty);
574
575 return $object;
576 }
577
585 private function _validate($data)
586 {
587 $contact = array();
588 foreach (Contacts::$FIELDS as $field) {
589 if (!isset($data[$field])) {
590 throw new RestException(400, "$field field missing");
591 }
592 $contact[$field] = $data[$field];
593 }
594
595 return $contact;
596 }
597}
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.
index($sortfield="t.rowid", $sortorder='ASC', $limit=100, $page=0, $thirdparty_ids='', $category=0, $sqlfilters='', $includecount=0, $includeroles=0)
List contacts.
_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.
Class for API REST v1.
Definition api.class.php:31
static _checkAccessToResource($resource, $resource_id=0, $dbtablename='', $feature2='', $dbt_keyfield='fk_soc', $dbt_select='rowid')
Check access by user to a given resource.
Class to manage Dolibarr users.
forgeSQLFromUniversalSearchCriteria($filter, &$errorstr='', $noand=0, $nopar=0, $noerror=0)
forgeSQLFromUniversalSearchCriteria