Merge pull request #16609 from wmortada/core#1331-3
[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']);
5d8ba7a7 768 // Unique name contact_id = id
1aba4d9a
CW
769 if ($field_name == 'contact_id') {
770 $field_name = 'id';
5d8ba7a7 771 }
9384c60a
MD
772 // core#1420 : trim non-numeric character from phone search string
773 elseif ($field_name == 'phone_numeric') {
774 $name = preg_replace('/[^\d]/', '', $name);
775 }
4235341b
CW
776 if (isset($table_names[$field_name])) {
777 $table_name = $table_names[$field_name];
778 }
779 elseif (strpos($field_name, 'custom_') === 0) {
1f8ac3d2 780 $customField = civicrm_api3('CustomField', 'getsingle', [
4235341b 781 'id' => substr($field_name, 7),
59ca5f92 782 'return' => [
783 'custom_group_id.table_name',
784 'column_name',
785 'data_type',
786 'option_group_id',
787 'html_type',
788 ],
4235341b 789 ]);
1f8ac3d2
CW
790 $field_name = $customField['column_name'];
791 $table_name = CRM_Utils_String::munge($customField['custom_group_id.table_name']);
4235341b 792 $from[$field_name] = "LEFT JOIN `$table_name` ON cc.id = `$table_name`.entity_id";
1f8ac3d2
CW
793 if (CRM_Core_BAO_CustomField::hasOptions($customField)) {
794 $customOptionsWhere = [];
795 $customFieldOptions = CRM_Contact_BAO_Contact::buildOptions('custom_' . $customField['id'], 'search');
796 $isMultivalueField = CRM_Core_BAO_CustomField::isSerialized($customField);
797 $sep = CRM_Core_DAO::VALUE_SEPARATOR;
798 foreach ($customFieldOptions as $optionKey => $optionLabel) {
799 if (mb_stripos($optionLabel, $name) !== FALSE) {
800 $customOptionsWhere[$optionKey] = "$table_name.$field_name " . ($isMultivalueField ? "LIKE '%{$sep}{$optionKey}{$sep}%'" : "= '$optionKey'");
801 }
802 }
803 }
4235341b 804 }
6a488035 805 // phone_numeric should be phone
1aba4d9a 806 $searchField = str_replace('_numeric', '', $field_name);
22e263ad 807 if (!in_array($searchField, $list)) {
6a488035
TO
808 $list[] = $searchField;
809 }
810 }
2baa1e00 811 else {
812 // Set field name to first name for exact match checking.
813 $field_name = 'sort_name';
814 }
6a488035 815
59ca5f92 816 $select = $actualSelectElements = ['sort_name'];
817 $where = '';
6a488035
TO
818 foreach ($list as $value) {
819 $suffix = substr($value, 0, 2) . substr($value, -1);
820 switch ($value) {
821 case 'street_address':
822 case 'city':
823 case 'postal_code':
824 $selectText = $value;
59ca5f92 825 $value = "address";
826 $suffix = 'sts';
6a488035
TO
827 case 'phone':
828 case 'email':
829 $actualSelectElements[] = $select[] = ($value == 'address') ? $selectText : $value;
aebdef3c
JL
830 if ($value == 'phone') {
831 $actualSelectElements[] = $select[] = 'phone_ext';
832 }
6a488035
TO
833 $from[$value] = "LEFT JOIN civicrm_{$value} {$suffix} ON ( cc.id = {$suffix}.contact_id AND {$suffix}.is_primary = 1 ) ";
834 break;
835
836 case 'country':
837 case 'state_province':
838 $select[] = "{$suffix}.name as {$value}";
839 $actualSelectElements[] = "{$suffix}.name";
840 if (!in_array('address', $from)) {
841 $from['address'] = 'LEFT JOIN civicrm_address sts ON ( cc.id = sts.contact_id AND sts.is_primary = 1) ';
842 }
843 $from[$value] = " LEFT JOIN civicrm_{$value} {$suffix} ON ( sts.{$value}_id = {$suffix}.id ) ";
844 break;
845
846 default:
4235341b
CW
847 if ($value == 'id') {
848 $actualSelectElements[] = 'cc.id';
849 }
850 elseif ($value != 'sort_name') {
6a488035 851 $suffix = 'cc';
4235341b
CW
852 if ($field_name == $value) {
853 $suffix = $table_name;
6a488035
TO
854 }
855 $actualSelectElements[] = $select[] = $suffix . '.' . $value;
856 }
857 break;
858 }
859 }
860
861 $config = CRM_Core_Config::singleton();
59ca5f92 862 $as = $select;
6a488035
TO
863 $select = implode(', ', $select);
864 if (!empty($select)) {
865 $select = ", $select";
866 }
867 $actualSelectElements = implode(', ', $actualSelectElements);
6a488035 868 $from = implode(' ', $from);
2975f0aa 869 $limit = (int) ($params['limit'] ?? 0);
89595c92 870 $limit = $limit > 0 ? $limit : Civi::settings()->get('search_autocomplete_count');
6a488035
TO
871
872 // add acl clause here
873 list($aclFrom, $aclWhere) = CRM_Contact_BAO_Contact_Permission::cacheClause('cc');
874
875 if ($aclWhere) {
876 $where .= " AND $aclWhere ";
877 }
613643e0 878 $isPrependWildcard = \Civi::settings()->get('includeWildCardInName');
6a488035 879
a7488080 880 if (!empty($params['org'])) {
6a488035
TO
881 $where .= " AND contact_type = \"Organization\"";
882
883 // CRM-7157, hack: get current employer details when
884 // employee_id is present.
59ca5f92 885 $currEmpDetails = [];
a7488080 886 if (!empty($params['employee_id'])) {
6a488035 887 if ($currentEmployer = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact',
59ca5f92 888 (int) $params['employee_id'],
889 'employer_id'
890 )) {
613643e0 891 if ($isPrependWildcard) {
6a488035
TO
892 $strSearch = "%$name%";
893 }
894 else {
895 $strSearch = "$name%";
896 }
897
898 // get current employer details
899 $dao = CRM_Core_DAO::executeQuery("SELECT cc.id as id, CONCAT_WS( ' :: ', {$actualSelectElements} ) as data, sort_name
900 FROM civicrm_contact cc {$from} WHERE cc.contact_type = \"Organization\" AND cc.id = {$currentEmployer} AND cc.sort_name LIKE '$strSearch'");
901 if ($dao->fetch()) {
59ca5f92 902 $currEmpDetails = [
6a488035
TO
903 'id' => $dao->id,
904 'data' => $dao->data,
59ca5f92 905 ];
6a488035
TO
906 }
907 }
908 }
909 }
910
a7488080 911 if (!empty($params['contact_sub_type'])) {
69164898
N
912 $contactSubType = CRM_Utils_Type::escape($params['contact_sub_type'], 'String');
913 $where .= " AND cc.contact_sub_type = '{$contactSubType}'";
914 }
915
e1b717cb
P
916 if (!empty($params['contact_type'])) {
917 $contactType = CRM_Utils_Type::escape($params['contact_type'], 'String');
918 $where .= " AND cc.contact_type LIKE '{$contactType}'";
919 }
920
244bbdd8 921 // Set default for current_employer or return contact with particular id
a7488080 922 if (!empty($params['id'])) {
1aba4d9a 923 $where .= " AND cc.id = " . (int) $params['id'];
6a488035
TO
924 }
925
a7488080 926 if (!empty($params['cid'])) {
1aba4d9a 927 $where .= " AND cc.id <> " . (int) $params['cid'];
6a488035
TO
928 }
929
244bbdd8 930 // Contact's based of relationhip type
6a488035 931 $relType = NULL;
a7488080 932 if (!empty($params['rel'])) {
6a488035 933 $relation = explode('_', CRM_Utils_Array::value('rel', $params));
59ca5f92 934 $relType = CRM_Utils_Type::escape($relation[0], 'Integer');
935 $rel = CRM_Utils_Type::escape($relation[2], 'String');
6a488035
TO
936 }
937
613643e0 938 if ($isPrependWildcard) {
6a488035
TO
939 $strSearch = "%$name%";
940 }
941 else {
942 $strSearch = "$name%";
943 }
1f8ac3d2 944 $includeEmailFrom = $includeNickName = '';
6a488035
TO
945 if ($config->includeNickNameInName) {
946 $includeNickName = " OR nick_name LIKE '$strSearch'";
6a488035
TO
947 }
948
1f8ac3d2
CW
949 if (isset($customOptionsWhere)) {
950 $customOptionsWhere = $customOptionsWhere ?: [0];
951 $whereClause = " WHERE (" . implode(' OR ', $customOptionsWhere) . ") $where";
952 }
d976e590 953 elseif (!empty($params['field_name']) && !empty($params['table_name']) && $params['field_name'] != 'sort_name') {
8d3b1aa6 954 $whereClause = " WHERE ( $table_name.$field_name LIKE '$strSearch') {$where}";
6a488035
TO
955 // Search by id should be exact
956 if ($field_name == 'id' || $field_name == 'external_identifier') {
613643e0 957 $whereClause = " WHERE ( $table_name.$field_name = '$name') {$where}";
6a488035
TO
958 }
959 }
960 else {
a5728a28 961 $whereClause = " WHERE ( sort_name LIKE '$strSearch' $includeNickName ) {$where} ";
6a488035
TO
962 if ($config->includeEmailInName) {
963 if (!in_array('email', $list)) {
964 $includeEmailFrom = "LEFT JOIN civicrm_email eml ON ( cc.id = eml.contact_id AND eml.is_primary = 1 )";
965 }
36575b09 966 $emailWhere = " WHERE email LIKE '$strSearch'";
6a488035
TO
967 }
968 }
969
970 $additionalFrom = '';
971 if ($relType) {
972 $additionalFrom = "
973 INNER JOIN civicrm_relationship_type r ON (
974 r.id = {$relType}
975 AND ( cc.contact_type = r.contact_type_{$rel} OR r.contact_type_{$rel} IS NULL )
976 AND ( cc.contact_sub_type = r.contact_sub_type_{$rel} OR r.contact_sub_type_{$rel} IS NULL )
977 )";
978 }
979
980 // check if only CMS users are requested
a7488080 981 if (!empty($params['cmsuser'])) {
6a488035
TO
982 $additionalFrom = "
983 INNER JOIN civicrm_uf_match um ON (um.contact_id=cc.id)
984 ";
985 }
613643e0 986 $orderBy = _civicrm_api3_quicksearch_get_order_by($name, $isPrependWildcard, $field_name);
51e61eae 987
6a488035
TO
988 //CRM-5954
989 $query = "
1f8ac3d2 990 SELECT DISTINCT(id), data, sort_name, exactFirst
6a488035 991 FROM (
2baa1e00 992 ( SELECT IF($table_name.$field_name = '{$name}', 0, 1) as exactFirst, cc.id as id, CONCAT_WS( ' :: ',
993 {$actualSelectElements} )
994 as data
995 {$select}
6a488035
TO
996 FROM civicrm_contact cc {$from}
997 {$aclFrom}
a5728a28 998 {$additionalFrom}
6a488035 999 {$whereClause}
613643e0 1000 {$orderBy}
6a488035 1001 LIMIT 0, {$limit} )
6a488035 1002 ";
a5728a28 1003
1004 if (!empty($emailWhere)) {
1005 $query .= "
1006 UNION (
1007 SELECT IF($table_name.$field_name = '{$name}', 0, 1) as exactFirst, cc.id as id, CONCAT_WS( ' :: ',
1008 {$actualSelectElements} )
1009 as data
1010 {$select}
1011 FROM civicrm_contact cc {$from}
1012 {$aclFrom}
1013 {$additionalFrom} {$includeEmailFrom}
c37a2d66 1014 {$emailWhere} AND cc.is_deleted = 0 " . ($aclWhere ? " AND $aclWhere " : '') . "
613643e0 1015 {$orderBy}
a5728a28 1016 LIMIT 0, {$limit}
1017 )
1018 ";
1019 }
36575b09 1020 $query .= ") t
613643e0 1021 {$orderBy}
2baa1e00 1022 LIMIT 0, {$limit}
1023 ";
1024
6a488035
TO
1025 // send query to hook to be modified if needed
1026 CRM_Utils_Hook::contactListQuery($query,
1027 $name,
133da98d
CW
1028 empty($params['context']) ? NULL : CRM_Utils_Type::escape($params['context'], 'String'),
1029 empty($params['id']) ? NULL : $params['id']
6a488035
TO
1030 );
1031
1032 $dao = CRM_Core_DAO::executeQuery($query);
1033
59ca5f92 1034 $contactList = [];
6a488035
TO
1035 $listCurrentEmployer = TRUE;
1036 while ($dao->fetch()) {
59ca5f92 1037 $t = ['id' => $dao->id];
6a488035 1038 foreach ($as as $k) {
2e1f50d6 1039 $t[$k] = $dao->$k ?? '';
6a488035
TO
1040 }
1041 $t['data'] = $dao->data;
1f8ac3d2
CW
1042 // Replace keys with values when displaying fields from an option list
1043 if (!empty($customOptionsWhere)) {
1044 $data = explode(' :: ', $dao->data);
1045 $pos = count($data) - 1;
1046 $customValue = array_intersect(CRM_Utils_Array::explodePadded($data[$pos]), array_keys($customOptionsWhere));
1047 $data[$pos] = implode(', ', array_intersect_key($customFieldOptions, array_flip($customValue)));
1048 $t['data'] = implode(' :: ', $data);
1049 }
6a488035 1050 $contactList[] = $t;
a7488080 1051 if (!empty($params['org']) &&
6a488035
TO
1052 !empty($currEmpDetails) &&
1053 $dao->id == $currEmpDetails['id']
1054 ) {
1055 $listCurrentEmployer = FALSE;
1056 }
1057 }
1058
1059 //return organization name if doesn't exist in db
1060 if (empty($contactList)) {
a7488080 1061 if (!empty($params['org'])) {
6a488035 1062 if ($listCurrentEmployer && !empty($currEmpDetails)) {
59ca5f92 1063 $contactList = [
1064 [
d5cc0fc2 1065 'data' => $currEmpDetails['data'],
59ca5f92 1066 'id' => $currEmpDetails['id'],
1067 ],
1068 ];
6a488035
TO
1069 }
1070 else {
59ca5f92 1071 $contactList = [
1072 [
6a488035 1073 'data' => $name,
59ca5f92 1074 'id' => $name,
1075 ],
1076 ];
6a488035
TO
1077 }
1078 }
1079 }
1080
244bbdd8 1081 return civicrm_api3_create_success($contactList, $params, 'Contact', 'getquick');
a14e9d08
CW
1082}
1083
613643e0 1084/**
1085 * Get the order by string for the quicksearch query.
1086 *
1087 * Get the order by string. The string might be
1088 * - sort name if there is no search value provided and the site is configured
1089 * to search by sort name
1090 * - empty if there is no search value provided and the site is not configured
1091 * to search by sort name
1092 * - exactFirst and then sort name if a search value is provided and the site is configured
1093 * to search by sort name
1094 * - exactFirst if a search value is provided and the site is not configured
1095 * to search by sort name
1096 *
1097 * exactFirst means 'yes if the search value exactly matches the searched field. else no'.
1098 * It is intended to prioritise exact matches for the entered string so on a first name search
1099 * for 'kath' contacts with a first name of exactly Kath rise to the top.
1100 *
1101 * On short strings it is expensive. Per CRM-19547 there is still an open question
1102 * as to whether we should only do exactMatch on a minimum length or on certain fields.
1103 *
1104 * However, we have mitigated this somewhat by not doing an exact match search on
1105 * empty strings, non-wildcard sort-name searches and email searches where there is
1106 * no @ after the first character.
1107 *
1108 * For the user it is further mitigated by the fact they just don't know the
1109 * slower queries are firing. If they type 'smit' slowly enough 4 queries will trigger
1110 * but if the first 3 are slow the first result they see may be off the 4th query.
1111 *
1112 * @param string $name
1113 * @param bool $isPrependWildcard
1114 * @param string $field_name
1115 *
1116 * @return string
1117 */
1118function _civicrm_api3_quicksearch_get_order_by($name, $isPrependWildcard, $field_name) {
1119 $skipExactMatch = ($name === '%');
1120 if ($field_name === 'email' && !strpos('@', $name)) {
1121 $skipExactMatch = TRUE;
1122 }
1123
1124 if (!\Civi::settings()->get('includeOrderByClause')) {
1125 return $skipExactMatch ? '' : "ORDER BY exactFirst";
1126 }
1127 if ($skipExactMatch || (!$isPrependWildcard && $field_name === 'sort_name')) {
1128 // If there is no wildcard then sorting by exactFirst would have the same
1129 // effect as just a sort_name search, but slower.
1130 return "ORDER BY sort_name";
1131 }
1132
1133 return "ORDER BY exactFirst, sort_name";
1134}
1135
a14e9d08 1136/**
35823763
EM
1137 * Declare deprecated api functions.
1138 *
a14e9d08 1139 * @deprecated api notice
a6c01b45 1140 * @return array
16b10e64 1141 * Array of deprecated actions
a14e9d08
CW
1142 */
1143function _civicrm_api3_contact_deprecation() {
59ca5f92 1144 return ['getquick' => 'The "getquick" action is deprecated in favor of "getlist".'];
6a488035
TO
1145}
1146
1147/**
1148 * Merges given pair of duplicate contacts.
1149 *
cf470720 1150 * @param array $params
b081365f
CW
1151 * Allowed array keys are:
1152 * -int main_id: main contact id with whom merge has to happen
1153 * -int other_id: duplicate contact which would be deleted after merge operation
1154 * -string mode: "safe" skips the merge if there are no conflicts. Does a force merge otherwise.
6a488035 1155 *
a6c01b45 1156 * @return array
72b3a70c 1157 * API Result Array
17d8f8a8 1158 *
fedc3428 1159 * @throws API_Exception
17d8f8a8 1160 * @throws \CiviCRM_API3_Exception
1161 * @throws \CRM_Core_Exception
6a488035
TO
1162 */
1163function civicrm_api3_contact_merge($params) {
8b5445c8 1164 if (($result = CRM_Dedupe_Merger::merge(
1165 [['srcID' => $params['to_remove_id'], 'dstID' => $params['to_keep_id']]],
1166 [],
1167 $params['mode'],
1168 FALSE,
1169 CRM_Utils_Array::value('check_permissions', $params)
1170 )) != FALSE) {
1171
12d73bba 1172 return civicrm_api3_create_success($result, $params);
6a488035 1173 }
fedc3428 1174 throw new API_Exception('Merge failed');
12d73bba 1175}
1176
1177/**
5ea06a7b 1178 * Adjust metadata for contact_merge api function.
12d73bba 1179 *
1180 * @param array $params
1181 */
1182function _civicrm_api3_contact_merge_spec(&$params) {
59ca5f92 1183 $params['to_remove_id'] = [
aefc291e 1184 'title' => ts('ID of the contact to merge & remove'),
1185 'description' => ts('Wow - these 2 aliased params are the logical reverse of what I expect - but what to do?'),
12d73bba 1186 'api.required' => 1,
1187 'type' => CRM_Utils_Type::T_INT,
59ca5f92 1188 'api.aliases' => ['main_id'],
1189 ];
1190 $params['to_keep_id'] = [
aefc291e 1191 'title' => ts('ID of the contact to keep'),
1192 'description' => ts('Wow - these 2 aliased params are the logical reverse of what I expect - but what to do?'),
12d73bba 1193 'api.required' => 1,
1194 'type' => CRM_Utils_Type::T_INT,
59ca5f92 1195 'api.aliases' => ['other_id'],
1196 ];
1197 $params['mode'] = [
aefc291e 1198 'title' => ts('Dedupe mode'),
1199 'description' => ts("In 'safe' mode conflicts will result in no merge. In 'aggressive' mode the merge will still proceed (hook dependent)"),
6f2c4a24 1200 'api.default' => 'safe',
712ee28f 1201 'options' => ['safe' => ts('Abort on unhandled conflict'), 'aggressive' => ts('Proceed on unhandled conflict. Note hooks may change handling here.')],
aefc291e 1202 ];
1203}
1204
1205/**
1206 * Determines if given pair of contaacts have conflicts that would affect merging them.
1207 *
1208 * @param array $params
1209 * Allowed array keys are:
1210 * -int main_id: main contact id with whom merge has to happen
1211 * -int other_id: duplicate contact which would be deleted after merge operation
1212 * -string mode: "safe" skips the merge if there are no conflicts. Does a force merge otherwise.
1213 *
1214 * @return array
1215 * API Result Array
1216 *
1217 * @throws \CRM_Core_Exception
1218 * @throws \CiviCRM_API3_Exception
712ee28f 1219 * @throws \API_Exception
aefc291e 1220 */
1221function civicrm_api3_contact_get_merge_conflicts($params) {
1222 $migrationInfo = [];
ffa59d18 1223 $result = [];
712ee28f 1224 foreach ((array) $params['mode'] as $mode) {
403400d9 1225 $result[$mode] = CRM_Dedupe_Merger::getConflicts(
712ee28f 1226 $migrationInfo,
aefc291e 1227 $params['to_remove_id'], $params['to_keep_id'],
ffa59d18 1228 $mode
712ee28f 1229 );
aefc291e 1230 }
ffa59d18 1231 return civicrm_api3_create_success($result, $params);
aefc291e 1232}
1233
1234/**
1235 * Adjust metadata for contact_merge api function.
1236 *
1237 * @param array $params
1238 */
1239function _civicrm_api3_contact_get_merge_conflicts_spec(&$params) {
1240 $params['to_remove_id'] = [
1241 'title' => ts('ID of the contact to merge & remove'),
1242 'api.required' => 1,
1243 'type' => CRM_Utils_Type::T_INT,
1244 ];
1245 $params['to_keep_id'] = [
1246 'title' => ts('ID of the contact to keep'),
1247 'api.required' => 1,
1248 'type' => CRM_Utils_Type::T_INT,
1249 ];
1250 $params['mode'] = [
1251 'title' => ts('Dedupe mode'),
1252 'description' => ts("'safe' or 'aggressive' - these modes map to the merge actions & may affect resolution done by hooks "),
ffa59d18 1253 'api.default' => 'safe',
59ca5f92 1254 ];
6a488035
TO
1255}
1256
734cd0d5 1257/**
1258 * Get the ultimate contact a contact was merged to.
1259 *
1260 * @param array $params
1261 *
1262 * @return array
1263 * API Result Array
17d8f8a8 1264 *
1265 * @throws \CiviCRM_API3_Exception
734cd0d5 1266 */
1267function civicrm_api3_contact_getmergedto($params) {
1268 $contactID = _civicrm_api3_contact_getmergedto($params);
1269 if ($contactID) {
1270 $values = [$contactID => ['id' => $contactID]];
1271 }
1272 else {
1273 $values = [];
1274 }
1275 return civicrm_api3_create_success($values, $params);
1276}
1277
1278/**
1279 * Get the contact our contact was finally merged to.
1280 *
1281 * If the contact has been merged multiple times the crucial parent activity will have
1282 * wound up on the ultimate contact so we can figure out the final resting place of the
1283 * contact with only 2 activities even if 50 merges took place.
1284 *
1285 * @param array $params
1286 *
1287 * @return int|false
17d8f8a8 1288 *
1289 * @throws \CiviCRM_API3_Exception
734cd0d5 1290 */
1291function _civicrm_api3_contact_getmergedto($params) {
1292 $contactID = FALSE;
1293 $deleteActivity = civicrm_api3('ActivityContact', 'get', [
1294 'contact_id' => $params['contact_id'],
1295 'activity_id.activity_type_id' => 'Contact Deleted By Merge',
1296 'is_deleted' => 0,
1297 'is_test' => $params['is_test'],
1298 'record_type_id' => 'Activity Targets',
1299 'return' => ['activity_id.parent_id'],
1300 'sequential' => 1,
1301 'options' => [
1302 'limit' => 1,
59ca5f92 1303 'sort' => 'activity_id.activity_date_time DESC',
734cd0d5 1304 ],
1305 ])['values'];
1306 if (!empty($deleteActivity)) {
1307 $contactID = civicrm_api3('ActivityContact', 'getvalue', [
1308 'activity_id' => $deleteActivity[0]['activity_id.parent_id'],
1309 'record_type_id' => 'Activity Targets',
1310 'return' => 'contact_id',
1311 ]);
1312 }
1313 return $contactID;
1314}
1315
1316/**
1317 * Adjust metadata for contact_merge api function.
1318 *
1319 * @param array $params
1320 */
1321function _civicrm_api3_contact_getmergedto_spec(&$params) {
1322 $params['contact_id'] = [
1323 'title' => ts('ID of contact to find ultimate contact for'),
1324 'type' => CRM_Utils_Type::T_INT,
1325 'api.required' => TRUE,
1326 ];
1327 $params['is_test'] = [
1328 'title' => ts('Get test deletions rather than live?'),
1329 'type' => CRM_Utils_Type::T_BOOLEAN,
1330 'api.default' => 0,
1331 ];
1332}
1333
1334/**
1335 * Get the ultimate contact a contact was merged to.
1336 *
1337 * @param array $params
1338 *
1339 * @return array
1340 * API Result Array
17d8f8a8 1341 *
1342 * @throws \CiviCRM_API3_Exception
734cd0d5 1343 */
1344function civicrm_api3_contact_getmergedfrom($params) {
1345 $contacts = _civicrm_api3_contact_getmergedfrom($params);
1346 return civicrm_api3_create_success($contacts, $params);
1347}
1348
1349/**
1350 * Get all the contacts merged into our contact.
1351 *
1352 * @param array $params
1353 *
1354 * @return array
17d8f8a8 1355 *
1356 * @throws \CiviCRM_API3_Exception
734cd0d5 1357 */
1358function _civicrm_api3_contact_getmergedfrom($params) {
1359 $activities = [];
1360 $deleteActivities = civicrm_api3('ActivityContact', 'get', [
1361 'contact_id' => $params['contact_id'],
1362 'activity_id.activity_type_id' => 'Contact Merged',
1363 'is_deleted' => 0,
1364 'is_test' => $params['is_test'],
1365 'record_type_id' => 'Activity Targets',
1366 'return' => 'activity_id',
1367 ])['values'];
1368
1369 foreach ($deleteActivities as $deleteActivity) {
1370 $activities[] = $deleteActivity['activity_id'];
1371 }
1372 if (empty($activities)) {
1373 return [];
1374 }
1375
1376 $activityContacts = civicrm_api3('ActivityContact', 'get', [
1377 'activity_id.parent_id' => ['IN' => $activities],
1378 'record_type_id' => 'Activity Targets',
1379 'return' => 'contact_id',
1380 ])['values'];
1381 $contacts = [];
1382 foreach ($activityContacts as $activityContact) {
1383 $contacts[$activityContact['contact_id']] = ['id' => $activityContact['contact_id']];
1384 }
1385 return $contacts;
1386}
1387
1388/**
1389 * Adjust metadata for contact_merge api function.
1390 *
1391 * @param array $params
1392 */
1393function _civicrm_api3_contact_getmergedfrom_spec(&$params) {
1394 $params['contact_id'] = [
1395 'title' => ts('ID of contact to find ultimate contact for'),
1396 'type' => CRM_Utils_Type::T_INT,
1397 'api.required' => TRUE,
1398 ];
1399 $params['is_test'] = [
1400 'title' => ts('Get test deletions rather than live?'),
1401 'type' => CRM_Utils_Type::T_BOOLEAN,
1402 'api.default' => 0,
1403 ];
1404}
1405
aa1b1481 1406/**
9d32e6f7
EM
1407 * Adjust metadata for contact_proximity api function.
1408 *
c490a46a 1409 * @param array $params
aa1b1481 1410 */
6a488035 1411function _civicrm_api3_contact_proximity_spec(&$params) {
59ca5f92 1412 $params['latitude'] = [
d142432b
EM
1413 'title' => 'Latitude',
1414 'api.required' => 1,
1415 'type' => CRM_Utils_Type::T_STRING,
59ca5f92 1416 ];
1417 $params['longitude'] = [
d142432b
EM
1418 'title' => 'Longitude',
1419 'api.required' => 1,
1420 'type' => CRM_Utils_Type::T_STRING,
59ca5f92 1421 ];
d142432b 1422
59ca5f92 1423 $params['unit'] = [
d142432b
EM
1424 'title' => 'Unit of Measurement',
1425 'api.default' => 'meter',
1426 'type' => CRM_Utils_Type::T_STRING,
59ca5f92 1427 ];
6a488035
TO
1428}
1429
aa1b1481 1430/**
9d32e6f7
EM
1431 * Get contacts by proximity.
1432 *
c490a46a 1433 * @param array $params
aa1b1481
EM
1434 *
1435 * @return array
1436 * @throws Exception
1437 */
6a488035 1438function civicrm_api3_contact_proximity($params) {
f748c073 1439 $latitude = $params['latitude'] ?? NULL;
1440 $longitude = $params['longitude'] ?? NULL;
1441 $distance = $params['distance'] ?? NULL;
6a488035 1442
f748c073 1443 $unit = $params['unit'] ?? NULL;
6a488035
TO
1444
1445 // check and ensure that lat/long and distance are floats
1446 if (
1447 !CRM_Utils_Rule::numeric($latitude) ||
1448 !CRM_Utils_Rule::numeric($longitude) ||
1449 !CRM_Utils_Rule::numeric($distance)
1450 ) {
17d8f8a8 1451 throw new API_Exception(ts('Latitude, Longitude and Distance should exist and be numeric'));
6a488035
TO
1452 }
1453
17d8f8a8 1454 if ($unit === 'mile') {
6a488035
TO
1455 $conversionFactor = 1609.344;
1456 }
1457 else {
1458 $conversionFactor = 1000;
1459 }
1460 //Distance in meters
1461 $distance = $distance * $conversionFactor;
1462
1463 $whereClause = CRM_Contact_BAO_ProximityQuery::where($latitude, $longitude, $distance);
1464
1465 $query = "
1466SELECT civicrm_contact.id as contact_id,
1467 civicrm_contact.display_name as display_name
1468FROM civicrm_contact
1469LEFT JOIN civicrm_address ON civicrm_contact.id = civicrm_address.contact_id
1470WHERE $whereClause
1471";
1472
1473 $dao = CRM_Core_DAO::executeQuery($query);
59ca5f92 1474 $contacts = [];
6a488035
TO
1475 while ($dao->fetch()) {
1476 $contacts[] = $dao->toArray();
1477 }
1478
244bbdd8 1479 return civicrm_api3_create_success($contacts, $params, 'Contact', 'get_by_location', $dao);
6a488035
TO
1480}
1481
ff88d165 1482/**
22242c87
EM
1483 * Get parameters for getlist function.
1484 *
a6c6059d 1485 * @see _civicrm_api3_generic_getlist_params
ff88d165 1486 *
8c6b335b 1487 * @param array $request
ff88d165
CW
1488 */
1489function _civicrm_api3_contact_getlist_params(&$request) {
1490 // get the autocomplete options from settings
1491 $acpref = explode(CRM_Core_DAO::VALUE_SEPARATOR,
1492 CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME,
1493 'contact_autocomplete_options'
1494 )
1495 );
1496
1497 // get the option values for contact autocomplete
1498 $acOptions = CRM_Core_OptionGroup::values('contact_autocomplete_options', FALSE, FALSE, FALSE, NULL, 'name');
1499
59ca5f92 1500 $list = [];
ff88d165
CW
1501 foreach ($acpref as $value) {
1502 if ($value && !empty($acOptions[$value])) {
1503 $list[] = $acOptions[$value];
1504 }
1505 }
1506 // If we are doing quicksearch by a field other than name, make sure that field is added to results
1507 $field_name = CRM_Utils_String::munge($request['search_field']);
1508 // Unique name contact_id = id
17d8f8a8 1509 if ($field_name === 'contact_id') {
ff88d165
CW
1510 $field_name = 'id';
1511 }
1512 // phone_numeric should be phone
1513 $searchField = str_replace('_numeric', '', $field_name);
22e263ad 1514 if (!in_array($searchField, $list)) {
ff88d165
CW
1515 $list[] = $searchField;
1516 }
8250601e 1517 $request['description_field'] = $list;
54bee7df 1518 $list[] = 'contact_type';
8250601e 1519 $request['params']['return'] = array_unique(array_merge($list, $request['extra']));
ff88d165
CW
1520 $request['params']['options']['sort'] = 'sort_name';
1521 // Contact api doesn't support array(LIKE => 'foo') syntax
609a8c53 1522 if (!empty($request['input'])) {
fd816db5 1523 $request['params'][$request['search_field']] = $request['input'];
81b7bb6f 1524 // Temporarily override wildcard setting
17d8f8a8 1525 if (Civi::settings()->get('includeWildCardInName') !== $request['add_wildcard']) {
81b7bb6f
CW
1526 Civi::$statics['civicrm_api3_contact_getlist']['override_wildcard'] = !$request['add_wildcard'];
1527 Civi::settings()->set('includeWildCardInName', $request['add_wildcard']);
1528 }
609a8c53 1529 }
ff88d165
CW
1530}
1531
1532/**
22242c87
EM
1533 * Get output for getlist function.
1534 *
a6c6059d 1535 * @see _civicrm_api3_generic_getlist_output
ff88d165 1536 *
8c6b335b
CW
1537 * @param array $result
1538 * @param array $request
ff88d165
CW
1539 *
1540 * @return array
1541 */
1542function _civicrm_api3_contact_getlist_output($result, $request) {
59ca5f92 1543 $output = [];
ff88d165 1544 if (!empty($result['values'])) {
59ca5f92 1545 $addressFields = array_intersect([
1546 'street_address',
1547 'city',
1548 'state_province',
1549 'country',
1550 ],
dc64d047 1551 $request['params']['return']);
ff88d165 1552 foreach ($result['values'] as $row) {
59ca5f92 1553 $data = [
ff88d165
CW
1554 'id' => $row[$request['id_field']],
1555 'label' => $row[$request['label_field']],
59ca5f92 1556 'description' => [],
1557 ];
8250601e
CW
1558 foreach ($request['description_field'] as $item) {
1559 if (!strpos($item, '_name') && !in_array($item, $addressFields) && !empty($row[$item])) {
88881f79 1560 $data['description'][] = $row[$item];
ff88d165
CW
1561 }
1562 }
59ca5f92 1563 $address = [];
22e263ad 1564 foreach ($addressFields as $item) {
88881f79
CW
1565 if (!empty($row[$item])) {
1566 $address[] = $row[$item];
1567 }
1568 }
1569 if ($address) {
1570 $data['description'][] = implode(' ', $address);
1571 }
ff88d165 1572 if (!empty($request['image_field'])) {
2e1f50d6 1573 $data['image'] = $row[$request['image_field']] ?? '';
54bee7df
CW
1574 }
1575 else {
1576 $data['icon_class'] = $row['contact_type'];
1577 }
ff88d165
CW
1578 $output[] = $data;
1579 }
1580 }
81b7bb6f
CW
1581 // Restore wildcard override by _civicrm_api3_contact_getlist_params
1582 if (isset(Civi::$statics['civicrm_api3_contact_getlist']['override_wildcard'])) {
1583 Civi::settings()->set('includeWildCardInName', Civi::$statics['civicrm_api3_contact_getlist']['override_wildcard']);
1584 unset(Civi::$statics['civicrm_api3_contact_getlist']['override_wildcard']);
1585 }
ff88d165
CW
1586 return $output;
1587}
eb5f7260 1588
1589/**
1590 * Check for duplicate contacts.
1591 *
1592 * @param array $params
1593 * Params per getfields metadata.
1594 *
1595 * @return array
1596 * API formatted array
17d8f8a8 1597 *
1598 * @throws \CiviCRM_API3_Exception
eb5f7260 1599 */
1600function civicrm_api3_contact_duplicatecheck($params) {
fedc3428 1601 $dupes = CRM_Contact_BAO_Contact::getDuplicateContacts(
1602 $params['match'],
1603 $params['match']['contact_type'],
d6def514 1604 $params['rule_type'],
1e8be62b 1605 CRM_Utils_Array::value('exclude', $params, []),
fedc3428 1606 CRM_Utils_Array::value('check_permissions', $params),
1607 CRM_Utils_Array::value('dedupe_rule_id', $params)
1608 );
59ca5f92 1609 $values = [];
d6def514 1610 if ($dupes && !empty($params['return'])) {
59ca5f92 1611 return civicrm_api3('Contact', 'get', [
d6def514 1612 'return' => $params['return'],
59ca5f92 1613 'id' => ['IN' => $dupes],
6b409353
CW
1614 'options' => $params['options'] ?? NULL,
1615 'sequential' => $params['sequential'] ?? NULL,
1616 'check_permissions' => $params['check_permissions'] ?? NULL,
59ca5f92 1617 ]);
d6def514
CW
1618 }
1619 foreach ($dupes as $dupe) {
59ca5f92 1620 $values[$dupe] = ['id' => $dupe];
d6def514 1621 }
eb5f7260 1622 return civicrm_api3_create_success($values, $params, 'Contact', 'duplicatecheck');
1623}
1624
1625/**
1626 * Declare metadata for contact dedupe function.
1627 *
17d8f8a8 1628 * @param array $params
eb5f7260 1629 */
1630function _civicrm_api3_contact_duplicatecheck_spec(&$params) {
59ca5f92 1631 $params['dedupe_rule_id'] = [
eb5f7260 1632 'title' => 'Dedupe Rule ID (optional)',
1633 'description' => 'This will default to the built in unsupervised rule',
1634 'type' => CRM_Utils_Type::T_INT,
59ca5f92 1635 ];
1636 $params['rule_type'] = [
d6def514
CW
1637 'title' => 'Dedupe Rule Type',
1638 'description' => 'If no rule id specified, pass "Unsupervised" or "Supervised"',
1639 'type' => CRM_Utils_Type::T_STRING,
1640 'api.default' => 'Unsupervised',
59ca5f92 1641 ];
eb5f7260 1642 // @todo declare 'match' parameter. We don't have a standard for type = array yet.
1643}