dolibarr  13.0.2
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  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  {
76  throw new RestException(401, 'No permission to read contacts');
77  }
78  if ($id == 0) {
79  $result = $this->contact->initAsSpecimen();
80  } else {
81  $result = $this->contact->fetch($id);
82  }
83 
84  if (!$result)
85  {
86  throw new RestException(404, 'Contact not found');
87  }
88 
89  if (!DolibarrApi::_checkAccessToResource('contact', $this->contact->id, 'socpeople&societe'))
90  {
91  throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
92  }
93 
94  if ($includecount)
95  {
96  $this->contact->load_ref_elements();
97  }
98 
99  if ($includeroles)
100  {
101  $this->contact->fetchRoles();
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  {
124  throw new RestException(401, 'No permission to read contacts');
125  }
126  if (empty($email)) {
127  $result = $this->contact->initAsSpecimen();
128  } else {
129  $result = $this->contact->fetch('', '', '', $email);
130  }
131 
132  if (!$result)
133  {
134  throw new RestException(404, 'Contact not found');
135  }
136 
137  if (!DolibarrApi::_checkAccessToResource('contact', $this->contact->id, 'socpeople&societe'))
138  {
139  throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
140  }
141 
142  if ($includecount)
143  {
144  $this->contact->load_ref_elements();
145  }
146 
147  if ($includeroles)
148  {
149  $this->contact->fetchRoles();
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  {
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  $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('socpeople').')';
204  if ($socids) $sql .= " AND t.fk_soc IN (".$socids.")";
205 
206  if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0)
207  $sql .= " AND t.fk_soc = sc.fk_soc";
208  if ($search_sale > 0)
209  $sql .= " AND s.rowid = sc.fk_soc"; // Join for the needed table to filter by sale
210  // Insert sale filter
211  if ($search_sale > 0)
212  {
213  $sql .= " AND sc.fk_user = ".$search_sale;
214  }
215 
216  // Select contacts of given category
217  if ($category > 0) {
218  $sql .= " AND c.fk_categorie = ".$this->db->escape($category);
219  $sql .= " AND c.fk_socpeople = t.rowid ";
220  }
221 
222  // Add sql filters
223  if ($sqlfilters)
224  {
225  if (!DolibarrApi::_checkFilters($sqlfilters))
226  {
227  throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters);
228  }
229  $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)';
230  $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")";
231  }
232 
233  $sql .= $this->db->order($sortfield, $sortorder);
234 
235  if ($limit)
236  {
237  if ($page < 0)
238  {
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  {
248  $num = $this->db->num_rows($result);
249  $min = min($num, ($limit <= 0 ? $num : $limit));
250  $i = 0;
251  while ($i < $min)
252  {
253  $obj = $this->db->fetch_object($result);
254  $contact_static = new Contact($this->db);
255  if ($contact_static->fetch($obj->rowid))
256  {
257  $contact_static->fetchRoles();
258  if ($includecount)
259  {
260  $contact_static->load_ref_elements();
261  }
262  if ($includeroles)
263  {
264  $contact_static->fetchRoles();
265  }
266 
267  $obj_ret[] = $this->_cleanObjectDatas($contact_static);
268  }
269 
270  $i++;
271  }
272  } else {
273  throw new RestException(503, 'Error when retrieve contacts : '.$sql);
274  }
275  if (!count($obj_ret))
276  {
277  throw new RestException(404, 'Contacts not found');
278  }
279  return $obj_ret;
280  }
281 
288  public function post($request_data = null)
289  {
290  if (!DolibarrApiAccess::$user->rights->societe->contact->creer)
291  {
292  throw new RestException(401, 'No permission to create/update contacts');
293  }
294  // Check mandatory fields
295  $result = $this->_validate($request_data);
296 
297  foreach ($request_data as $field => $value)
298  {
299  $this->contact->$field = $value;
300  }
301  if ($this->contact->create(DolibarrApiAccess::$user) < 0) {
302  throw new RestException(500, "Error creating contact", array_merge(array($this->contact->error), $this->contact->errors));
303  }
304  return $this->contact->id;
305  }
306 
314  public function put($id, $request_data = null)
315  {
316  if (!DolibarrApiAccess::$user->rights->societe->contact->creer)
317  {
318  throw new RestException(401, 'No permission to create/update contacts');
319  }
320 
321  $result = $this->contact->fetch($id);
322  if (!$result)
323  {
324  throw new RestException(404, 'Contact not found');
325  }
326 
327  if (!DolibarrApi::_checkAccessToResource('contact', $this->contact->id, 'socpeople&societe'))
328  {
329  throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
330  }
331 
332  foreach ($request_data as $field => $value)
333  {
334  if ($field == 'id') continue;
335  $this->contact->$field = $value;
336  }
337 
338  if ($this->contact->update($id, DolibarrApiAccess::$user, 1, '', '', 'update'))
339  return $this->get($id);
340 
341  return false;
342  }
343 
350  public function delete($id)
351  {
352  if (!DolibarrApiAccess::$user->rights->societe->contact->supprimer)
353  {
354  throw new RestException(401, 'No permission to delete contacts');
355  }
356  $result = $this->contact->fetch($id);
357  if (!$result)
358  {
359  throw new RestException(404, 'Contact not found');
360  }
361 
362  if (!DolibarrApi::_checkAccessToResource('contact', $this->contact->id, 'socpeople&societe'))
363  {
364  throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
365  }
366  $this->contact->oldcopy = clone $this->contact;
367  return $this->contact->delete();
368  }
369 
379  public function createUser($id, $request_data = null)
380  {
381  //if (!DolibarrApiAccess::$user->rights->user->user->creer) {
382  //throw new RestException(401);
383  //}
384 
385  if (!isset($request_data["login"]))
386  throw new RestException(400, "login field missing");
387  if (!isset($request_data["password"]))
388  throw new RestException(400, "password field missing");
389 
390  if (!DolibarrApiAccess::$user->rights->societe->contact->lire) {
391  throw new RestException(401, 'No permission to read contacts');
392  }
393  if (!DolibarrApiAccess::$user->rights->user->user->creer) {
394  throw new RestException(401, 'No permission to create user');
395  }
396 
397  $contact = new Contact($this->db);
398  $contact->fetch($id);
399  if ($contact->id <= 0) {
400  throw new RestException(404, 'Contact not found');
401  }
402 
403  if (!DolibarrApi::_checkAccessToResource('contact', $contact->id, 'socpeople&societe')) {
404  throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
405  }
406 
407  // Check mandatory fields
408  $login = $request_data["login"];
409  $password = $request_data["password"];
410  $useraccount = new User($this->db);
411  $result = $useraccount->create_from_contact($contact, $login, $password);
412  if ($result <= 0) {
413  throw new RestException(500, "User not created");
414  }
415  // password parameter not used in create_from_contact
416  $useraccount->setPassword($useraccount, $password);
417 
418  return $result;
419  }
420 
434  public function getCategories($id, $sortfield = "s.rowid", $sortorder = 'ASC', $limit = 0, $page = 0)
435  {
436  if (!DolibarrApiAccess::$user->rights->categorie->lire) {
437  throw new RestException(401);
438  }
439 
440  $categories = new Categorie($this->db);
441 
442  $result = $categories->getListForItem($id, 'contact', $sortfield, $sortorder, $limit, $page);
443 
444  if (empty($result)) {
445  throw new RestException(404, 'No category found');
446  }
447 
448  if ($result < 0) {
449  throw new RestException(503, 'Error when retrieve category list : '.$categories->error);
450  }
451 
452  return $result;
453  }
454 
468  public function addCategory($id, $category_id)
469  {
470  if (!DolibarrApiAccess::$user->rights->societe->contact->creer) {
471  throw new RestException(401, 'Insufficient rights');
472  }
473 
474  $result = $this->contact->fetch($id);
475  if (!$result) {
476  throw new RestException(404, 'Contact not found');
477  }
478  $category = new Categorie($this->db);
479  $result = $category->fetch($category_id);
480  if (!$result) {
481  throw new RestException(404, 'category not found');
482  }
483 
484  if (!DolibarrApi::_checkAccessToResource('contact', $this->contact->id)) {
485  throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
486  }
487  if (!DolibarrApi::_checkAccessToResource('category', $category->id)) {
488  throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
489  }
490 
491  $category->add_type($this->contact, 'contact');
492 
493  return $this->_cleanObjectDatas($this->contact);
494  }
495 
508  public function deleteCategory($id, $category_id)
509  {
510  if (!DolibarrApiAccess::$user->rights->societe->contact->creer) {
511  throw new RestException(401, 'Insufficient rights');
512  }
513 
514  $result = $this->contact->fetch($id);
515  if (!$result) {
516  throw new RestException(404, 'Contact not found');
517  }
518  $category = new Categorie($this->db);
519  $result = $category->fetch($category_id);
520  if (!$result) {
521  throw new RestException(404, 'category not found');
522  }
523 
524  if (!DolibarrApi::_checkAccessToResource('contact', $this->contact->id)) {
525  throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
526  }
527  if (!DolibarrApi::_checkAccessToResource('category', $category->id)) {
528  throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
529  }
530 
531  $category->del_type($this->contact, 'contact');
532 
533  return $this->_cleanObjectDatas($this->contact);
534  }
535 
536  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
543  protected function _cleanObjectDatas($object)
544  {
545  // phpcs:enable
546  $object = parent::_cleanObjectDatas($object);
547 
548  unset($object->total_ht);
549  unset($object->total_tva);
550  unset($object->total_localtax1);
551  unset($object->total_localtax2);
552  unset($object->total_ttc);
553 
554  unset($object->note);
555  unset($object->lines);
556  unset($object->thirdparty);
557 
558  return $object;
559  }
560 
568  private function _validate($data)
569  {
570  $contact = array();
571  foreach (Contacts::$FIELDS as $field) {
572  if (!isset($data[$field])) {
573  throw new RestException(400, "$field field missing");
574  }
575  $contact[$field] = $data[$field];
576  }
577 
578  return $contact;
579  }
580 }
_cleanObjectDatas($object)
Clean sensible object datas.
Class to manage contact/addresses.
Class to manage Dolibarr users.
Definition: user.class.php:44
_validate($data)
Validate fields before create or update object.
$conf db
API class for accounts.
Definition: inc.php:54
_checkFilters($sqlfilters)
Return if a $sqlfilters parameter is valid.
Definition: api.class.php:278
Class for API REST v1.
Definition: api.class.php:30
post($request_data=null)
Create contact object.
Class to manage categories.
getByEmail($email, $includecount=0, $includeroles=0)
Get properties of a contact object by Email.
put($id, $request_data=null)
Update contact.
deleteCategory($id, $category_id)
Remove the link between a category and a contact.
static _checkAccessToResource($resource, $resource_id=0, $dbtablename= '', $feature2= '', $dbt_keyfield= 'fk_soc', $dbt_select= 'rowid')
Check user access to a resource.
Definition: api.class.php:252
index($sortfield="t.rowid", $sortorder= 'ASC', $limit=100, $page=0, $thirdparty_ids= '', $category=0, $sqlfilters= '', $includecount=0, $includeroles=0)
List contacts.
getCategories($id, $sortfield="s.rowid", $sortorder= 'ASC', $limit=0, $page=0)
Get categories for a contact.
__construct()
Constructor.
addCategory($id, $category_id)
Add a category to a contact.
createUser($id, $request_data=null)
Create an user account object from contact (external user)