Merge pull request #19307 from eileenmcnaughton/534
[civicrm-core.git] / api / v3 / Contact.php
CommitLineData
6a488035 1<?php
6a488035 2/*
a30c801b
TO
3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
5 | |
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
9 +--------------------------------------------------------------------+
e70a7fc0 10 */
6a488035
TO
11
12/**
c28e1768 13 * This api exposes CiviCRM contacts.
244bbdd8 14 *
c28e1768
CW
15 * Contacts are the main entity in CiviCRM and this api is more robust than most.
16 * - Get action allows all params supported by advanced search.
b081365f 17 * - Create action allows creating several related entities at once (e.g. email).
c28e1768
CW
18 * - Create allows checking for duplicate contacts.
19 * Use getfields to list the full range of parameters and options supported by each action.
6a488035
TO
20 *
21 * @package CiviCRM_APIv3
6a488035
TO
22 */
23
24/**
244bbdd8 25 * Create or update a Contact.
6a488035 26 *
cf470720
TO
27 * @param array $params
28 * Input parameters.
6a488035 29 *
a6c01b45 30 * @return array
72b3a70c 31 * API Result Array
17d8f8a8 32 *
33 * @throws \CiviCRM_API3_Exception
34 * @throws API_Exception
35 * @throws \CRM_Core_Exception
6a488035
TO
36 */
37function civicrm_api3_contact_create($params) {
6a488035 38 $contactID = CRM_Utils_Array::value('contact_id', $params, CRM_Utils_Array::value('id', $params));
c16ed19b
CW
39
40 if ($contactID && !empty($params['check_permissions']) && !CRM_Contact_BAO_Contact_Permission::allow($contactID, CRM_Core_Permission::EDIT)) {
41 throw new \Civi\API\Exception\UnauthorizedException('Permission denied to modify contact record');
42 }
43
fedc3428 44 if (!empty($params['dupe_check'])) {
59ca5f92 45 $ids = CRM_Contact_BAO_Contact::getDuplicateContacts($params, $params['contact_type'], 'Unsupervised', [], $params['check_permission']);
fedc3428 46 if (count($ids) > 0) {
59ca5f92 47 throw new API_Exception("Found matching contacts: " . implode(',', $ids), "duplicate", ["ids" => $ids]);
fedc3428 48 }
49 }
50
51 $values = _civicrm_api3_contact_check_params($params);
6a488035
TO
52 if ($values) {
53 return $values;
54 }
55
56 if (!$contactID) {
57 // If we get here, we're ready to create a new contact
58 if (($email = CRM_Utils_Array::value('email', $params)) && !is_array($params['email'])) {
59 $defLocType = CRM_Core_BAO_LocationType::getDefault();
59ca5f92 60 $params['email'] = [
61 1 => [
d5cc0fc2 62 'email' => $email,
6a488035
TO
63 'is_primary' => 1,
64 'location_type_id' => ($defLocType->id) ? $defLocType->id : 1,
59ca5f92 65 ],
66 ];
6a488035
TO
67 }
68 }
69
70 if (!empty($params['home_url'])) {
cbf48754 71 $websiteTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Website', 'website_type_id');
59ca5f92 72 $params['website'] = [
73 1 => [
d5cc0fc2 74 'website_type_id' => key($websiteTypes),
6a488035 75 'url' => $params['home_url'],
59ca5f92 76 ],
77 ];
6a488035
TO
78 }
79
6ecbca5b 80 _civicrm_api3_greeting_format_params($params);
6a488035 81
59ca5f92 82 $values = [];
6a488035 83
6ecbca5b 84 if (empty($params['contact_type']) && $contactID) {
85 $params['contact_type'] = CRM_Contact_BAO_Contact::getContactType($contactID);
080b7aca
CW
86 if (!$params['contact_type']) {
87 throw new API_Exception('Contact id ' . $contactID . ' not found.');
88 }
6a488035
TO
89 }
90
6ecbca5b 91 if (!isset($params['contact_sub_type']) && $contactID) {
92 $params['contact_sub_type'] = CRM_Contact_BAO_Contact::getContactSubType($contactID);
6a488035
TO
93 }
94
6ecbca5b 95 _civicrm_api3_custom_format_params($params, $values, $params['contact_type'], $contactID);
6a488035
TO
96
97 $params = array_merge($params, $values);
6ecbca5b 98 //@todo we should just call basic_create here - but need to make contact:create accept 'id' on the bao
6a488035
TO
99 $contact = _civicrm_api3_contact_update($params, $contactID);
100
101 if (is_a($contact, 'CRM_Core_Error')) {
6ecbca5b 102 throw new API_Exception($contact->_errors[0]['message']);
6a488035
TO
103 }
104 else {
59ca5f92 105 $values = [];
6a488035
TO
106 _civicrm_api3_object_to_array_unique_fields($contact, $values[$contact->id]);
107 }
108
109 return civicrm_api3_create_success($values, $params, 'Contact', 'create');
110}
111
11e09c59 112/**
0aa0303c 113 * Adjust Metadata for Create action.
6a488035 114 *
cf470720 115 * @param array $params
b081365f 116 * Array of parameters determined by getfields.
6a488035
TO
117 */
118function _civicrm_api3_contact_create_spec(&$params) {
119 $params['contact_type']['api.required'] = 1;
59ca5f92 120 $params['id']['api.aliases'] = ['contact_id'];
121 $params['current_employer'] = [
6a488035
TO
122 'title' => 'Current Employer',
123 'description' => 'Name of Current Employer',
9c5991b3 124 'type' => CRM_Utils_Type::T_STRING,
59ca5f92 125 ];
126 $params['dupe_check'] = [
0391dc25 127 'title' => 'Check for Duplicates',
128 'description' => 'Throw error if contact create matches dedupe rule',
d142432b 129 'type' => CRM_Utils_Type::T_BOOLEAN,
59ca5f92 130 ];
131 $params['skip_greeting_processing'] = [
d29b0fe7 132 'title' => 'Skip Greeting processing',
133 'description' => 'Do not process greetings, (these can be done by scheduled job and there may be a preference to do so for performance reasons)',
134 'type' => CRM_Utils_Type::T_BOOLEAN,
135 'api.default' => 0,
59ca5f92 136 ];
137 $params['prefix_id']['api.aliases'] = [
138 'individual_prefix',
139 'individual_prefix_id',
140 ];
141 $params['suffix_id']['api.aliases'] = [
142 'individual_suffix',
143 'individual_suffix_id',
144 ];
145 $params['gender_id']['api.aliases'] = ['gender'];
6a488035
TO
146}
147
148/**
61fe4988
EM
149 * Retrieve one or more contacts, given a set of search params.
150 *
151 * @param array $params
6a488035 152 *
a6c01b45 153 * @return array
72b3a70c 154 * API Result Array
b69793be 155 *
156 * @throws \API_Exception
17d8f8a8 157 * @throws \CiviCRM_API3_Exception
6a488035
TO
158 */
159function civicrm_api3_contact_get($params) {
59ca5f92 160 $options = [];
6a488035 161 _civicrm_api3_contact_get_supportanomalies($params, $options);
244bbdd8 162 $contacts = _civicrm_api3_get_using_query_object('Contact', $params, $options);
dc2add4f
SL
163 if (!empty($params['check_permissions'])) {
164 CRM_Contact_BAO_Contact::unsetProtectedFields($contacts);
c10bca20 165 }
dc2add4f 166 return civicrm_api3_create_success($contacts, $params, 'Contact');
c10bca20
TO
167}
168
aa1b1481 169/**
244bbdd8 170 * Get number of contacts matching the supplied criteria.
61fe4988 171 *
c490a46a 172 * @param array $params
aa1b1481
EM
173 *
174 * @return int
17d8f8a8 175 * @throws \API_Exception
aa1b1481 176 */
6a488035 177function civicrm_api3_contact_getcount($params) {
59ca5f92 178 $options = [];
6a488035 179 _civicrm_api3_contact_get_supportanomalies($params, $options);
244bbdd8 180 $count = _civicrm_api3_get_using_query_object('Contact', $params, $options, 1);
972322c5 181 return (int) $count;
6a488035 182}
11e09c59
TO
183
184/**
9d32e6f7 185 * Adjust Metadata for Get action.
6a488035 186 *
cf470720 187 * @param array $params
b081365f 188 * Array of parameters determined by getfields.
6a488035
TO
189 */
190function _civicrm_api3_contact_get_spec(&$params) {
191 $params['contact_is_deleted']['api.default'] = 0;
192
9d32e6f7 193 // We declare all these pseudoFields as there are other undocumented fields accessible
6a488035 194 // via the api - but if check permissions is set we only allow declared fields
59ca5f92 195 $params['address_id'] = [
d142432b
EM
196 'title' => 'Primary Address ID',
197 'type' => CRM_Utils_Type::T_INT,
59ca5f92 198 ];
199 $params['street_address'] = [
d142432b
EM
200 'title' => 'Primary Address Street Address',
201 'type' => CRM_Utils_Type::T_STRING,
59ca5f92 202 ];
203 $params['supplemental_address_1'] = [
d142432b
EM
204 'title' => 'Primary Address Supplemental Address 1',
205 'type' => CRM_Utils_Type::T_STRING,
59ca5f92 206 ];
207 $params['supplemental_address_2'] = [
d142432b
EM
208 'title' => 'Primary Address Supplemental Address 2',
209 'type' => CRM_Utils_Type::T_STRING,
59ca5f92 210 ];
211 $params['supplemental_address_3'] = [
207f62c6
AS
212 'title' => 'Primary Address Supplemental Address 3',
213 'type' => CRM_Utils_Type::T_STRING,
59ca5f92 214 ];
215 $params['current_employer'] = [
d142432b
EM
216 'title' => 'Current Employer',
217 'type' => CRM_Utils_Type::T_STRING,
59ca5f92 218 ];
219 $params['city'] = [
d142432b
EM
220 'title' => 'Primary Address City',
221 'type' => CRM_Utils_Type::T_STRING,
59ca5f92 222 ];
223 $params['postal_code_suffix'] = [
d142432b
EM
224 'title' => 'Primary Address Post Code Suffix',
225 'type' => CRM_Utils_Type::T_STRING,
59ca5f92 226 ];
227 $params['postal_code'] = [
d142432b
EM
228 'title' => 'Primary Address Post Code',
229 'type' => CRM_Utils_Type::T_STRING,
59ca5f92 230 ];
231 $params['geo_code_1'] = [
d142432b
EM
232 'title' => 'Primary Address Latitude',
233 'type' => CRM_Utils_Type::T_STRING,
59ca5f92 234 ];
235 $params['geo_code_2'] = [
d142432b
EM
236 'title' => 'Primary Address Longitude',
237 'type' => CRM_Utils_Type::T_STRING,
59ca5f92 238 ];
239 $params['state_province_id'] = [
d142432b
EM
240 'title' => 'Primary Address State Province ID',
241 'type' => CRM_Utils_Type::T_INT,
59ca5f92 242 'pseudoconstant' => [
3493947a 243 'table' => 'civicrm_state_province',
59ca5f92 244 ],
245 ];
246 $params['state_province_name'] = [
d142432b
EM
247 'title' => 'Primary Address State Province Name',
248 'type' => CRM_Utils_Type::T_STRING,
59ca5f92 249 'pseudoconstant' => [
3493947a 250 'table' => 'civicrm_state_province',
59ca5f92 251 ],
252 ];
253 $params['state_province'] = [
d142432b
EM
254 'title' => 'Primary Address State Province',
255 'type' => CRM_Utils_Type::T_STRING,
59ca5f92 256 'pseudoconstant' => [
3493947a 257 'table' => 'civicrm_state_province',
59ca5f92 258 ],
259 ];
260 $params['country_id'] = [
d142432b
EM
261 'title' => 'Primary Address Country ID',
262 'type' => CRM_Utils_Type::T_INT,
59ca5f92 263 'pseudoconstant' => [
3493947a 264 'table' => 'civicrm_country',
59ca5f92 265 ],
266 ];
267 $params['country'] = [
d142432b
EM
268 'title' => 'Primary Address country',
269 'type' => CRM_Utils_Type::T_STRING,
59ca5f92 270 'pseudoconstant' => [
3493947a 271 'table' => 'civicrm_country',
59ca5f92 272 ],
273 ];
274 $params['worldregion_id'] = [
d142432b
EM
275 'title' => 'Primary Address World Region ID',
276 'type' => CRM_Utils_Type::T_INT,
59ca5f92 277 'pseudoconstant' => [
3493947a 278 'table' => 'civicrm_world_region',
59ca5f92 279 ],
280 ];
281 $params['worldregion'] = [
d142432b
EM
282 'title' => 'Primary Address World Region',
283 'type' => CRM_Utils_Type::T_STRING,
59ca5f92 284 'pseudoconstant' => [
3493947a 285 'table' => 'civicrm_world_region',
59ca5f92 286 ],
287 ];
288 $params['phone_id'] = [
d142432b
EM
289 'title' => 'Primary Phone ID',
290 'type' => CRM_Utils_Type::T_INT,
59ca5f92 291 ];
292 $params['phone'] = [
d142432b
EM
293 'title' => 'Primary Phone',
294 'type' => CRM_Utils_Type::T_STRING,
59ca5f92 295 ];
296 $params['phone_type_id'] = [
d142432b
EM
297 'title' => 'Primary Phone Type ID',
298 'type' => CRM_Utils_Type::T_INT,
59ca5f92 299 ];
300 $params['provider_id'] = [
d142432b
EM
301 'title' => 'Primary Phone Provider ID',
302 'type' => CRM_Utils_Type::T_INT,
59ca5f92 303 ];
304 $params['email_id'] = [
d142432b
EM
305 'title' => 'Primary Email ID',
306 'type' => CRM_Utils_Type::T_INT,
59ca5f92 307 ];
308 $params['email'] = [
d142432b
EM
309 'title' => 'Primary Email',
310 'type' => CRM_Utils_Type::T_STRING,
59ca5f92 311 ];
312 $params['on_hold'] = [
d142432b
EM
313 'title' => 'Primary Email On Hold',
314 'type' => CRM_Utils_Type::T_BOOLEAN,
59ca5f92 315 ];
316 $params['im'] = [
d142432b
EM
317 'title' => 'Primary Instant Messenger',
318 'type' => CRM_Utils_Type::T_STRING,
59ca5f92 319 ];
320 $params['im_id'] = [
d142432b
EM
321 'title' => 'Primary Instant Messenger ID',
322 'type' => CRM_Utils_Type::T_INT,
59ca5f92 323 ];
324 $params['group'] = [
985f4890 325 'title' => 'Group',
59ca5f92 326 'pseudoconstant' => [
985f4890 327 'table' => 'civicrm_group',
59ca5f92 328 ],
329 ];
330 $params['tag'] = [
985f4890 331 'title' => 'Tags',
59ca5f92 332 'pseudoconstant' => [
985f4890 333 'table' => 'civicrm_tag',
59ca5f92 334 ],
335 ];
336 $params['uf_user'] = [
8d475ce9
CW
337 'title' => 'CMS User',
338 'type' => CRM_Utils_Type::T_BOOLEAN,
59ca5f92 339 ];
340 $params['birth_date_low'] = [
341 'name' => 'birth_date_low',
342 'type' => CRM_Utils_Type::T_DATE,
343 'title' => ts('Birth Date is equal to or greater than'),
344 ];
345 $params['birth_date_high'] = [
346 'name' => 'birth_date_high',
347 'type' => CRM_Utils_Type::T_DATE,
348 'title' => ts('Birth Date is equal to or less than'),
349 ];
350 $params['deceased_date_low'] = [
351 'name' => 'deceased_date_low',
352 'type' => CRM_Utils_Type::T_DATE,
353 'title' => ts('Deceased Date is equal to or greater than'),
354 ];
355 $params['deceased_date_high'] = [
356 'name' => 'deceased_date_high',
357 'type' => CRM_Utils_Type::T_DATE,
358 'title' => ts('Deceased Date is equal to or less than'),
359 ];
6a488035
TO
360}
361
11e09c59 362/**
9d32e6f7
EM
363 * Support for historical oddities.
364 *
244bbdd8 365 * We are supporting 'showAll' = 'all', 'trash' or 'active' for Contact get
6a488035
TO
366 * and for getcount
367 * - hopefully some day we'll come up with a std syntax for the 3-way-boolean of
368 * 0, 1 or not set
369 *
370 * We also support 'filter_group_id' & 'filter.group_id'
371 *
cf470720
TO
372 * @param array $params
373 * As passed into api get or getcount function.
374 * @param array $options
375 * Array of options (so we can modify the filter).
6a488035
TO
376 */
377function _civicrm_api3_contact_get_supportanomalies(&$params, &$options) {
b69793be 378 if (!empty($params['email']) && !is_array($params['email'])) {
379 // Fix this to be in array format so the query object does not add LIKE
380 // I think there is a better fix that I will do for master.
381 $params['email'] = ['=' => $params['email']];
382 }
6a488035
TO
383 if (isset($params['showAll'])) {
384 if (strtolower($params['showAll']) == "active") {
385 $params['contact_is_deleted'] = 0;
386 }
387 if (strtolower($params['showAll']) == "trash") {
388 $params['contact_is_deleted'] = 1;
389 }
390 if (strtolower($params['showAll']) == "all" && isset($params['contact_is_deleted'])) {
391 unset($params['contact_is_deleted']);
392 }
393 }
394 // support for group filters
395 if (array_key_exists('filter_group_id', $params)) {
396 $params['filter.group_id'] = $params['filter_group_id'];
397 unset($params['filter_group_id']);
398 }
399 // filter.group_id works both for 1,2,3 and array (1,2,3)
400 if (array_key_exists('filter.group_id', $params)) {
401 if (is_array($params['filter.group_id'])) {
402 $groups = $params['filter.group_id'];
403 }
4f99ca55
TO
404 else {
405 $groups = explode(',', $params['filter.group_id']);
35671d00 406 }
6a488035 407 unset($params['filter.group_id']);
6a488035 408 $options['input_params']['group'] = $groups;
51c4748e
SL
409 }
410 if (isset($params['group'])) {
411 $groups = $params['group'];
f639bf2f
PN
412 $groupsByTitle = CRM_Core_PseudoConstant::group();
413 $groupsByName = CRM_Contact_BAO_GroupContact::buildOptions('group_id', 'validate');
414 $allGroups = array_merge(array_flip($groupsByTitle), array_flip($groupsByName));
51c4748e 415 if (is_array($groups) && in_array(key($groups), CRM_Core_DAO::acceptedSQLOperators(), TRUE)) {
0c66b30c 416 // Get the groups array.
51c4748e 417 $groupsArray = $groups[key($groups)];
0c66b30c 418 foreach ($groupsArray as &$group) {
f639bf2f
PN
419 if (!is_numeric($group) && !empty($allGroups[$group])) {
420 $group = $allGroups[$group];
51c4748e
SL
421 }
422 }
0c66b30c 423 // Now reset the $groups array with the ids not the titles.
56272bee 424 $groups[key($groups)] = $groupsArray;
51c4748e 425 }
0c66b30c 426 // handle format like 'group' => array('title1', 'title2').
51c4748e
SL
427 elseif (is_array($groups)) {
428 foreach ($groups as $k => &$group) {
f639bf2f
PN
429 if (!is_numeric($group) && !empty($allGroups[$group])) {
430 $group = $allGroups[$group];
51c4748e 431 }
f639bf2f 432 if (!is_numeric($k) && !empty($allGroups[$k])) {
b6b28d93 433 unset($groups[$k]);
f639bf2f 434 $groups[$allGroups[$k]] = $group;
b6b28d93 435 }
51c4748e
SL
436 }
437 }
59ca5f92 438 elseif (!is_numeric($groups) && !empty($allGroups[$groups])) {
f639bf2f 439 $groups = $allGroups[$groups];
51c4748e
SL
440 }
441 $params['group'] = $groups;
6a488035
TO
442 }
443}
444
445/**
244bbdd8 446 * Delete a Contact with given contact_id.
6a488035 447 *
cf470720 448 * @param array $params
c23f45d3 449 * input parameters per getfields
6a488035 450 *
a6c01b45 451 * @return array
72b3a70c 452 * API Result Array
17d8f8a8 453 * @throws \CRM_Core_Exception
454 * @throws \CiviCRM_API3_Exception
455 * @throws \Civi\API\Exception\UnauthorizedException
6a488035
TO
456 */
457function civicrm_api3_contact_delete($params) {
17d8f8a8 458 $contactID = (int) $params['id'];
6a488035 459
c16ed19b
CW
460 if (!empty($params['check_permissions']) && !CRM_Contact_BAO_Contact_Permission::allow($contactID, CRM_Core_Permission::DELETE)) {
461 throw new \Civi\API\Exception\UnauthorizedException('Permission denied to modify contact record');
462 }
463
17d8f8a8 464 if ($contactID == CRM_Core_Session::getLoggedInContactID()) {
465 throw new API_Exception('This contact record is linked to the currently logged in user account - and cannot be deleted.');
6a488035 466 }
1699214f 467 $restore = !empty($params['restore']);
468 $skipUndelete = !empty($params['skip_undelete']);
f182074e
PN
469
470 // CRM-12929
471 // restrict permanent delete if a contact has financial trxn associated with it
472 $error = NULL;
59ca5f92 473 if ($skipUndelete && CRM_Financial_BAO_FinancialItem::checkContactPresent([$contactID], $error)) {
17d8f8a8 474 throw new API_Exception($error['_qf_default']);
f182074e 475 }
fa6448fa
EM
476 if (CRM_Contact_BAO_Contact::deleteContact($contactID, $restore, $skipUndelete,
477 CRM_Utils_Array::value('check_permissions', $params))) {
6a488035
TO
478 return civicrm_api3_create_success();
479 }
17d8f8a8 480 throw new CiviCRM_API3_Exception('Could not delete contact');
6a488035
TO
481}
482
aa1b1481 483/**
9d32e6f7
EM
484 * Check parameters passed in.
485 *
486 * This function is on it's way out.
487 *
c490a46a 488 * @param array $params
aa1b1481
EM
489 *
490 * @return null
491 * @throws API_Exception
492 * @throws CiviCRM_API3_Exception
493 */
fedc3428 494function _civicrm_api3_contact_check_params(&$params) {
6a488035
TO
495
496 switch (strtolower(CRM_Utils_Array::value('contact_type', $params))) {
497 case 'household':
59ca5f92 498 civicrm_api3_verify_mandatory($params, NULL, ['household_name']);
6a488035 499 break;
35671d00 500
6a488035 501 case 'organization':
59ca5f92 502 civicrm_api3_verify_mandatory($params, NULL, ['organization_name']);
6a488035 503 break;
35671d00 504
6a488035 505 case 'individual':
59ca5f92 506 civicrm_api3_verify_one_mandatory($params, NULL, [
7c31ae57
SL
507 'first_name',
508 'last_name',
509 'email',
510 'display_name',
511 ]);
35671d00 512 break;
6a488035
TO
513 }
514
8cc574cf 515 if (!empty($params['contact_sub_type']) && !empty($params['contact_type'])) {
35671d00
TO
516 if (!(CRM_Contact_BAO_ContactType::isExtendsContactType($params['contact_sub_type'], $params['contact_type']))) {
517 throw new API_Exception("Invalid or Mismatched Contact Subtype: " . implode(', ', (array) $params['contact_sub_type']));
6a488035 518 }
35671d00 519 }
6a488035 520
8d99ab37 521 // The BAO no longer supports the legacy param "current_employer" so here is a shim for api backward-compatability
6a488035 522 if (!empty($params['current_employer'])) {
59ca5f92 523 $organizationParams = [
8d99ab37 524 'organization_name' => $params['current_employer'],
59ca5f92 525 ];
6a488035 526
59ca5f92 527 $dupeIds = CRM_Contact_BAO_Contact::getDuplicateContacts($organizationParams, 'Organization', 'Supervised', [], FALSE);
6a488035
TO
528
529 // check for mismatch employer name and id
530 if (!empty($params['employer_id']) && !in_array($params['employer_id'], $dupeIds)) {
531 throw new API_Exception('Employer name and Employer id Mismatch');
532 }
533
534 // show error if multiple organisation with same name exist
535 if (empty($params['employer_id']) && (count($dupeIds) > 1)) {
536 throw new API_Exception('Found more than one Organisation with same Name.');
537 }
8d99ab37
CW
538
539 if ($dupeIds) {
540 $params['employer_id'] = $dupeIds[0];
541 }
542 else {
59ca5f92 543 $result = civicrm_api3('Contact', 'create', [
8d99ab37 544 'organization_name' => $params['current_employer'],
21dfd5f5 545 'contact_type' => 'Organization',
59ca5f92 546 ]);
8d99ab37
CW
547 $params['employer_id'] = $result['id'];
548 }
6a488035
TO
549 }
550
551 return NULL;
552}
553
554/**
244bbdd8 555 * Helper function for Contact create.
6a488035 556 *
cf470720
TO
557 * @param array $params
558 * (reference ) an assoc array of name/value pairs.
559 * @param int $contactID
560 * If present the contact with that ID is updated.
6a488035 561 *
54f1aa2a 562 * @return CRM_Contact_BAO_Contact|CRM_Core_Error
17d8f8a8 563 *
564 * @throws \CRM_Core_Exception
565 * @throws \CiviCRM_API3_Exception
566 * @throws \Civi\API\Exception\UnauthorizedException
6a488035
TO
567 */
568function _civicrm_api3_contact_update($params, $contactID = NULL) {
6ecbca5b 569 //@todo - doesn't contact create support 'id' which is already set- check & remove
6a488035
TO
570 if ($contactID) {
571 $params['contact_id'] = $contactID;
572 }
573
6ecbca5b 574 return CRM_Contact_BAO_Contact::create($params);
6a488035
TO
575}
576
577/**
9d32e6f7 578 * Validate the addressee or email or postal greetings.
6a488035 579 *
cf470720 580 * @param array $params
9d32e6f7 581 * Array per getfields metadata.
6a488035 582 *
77b97be7 583 * @throws API_Exception
17d8f8a8 584 * @throws \CRM_Core_Exception
6a488035
TO
585 */
586function _civicrm_api3_greeting_format_params($params) {
59ca5f92 587 $greetingParams = ['', '_id', '_custom'];
588 foreach (['email', 'postal', 'addressee'] as $key) {
6a488035
TO
589 $greeting = '_greeting';
590 if ($key == 'addressee') {
591 $greeting = '';
592 }
593
594 $formatParams = FALSE;
22242c87 595 // Unset display value from params.
6a488035
TO
596 if (isset($params["{$key}{$greeting}_display"])) {
597 unset($params["{$key}{$greeting}_display"]);
598 }
599
600 // check if greetings are present in present
601 foreach ($greetingParams as $greetingValues) {
602 if (array_key_exists("{$key}{$greeting}{$greetingValues}", $params)) {
603 $formatParams = TRUE;
604 break;
605 }
606 }
607
608 if (!$formatParams) {
609 continue;
610 }
611
612 $nullValue = FALSE;
59ca5f92 613 $filter = [
6a488035 614 'greeting_type' => "{$key}{$greeting}",
59ca5f92 615 ];
6a488035 616
59ca5f92 617 $greetings = CRM_Core_PseudoConstant::greeting($filter);
f748c073 618 $greetingId = $params["{$key}{$greeting}_id"] ?? NULL;
619 $greetingVal = $params["{$key}{$greeting}"] ?? NULL;
620 $customGreeting = $params["{$key}{$greeting}_custom"] ?? NULL;
6a488035
TO
621
622 if (!$greetingId && $greetingVal) {
623 $params["{$key}{$greeting}_id"] = CRM_Utils_Array::key($params["{$key}{$greeting}"], $greetings);
624 }
625
626 if ($customGreeting && $greetingId &&
627 ($greetingId != array_search('Customized', $greetings))
628 ) {
6ecbca5b 629 throw new API_Exception(ts('Provide either %1 greeting id and/or %1 greeting or custom %1 greeting',
59ca5f92 630 [1 => $key]
631 ));
6a488035
TO
632 }
633
634 if ($greetingVal && $greetingId &&
635 ($greetingId != CRM_Utils_Array::key($greetingVal, $greetings))
636 ) {
6ecbca5b 637 throw new API_Exception(ts('Mismatch in %1 greeting id and %1 greeting',
59ca5f92 638 [1 => $key]
639 ));
6a488035
TO
640 }
641
642 if ($greetingId) {
6a488035 643 if (!$customGreeting && ($greetingId == array_search('Customized', $greetings))) {
6ecbca5b 644 throw new API_Exception(ts('Please provide a custom value for %1 greeting',
59ca5f92 645 [1 => $key]
646 ));
6a488035
TO
647 }
648 }
649 elseif ($greetingVal) {
650
651 if (!in_array($greetingVal, $greetings)) {
59ca5f92 652 throw new API_Exception(ts('Invalid %1 greeting', [1 => $key]));
6a488035
TO
653 }
654
655 $greetingId = CRM_Utils_Array::key($greetingVal, $greetings);
656 }
657
658 if ($customGreeting) {
659 $greetingId = CRM_Utils_Array::key('Customized', $greetings);
660 }
661
35671d00 662 $customValue = isset($params['contact_id']) ? CRM_Core_DAO::getFieldValue(
59ca5f92 663 'CRM_Contact_DAO_Contact',
664 $params['contact_id'],
665 "{$key}{$greeting}_custom"
666 ) : FALSE;
6a488035
TO
667
668 if (array_key_exists("{$key}{$greeting}_id", $params) && empty($params["{$key}{$greeting}_id"])) {
669 $nullValue = TRUE;
670 }
671 elseif (array_key_exists("{$key}{$greeting}", $params) && empty($params["{$key}{$greeting}"])) {
672 $nullValue = TRUE;
673 }
674 elseif ($customValue && array_key_exists("{$key}{$greeting}_custom", $params)
675 && empty($params["{$key}{$greeting}_custom"])
676 ) {
677 $nullValue = TRUE;
678 }
679
680 $params["{$key}{$greeting}_id"] = $greetingId;
681
682 if (!$customValue && !$customGreeting && array_key_exists("{$key}{$greeting}_custom", $params)) {
683 unset($params["{$key}{$greeting}_custom"]);
684 }
685
686 if ($nullValue) {
687 $params["{$key}{$greeting}_id"] = '';
688 $params["{$key}{$greeting}_custom"] = '';
689 }
690
691 if (isset($params["{$key}{$greeting}"])) {
692 unset($params["{$key}{$greeting}"]);
693 }
694 }
695}
696
2baa1e00 697/**
698 * Adjust Metadata for Get action.
699 *
700 * @param array $params
701 * Array of parameters determined by getfields.
702 */
703function _civicrm_api3_contact_getquick_spec(&$params) {
704 $params['name']['api.required'] = TRUE;
705 $params['name']['title'] = ts('String to search on');
706 $params['name']['type'] = CRM_Utils_Type::T_STRING;
707 $params['field']['type'] = CRM_Utils_Type::T_STRING;
708 $params['field']['title'] = ts('Field to search on');
59ca5f92 709 $params['field']['options'] = [
2baa1e00 710 '',
711 'id',
712 'contact_id',
713 'external_identifier',
714 'first_name',
715 'last_name',
716 'job_title',
717 'postal_code',
718 'street_address',
719 'email',
720 'city',
721 'phone_numeric',
59ca5f92 722 ];
2baa1e00 723 $params['table_name']['type'] = CRM_Utils_Type::T_STRING;
724 $params['table_name']['title'] = ts('Table alias to search on');
725 $params['table_name']['api.default'] = 'cc';
726}
727
6a488035 728/**
244bbdd8 729 * Old Contact quick search api.
6a488035 730 *
03f32517 731 * @deprecated
6a488035 732 *
d0997921 733 * @param array $params
9d32e6f7 734 *
645ee340
EM
735 * @return array
736 * @throws \API_Exception
6a488035 737 */
6a488035 738function civicrm_api3_contact_getquick($params) {
aca85468 739 $name = CRM_Utils_Type::escape(CRM_Utils_Array::value('name', $params), 'String');
2baa1e00 740 $table_name = CRM_Utils_String::munge($params['table_name']);
6a488035
TO
741 // get the autocomplete options from settings
742 $acpref = explode(CRM_Core_DAO::VALUE_SEPARATOR,
743 CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME,
744 'contact_autocomplete_options'
745 )
746 );
747
4235341b
CW
748 $table_names = [
749 'email' => 'eml',
750 'phone_numeric' => 'phe',
751 'street_address' => 'sts',
752 'city' => 'sts',
753 'postal_code' => 'sts',
754 ];
755
6a488035
TO
756 // get the option values for contact autocomplete
757 $acOptions = CRM_Core_OptionGroup::values('contact_autocomplete_options', FALSE, FALSE, FALSE, NULL, 'name');
758
59ca5f92 759 $list = $from = [];
6a488035 760 foreach ($acpref as $value) {
8cc574cf 761 if ($value && !empty($acOptions[$value])) {
6a488035
TO
762 $list[$value] = $acOptions[$value];
763 }
764 }
765 // If we are doing quicksearch by a field other than name, make sure that field is added to results
766 if (!empty($params['field_name'])) {
1aba4d9a 767 $field_name = CRM_Utils_String::munge($params['field_name']);
d2cad5f0
PF
768 // there is no good reason to request api_key via getquick
769 if ($field_name == 'api_key') {
770 throw new API_Exception('Illegal value "api_key" for parameter "field_name"');
771 }
5d8ba7a7 772 // Unique name contact_id = id
1aba4d9a
CW
773 if ($field_name == 'contact_id') {
774 $field_name = 'id';
5d8ba7a7 775 }
9384c60a
MD
776 // core#1420 : trim non-numeric character from phone search string
777 elseif ($field_name == 'phone_numeric') {
778 $name = preg_replace('/[^\d]/', '', $name);
779 }
4235341b
CW
780 if (isset($table_names[$field_name])) {
781 $table_name = $table_names[$field_name];
782 }
783 elseif (strpos($field_name, 'custom_') === 0) {
1f8ac3d2 784 $customField = civicrm_api3('CustomField', 'getsingle', [
4235341b 785 'id' => substr($field_name, 7),
59ca5f92 786 'return' => [
787 'custom_group_id.table_name',
788 'column_name',
789 'data_type',
790 'option_group_id',
791 'html_type',
792 ],
4235341b 793 ]);
1f8ac3d2
CW
794 $field_name = $customField['column_name'];
795 $table_name = CRM_Utils_String::munge($customField['custom_group_id.table_name']);
4235341b 796 $from[$field_name] = "LEFT JOIN `$table_name` ON cc.id = `$table_name`.entity_id";
1f8ac3d2
CW
797 if (CRM_Core_BAO_CustomField::hasOptions($customField)) {
798 $customOptionsWhere = [];
799 $customFieldOptions = CRM_Contact_BAO_Contact::buildOptions('custom_' . $customField['id'], 'search');
800 $isMultivalueField = CRM_Core_BAO_CustomField::isSerialized($customField);
801 $sep = CRM_Core_DAO::VALUE_SEPARATOR;
802 foreach ($customFieldOptions as $optionKey => $optionLabel) {
803 if (mb_stripos($optionLabel, $name) !== FALSE) {
804 $customOptionsWhere[$optionKey] = "$table_name.$field_name " . ($isMultivalueField ? "LIKE '%{$sep}{$optionKey}{$sep}%'" : "= '$optionKey'");
805 }
806 }
807 }
4235341b 808 }
6a488035 809 // phone_numeric should be phone
1aba4d9a 810 $searchField = str_replace('_numeric', '', $field_name);
22e263ad 811 if (!in_array($searchField, $list)) {
6a488035
TO
812 $list[] = $searchField;
813 }
814 }
2baa1e00 815 else {
816 // Set field name to first name for exact match checking.
817 $field_name = 'sort_name';
818 }
6a488035 819
59ca5f92 820 $select = $actualSelectElements = ['sort_name'];
c3cea83f 821
6a488035
TO
822 foreach ($list as $value) {
823 $suffix = substr($value, 0, 2) . substr($value, -1);
824 switch ($value) {
825 case 'street_address':
826 case 'city':
827 case 'postal_code':
828 $selectText = $value;
59ca5f92 829 $value = "address";
830 $suffix = 'sts';
6a488035
TO
831 case 'phone':
832 case 'email':
833 $actualSelectElements[] = $select[] = ($value == 'address') ? $selectText : $value;
aebdef3c
JL
834 if ($value == 'phone') {
835 $actualSelectElements[] = $select[] = 'phone_ext';
836 }
6a488035
TO
837 $from[$value] = "LEFT JOIN civicrm_{$value} {$suffix} ON ( cc.id = {$suffix}.contact_id AND {$suffix}.is_primary = 1 ) ";
838 break;
839
840 case 'country':
841 case 'state_province':
842 $select[] = "{$suffix}.name as {$value}";
843 $actualSelectElements[] = "{$suffix}.name";
844 if (!in_array('address', $from)) {
845 $from['address'] = 'LEFT JOIN civicrm_address sts ON ( cc.id = sts.contact_id AND sts.is_primary = 1) ';
846 }
847 $from[$value] = " LEFT JOIN civicrm_{$value} {$suffix} ON ( sts.{$value}_id = {$suffix}.id ) ";
848 break;
849
850 default:
4235341b
CW
851 if ($value == 'id') {
852 $actualSelectElements[] = 'cc.id';
853 }
854 elseif ($value != 'sort_name') {
6a488035 855 $suffix = 'cc';
4235341b
CW
856 if ($field_name == $value) {
857 $suffix = $table_name;
6a488035
TO
858 }
859 $actualSelectElements[] = $select[] = $suffix . '.' . $value;
860 }
861 break;
862 }
863 }
864
865 $config = CRM_Core_Config::singleton();
59ca5f92 866 $as = $select;
6a488035
TO
867 $select = implode(', ', $select);
868 if (!empty($select)) {
869 $select = ", $select";
870 }
871 $actualSelectElements = implode(', ', $actualSelectElements);
6a488035 872 $from = implode(' ', $from);
2975f0aa 873 $limit = (int) ($params['limit'] ?? 0);
89595c92 874 $limit = $limit > 0 ? $limit : Civi::settings()->get('search_autocomplete_count');
6a488035
TO
875
876 // add acl clause here
877 list($aclFrom, $aclWhere) = CRM_Contact_BAO_Contact_Permission::cacheClause('cc');
c3cea83f 878 $whereClauses = ['cc.is_deleted = 0'];
6a488035 879 if ($aclWhere) {
c3cea83f 880 $whereClauses[] = $aclWhere;
6a488035 881 }
613643e0 882 $isPrependWildcard = \Civi::settings()->get('includeWildCardInName');
6a488035 883
a7488080 884 if (!empty($params['org'])) {
c3cea83f 885 $whereClauses[] = 'contact_type = "Organization"';
6a488035
TO
886
887 // CRM-7157, hack: get current employer details when
888 // employee_id is present.
59ca5f92 889 $currEmpDetails = [];
a7488080 890 if (!empty($params['employee_id'])) {
6a488035 891 if ($currentEmployer = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact',
59ca5f92 892 (int) $params['employee_id'],
893 'employer_id'
894 )) {
613643e0 895 if ($isPrependWildcard) {
6a488035
TO
896 $strSearch = "%$name%";
897 }
898 else {
899 $strSearch = "$name%";
900 }
901
902 // get current employer details
903 $dao = CRM_Core_DAO::executeQuery("SELECT cc.id as id, CONCAT_WS( ' :: ', {$actualSelectElements} ) as data, sort_name
904 FROM civicrm_contact cc {$from} WHERE cc.contact_type = \"Organization\" AND cc.id = {$currentEmployer} AND cc.sort_name LIKE '$strSearch'");
905 if ($dao->fetch()) {
59ca5f92 906 $currEmpDetails = [
6a488035
TO
907 'id' => $dao->id,
908 'data' => $dao->data,
59ca5f92 909 ];
6a488035
TO
910 }
911 }
912 }
913 }
914
a7488080 915 if (!empty($params['contact_sub_type'])) {
69164898 916 $contactSubType = CRM_Utils_Type::escape($params['contact_sub_type'], 'String');
c3cea83f 917 $whereClauses[] = "cc.contact_sub_type = '{$contactSubType}'";
69164898
N
918 }
919
e1b717cb
P
920 if (!empty($params['contact_type'])) {
921 $contactType = CRM_Utils_Type::escape($params['contact_type'], 'String');
c3cea83f 922 $whereClauses[] = "cc.contact_type LIKE '{$contactType}'";
e1b717cb
P
923 }
924
244bbdd8 925 // Set default for current_employer or return contact with particular id
a7488080 926 if (!empty($params['id'])) {
c3cea83f 927 $whereClauses[] = 'cc.id = ' . (int) $params['id'];
6a488035
TO
928 }
929
a7488080 930 if (!empty($params['cid'])) {
c3cea83f 931 $whereClauses[] = 'cc.id <> ' . (int) $params['cid'];
6a488035
TO
932 }
933
244bbdd8 934 // Contact's based of relationhip type
6a488035 935 $relType = NULL;
a7488080 936 if (!empty($params['rel'])) {
2cfe2cf4 937 $relation = explode('_', $params['rel']);
59ca5f92 938 $relType = CRM_Utils_Type::escape($relation[0], 'Integer');
939 $rel = CRM_Utils_Type::escape($relation[2], 'String');
6a488035
TO
940 }
941
613643e0 942 if ($isPrependWildcard) {
6a488035
TO
943 $strSearch = "%$name%";
944 }
945 else {
946 $strSearch = "$name%";
947 }
1f8ac3d2 948 $includeEmailFrom = $includeNickName = '';
6a488035
TO
949 if ($config->includeNickNameInName) {
950 $includeNickName = " OR nick_name LIKE '$strSearch'";
6a488035 951 }
c3cea83f 952 $where = ' AND ' . implode(' AND ', $whereClauses);
1f8ac3d2
CW
953 if (isset($customOptionsWhere)) {
954 $customOptionsWhere = $customOptionsWhere ?: [0];
c3cea83f 955 $whereClause = ' WHERE (' . implode(' OR ', $customOptionsWhere) . ") $where";
1f8ac3d2 956 }
d976e590 957 elseif (!empty($params['field_name']) && !empty($params['table_name']) && $params['field_name'] != 'sort_name') {
8d3b1aa6 958 $whereClause = " WHERE ( $table_name.$field_name LIKE '$strSearch') {$where}";
6a488035
TO
959 // Search by id should be exact
960 if ($field_name == 'id' || $field_name == 'external_identifier') {
613643e0 961 $whereClause = " WHERE ( $table_name.$field_name = '$name') {$where}";
6a488035
TO
962 }
963 }
964 else {
a5728a28 965 $whereClause = " WHERE ( sort_name LIKE '$strSearch' $includeNickName ) {$where} ";
6a488035
TO
966 if ($config->includeEmailInName) {
967 if (!in_array('email', $list)) {
968 $includeEmailFrom = "LEFT JOIN civicrm_email eml ON ( cc.id = eml.contact_id AND eml.is_primary = 1 )";
969 }
36575b09 970 $emailWhere = " WHERE email LIKE '$strSearch'";
6a488035
TO
971 }
972 }
973
974 $additionalFrom = '';
975 if ($relType) {
976 $additionalFrom = "
977 INNER JOIN civicrm_relationship_type r ON (
978 r.id = {$relType}
979 AND ( cc.contact_type = r.contact_type_{$rel} OR r.contact_type_{$rel} IS NULL )
980 AND ( cc.contact_sub_type = r.contact_sub_type_{$rel} OR r.contact_sub_type_{$rel} IS NULL )
981 )";
982 }
983
984 // check if only CMS users are requested
a7488080 985 if (!empty($params['cmsuser'])) {
6a488035
TO
986 $additionalFrom = "
987 INNER JOIN civicrm_uf_match um ON (um.contact_id=cc.id)
988 ";
989 }
613643e0 990 $orderBy = _civicrm_api3_quicksearch_get_order_by($name, $isPrependWildcard, $field_name);
51e61eae 991
6a488035
TO
992 //CRM-5954
993 $query = "
1f8ac3d2 994 SELECT DISTINCT(id), data, sort_name, exactFirst
6a488035 995 FROM (
2baa1e00 996 ( SELECT IF($table_name.$field_name = '{$name}', 0, 1) as exactFirst, cc.id as id, CONCAT_WS( ' :: ',
997 {$actualSelectElements} )
998 as data
999 {$select}
6a488035
TO
1000 FROM civicrm_contact cc {$from}
1001 {$aclFrom}
a5728a28 1002 {$additionalFrom}
6a488035 1003 {$whereClause}
613643e0 1004 {$orderBy}
6a488035 1005 LIMIT 0, {$limit} )
6a488035 1006 ";
a5728a28 1007
1008 if (!empty($emailWhere)) {
1009 $query .= "
1010 UNION (
1011 SELECT IF($table_name.$field_name = '{$name}', 0, 1) as exactFirst, cc.id as id, CONCAT_WS( ' :: ',
1012 {$actualSelectElements} )
1013 as data
1014 {$select}
1015 FROM civicrm_contact cc {$from}
1016 {$aclFrom}
1017 {$additionalFrom} {$includeEmailFrom}
c37a2d66 1018 {$emailWhere} AND cc.is_deleted = 0 " . ($aclWhere ? " AND $aclWhere " : '') . "
613643e0 1019 {$orderBy}
a5728a28 1020 LIMIT 0, {$limit}
1021 )
1022 ";
1023 }
36575b09 1024 $query .= ") t
613643e0 1025 {$orderBy}
2baa1e00 1026 LIMIT 0, {$limit}
1027 ";
1028
6a488035
TO
1029 // send query to hook to be modified if needed
1030 CRM_Utils_Hook::contactListQuery($query,
1031 $name,
133da98d
CW
1032 empty($params['context']) ? NULL : CRM_Utils_Type::escape($params['context'], 'String'),
1033 empty($params['id']) ? NULL : $params['id']
6a488035
TO
1034 );
1035
1036 $dao = CRM_Core_DAO::executeQuery($query);
1037
59ca5f92 1038 $contactList = [];
6a488035
TO
1039 $listCurrentEmployer = TRUE;
1040 while ($dao->fetch()) {
59ca5f92 1041 $t = ['id' => $dao->id];
6a488035 1042 foreach ($as as $k) {
2e1f50d6 1043 $t[$k] = $dao->$k ?? '';
6a488035
TO
1044 }
1045 $t['data'] = $dao->data;
1f8ac3d2
CW
1046 // Replace keys with values when displaying fields from an option list
1047 if (!empty($customOptionsWhere)) {
1048 $data = explode(' :: ', $dao->data);
1049 $pos = count($data) - 1;
1050 $customValue = array_intersect(CRM_Utils_Array::explodePadded($data[$pos]), array_keys($customOptionsWhere));
1051 $data[$pos] = implode(', ', array_intersect_key($customFieldOptions, array_flip($customValue)));
1052 $t['data'] = implode(' :: ', $data);
1053 }
6a488035 1054 $contactList[] = $t;
a7488080 1055 if (!empty($params['org']) &&
6a488035
TO
1056 !empty($currEmpDetails) &&
1057 $dao->id == $currEmpDetails['id']
1058 ) {
1059 $listCurrentEmployer = FALSE;
1060 }
1061 }
1062
1063 //return organization name if doesn't exist in db
1064 if (empty($contactList)) {
a7488080 1065 if (!empty($params['org'])) {
6a488035 1066 if ($listCurrentEmployer && !empty($currEmpDetails)) {
59ca5f92 1067 $contactList = [
1068 [
d5cc0fc2 1069 'data' => $currEmpDetails['data'],
59ca5f92 1070 'id' => $currEmpDetails['id'],
1071 ],
1072 ];
6a488035
TO
1073 }
1074 else {
59ca5f92 1075 $contactList = [
1076 [
6a488035 1077 'data' => $name,
59ca5f92 1078 'id' => $name,
1079 ],
1080 ];
6a488035
TO
1081 }
1082 }
1083 }
1084
244bbdd8 1085 return civicrm_api3_create_success($contactList, $params, 'Contact', 'getquick');
a14e9d08
CW
1086}
1087
613643e0 1088/**
1089 * Get the order by string for the quicksearch query.
1090 *
1091 * Get the order by string. The string might be
1092 * - sort name if there is no search value provided and the site is configured
1093 * to search by sort name
1094 * - empty if there is no search value provided and the site is not configured
1095 * to search by sort name
1096 * - exactFirst and then sort name if a search value is provided and the site is configured
1097 * to search by sort name
1098 * - exactFirst if a search value is provided and the site is not configured
1099 * to search by sort name
1100 *
1101 * exactFirst means 'yes if the search value exactly matches the searched field. else no'.
1102 * It is intended to prioritise exact matches for the entered string so on a first name search
1103 * for 'kath' contacts with a first name of exactly Kath rise to the top.
1104 *
1105 * On short strings it is expensive. Per CRM-19547 there is still an open question
1106 * as to whether we should only do exactMatch on a minimum length or on certain fields.
1107 *
1108 * However, we have mitigated this somewhat by not doing an exact match search on
1109 * empty strings, non-wildcard sort-name searches and email searches where there is
1110 * no @ after the first character.
1111 *
1112 * For the user it is further mitigated by the fact they just don't know the
1113 * slower queries are firing. If they type 'smit' slowly enough 4 queries will trigger
1114 * but if the first 3 are slow the first result they see may be off the 4th query.
1115 *
1116 * @param string $name
1117 * @param bool $isPrependWildcard
1118 * @param string $field_name
1119 *
1120 * @return string
1121 */
1122function _civicrm_api3_quicksearch_get_order_by($name, $isPrependWildcard, $field_name) {
1123 $skipExactMatch = ($name === '%');
1124 if ($field_name === 'email' && !strpos('@', $name)) {
1125 $skipExactMatch = TRUE;
1126 }
1127
1128 if (!\Civi::settings()->get('includeOrderByClause')) {
1129 return $skipExactMatch ? '' : "ORDER BY exactFirst";
1130 }
1131 if ($skipExactMatch || (!$isPrependWildcard && $field_name === 'sort_name')) {
1132 // If there is no wildcard then sorting by exactFirst would have the same
1133 // effect as just a sort_name search, but slower.
1134 return "ORDER BY sort_name";
1135 }
1136
1137 return "ORDER BY exactFirst, sort_name";
1138}
1139
a14e9d08 1140/**
35823763
EM
1141 * Declare deprecated api functions.
1142 *
a14e9d08 1143 * @deprecated api notice
a6c01b45 1144 * @return array
16b10e64 1145 * Array of deprecated actions
a14e9d08
CW
1146 */
1147function _civicrm_api3_contact_deprecation() {
59ca5f92 1148 return ['getquick' => 'The "getquick" action is deprecated in favor of "getlist".'];
6a488035
TO
1149}
1150
1151/**
1152 * Merges given pair of duplicate contacts.
1153 *
cf470720 1154 * @param array $params
b081365f
CW
1155 * Allowed array keys are:
1156 * -int main_id: main contact id with whom merge has to happen
1157 * -int other_id: duplicate contact which would be deleted after merge operation
1158 * -string mode: "safe" skips the merge if there are no conflicts. Does a force merge otherwise.
6a488035 1159 *
a6c01b45 1160 * @return array
72b3a70c 1161 * API Result Array
17d8f8a8 1162 *
fedc3428 1163 * @throws API_Exception
17d8f8a8 1164 * @throws \CiviCRM_API3_Exception
1165 * @throws \CRM_Core_Exception
6a488035
TO
1166 */
1167function civicrm_api3_contact_merge($params) {
8b5445c8 1168 if (($result = CRM_Dedupe_Merger::merge(
1169 [['srcID' => $params['to_remove_id'], 'dstID' => $params['to_keep_id']]],
1170 [],
1171 $params['mode'],
1172 FALSE,
1173 CRM_Utils_Array::value('check_permissions', $params)
1174 )) != FALSE) {
1175
12d73bba 1176 return civicrm_api3_create_success($result, $params);
6a488035 1177 }
fedc3428 1178 throw new API_Exception('Merge failed');
12d73bba 1179}
1180
1181/**
5ea06a7b 1182 * Adjust metadata for contact_merge api function.
12d73bba 1183 *
1184 * @param array $params
1185 */
1186function _civicrm_api3_contact_merge_spec(&$params) {
59ca5f92 1187 $params['to_remove_id'] = [
aefc291e 1188 'title' => ts('ID of the contact to merge & remove'),
1189 'description' => ts('Wow - these 2 aliased params are the logical reverse of what I expect - but what to do?'),
12d73bba 1190 'api.required' => 1,
1191 'type' => CRM_Utils_Type::T_INT,
59ca5f92 1192 'api.aliases' => ['main_id'],
1193 ];
1194 $params['to_keep_id'] = [
aefc291e 1195 'title' => ts('ID of the contact to keep'),
1196 'description' => ts('Wow - these 2 aliased params are the logical reverse of what I expect - but what to do?'),
12d73bba 1197 'api.required' => 1,
1198 'type' => CRM_Utils_Type::T_INT,
59ca5f92 1199 'api.aliases' => ['other_id'],
1200 ];
1201 $params['mode'] = [
aefc291e 1202 'title' => ts('Dedupe mode'),
1203 'description' => ts("In 'safe' mode conflicts will result in no merge. In 'aggressive' mode the merge will still proceed (hook dependent)"),
6f2c4a24 1204 'api.default' => 'safe',
712ee28f 1205 'options' => ['safe' => ts('Abort on unhandled conflict'), 'aggressive' => ts('Proceed on unhandled conflict. Note hooks may change handling here.')],
aefc291e 1206 ];
1207}
1208
1209/**
1210 * Determines if given pair of contaacts have conflicts that would affect merging them.
1211 *
1212 * @param array $params
1213 * Allowed array keys are:
1214 * -int main_id: main contact id with whom merge has to happen
1215 * -int other_id: duplicate contact which would be deleted after merge operation
1216 * -string mode: "safe" skips the merge if there are no conflicts. Does a force merge otherwise.
1217 *
1218 * @return array
1219 * API Result Array
1220 *
1221 * @throws \CRM_Core_Exception
1222 * @throws \CiviCRM_API3_Exception
712ee28f 1223 * @throws \API_Exception
aefc291e 1224 */
1225function civicrm_api3_contact_get_merge_conflicts($params) {
1226 $migrationInfo = [];
ffa59d18 1227 $result = [];
712ee28f 1228 foreach ((array) $params['mode'] as $mode) {
403400d9 1229 $result[$mode] = CRM_Dedupe_Merger::getConflicts(
712ee28f 1230 $migrationInfo,
aefc291e 1231 $params['to_remove_id'], $params['to_keep_id'],
ffa59d18 1232 $mode
712ee28f 1233 );
aefc291e 1234 }
ffa59d18 1235 return civicrm_api3_create_success($result, $params);
aefc291e 1236}
1237
1238/**
1239 * Adjust metadata for contact_merge api function.
1240 *
1241 * @param array $params
1242 */
1243function _civicrm_api3_contact_get_merge_conflicts_spec(&$params) {
1244 $params['to_remove_id'] = [
1245 'title' => ts('ID of the contact to merge & remove'),
1246 'api.required' => 1,
1247 'type' => CRM_Utils_Type::T_INT,
1248 ];
1249 $params['to_keep_id'] = [
1250 'title' => ts('ID of the contact to keep'),
1251 'api.required' => 1,
1252 'type' => CRM_Utils_Type::T_INT,
1253 ];
1254 $params['mode'] = [
1255 'title' => ts('Dedupe mode'),
1256 'description' => ts("'safe' or 'aggressive' - these modes map to the merge actions & may affect resolution done by hooks "),
ffa59d18 1257 'api.default' => 'safe',
59ca5f92 1258 ];
6a488035
TO
1259}
1260
734cd0d5 1261/**
1262 * Get the ultimate contact a contact was merged to.
1263 *
1264 * @param array $params
1265 *
1266 * @return array
1267 * API Result Array
17d8f8a8 1268 *
1269 * @throws \CiviCRM_API3_Exception
734cd0d5 1270 */
1271function civicrm_api3_contact_getmergedto($params) {
1272 $contactID = _civicrm_api3_contact_getmergedto($params);
1273 if ($contactID) {
1274 $values = [$contactID => ['id' => $contactID]];
1275 }
1276 else {
1277 $values = [];
1278 }
1279 return civicrm_api3_create_success($values, $params);
1280}
1281
1282/**
1283 * Get the contact our contact was finally merged to.
1284 *
1285 * If the contact has been merged multiple times the crucial parent activity will have
1286 * wound up on the ultimate contact so we can figure out the final resting place of the
1287 * contact with only 2 activities even if 50 merges took place.
1288 *
1289 * @param array $params
1290 *
1291 * @return int|false
17d8f8a8 1292 *
1293 * @throws \CiviCRM_API3_Exception
734cd0d5 1294 */
1295function _civicrm_api3_contact_getmergedto($params) {
1296 $contactID = FALSE;
1297 $deleteActivity = civicrm_api3('ActivityContact', 'get', [
1298 'contact_id' => $params['contact_id'],
1299 'activity_id.activity_type_id' => 'Contact Deleted By Merge',
1300 'is_deleted' => 0,
1301 'is_test' => $params['is_test'],
1302 'record_type_id' => 'Activity Targets',
1303 'return' => ['activity_id.parent_id'],
1304 'sequential' => 1,
1305 'options' => [
1306 'limit' => 1,
59ca5f92 1307 'sort' => 'activity_id.activity_date_time DESC',
734cd0d5 1308 ],
1309 ])['values'];
1310 if (!empty($deleteActivity)) {
1311 $contactID = civicrm_api3('ActivityContact', 'getvalue', [
1312 'activity_id' => $deleteActivity[0]['activity_id.parent_id'],
1313 'record_type_id' => 'Activity Targets',
1314 'return' => 'contact_id',
1315 ]);
1316 }
1317 return $contactID;
1318}
1319
1320/**
1321 * Adjust metadata for contact_merge api function.
1322 *
1323 * @param array $params
1324 */
1325function _civicrm_api3_contact_getmergedto_spec(&$params) {
1326 $params['contact_id'] = [
1327 'title' => ts('ID of contact to find ultimate contact for'),
1328 'type' => CRM_Utils_Type::T_INT,
1329 'api.required' => TRUE,
1330 ];
1331 $params['is_test'] = [
1332 'title' => ts('Get test deletions rather than live?'),
1333 'type' => CRM_Utils_Type::T_BOOLEAN,
1334 'api.default' => 0,
1335 ];
1336}
1337
1338/**
1339 * Get the ultimate contact a contact was merged to.
1340 *
1341 * @param array $params
1342 *
1343 * @return array
1344 * API Result Array
17d8f8a8 1345 *
1346 * @throws \CiviCRM_API3_Exception
734cd0d5 1347 */
1348function civicrm_api3_contact_getmergedfrom($params) {
1349 $contacts = _civicrm_api3_contact_getmergedfrom($params);
1350 return civicrm_api3_create_success($contacts, $params);
1351}
1352
1353/**
1354 * Get all the contacts merged into our contact.
1355 *
1356 * @param array $params
1357 *
1358 * @return array
17d8f8a8 1359 *
1360 * @throws \CiviCRM_API3_Exception
734cd0d5 1361 */
1362function _civicrm_api3_contact_getmergedfrom($params) {
1363 $activities = [];
1364 $deleteActivities = civicrm_api3('ActivityContact', 'get', [
1365 'contact_id' => $params['contact_id'],
1366 'activity_id.activity_type_id' => 'Contact Merged',
1367 'is_deleted' => 0,
1368 'is_test' => $params['is_test'],
1369 'record_type_id' => 'Activity Targets',
1370 'return' => 'activity_id',
1371 ])['values'];
1372
1373 foreach ($deleteActivities as $deleteActivity) {
1374 $activities[] = $deleteActivity['activity_id'];
1375 }
1376 if (empty($activities)) {
1377 return [];
1378 }
1379
1380 $activityContacts = civicrm_api3('ActivityContact', 'get', [
1381 'activity_id.parent_id' => ['IN' => $activities],
1382 'record_type_id' => 'Activity Targets',
1383 'return' => 'contact_id',
1384 ])['values'];
1385 $contacts = [];
1386 foreach ($activityContacts as $activityContact) {
1387 $contacts[$activityContact['contact_id']] = ['id' => $activityContact['contact_id']];
1388 }
1389 return $contacts;
1390}
1391
1392/**
1393 * Adjust metadata for contact_merge api function.
1394 *
1395 * @param array $params
1396 */
1397function _civicrm_api3_contact_getmergedfrom_spec(&$params) {
1398 $params['contact_id'] = [
1399 'title' => ts('ID of contact to find ultimate contact for'),
1400 'type' => CRM_Utils_Type::T_INT,
1401 'api.required' => TRUE,
1402 ];
1403 $params['is_test'] = [
1404 'title' => ts('Get test deletions rather than live?'),
1405 'type' => CRM_Utils_Type::T_BOOLEAN,
1406 'api.default' => 0,
1407 ];
1408}
1409
aa1b1481 1410/**
9d32e6f7
EM
1411 * Adjust metadata for contact_proximity api function.
1412 *
c490a46a 1413 * @param array $params
aa1b1481 1414 */
6a488035 1415function _civicrm_api3_contact_proximity_spec(&$params) {
59ca5f92 1416 $params['latitude'] = [
d142432b
EM
1417 'title' => 'Latitude',
1418 'api.required' => 1,
1419 'type' => CRM_Utils_Type::T_STRING,
59ca5f92 1420 ];
1421 $params['longitude'] = [
d142432b
EM
1422 'title' => 'Longitude',
1423 'api.required' => 1,
1424 'type' => CRM_Utils_Type::T_STRING,
59ca5f92 1425 ];
d142432b 1426
59ca5f92 1427 $params['unit'] = [
d142432b
EM
1428 'title' => 'Unit of Measurement',
1429 'api.default' => 'meter',
1430 'type' => CRM_Utils_Type::T_STRING,
59ca5f92 1431 ];
6a488035
TO
1432}
1433
aa1b1481 1434/**
9d32e6f7
EM
1435 * Get contacts by proximity.
1436 *
c490a46a 1437 * @param array $params
aa1b1481
EM
1438 *
1439 * @return array
1440 * @throws Exception
1441 */
6a488035 1442function civicrm_api3_contact_proximity($params) {
f748c073 1443 $latitude = $params['latitude'] ?? NULL;
1444 $longitude = $params['longitude'] ?? NULL;
1445 $distance = $params['distance'] ?? NULL;
6a488035 1446
f748c073 1447 $unit = $params['unit'] ?? NULL;
6a488035
TO
1448
1449 // check and ensure that lat/long and distance are floats
1450 if (
1451 !CRM_Utils_Rule::numeric($latitude) ||
1452 !CRM_Utils_Rule::numeric($longitude) ||
1453 !CRM_Utils_Rule::numeric($distance)
1454 ) {
17d8f8a8 1455 throw new API_Exception(ts('Latitude, Longitude and Distance should exist and be numeric'));
6a488035
TO
1456 }
1457
17d8f8a8 1458 if ($unit === 'mile') {
6a488035
TO
1459 $conversionFactor = 1609.344;
1460 }
1461 else {
1462 $conversionFactor = 1000;
1463 }
1464 //Distance in meters
1465 $distance = $distance * $conversionFactor;
1466
1467 $whereClause = CRM_Contact_BAO_ProximityQuery::where($latitude, $longitude, $distance);
1468
1469 $query = "
1470SELECT civicrm_contact.id as contact_id,
1471 civicrm_contact.display_name as display_name
1472FROM civicrm_contact
1473LEFT JOIN civicrm_address ON civicrm_contact.id = civicrm_address.contact_id
1474WHERE $whereClause
1475";
1476
1477 $dao = CRM_Core_DAO::executeQuery($query);
59ca5f92 1478 $contacts = [];
6a488035
TO
1479 while ($dao->fetch()) {
1480 $contacts[] = $dao->toArray();
1481 }
1482
244bbdd8 1483 return civicrm_api3_create_success($contacts, $params, 'Contact', 'get_by_location', $dao);
6a488035
TO
1484}
1485
ff88d165 1486/**
22242c87
EM
1487 * Get parameters for getlist function.
1488 *
a6c6059d 1489 * @see _civicrm_api3_generic_getlist_params
ff88d165 1490 *
8c6b335b 1491 * @param array $request
ff88d165
CW
1492 */
1493function _civicrm_api3_contact_getlist_params(&$request) {
1494 // get the autocomplete options from settings
1495 $acpref = explode(CRM_Core_DAO::VALUE_SEPARATOR,
1496 CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME,
1497 'contact_autocomplete_options'
1498 )
1499 );
1500
1501 // get the option values for contact autocomplete
1502 $acOptions = CRM_Core_OptionGroup::values('contact_autocomplete_options', FALSE, FALSE, FALSE, NULL, 'name');
1503
59ca5f92 1504 $list = [];
ff88d165
CW
1505 foreach ($acpref as $value) {
1506 if ($value && !empty($acOptions[$value])) {
1507 $list[] = $acOptions[$value];
1508 }
1509 }
1510 // If we are doing quicksearch by a field other than name, make sure that field is added to results
1511 $field_name = CRM_Utils_String::munge($request['search_field']);
1512 // Unique name contact_id = id
17d8f8a8 1513 if ($field_name === 'contact_id') {
ff88d165
CW
1514 $field_name = 'id';
1515 }
1516 // phone_numeric should be phone
1517 $searchField = str_replace('_numeric', '', $field_name);
22e263ad 1518 if (!in_array($searchField, $list)) {
ff88d165
CW
1519 $list[] = $searchField;
1520 }
8250601e 1521 $request['description_field'] = $list;
54bee7df 1522 $list[] = 'contact_type';
8250601e 1523 $request['params']['return'] = array_unique(array_merge($list, $request['extra']));
ff88d165
CW
1524 $request['params']['options']['sort'] = 'sort_name';
1525 // Contact api doesn't support array(LIKE => 'foo') syntax
609a8c53 1526 if (!empty($request['input'])) {
fd816db5 1527 $request['params'][$request['search_field']] = $request['input'];
81b7bb6f 1528 // Temporarily override wildcard setting
17d8f8a8 1529 if (Civi::settings()->get('includeWildCardInName') !== $request['add_wildcard']) {
81b7bb6f
CW
1530 Civi::$statics['civicrm_api3_contact_getlist']['override_wildcard'] = !$request['add_wildcard'];
1531 Civi::settings()->set('includeWildCardInName', $request['add_wildcard']);
1532 }
609a8c53 1533 }
ff88d165
CW
1534}
1535
1536/**
22242c87
EM
1537 * Get output for getlist function.
1538 *
a6c6059d 1539 * @see _civicrm_api3_generic_getlist_output
ff88d165 1540 *
8c6b335b
CW
1541 * @param array $result
1542 * @param array $request
ff88d165
CW
1543 *
1544 * @return array
1545 */
1546function _civicrm_api3_contact_getlist_output($result, $request) {
59ca5f92 1547 $output = [];
ff88d165 1548 if (!empty($result['values'])) {
59ca5f92 1549 $addressFields = array_intersect([
1550 'street_address',
1551 'city',
1552 'state_province',
1553 'country',
1554 ],
dc64d047 1555 $request['params']['return']);
ff88d165 1556 foreach ($result['values'] as $row) {
59ca5f92 1557 $data = [
ff88d165
CW
1558 'id' => $row[$request['id_field']],
1559 'label' => $row[$request['label_field']],
59ca5f92 1560 'description' => [],
1561 ];
8250601e
CW
1562 foreach ($request['description_field'] as $item) {
1563 if (!strpos($item, '_name') && !in_array($item, $addressFields) && !empty($row[$item])) {
88881f79 1564 $data['description'][] = $row[$item];
ff88d165
CW
1565 }
1566 }
59ca5f92 1567 $address = [];
22e263ad 1568 foreach ($addressFields as $item) {
88881f79
CW
1569 if (!empty($row[$item])) {
1570 $address[] = $row[$item];
1571 }
1572 }
1573 if ($address) {
1574 $data['description'][] = implode(' ', $address);
1575 }
ff88d165 1576 if (!empty($request['image_field'])) {
2e1f50d6 1577 $data['image'] = $row[$request['image_field']] ?? '';
54bee7df
CW
1578 }
1579 else {
1580 $data['icon_class'] = $row['contact_type'];
1581 }
ff88d165
CW
1582 $output[] = $data;
1583 }
1584 }
81b7bb6f
CW
1585 // Restore wildcard override by _civicrm_api3_contact_getlist_params
1586 if (isset(Civi::$statics['civicrm_api3_contact_getlist']['override_wildcard'])) {
1587 Civi::settings()->set('includeWildCardInName', Civi::$statics['civicrm_api3_contact_getlist']['override_wildcard']);
1588 unset(Civi::$statics['civicrm_api3_contact_getlist']['override_wildcard']);
1589 }
ff88d165
CW
1590 return $output;
1591}
eb5f7260 1592
1593/**
1594 * Check for duplicate contacts.
1595 *
1596 * @param array $params
1597 * Params per getfields metadata.
1598 *
1599 * @return array
1600 * API formatted array
17d8f8a8 1601 *
1602 * @throws \CiviCRM_API3_Exception
eb5f7260 1603 */
1604function civicrm_api3_contact_duplicatecheck($params) {
fedc3428 1605 $dupes = CRM_Contact_BAO_Contact::getDuplicateContacts(
1606 $params['match'],
1607 $params['match']['contact_type'],
d6def514 1608 $params['rule_type'],
1e8be62b 1609 CRM_Utils_Array::value('exclude', $params, []),
fedc3428 1610 CRM_Utils_Array::value('check_permissions', $params),
1611 CRM_Utils_Array::value('dedupe_rule_id', $params)
1612 );
59ca5f92 1613 $values = [];
d6def514 1614 if ($dupes && !empty($params['return'])) {
59ca5f92 1615 return civicrm_api3('Contact', 'get', [
d6def514 1616 'return' => $params['return'],
59ca5f92 1617 'id' => ['IN' => $dupes],
6b409353
CW
1618 'options' => $params['options'] ?? NULL,
1619 'sequential' => $params['sequential'] ?? NULL,
1620 'check_permissions' => $params['check_permissions'] ?? NULL,
59ca5f92 1621 ]);
d6def514
CW
1622 }
1623 foreach ($dupes as $dupe) {
59ca5f92 1624 $values[$dupe] = ['id' => $dupe];
d6def514 1625 }
eb5f7260 1626 return civicrm_api3_create_success($values, $params, 'Contact', 'duplicatecheck');
1627}
1628
1629/**
1630 * Declare metadata for contact dedupe function.
1631 *
17d8f8a8 1632 * @param array $params
eb5f7260 1633 */
1634function _civicrm_api3_contact_duplicatecheck_spec(&$params) {
59ca5f92 1635 $params['dedupe_rule_id'] = [
eb5f7260 1636 'title' => 'Dedupe Rule ID (optional)',
1637 'description' => 'This will default to the built in unsupervised rule',
1638 'type' => CRM_Utils_Type::T_INT,
59ca5f92 1639 ];
1640 $params['rule_type'] = [
d6def514
CW
1641 'title' => 'Dedupe Rule Type',
1642 'description' => 'If no rule id specified, pass "Unsupervised" or "Supervised"',
1643 'type' => CRM_Utils_Type::T_STRING,
1644 'api.default' => 'Unsupervised',
59ca5f92 1645 ];
eb5f7260 1646 // @todo declare 'match' parameter. We don't have a standard for type = array yet.
1647}