api_contacts.class.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579
  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. * @return array Array of contact objects
  145. *
  146. * @throws RestException
  147. */
  148. public function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $thirdparty_ids = '', $category = 0, $sqlfilters = '', $includecount = 0, $includeroles = 0)
  149. {
  150. global $db, $conf;
  151. $obj_ret = array();
  152. if (!DolibarrApiAccess::$user->rights->societe->contact->lire) {
  153. throw new RestException(401, 'No permission to read contacts');
  154. }
  155. // case of external user, $thirdparty_ids param is ignored and replaced by user's socid
  156. $socids = DolibarrApiAccess::$user->socid ? DolibarrApiAccess::$user->socid : $thirdparty_ids;
  157. // If the internal user must only see his customers, force searching by him
  158. $search_sale = 0;
  159. if (!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) {
  160. $search_sale = DolibarrApiAccess::$user->id;
  161. }
  162. $sql = "SELECT t.rowid";
  163. $sql .= " FROM ".MAIN_DB_PREFIX."socpeople as t";
  164. if ($category > 0) {
  165. $sql .= ", ".MAIN_DB_PREFIX."categorie_contact as c";
  166. }
  167. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."socpeople_extrafields as te ON te.fk_object = t.rowid";
  168. if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) {
  169. // We need this table joined to the select in order to filter by sale
  170. $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
  171. }
  172. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON t.fk_soc = s.rowid";
  173. $sql .= ' WHERE t.entity IN ('.getEntity('contact').')';
  174. if ($socids) {
  175. $sql .= " AND t.fk_soc IN (".$this->db->sanitize($socids).")";
  176. }
  177. if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) {
  178. $sql .= " AND t.fk_soc = sc.fk_soc";
  179. }
  180. if ($search_sale > 0) {
  181. $sql .= " AND s.rowid = sc.fk_soc"; // Join for the needed table to filter by sale
  182. }
  183. // Insert sale filter
  184. if ($search_sale > 0) {
  185. $sql .= " AND sc.fk_user = ".((int) $search_sale);
  186. }
  187. // Select contacts of given category
  188. if ($category > 0) {
  189. $sql .= " AND c.fk_categorie = ".((int) $category);
  190. $sql .= " AND c.fk_socpeople = t.rowid ";
  191. }
  192. // Add sql filters
  193. if ($sqlfilters) {
  194. $errormessage = '';
  195. $sql .= forgeSQLFromUniversalSearchCriteria($sqlfilters, $errormessage);
  196. if ($errormessage) {
  197. throw new RestException(400, 'Error when validating parameter sqlfilters -> '.$errormessage);
  198. }
  199. }
  200. $sql .= $this->db->order($sortfield, $sortorder);
  201. if ($limit) {
  202. if ($page < 0) {
  203. $page = 0;
  204. }
  205. $offset = $limit * $page;
  206. $sql .= $this->db->plimit($limit + 1, $offset);
  207. }
  208. $result = $this->db->query($sql);
  209. if ($result) {
  210. $num = $this->db->num_rows($result);
  211. $min = min($num, ($limit <= 0 ? $num : $limit));
  212. $i = 0;
  213. while ($i < $min) {
  214. $obj = $this->db->fetch_object($result);
  215. $contact_static = new Contact($this->db);
  216. if ($contact_static->fetch($obj->rowid)) {
  217. $contact_static->fetchRoles();
  218. if ($includecount) {
  219. $contact_static->load_ref_elements();
  220. }
  221. if ($includeroles) {
  222. $contact_static->fetchRoles();
  223. }
  224. if (isModEnabled('mailing')) {
  225. $contact_static->getNoEmail();
  226. }
  227. $obj_ret[] = $this->_cleanObjectDatas($contact_static);
  228. }
  229. $i++;
  230. }
  231. } else {
  232. throw new RestException(503, 'Error when retrieve contacts : '.$sql);
  233. }
  234. if (!count($obj_ret)) {
  235. throw new RestException(404, 'Contacts not found');
  236. }
  237. return $obj_ret;
  238. }
  239. /**
  240. * Create contact object
  241. *
  242. * @param array $request_data Request datas
  243. * @return int ID of contact
  244. */
  245. public function post($request_data = null)
  246. {
  247. if (!DolibarrApiAccess::$user->rights->societe->contact->creer) {
  248. throw new RestException(401, 'No permission to create/update contacts');
  249. }
  250. // Check mandatory fields
  251. $result = $this->_validate($request_data);
  252. foreach ($request_data as $field => $value) {
  253. $this->contact->$field = $value;
  254. }
  255. if ($this->contact->create(DolibarrApiAccess::$user) < 0) {
  256. throw new RestException(500, "Error creating contact", array_merge(array($this->contact->error), $this->contact->errors));
  257. }
  258. if (isModEnabled('mailing') && !empty($this->contact->email) && isset($this->contact->no_email)) {
  259. $this->contact->setNoEmail($this->contact->no_email);
  260. }
  261. return $this->contact->id;
  262. }
  263. /**
  264. * Update contact
  265. *
  266. * @param int $id Id of contact to update
  267. * @param array $request_data Datas
  268. * @return int
  269. */
  270. public function put($id, $request_data = null)
  271. {
  272. if (!DolibarrApiAccess::$user->rights->societe->contact->creer) {
  273. throw new RestException(401, 'No permission to create/update contacts');
  274. }
  275. $result = $this->contact->fetch($id);
  276. if (!$result) {
  277. throw new RestException(404, 'Contact not found');
  278. }
  279. if (!DolibarrApi::_checkAccessToResource('contact', $this->contact->id, 'socpeople&societe')) {
  280. throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
  281. }
  282. foreach ($request_data as $field => $value) {
  283. if ($field == 'id') {
  284. continue;
  285. }
  286. $this->contact->$field = $value;
  287. }
  288. if (isModEnabled('mailing') && !empty($this->contact->email) && isset($this->contact->no_email)) {
  289. $this->contact->setNoEmail($this->contact->no_email);
  290. }
  291. if ($this->contact->update($id, DolibarrApiAccess::$user, 1, 'update')) {
  292. return $this->get($id);
  293. }
  294. return false;
  295. }
  296. /**
  297. * Delete contact
  298. *
  299. * @param int $id Contact ID
  300. * @return integer
  301. */
  302. public function delete($id)
  303. {
  304. if (!DolibarrApiAccess::$user->rights->societe->contact->supprimer) {
  305. throw new RestException(401, 'No permission to delete contacts');
  306. }
  307. $result = $this->contact->fetch($id);
  308. if (!$result) {
  309. throw new RestException(404, 'Contact not found');
  310. }
  311. if (!DolibarrApi::_checkAccessToResource('contact', $this->contact->id, 'socpeople&societe')) {
  312. throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
  313. }
  314. $this->contact->oldcopy = clone $this->contact;
  315. return $this->contact->delete();
  316. }
  317. /**
  318. * Create an user account object from contact (external user)
  319. *
  320. * @param int $id Id of contact
  321. * @param array $request_data Request datas
  322. * @return int ID of user
  323. *
  324. * @url POST {id}/createUser
  325. */
  326. public function createUser($id, $request_data = null)
  327. {
  328. //if (!DolibarrApiAccess::$user->rights->user->user->creer) {
  329. //throw new RestException(401);
  330. //}
  331. if (!isset($request_data["login"])) {
  332. throw new RestException(400, "login field missing");
  333. }
  334. if (!isset($request_data["password"])) {
  335. throw new RestException(400, "password field missing");
  336. }
  337. if (!DolibarrApiAccess::$user->rights->societe->contact->lire) {
  338. throw new RestException(401, 'No permission to read contacts');
  339. }
  340. if (!DolibarrApiAccess::$user->rights->user->user->creer) {
  341. throw new RestException(401, 'No permission to create user');
  342. }
  343. $contact = new Contact($this->db);
  344. $contact->fetch($id);
  345. if ($contact->id <= 0) {
  346. throw new RestException(404, 'Contact not found');
  347. }
  348. if (!DolibarrApi::_checkAccessToResource('contact', $contact->id, 'socpeople&societe')) {
  349. throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
  350. }
  351. // Check mandatory fields
  352. $login = $request_data["login"];
  353. $password = $request_data["password"];
  354. $useraccount = new User($this->db);
  355. $result = $useraccount->create_from_contact($contact, $login, $password);
  356. if ($result <= 0) {
  357. throw new RestException(500, "User not created");
  358. }
  359. // password parameter not used in create_from_contact
  360. $useraccount->setPassword($useraccount, $password);
  361. return $result;
  362. }
  363. /**
  364. * Get categories for a contact
  365. *
  366. * @param int $id ID of contact
  367. * @param string $sortfield Sort field
  368. * @param string $sortorder Sort order
  369. * @param int $limit Limit for list
  370. * @param int $page Page number
  371. *
  372. * @return mixed
  373. *
  374. * @url GET {id}/categories
  375. */
  376. public function getCategories($id, $sortfield = "s.rowid", $sortorder = 'ASC', $limit = 0, $page = 0)
  377. {
  378. if (!DolibarrApiAccess::$user->rights->categorie->lire) {
  379. throw new RestException(401);
  380. }
  381. $categories = new Categorie($this->db);
  382. $result = $categories->getListForItem($id, 'contact', $sortfield, $sortorder, $limit, $page);
  383. if (empty($result)) {
  384. throw new RestException(404, 'No category found');
  385. }
  386. if ($result < 0) {
  387. throw new RestException(503, 'Error when retrieve category list : '.$categories->error);
  388. }
  389. return $result;
  390. }
  391. /**
  392. * Add a category to a contact
  393. *
  394. * @url POST {id}/categories/{category_id}
  395. *
  396. * @param int $id Id of contact
  397. * @param int $category_id Id of category
  398. *
  399. * @return mixed
  400. *
  401. * @throws RestException 401 Insufficient rights
  402. * @throws RestException 404 Category or contact not found
  403. */
  404. public function addCategory($id, $category_id)
  405. {
  406. if (!DolibarrApiAccess::$user->rights->societe->contact->creer) {
  407. throw new RestException(401, 'Insufficient rights');
  408. }
  409. $result = $this->contact->fetch($id);
  410. if (!$result) {
  411. throw new RestException(404, 'Contact not found');
  412. }
  413. $category = new Categorie($this->db);
  414. $result = $category->fetch($category_id);
  415. if (!$result) {
  416. throw new RestException(404, 'category not found');
  417. }
  418. if (!DolibarrApi::_checkAccessToResource('contact', $this->contact->id)) {
  419. throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
  420. }
  421. if (!DolibarrApi::_checkAccessToResource('category', $category->id)) {
  422. throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
  423. }
  424. $category->add_type($this->contact, 'contact');
  425. return $this->_cleanObjectDatas($this->contact);
  426. }
  427. /**
  428. * Remove the link between a category and a contact
  429. *
  430. * @url DELETE {id}/categories/{category_id}
  431. *
  432. * @param int $id Id of contact
  433. * @param int $category_id Id of category
  434. * @return mixed
  435. *
  436. * @throws RestException 401 Insufficient rights
  437. * @throws RestException 404 Category or contact not found
  438. */
  439. public function deleteCategory($id, $category_id)
  440. {
  441. if (!DolibarrApiAccess::$user->rights->societe->contact->creer) {
  442. throw new RestException(401, 'Insufficient rights');
  443. }
  444. $result = $this->contact->fetch($id);
  445. if (!$result) {
  446. throw new RestException(404, 'Contact not found');
  447. }
  448. $category = new Categorie($this->db);
  449. $result = $category->fetch($category_id);
  450. if (!$result) {
  451. throw new RestException(404, 'category not found');
  452. }
  453. if (!DolibarrApi::_checkAccessToResource('contact', $this->contact->id)) {
  454. throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
  455. }
  456. if (!DolibarrApi::_checkAccessToResource('category', $category->id)) {
  457. throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
  458. }
  459. $category->del_type($this->contact, 'contact');
  460. return $this->_cleanObjectDatas($this->contact);
  461. }
  462. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
  463. /**
  464. * Clean sensible object datas
  465. *
  466. * @param Object $object Object to clean
  467. * @return Object Object with cleaned properties
  468. */
  469. protected function _cleanObjectDatas($object)
  470. {
  471. // phpcs:enable
  472. $object = parent::_cleanObjectDatas($object);
  473. unset($object->total_ht);
  474. unset($object->total_tva);
  475. unset($object->total_localtax1);
  476. unset($object->total_localtax2);
  477. unset($object->total_ttc);
  478. unset($object->note);
  479. unset($object->lines);
  480. unset($object->thirdparty);
  481. return $object;
  482. }
  483. /**
  484. * Validate fields before create or update object
  485. *
  486. * @param array|null $data Data to validate
  487. * @return array
  488. * @throws RestException
  489. */
  490. private function _validate($data)
  491. {
  492. $contact = array();
  493. foreach (Contacts::$FIELDS as $field) {
  494. if (!isset($data[$field])) {
  495. throw new RestException(400, "$field field missing");
  496. }
  497. $contact[$field] = $data[$field];
  498. }
  499. return $contact;
  500. }
  501. }