api_contacts.class.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600
  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. use Luracast\Restler\RestException;
  19. //require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
  20. //require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
  21. /**
  22. * API class for contacts
  23. *
  24. * @access protected
  25. * @class DolibarrApiAccess {@requires user,external}
  26. */
  27. class Contacts extends DolibarrApi
  28. {
  29. /**
  30. *
  31. * @var array $FIELDS Mandatory fields, checked when create and update object
  32. */
  33. public static $FIELDS = array(
  34. 'lastname',
  35. );
  36. /**
  37. * @var Contact $contact {@type Contact}
  38. */
  39. public $contact;
  40. /**
  41. * Constructor
  42. */
  43. public function __construct()
  44. {
  45. global $db, $conf;
  46. $this->db = $db;
  47. require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
  48. require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
  49. $this->contact = new Contact($this->db);
  50. }
  51. /**
  52. * Get properties of a contact object
  53. *
  54. * Return an array with contact informations
  55. *
  56. * @param int $id ID of contact
  57. * @param int $includecount Count and return also number of elements the contact is used as a link for
  58. * @param int $includeroles Includes roles of the contact
  59. * @return array|mixed data without useless information
  60. *
  61. * @throws RestException
  62. */
  63. public function get($id, $includecount = 0, $includeroles = 0)
  64. {
  65. if (!DolibarrApiAccess::$user->rights->societe->contact->lire) {
  66. throw new RestException(401, 'No permission to read contacts');
  67. }
  68. if ($id === 0) {
  69. $result = $this->contact->initAsSpecimen();
  70. } else {
  71. $result = $this->contact->fetch($id);
  72. }
  73. if (!$result) {
  74. throw new RestException(404, 'Contact not found');
  75. }
  76. if (!DolibarrApi::_checkAccessToResource('contact', $this->contact->id, 'socpeople&societe')) {
  77. throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
  78. }
  79. if ($includecount) {
  80. $this->contact->load_ref_elements();
  81. }
  82. if ($includeroles) {
  83. $this->contact->fetchRoles();
  84. }
  85. if (isModEnabled('mailing')) {
  86. $this->contact->getNoEmail();
  87. }
  88. return $this->_cleanObjectDatas($this->contact);
  89. }
  90. /**
  91. * Get properties of a contact object by Email
  92. *
  93. * @param string $email Email of contact
  94. * @param int $includecount Count and return also number of elements the contact is used as a link for
  95. * @param int $includeroles Includes roles of the contact
  96. * @return array|mixed data without useless information
  97. *
  98. * @url GET email/{email}
  99. *
  100. * @throws RestException 401 Insufficient rights
  101. * @throws RestException 404 User or group not found
  102. */
  103. public function getByEmail($email, $includecount = 0, $includeroles = 0)
  104. {
  105. if (!DolibarrApiAccess::$user->rights->societe->contact->lire) {
  106. throw new RestException(401, 'No permission to read contacts');
  107. }
  108. if (empty($email)) {
  109. $result = $this->contact->initAsSpecimen();
  110. } else {
  111. $result = $this->contact->fetch('', '', '', $email);
  112. }
  113. if (!$result) {
  114. throw new RestException(404, 'Contact not found');
  115. }
  116. if (!DolibarrApi::_checkAccessToResource('contact', $this->contact->id, 'socpeople&societe')) {
  117. throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
  118. }
  119. if ($includecount) {
  120. $this->contact->load_ref_elements();
  121. }
  122. if ($includeroles) {
  123. $this->contact->fetchRoles();
  124. }
  125. if (isModEnabled('mailing')) {
  126. $this->contact->getNoEmail();
  127. }
  128. return $this->_cleanObjectDatas($this->contact);
  129. }
  130. /**
  131. * List contacts
  132. *
  133. * Get a list of contacts
  134. *
  135. * @param string $sortfield Sort field
  136. * @param string $sortorder Sort order
  137. * @param int $limit Limit for list
  138. * @param int $page Page number
  139. * @param string $thirdparty_ids Thirdparty ids to filter contacts of (example '1' or '1,2,3') {@pattern /^[0-9,]*$/i}
  140. * @param int $category Use this param to filter list by category
  141. * @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.ref:like:'SO-%') and (t.date_creation:<:'20160101')"
  142. * @param int $includecount Count and return also number of elements the contact is used as a link for
  143. * @param int $includeroles Includes roles of the contact
  144. * @param string $properties Restrict the data returned to theses properties. Ignored if empty. Comma separated list of properties names
  145. * @return array Array of contact objects
  146. *
  147. * @throws RestException
  148. */
  149. public function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $thirdparty_ids = '', $category = 0, $sqlfilters = '', $includecount = 0, $includeroles = 0, $properties = '')
  150. {
  151. global $db, $conf;
  152. $obj_ret = array();
  153. if (!DolibarrApiAccess::$user->rights->societe->contact->lire) {
  154. throw new RestException(401, 'No permission to read contacts');
  155. }
  156. // case of external user, $thirdparty_ids param is ignored and replaced by user's socid
  157. $socids = DolibarrApiAccess::$user->socid ? DolibarrApiAccess::$user->socid : $thirdparty_ids;
  158. // If the internal user must only see his customers, force searching by him
  159. $search_sale = 0;
  160. if (!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) {
  161. $search_sale = DolibarrApiAccess::$user->id;
  162. }
  163. $sql = "SELECT t.rowid";
  164. $sql .= " FROM ".MAIN_DB_PREFIX."socpeople as t";
  165. if ($category > 0) {
  166. $sql .= ", ".MAIN_DB_PREFIX."categorie_contact as c";
  167. }
  168. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."socpeople_extrafields as te ON te.fk_object = t.rowid";
  169. if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) {
  170. // We need this table joined to the select in order to filter by sale
  171. $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
  172. }
  173. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON t.fk_soc = s.rowid";
  174. $sql .= ' WHERE t.entity IN ('.getEntity('contact').')';
  175. if ($socids) {
  176. $sql .= " AND t.fk_soc IN (".$this->db->sanitize($socids).")";
  177. }
  178. if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) {
  179. $sql .= " AND t.fk_soc = sc.fk_soc";
  180. }
  181. if ($search_sale > 0) {
  182. $sql .= " AND s.rowid = sc.fk_soc"; // Join for the needed table to filter by sale
  183. }
  184. // Insert sale filter
  185. if ($search_sale > 0) {
  186. $sql .= " AND sc.fk_user = ".((int) $search_sale);
  187. }
  188. // Select contacts of given category
  189. if ($category > 0) {
  190. $sql .= " AND c.fk_categorie = ".((int) $category);
  191. $sql .= " AND c.fk_socpeople = t.rowid ";
  192. }
  193. // Add sql filters
  194. if ($sqlfilters) {
  195. $errormessage = '';
  196. $sql .= forgeSQLFromUniversalSearchCriteria($sqlfilters, $errormessage);
  197. if ($errormessage) {
  198. throw new RestException(400, 'Error when validating parameter sqlfilters -> '.$errormessage);
  199. }
  200. }
  201. $sql .= $this->db->order($sortfield, $sortorder);
  202. if ($limit) {
  203. if ($page < 0) {
  204. $page = 0;
  205. }
  206. $offset = $limit * $page;
  207. $sql .= $this->db->plimit($limit + 1, $offset);
  208. }
  209. $result = $this->db->query($sql);
  210. if ($result) {
  211. $num = $this->db->num_rows($result);
  212. $min = min($num, ($limit <= 0 ? $num : $limit));
  213. $i = 0;
  214. while ($i < $min) {
  215. $obj = $this->db->fetch_object($result);
  216. $contact_static = new Contact($this->db);
  217. if ($contact_static->fetch($obj->rowid)) {
  218. $contact_static->fetchRoles();
  219. if ($includecount) {
  220. $contact_static->load_ref_elements();
  221. }
  222. if ($includeroles) {
  223. $contact_static->fetchRoles();
  224. }
  225. if (isModEnabled('mailing')) {
  226. $contact_static->getNoEmail();
  227. }
  228. $obj_ret[] = $this->_filterObjectProperties($this->_cleanObjectDatas($contact_static), $properties);
  229. }
  230. $i++;
  231. }
  232. } else {
  233. throw new RestException(503, 'Error when retrieve contacts : '.$sql);
  234. }
  235. if (!count($obj_ret)) {
  236. throw new RestException(404, 'Contacts not found');
  237. }
  238. return $obj_ret;
  239. }
  240. /**
  241. * Create contact object
  242. *
  243. * @param array $request_data Request datas
  244. * @return int ID of contact
  245. */
  246. public function post($request_data = null)
  247. {
  248. if (!DolibarrApiAccess::$user->rights->societe->contact->creer) {
  249. throw new RestException(401, 'No permission to create/update contacts');
  250. }
  251. // Check mandatory fields
  252. $result = $this->_validate($request_data);
  253. foreach ($request_data as $field => $value) {
  254. if ($field === 'caller') {
  255. // 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
  256. $this->contact->context['caller'] = $request_data['caller'];
  257. continue;
  258. }
  259. if ($field == 'array_options' && is_array($value)) {
  260. foreach ($value as $index => $val) {
  261. $this->contact->array_options[$index] = $val;
  262. }
  263. continue;
  264. }
  265. $this->contact->$field = $this->_checkValForAPI($field, $value, $this->contact);
  266. }
  267. if ($this->contact->create(DolibarrApiAccess::$user) < 0) {
  268. throw new RestException(500, "Error creating contact", array_merge(array($this->contact->error), $this->contact->errors));
  269. }
  270. if (isModEnabled('mailing') && !empty($this->contact->email) && isset($this->contact->no_email)) {
  271. $this->contact->setNoEmail($this->contact->no_email);
  272. }
  273. return $this->contact->id;
  274. }
  275. /**
  276. * Update contact
  277. *
  278. * @param int $id Id of contact to update
  279. * @param array $request_data Datas
  280. * @return int
  281. */
  282. public function put($id, $request_data = null)
  283. {
  284. if (!DolibarrApiAccess::$user->rights->societe->contact->creer) {
  285. throw new RestException(401, 'No permission to create/update contacts');
  286. }
  287. $result = $this->contact->fetch($id);
  288. if (!$result) {
  289. throw new RestException(404, 'Contact not found');
  290. }
  291. if (!DolibarrApi::_checkAccessToResource('contact', $this->contact->id, 'socpeople&societe')) {
  292. throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
  293. }
  294. foreach ($request_data as $field => $value) {
  295. if ($field == 'id') {
  296. continue;
  297. }
  298. if ($field === 'caller') {
  299. // 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
  300. $this->contact->context['caller'] = $request_data['caller'];
  301. continue;
  302. }
  303. if ($field == 'array_options' && is_array($value)) {
  304. foreach ($value as $index => $val) {
  305. $this->contact->array_options[$index] = $val;
  306. }
  307. continue;
  308. }
  309. $this->contact->$field = $this->_checkValForAPI($field, $value, $this->contact);
  310. }
  311. if (isModEnabled('mailing') && !empty($this->contact->email) && isset($this->contact->no_email)) {
  312. $this->contact->setNoEmail($this->contact->no_email);
  313. }
  314. if ($this->contact->update($id, DolibarrApiAccess::$user, 1, 'update')) {
  315. return $this->get($id);
  316. }
  317. return false;
  318. }
  319. /**
  320. * Delete contact
  321. *
  322. * @param int $id Contact ID
  323. * @return integer
  324. */
  325. public function delete($id)
  326. {
  327. if (!DolibarrApiAccess::$user->rights->societe->contact->supprimer) {
  328. throw new RestException(401, 'No permission to delete contacts');
  329. }
  330. $result = $this->contact->fetch($id);
  331. if (!$result) {
  332. throw new RestException(404, 'Contact not found');
  333. }
  334. if (!DolibarrApi::_checkAccessToResource('contact', $this->contact->id, 'socpeople&societe')) {
  335. throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
  336. }
  337. $this->contact->oldcopy = clone $this->contact;
  338. return $this->contact->delete(DolibarrApiAccess::$user);
  339. }
  340. /**
  341. * Create an user account object from contact (external user)
  342. *
  343. * @param int $id Id of contact
  344. * @param array $request_data Request datas
  345. * @return int ID of user
  346. *
  347. * @url POST {id}/createUser
  348. */
  349. public function createUser($id, $request_data = null)
  350. {
  351. //if (!DolibarrApiAccess::$user->hasRight('user', 'user', 'creer')) {
  352. //throw new RestException(401);
  353. //}
  354. if (!isset($request_data["login"])) {
  355. throw new RestException(400, "login field missing");
  356. }
  357. if (!isset($request_data["password"])) {
  358. throw new RestException(400, "password field missing");
  359. }
  360. if (!DolibarrApiAccess::$user->rights->societe->contact->lire) {
  361. throw new RestException(401, 'No permission to read contacts');
  362. }
  363. if (!DolibarrApiAccess::$user->hasRight('user', 'user', 'creer')) {
  364. throw new RestException(401, 'No permission to create user');
  365. }
  366. $contact = new Contact($this->db);
  367. $contact->fetch($id);
  368. if ($contact->id <= 0) {
  369. throw new RestException(404, 'Contact not found');
  370. }
  371. if (!DolibarrApi::_checkAccessToResource('contact', $contact->id, 'socpeople&societe')) {
  372. throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
  373. }
  374. // Check mandatory fields
  375. $login = $request_data["login"];
  376. $password = $request_data["password"];
  377. $useraccount = new User($this->db);
  378. $result = $useraccount->create_from_contact($contact, $login, $password);
  379. if ($result <= 0) {
  380. throw new RestException(500, "User not created");
  381. }
  382. // password parameter not used in create_from_contact
  383. $useraccount->setPassword($useraccount, $password);
  384. return $result;
  385. }
  386. /**
  387. * Get categories for a contact
  388. *
  389. * @param int $id ID of contact
  390. * @param string $sortfield Sort field
  391. * @param string $sortorder Sort order
  392. * @param int $limit Limit for list
  393. * @param int $page Page number
  394. *
  395. * @return mixed
  396. *
  397. * @url GET {id}/categories
  398. */
  399. public function getCategories($id, $sortfield = "s.rowid", $sortorder = 'ASC', $limit = 0, $page = 0)
  400. {
  401. if (!DolibarrApiAccess::$user->rights->categorie->lire) {
  402. throw new RestException(401);
  403. }
  404. $categories = new Categorie($this->db);
  405. $result = $categories->getListForItem($id, 'contact', $sortfield, $sortorder, $limit, $page);
  406. if ($result < 0) {
  407. throw new RestException(503, 'Error when retrieve category list : '.$categories->error);
  408. }
  409. return $result;
  410. }
  411. /**
  412. * Add a category to a contact
  413. *
  414. * @url PUT {id}/categories/{category_id}
  415. *
  416. * @param int $id Id of contact
  417. * @param int $category_id Id of category
  418. *
  419. * @return mixed
  420. *
  421. * @throws RestException 401 Insufficient rights
  422. * @throws RestException 404 Category or contact not found
  423. */
  424. public function addCategory($id, $category_id)
  425. {
  426. if (!DolibarrApiAccess::$user->rights->societe->contact->creer) {
  427. throw new RestException(401, 'Insufficient rights');
  428. }
  429. $result = $this->contact->fetch($id);
  430. if (!$result) {
  431. throw new RestException(404, 'Contact not found');
  432. }
  433. $category = new Categorie($this->db);
  434. $result = $category->fetch($category_id);
  435. if (!$result) {
  436. throw new RestException(404, 'category not found');
  437. }
  438. if (!DolibarrApi::_checkAccessToResource('contact', $this->contact->id)) {
  439. throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
  440. }
  441. if (!DolibarrApi::_checkAccessToResource('category', $category->id)) {
  442. throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
  443. }
  444. $category->add_type($this->contact, 'contact');
  445. return $this->_cleanObjectDatas($this->contact);
  446. }
  447. /**
  448. * Remove the link between a category and a contact
  449. *
  450. * @url DELETE {id}/categories/{category_id}
  451. *
  452. * @param int $id Id of contact
  453. * @param int $category_id Id of category
  454. * @return mixed
  455. *
  456. * @throws RestException 401 Insufficient rights
  457. * @throws RestException 404 Category or contact not found
  458. */
  459. public function deleteCategory($id, $category_id)
  460. {
  461. if (!DolibarrApiAccess::$user->rights->societe->contact->creer) {
  462. throw new RestException(401, 'Insufficient rights');
  463. }
  464. $result = $this->contact->fetch($id);
  465. if (!$result) {
  466. throw new RestException(404, 'Contact not found');
  467. }
  468. $category = new Categorie($this->db);
  469. $result = $category->fetch($category_id);
  470. if (!$result) {
  471. throw new RestException(404, 'category not found');
  472. }
  473. if (!DolibarrApi::_checkAccessToResource('contact', $this->contact->id)) {
  474. throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
  475. }
  476. if (!DolibarrApi::_checkAccessToResource('category', $category->id)) {
  477. throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
  478. }
  479. $category->del_type($this->contact, 'contact');
  480. return $this->_cleanObjectDatas($this->contact);
  481. }
  482. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
  483. /**
  484. * Clean sensible object datas
  485. *
  486. * @param Object $object Object to clean
  487. * @return Object Object with cleaned properties
  488. */
  489. protected function _cleanObjectDatas($object)
  490. {
  491. // phpcs:enable
  492. $object = parent::_cleanObjectDatas($object);
  493. unset($object->total_ht);
  494. unset($object->total_tva);
  495. unset($object->total_localtax1);
  496. unset($object->total_localtax2);
  497. unset($object->total_ttc);
  498. unset($object->note);
  499. unset($object->lines);
  500. unset($object->thirdparty);
  501. return $object;
  502. }
  503. /**
  504. * Validate fields before create or update object
  505. *
  506. * @param array|null $data Data to validate
  507. * @return array
  508. * @throws RestException
  509. */
  510. private function _validate($data)
  511. {
  512. $contact = array();
  513. foreach (Contacts::$FIELDS as $field) {
  514. if (!isset($data[$field])) {
  515. throw new RestException(400, "$field field missing");
  516. }
  517. $contact[$field] = $data[$field];
  518. }
  519. return $contact;
  520. }
  521. }