dolibarr  16.0.5
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 
19 use 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 
31 class 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  return $this->_cleanObjectDatas($this->contact);
101  }
102 
116  public function getByEmail($email, $includecount = 0, $includeroles = 0)
117  {
118  if (!DolibarrApiAccess::$user->rights->societe->contact->lire) {
119  throw new RestException(401, 'No permission to read contacts');
120  }
121 
122  if (empty($email)) {
123  $result = $this->contact->initAsSpecimen();
124  } else {
125  $result = $this->contact->fetch('', '', '', $email);
126  }
127 
128  if (!$result) {
129  throw new RestException(404, 'Contact not found');
130  }
131 
132  if (!DolibarrApi::_checkAccessToResource('contact', $this->contact->id, 'socpeople&societe')) {
133  throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
134  }
135 
136  if ($includecount) {
137  $this->contact->load_ref_elements();
138  }
139 
140  if ($includeroles) {
141  $this->contact->fetchRoles();
142  }
143 
144  return $this->_cleanObjectDatas($this->contact);
145  }
146 
165  public function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $thirdparty_ids = '', $category = 0, $sqlfilters = '', $includecount = 0, $includeroles = 0)
166  {
167  global $db, $conf;
168 
169  $obj_ret = array();
170 
171  if (!DolibarrApiAccess::$user->rights->societe->contact->lire) {
172  throw new RestException(401, 'No permission to read contacts');
173  }
174 
175  // case of external user, $thirdparty_ids param is ignored and replaced by user's socid
176  $socids = DolibarrApiAccess::$user->socid ? DolibarrApiAccess::$user->socid : $thirdparty_ids;
177 
178  // If the internal user must only see his customers, force searching by him
179  $search_sale = 0;
180  if (!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) {
181  $search_sale = DolibarrApiAccess::$user->id;
182  }
183 
184  $sql = "SELECT t.rowid";
185  $sql .= " FROM ".MAIN_DB_PREFIX."socpeople as t";
186  if ($category > 0) {
187  $sql .= ", ".MAIN_DB_PREFIX."categorie_contact as c";
188  }
189  $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."socpeople_extrafields as te ON te.fk_object = t.rowid";
190  if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) {
191  // We need this table joined to the select in order to filter by sale
192  $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
193  }
194  $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON t.fk_soc = s.rowid";
195  $sql .= ' WHERE t.entity IN ('.getEntity('contact').')';
196  if ($socids) {
197  $sql .= " AND t.fk_soc IN (".$this->db->sanitize($socids).")";
198  }
199 
200  if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) {
201  $sql .= " AND t.fk_soc = sc.fk_soc";
202  }
203  if ($search_sale > 0) {
204  $sql .= " AND s.rowid = sc.fk_soc"; // Join for the needed table to filter by sale
205  }
206  // Insert sale filter
207  if ($search_sale > 0) {
208  $sql .= " AND sc.fk_user = ".((int) $search_sale);
209  }
210 
211  // Select contacts of given category
212  if ($category > 0) {
213  $sql .= " AND c.fk_categorie = ".((int) $category);
214  $sql .= " AND c.fk_socpeople = t.rowid ";
215  }
216 
217  // Add sql filters
218  if ($sqlfilters) {
219  $errormessage = '';
220  if (!DolibarrApi::_checkFilters($sqlfilters, $errormessage)) {
221  throw new RestException(503, 'Error when validating parameter sqlfilters -> '.$errormessage);
222  }
223  $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^\(\)]+)\)';
224  $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")";
225  }
226 
227  $sql .= $this->db->order($sortfield, $sortorder);
228 
229  if ($limit) {
230  if ($page < 0) {
231  $page = 0;
232  }
233  $offset = $limit * $page;
234 
235  $sql .= $this->db->plimit($limit + 1, $offset);
236  }
237  $result = $this->db->query($sql);
238  if ($result) {
239  $num = $this->db->num_rows($result);
240  $min = min($num, ($limit <= 0 ? $num : $limit));
241  $i = 0;
242  while ($i < $min) {
243  $obj = $this->db->fetch_object($result);
244  $contact_static = new Contact($this->db);
245  if ($contact_static->fetch($obj->rowid)) {
246  $contact_static->fetchRoles();
247  if ($includecount) {
248  $contact_static->load_ref_elements();
249  }
250  if ($includeroles) {
251  $contact_static->fetchRoles();
252  }
253 
254  $obj_ret[] = $this->_cleanObjectDatas($contact_static);
255  }
256 
257  $i++;
258  }
259  } else {
260  throw new RestException(503, 'Error when retrieve contacts : '.$sql);
261  }
262  if (!count($obj_ret)) {
263  throw new RestException(404, 'Contacts not found');
264  }
265  return $obj_ret;
266  }
267 
274  public function post($request_data = null)
275  {
276  if (!DolibarrApiAccess::$user->rights->societe->contact->creer) {
277  throw new RestException(401, 'No permission to create/update contacts');
278  }
279  // Check mandatory fields
280  $result = $this->_validate($request_data);
281 
282  foreach ($request_data as $field => $value) {
283  $this->contact->$field = $value;
284  }
285  if ($this->contact->create(DolibarrApiAccess::$user) < 0) {
286  throw new RestException(500, "Error creating contact", array_merge(array($this->contact->error), $this->contact->errors));
287  }
288  return $this->contact->id;
289  }
290 
298  public function put($id, $request_data = null)
299  {
300  if (!DolibarrApiAccess::$user->rights->societe->contact->creer) {
301  throw new RestException(401, 'No permission to create/update contacts');
302  }
303 
304  $result = $this->contact->fetch($id);
305  if (!$result) {
306  throw new RestException(404, 'Contact not found');
307  }
308 
309  if (!DolibarrApi::_checkAccessToResource('contact', $this->contact->id, 'socpeople&societe')) {
310  throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
311  }
312 
313  foreach ($request_data as $field => $value) {
314  if ($field == 'id') {
315  continue;
316  }
317  $this->contact->$field = $value;
318  }
319 
320  if ($this->contact->update($id, DolibarrApiAccess::$user, 1, '', '', 'update')) {
321  return $this->get($id);
322  }
323 
324  return false;
325  }
326 
333  public function delete($id)
334  {
335  if (!DolibarrApiAccess::$user->rights->societe->contact->supprimer) {
336  throw new RestException(401, 'No permission to delete contacts');
337  }
338  $result = $this->contact->fetch($id);
339  if (!$result) {
340  throw new RestException(404, 'Contact not found');
341  }
342 
343  if (!DolibarrApi::_checkAccessToResource('contact', $this->contact->id, 'socpeople&societe')) {
344  throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
345  }
346  $this->contact->oldcopy = clone $this->contact;
347  return $this->contact->delete();
348  }
349 
359  public function createUser($id, $request_data = null)
360  {
361  //if (!DolibarrApiAccess::$user->rights->user->user->creer) {
362  //throw new RestException(401);
363  //}
364 
365  if (!isset($request_data["login"])) {
366  throw new RestException(400, "login field missing");
367  }
368  if (!isset($request_data["password"])) {
369  throw new RestException(400, "password field missing");
370  }
371 
372  if (!DolibarrApiAccess::$user->rights->societe->contact->lire) {
373  throw new RestException(401, 'No permission to read contacts');
374  }
375  if (!DolibarrApiAccess::$user->rights->user->user->creer) {
376  throw new RestException(401, 'No permission to create user');
377  }
378 
379  $contact = new Contact($this->db);
380  $contact->fetch($id);
381  if ($contact->id <= 0) {
382  throw new RestException(404, 'Contact not found');
383  }
384 
385  if (!DolibarrApi::_checkAccessToResource('contact', $contact->id, 'socpeople&societe')) {
386  throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
387  }
388 
389  // Check mandatory fields
390  $login = $request_data["login"];
391  $password = $request_data["password"];
392  $useraccount = new User($this->db);
393  $result = $useraccount->create_from_contact($contact, $login, $password);
394  if ($result <= 0) {
395  throw new RestException(500, "User not created");
396  }
397  // password parameter not used in create_from_contact
398  $useraccount->setPassword($useraccount, $password);
399 
400  return $result;
401  }
402 
416  public function getCategories($id, $sortfield = "s.rowid", $sortorder = 'ASC', $limit = 0, $page = 0)
417  {
418  if (!DolibarrApiAccess::$user->rights->categorie->lire) {
419  throw new RestException(401);
420  }
421 
422  $categories = new Categorie($this->db);
423 
424  $result = $categories->getListForItem($id, 'contact', $sortfield, $sortorder, $limit, $page);
425 
426  if (empty($result)) {
427  throw new RestException(404, 'No category found');
428  }
429 
430  if ($result < 0) {
431  throw new RestException(503, 'Error when retrieve category list : '.$categories->error);
432  }
433 
434  return $result;
435  }
436 
450  public function addCategory($id, $category_id)
451  {
452  if (!DolibarrApiAccess::$user->rights->societe->contact->creer) {
453  throw new RestException(401, 'Insufficient rights');
454  }
455 
456  $result = $this->contact->fetch($id);
457  if (!$result) {
458  throw new RestException(404, 'Contact not found');
459  }
460  $category = new Categorie($this->db);
461  $result = $category->fetch($category_id);
462  if (!$result) {
463  throw new RestException(404, 'category not found');
464  }
465 
466  if (!DolibarrApi::_checkAccessToResource('contact', $this->contact->id)) {
467  throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
468  }
469  if (!DolibarrApi::_checkAccessToResource('category', $category->id)) {
470  throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
471  }
472 
473  $category->add_type($this->contact, 'contact');
474 
475  return $this->_cleanObjectDatas($this->contact);
476  }
477 
490  public function deleteCategory($id, $category_id)
491  {
492  if (!DolibarrApiAccess::$user->rights->societe->contact->creer) {
493  throw new RestException(401, 'Insufficient rights');
494  }
495 
496  $result = $this->contact->fetch($id);
497  if (!$result) {
498  throw new RestException(404, 'Contact not found');
499  }
500  $category = new Categorie($this->db);
501  $result = $category->fetch($category_id);
502  if (!$result) {
503  throw new RestException(404, 'category not found');
504  }
505 
506  if (!DolibarrApi::_checkAccessToResource('contact', $this->contact->id)) {
507  throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
508  }
509  if (!DolibarrApi::_checkAccessToResource('category', $category->id)) {
510  throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
511  }
512 
513  $category->del_type($this->contact, 'contact');
514 
515  return $this->_cleanObjectDatas($this->contact);
516  }
517 
518  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
525  protected function _cleanObjectDatas($object)
526  {
527  // phpcs:enable
528  $object = parent::_cleanObjectDatas($object);
529 
530  unset($object->total_ht);
531  unset($object->total_tva);
532  unset($object->total_localtax1);
533  unset($object->total_localtax2);
534  unset($object->total_ttc);
535 
536  unset($object->note);
537  unset($object->lines);
538  unset($object->thirdparty);
539 
540  return $object;
541  }
542 
550  private function _validate($data)
551  {
552  $contact = array();
553  foreach (Contacts::$FIELDS as $field) {
554  if (!isset($data[$field])) {
555  throw new RestException(400, "$field field missing");
556  }
557  $contact[$field] = $data[$field];
558  }
559 
560  return $contact;
561  }
562 }
Contacts\getCategories
getCategories($id, $sortfield="s.rowid", $sortorder='ASC', $limit=0, $page=0)
Get categories for a contact.
Definition: api_contacts.class.php:416
db
$conf db
API class for accounts.
Definition: inc.php:41
Contacts\index
index($sortfield="t.rowid", $sortorder='ASC', $limit=100, $page=0, $thirdparty_ids='', $category=0, $sqlfilters='', $includecount=0, $includeroles=0)
List contacts.
Definition: api_contacts.class.php:165
DolibarrApi\_checkAccessToResource
static _checkAccessToResource($resource, $resource_id=0, $dbtablename='', $feature2='', $dbt_keyfield='fk_soc', $dbt_select='rowid')
Check access by user to a given resource.
Definition: api.class.php:283
Categorie
Class to manage categories.
Definition: categorie.class.php:47
DolibarrApi
Class for API REST v1.
Definition: api.class.php:30
Contacts\deleteCategory
deleteCategory($id, $category_id)
Remove the link between a category and a contact.
Definition: api_contacts.class.php:490
Contacts\post
post($request_data=null)
Create contact object.
Definition: api_contacts.class.php:274
DolibarrApi\_checkFilters
_checkFilters($sqlfilters, &$error='')
Return if a $sqlfilters parameter is valid.
Definition: api.class.php:310
Contact
Class to manage contact/addresses.
Definition: contact.class.php:40
Contacts
Definition: api_contacts.class.php:31
Contacts\_validate
_validate($data)
Validate fields before create or update object.
Definition: api_contacts.class.php:550
Contacts\getByEmail
getByEmail($email, $includecount=0, $includeroles=0)
Get properties of a contact object by Email.
Definition: api_contacts.class.php:116
Contacts\put
put($id, $request_data=null)
Update contact.
Definition: api_contacts.class.php:298
User
Class to manage Dolibarr users.
Definition: user.class.php:44
Contacts\createUser
createUser($id, $request_data=null)
Create an user account object from contact (external user)
Definition: api_contacts.class.php:359
Contacts\_cleanObjectDatas
_cleanObjectDatas($object)
Clean sensible object datas.
Definition: api_contacts.class.php:525
Contacts\addCategory
addCategory($id, $category_id)
Add a category to a contact.
Definition: api_contacts.class.php:450
Contacts\__construct
__construct()
Constructor.
Definition: api_contacts.class.php:49