api_contacts.class.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580
  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. if (!DolibarrApi::_checkFilters($sqlfilters, $errormessage)) {
  196. throw new RestException(503, 'Error when validating parameter sqlfilters -> '.$errormessage);
  197. }
  198. $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^\(\)]+)\)';
  199. $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")";
  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->_cleanObjectDatas($contact_static);
  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. $this->contact->$field = $value;
  255. }
  256. if ($this->contact->create(DolibarrApiAccess::$user) < 0) {
  257. throw new RestException(500, "Error creating contact", array_merge(array($this->contact->error), $this->contact->errors));
  258. }
  259. if (isModEnabled('mailing') && !empty($this->contact->email) && isset($this->contact->no_email)) {
  260. $this->contact->setNoEmail($this->contact->no_email);
  261. }
  262. return $this->contact->id;
  263. }
  264. /**
  265. * Update contact
  266. *
  267. * @param int $id Id of contact to update
  268. * @param array $request_data Datas
  269. * @return int
  270. */
  271. public function put($id, $request_data = null)
  272. {
  273. if (!DolibarrApiAccess::$user->rights->societe->contact->creer) {
  274. throw new RestException(401, 'No permission to create/update contacts');
  275. }
  276. $result = $this->contact->fetch($id);
  277. if (!$result) {
  278. throw new RestException(404, 'Contact not found');
  279. }
  280. if (!DolibarrApi::_checkAccessToResource('contact', $this->contact->id, 'socpeople&societe')) {
  281. throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
  282. }
  283. foreach ($request_data as $field => $value) {
  284. if ($field == 'id') {
  285. continue;
  286. }
  287. $this->contact->$field = $value;
  288. }
  289. if (isModEnabled('mailing') && !empty($this->contact->email) && isset($this->contact->no_email)) {
  290. $this->contact->setNoEmail($this->contact->no_email);
  291. }
  292. if ($this->contact->update($id, DolibarrApiAccess::$user, 1, '', '', 'update')) {
  293. return $this->get($id);
  294. }
  295. return false;
  296. }
  297. /**
  298. * Delete contact
  299. *
  300. * @param int $id Contact ID
  301. * @return integer
  302. */
  303. public function delete($id)
  304. {
  305. if (!DolibarrApiAccess::$user->rights->societe->contact->supprimer) {
  306. throw new RestException(401, 'No permission to delete contacts');
  307. }
  308. $result = $this->contact->fetch($id);
  309. if (!$result) {
  310. throw new RestException(404, 'Contact not found');
  311. }
  312. if (!DolibarrApi::_checkAccessToResource('contact', $this->contact->id, 'socpeople&societe')) {
  313. throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
  314. }
  315. $this->contact->oldcopy = clone $this->contact;
  316. return $this->contact->delete();
  317. }
  318. /**
  319. * Create an user account object from contact (external user)
  320. *
  321. * @param int $id Id of contact
  322. * @param array $request_data Request datas
  323. * @return int ID of user
  324. *
  325. * @url POST {id}/createUser
  326. */
  327. public function createUser($id, $request_data = null)
  328. {
  329. //if (!DolibarrApiAccess::$user->rights->user->user->creer) {
  330. //throw new RestException(401);
  331. //}
  332. if (!isset($request_data["login"])) {
  333. throw new RestException(400, "login field missing");
  334. }
  335. if (!isset($request_data["password"])) {
  336. throw new RestException(400, "password field missing");
  337. }
  338. if (!DolibarrApiAccess::$user->rights->societe->contact->lire) {
  339. throw new RestException(401, 'No permission to read contacts');
  340. }
  341. if (!DolibarrApiAccess::$user->rights->user->user->creer) {
  342. throw new RestException(401, 'No permission to create user');
  343. }
  344. $contact = new Contact($this->db);
  345. $contact->fetch($id);
  346. if ($contact->id <= 0) {
  347. throw new RestException(404, 'Contact not found');
  348. }
  349. if (!DolibarrApi::_checkAccessToResource('contact', $contact->id, 'socpeople&societe')) {
  350. throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
  351. }
  352. // Check mandatory fields
  353. $login = $request_data["login"];
  354. $password = $request_data["password"];
  355. $useraccount = new User($this->db);
  356. $result = $useraccount->create_from_contact($contact, $login, $password);
  357. if ($result <= 0) {
  358. throw new RestException(500, "User not created");
  359. }
  360. // password parameter not used in create_from_contact
  361. $useraccount->setPassword($useraccount, $password);
  362. return $result;
  363. }
  364. /**
  365. * Get categories for a contact
  366. *
  367. * @param int $id ID of contact
  368. * @param string $sortfield Sort field
  369. * @param string $sortorder Sort order
  370. * @param int $limit Limit for list
  371. * @param int $page Page number
  372. *
  373. * @return mixed
  374. *
  375. * @url GET {id}/categories
  376. */
  377. public function getCategories($id, $sortfield = "s.rowid", $sortorder = 'ASC', $limit = 0, $page = 0)
  378. {
  379. if (!DolibarrApiAccess::$user->rights->categorie->lire) {
  380. throw new RestException(401);
  381. }
  382. $categories = new Categorie($this->db);
  383. $result = $categories->getListForItem($id, 'contact', $sortfield, $sortorder, $limit, $page);
  384. if (empty($result)) {
  385. throw new RestException(404, 'No category found');
  386. }
  387. if ($result < 0) {
  388. throw new RestException(503, 'Error when retrieve category list : '.$categories->error);
  389. }
  390. return $result;
  391. }
  392. /**
  393. * Add a category to a contact
  394. *
  395. * @url POST {id}/categories/{category_id}
  396. *
  397. * @param int $id Id of contact
  398. * @param int $category_id Id of category
  399. *
  400. * @return mixed
  401. *
  402. * @throws RestException 401 Insufficient rights
  403. * @throws RestException 404 Category or contact not found
  404. */
  405. public function addCategory($id, $category_id)
  406. {
  407. if (!DolibarrApiAccess::$user->rights->societe->contact->creer) {
  408. throw new RestException(401, 'Insufficient rights');
  409. }
  410. $result = $this->contact->fetch($id);
  411. if (!$result) {
  412. throw new RestException(404, 'Contact not found');
  413. }
  414. $category = new Categorie($this->db);
  415. $result = $category->fetch($category_id);
  416. if (!$result) {
  417. throw new RestException(404, 'category not found');
  418. }
  419. if (!DolibarrApi::_checkAccessToResource('contact', $this->contact->id)) {
  420. throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
  421. }
  422. if (!DolibarrApi::_checkAccessToResource('category', $category->id)) {
  423. throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
  424. }
  425. $category->add_type($this->contact, 'contact');
  426. return $this->_cleanObjectDatas($this->contact);
  427. }
  428. /**
  429. * Remove the link between a category and a contact
  430. *
  431. * @url DELETE {id}/categories/{category_id}
  432. *
  433. * @param int $id Id of contact
  434. * @param int $category_id Id of category
  435. * @return mixed
  436. *
  437. * @throws RestException 401 Insufficient rights
  438. * @throws RestException 404 Category or contact not found
  439. */
  440. public function deleteCategory($id, $category_id)
  441. {
  442. if (!DolibarrApiAccess::$user->rights->societe->contact->creer) {
  443. throw new RestException(401, 'Insufficient rights');
  444. }
  445. $result = $this->contact->fetch($id);
  446. if (!$result) {
  447. throw new RestException(404, 'Contact not found');
  448. }
  449. $category = new Categorie($this->db);
  450. $result = $category->fetch($category_id);
  451. if (!$result) {
  452. throw new RestException(404, 'category not found');
  453. }
  454. if (!DolibarrApi::_checkAccessToResource('contact', $this->contact->id)) {
  455. throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
  456. }
  457. if (!DolibarrApi::_checkAccessToResource('category', $category->id)) {
  458. throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
  459. }
  460. $category->del_type($this->contact, 'contact');
  461. return $this->_cleanObjectDatas($this->contact);
  462. }
  463. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
  464. /**
  465. * Clean sensible object datas
  466. *
  467. * @param Object $object Object to clean
  468. * @return Object Object with cleaned properties
  469. */
  470. protected function _cleanObjectDatas($object)
  471. {
  472. // phpcs:enable
  473. $object = parent::_cleanObjectDatas($object);
  474. unset($object->total_ht);
  475. unset($object->total_tva);
  476. unset($object->total_localtax1);
  477. unset($object->total_localtax2);
  478. unset($object->total_ttc);
  479. unset($object->note);
  480. unset($object->lines);
  481. unset($object->thirdparty);
  482. return $object;
  483. }
  484. /**
  485. * Validate fields before create or update object
  486. *
  487. * @param array|null $data Data to validate
  488. * @return array
  489. * @throws RestException
  490. */
  491. private function _validate($data)
  492. {
  493. $contact = array();
  494. foreach (Contacts::$FIELDS as $field) {
  495. if (!isset($data[$field])) {
  496. throw new RestException(400, "$field field missing");
  497. }
  498. $contact[$field] = $data[$field];
  499. }
  500. return $contact;
  501. }
  502. }