Merge pull request #17209 from civicrm/5.25
[civicrm-core.git] / api / v3 / Contact.php
1 <?php
2 /*
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 +--------------------------------------------------------------------+
10 */
11
12 /**
13 * This api exposes CiviCRM contacts.
14 *
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.
17 * - Create action allows creating several related entities at once (e.g. email).
18 * - Create allows checking for duplicate contacts.
19 * Use getfields to list the full range of parameters and options supported by each action.
20 *
21 * @package CiviCRM_APIv3
22 */
23
24 /**
25 * Create or update a Contact.
26 *
27 * @param array $params
28 * Input parameters.
29 *
30 * @return array
31 * API Result Array
32 *
33 * @throws \CiviCRM_API3_Exception
34 * @throws API_Exception
35 * @throws \CRM_Core_Exception
36 */
37 function civicrm_api3_contact_create($params) {
38 $contactID = CRM_Utils_Array::value('contact_id', $params, CRM_Utils_Array::value('id', $params));
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
44 if (!empty($params['dupe_check'])) {
45 $ids = CRM_Contact_BAO_Contact::getDuplicateContacts($params, $params['contact_type'], 'Unsupervised', [], $params['check_permission']);
46 if (count($ids) > 0) {
47 throw new API_Exception("Found matching contacts: " . implode(',', $ids), "duplicate", ["ids" => $ids]);
48 }
49 }
50
51 $values = _civicrm_api3_contact_check_params($params);
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();
60 $params['email'] = [
61 1 => [
62 'email' => $email,
63 'is_primary' => 1,
64 'location_type_id' => ($defLocType->id) ? $defLocType->id : 1,
65 ],
66 ];
67 }
68 }
69
70 if (!empty($params['home_url'])) {
71 $websiteTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Website', 'website_type_id');
72 $params['website'] = [
73 1 => [
74 'website_type_id' => key($websiteTypes),
75 'url' => $params['home_url'],
76 ],
77 ];
78 }
79
80 _civicrm_api3_greeting_format_params($params);
81
82 $values = [];
83
84 if (empty($params['contact_type']) && $contactID) {
85 $params['contact_type'] = CRM_Contact_BAO_Contact::getContactType($contactID);
86 if (!$params['contact_type']) {
87 throw new API_Exception('Contact id ' . $contactID . ' not found.');
88 }
89 }
90
91 if (!isset($params['contact_sub_type']) && $contactID) {
92 $params['contact_sub_type'] = CRM_Contact_BAO_Contact::getContactSubType($contactID);
93 }
94
95 _civicrm_api3_custom_format_params($params, $values, $params['contact_type'], $contactID);
96
97 $params = array_merge($params, $values);
98 //@todo we should just call basic_create here - but need to make contact:create accept 'id' on the bao
99 $contact = _civicrm_api3_contact_update($params, $contactID);
100
101 if (is_a($contact, 'CRM_Core_Error')) {
102 throw new API_Exception($contact->_errors[0]['message']);
103 }
104 else {
105 $values = [];
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
112 /**
113 * Adjust Metadata for Create action.
114 *
115 * @param array $params
116 * Array of parameters determined by getfields.
117 */
118 function _civicrm_api3_contact_create_spec(&$params) {
119 $params['contact_type']['api.required'] = 1;
120 $params['id']['api.aliases'] = ['contact_id'];
121 $params['current_employer'] = [
122 'title' => 'Current Employer',
123 'description' => 'Name of Current Employer',
124 'type' => CRM_Utils_Type::T_STRING,
125 ];
126 $params['dupe_check'] = [
127 'title' => 'Check for Duplicates',
128 'description' => 'Throw error if contact create matches dedupe rule',
129 'type' => CRM_Utils_Type::T_BOOLEAN,
130 ];
131 $params['skip_greeting_processing'] = [
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,
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'];
146 }
147
148 /**
149 * Retrieve one or more contacts, given a set of search params.
150 *
151 * @param array $params
152 *
153 * @return array
154 * API Result Array
155 *
156 * @throws \API_Exception
157 * @throws \CiviCRM_API3_Exception
158 */
159 function civicrm_api3_contact_get($params) {
160 $options = [];
161 _civicrm_api3_contact_get_supportanomalies($params, $options);
162 $contacts = _civicrm_api3_get_using_query_object('Contact', $params, $options);
163 if (!empty($params['check_permissions'])) {
164 CRM_Contact_BAO_Contact::unsetProtectedFields($contacts);
165 }
166 return civicrm_api3_create_success($contacts, $params, 'Contact');
167 }
168
169 /**
170 * Get number of contacts matching the supplied criteria.
171 *
172 * @param array $params
173 *
174 * @return int
175 * @throws \API_Exception
176 */
177 function civicrm_api3_contact_getcount($params) {
178 $options = [];
179 _civicrm_api3_contact_get_supportanomalies($params, $options);
180 $count = _civicrm_api3_get_using_query_object('Contact', $params, $options, 1);
181 return (int) $count;
182 }
183
184 /**
185 * Adjust Metadata for Get action.
186 *
187 * @param array $params
188 * Array of parameters determined by getfields.
189 */
190 function _civicrm_api3_contact_get_spec(&$params) {
191 $params['contact_is_deleted']['api.default'] = 0;
192
193 // We declare all these pseudoFields as there are other undocumented fields accessible
194 // via the api - but if check permissions is set we only allow declared fields
195 $params['address_id'] = [
196 'title' => 'Primary Address ID',
197 'type' => CRM_Utils_Type::T_INT,
198 ];
199 $params['street_address'] = [
200 'title' => 'Primary Address Street Address',
201 'type' => CRM_Utils_Type::T_STRING,
202 ];
203 $params['supplemental_address_1'] = [
204 'title' => 'Primary Address Supplemental Address 1',
205 'type' => CRM_Utils_Type::T_STRING,
206 ];
207 $params['supplemental_address_2'] = [
208 'title' => 'Primary Address Supplemental Address 2',
209 'type' => CRM_Utils_Type::T_STRING,
210 ];
211 $params['supplemental_address_3'] = [
212 'title' => 'Primary Address Supplemental Address 3',
213 'type' => CRM_Utils_Type::T_STRING,
214 ];
215 $params['current_employer'] = [
216 'title' => 'Current Employer',
217 'type' => CRM_Utils_Type::T_STRING,
218 ];
219 $params['city'] = [
220 'title' => 'Primary Address City',
221 'type' => CRM_Utils_Type::T_STRING,
222 ];
223 $params['postal_code_suffix'] = [
224 'title' => 'Primary Address Post Code Suffix',
225 'type' => CRM_Utils_Type::T_STRING,
226 ];
227 $params['postal_code'] = [
228 'title' => 'Primary Address Post Code',
229 'type' => CRM_Utils_Type::T_STRING,
230 ];
231 $params['geo_code_1'] = [
232 'title' => 'Primary Address Latitude',
233 'type' => CRM_Utils_Type::T_STRING,
234 ];
235 $params['geo_code_2'] = [
236 'title' => 'Primary Address Longitude',
237 'type' => CRM_Utils_Type::T_STRING,
238 ];
239 $params['state_province_id'] = [
240 'title' => 'Primary Address State Province ID',
241 'type' => CRM_Utils_Type::T_INT,
242 'pseudoconstant' => [
243 'table' => 'civicrm_state_province',
244 ],
245 ];
246 $params['state_province_name'] = [
247 'title' => 'Primary Address State Province Name',
248 'type' => CRM_Utils_Type::T_STRING,
249 'pseudoconstant' => [
250 'table' => 'civicrm_state_province',
251 ],
252 ];
253 $params['state_province'] = [
254 'title' => 'Primary Address State Province',
255 'type' => CRM_Utils_Type::T_STRING,
256 'pseudoconstant' => [
257 'table' => 'civicrm_state_province',
258 ],
259 ];
260 $params['country_id'] = [
261 'title' => 'Primary Address Country ID',
262 'type' => CRM_Utils_Type::T_INT,
263 'pseudoconstant' => [
264 'table' => 'civicrm_country',
265 ],
266 ];
267 $params['country'] = [
268 'title' => 'Primary Address country',
269 'type' => CRM_Utils_Type::T_STRING,
270 'pseudoconstant' => [
271 'table' => 'civicrm_country',
272 ],
273 ];
274 $params['worldregion_id'] = [
275 'title' => 'Primary Address World Region ID',
276 'type' => CRM_Utils_Type::T_INT,
277 'pseudoconstant' => [
278 'table' => 'civicrm_world_region',
279 ],
280 ];
281 $params['worldregion'] = [
282 'title' => 'Primary Address World Region',
283 'type' => CRM_Utils_Type::T_STRING,
284 'pseudoconstant' => [
285 'table' => 'civicrm_world_region',
286 ],
287 ];
288 $params['phone_id'] = [
289 'title' => 'Primary Phone ID',
290 'type' => CRM_Utils_Type::T_INT,
291 ];
292 $params['phone'] = [
293 'title' => 'Primary Phone',
294 'type' => CRM_Utils_Type::T_STRING,
295 ];
296 $params['phone_type_id'] = [
297 'title' => 'Primary Phone Type ID',
298 'type' => CRM_Utils_Type::T_INT,
299 ];
300 $params['provider_id'] = [
301 'title' => 'Primary Phone Provider ID',
302 'type' => CRM_Utils_Type::T_INT,
303 ];
304 $params['email_id'] = [
305 'title' => 'Primary Email ID',
306 'type' => CRM_Utils_Type::T_INT,
307 ];
308 $params['email'] = [
309 'title' => 'Primary Email',
310 'type' => CRM_Utils_Type::T_STRING,
311 ];
312 $params['on_hold'] = [
313 'title' => 'Primary Email On Hold',
314 'type' => CRM_Utils_Type::T_BOOLEAN,
315 ];
316 $params['im'] = [
317 'title' => 'Primary Instant Messenger',
318 'type' => CRM_Utils_Type::T_STRING,
319 ];
320 $params['im_id'] = [
321 'title' => 'Primary Instant Messenger ID',
322 'type' => CRM_Utils_Type::T_INT,
323 ];
324 $params['group'] = [
325 'title' => 'Group',
326 'pseudoconstant' => [
327 'table' => 'civicrm_group',
328 ],
329 ];
330 $params['tag'] = [
331 'title' => 'Tags',
332 'pseudoconstant' => [
333 'table' => 'civicrm_tag',
334 ],
335 ];
336 $params['uf_user'] = [
337 'title' => 'CMS User',
338 'type' => CRM_Utils_Type::T_BOOLEAN,
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 ];
360 }
361
362 /**
363 * Support for historical oddities.
364 *
365 * We are supporting 'showAll' = 'all', 'trash' or 'active' for Contact get
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 *
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).
376 */
377 function _civicrm_api3_contact_get_supportanomalies(&$params, &$options) {
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 }
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 }
404 else {
405 $groups = explode(',', $params['filter.group_id']);
406 }
407 unset($params['filter.group_id']);
408 $options['input_params']['group'] = $groups;
409 }
410 if (isset($params['group'])) {
411 $groups = $params['group'];
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));
415 if (is_array($groups) && in_array(key($groups), CRM_Core_DAO::acceptedSQLOperators(), TRUE)) {
416 // Get the groups array.
417 $groupsArray = $groups[key($groups)];
418 foreach ($groupsArray as &$group) {
419 if (!is_numeric($group) && !empty($allGroups[$group])) {
420 $group = $allGroups[$group];
421 }
422 }
423 // Now reset the $groups array with the ids not the titles.
424 $groups[key($groups)] = $groupsArray;
425 }
426 // handle format like 'group' => array('title1', 'title2').
427 elseif (is_array($groups)) {
428 foreach ($groups as $k => &$group) {
429 if (!is_numeric($group) && !empty($allGroups[$group])) {
430 $group = $allGroups[$group];
431 }
432 if (!is_numeric($k) && !empty($allGroups[$k])) {
433 unset($groups[$k]);
434 $groups[$allGroups[$k]] = $group;
435 }
436 }
437 }
438 elseif (!is_numeric($groups) && !empty($allGroups[$groups])) {
439 $groups = $allGroups[$groups];
440 }
441 $params['group'] = $groups;
442 }
443 }
444
445 /**
446 * Delete a Contact with given contact_id.
447 *
448 * @param array $params
449 * input parameters per getfields
450 *
451 * @return array
452 * API Result Array
453 * @throws \CRM_Core_Exception
454 * @throws \CiviCRM_API3_Exception
455 * @throws \Civi\API\Exception\UnauthorizedException
456 */
457 function civicrm_api3_contact_delete($params) {
458 $contactID = (int) $params['id'];
459
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
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.');
466 }
467 $restore = !empty($params['restore']);
468 $skipUndelete = !empty($params['skip_undelete']);
469
470 // CRM-12929
471 // restrict permanent delete if a contact has financial trxn associated with it
472 $error = NULL;
473 if ($skipUndelete && CRM_Financial_BAO_FinancialItem::checkContactPresent([$contactID], $error)) {
474 throw new API_Exception($error['_qf_default']);
475 }
476 if (CRM_Contact_BAO_Contact::deleteContact($contactID, $restore, $skipUndelete,
477 CRM_Utils_Array::value('check_permissions', $params))) {
478 return civicrm_api3_create_success();
479 }
480 throw new CiviCRM_API3_Exception('Could not delete contact');
481 }
482
483 /**
484 * Check parameters passed in.
485 *
486 * This function is on it's way out.
487 *
488 * @param array $params
489 *
490 * @return null
491 * @throws API_Exception
492 * @throws CiviCRM_API3_Exception
493 */
494 function _civicrm_api3_contact_check_params(&$params) {
495
496 switch (strtolower(CRM_Utils_Array::value('contact_type', $params))) {
497 case 'household':
498 civicrm_api3_verify_mandatory($params, NULL, ['household_name']);
499 break;
500
501 case 'organization':
502 civicrm_api3_verify_mandatory($params, NULL, ['organization_name']);
503 break;
504
505 case 'individual':
506 civicrm_api3_verify_one_mandatory($params, NULL, [
507 'first_name',
508 'last_name',
509 'email',
510 'display_name',
511 ]);
512 break;
513 }
514
515 if (!empty($params['contact_sub_type']) && !empty($params['contact_type'])) {
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']));
518 }
519 }
520
521 // The BAO no longer supports the legacy param "current_employer" so here is a shim for api backward-compatability
522 if (!empty($params['current_employer'])) {
523 $organizationParams = [
524 'organization_name' => $params['current_employer'],
525 ];
526
527 $dupeIds = CRM_Contact_BAO_Contact::getDuplicateContacts($organizationParams, 'Organization', 'Supervised', [], FALSE);
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 }
538
539 if ($dupeIds) {
540 $params['employer_id'] = $dupeIds[0];
541 }
542 else {
543 $result = civicrm_api3('Contact', 'create', [
544 'organization_name' => $params['current_employer'],
545 'contact_type' => 'Organization',
546 ]);
547 $params['employer_id'] = $result['id'];
548 }
549 }
550
551 return NULL;
552 }
553
554 /**
555 * Helper function for Contact create.
556 *
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.
561 *
562 * @return CRM_Contact_BAO_Contact|CRM_Core_Error
563 *
564 * @throws \CRM_Core_Exception
565 * @throws \CiviCRM_API3_Exception
566 * @throws \Civi\API\Exception\UnauthorizedException
567 */
568 function _civicrm_api3_contact_update($params, $contactID = NULL) {
569 //@todo - doesn't contact create support 'id' which is already set- check & remove
570 if ($contactID) {
571 $params['contact_id'] = $contactID;
572 }
573
574 return CRM_Contact_BAO_Contact::create($params);
575 }
576
577 /**
578 * Validate the addressee or email or postal greetings.
579 *
580 * @param array $params
581 * Array per getfields metadata.
582 *
583 * @throws API_Exception
584 * @throws \CRM_Core_Exception
585 */
586 function _civicrm_api3_greeting_format_params($params) {
587 $greetingParams = ['', '_id', '_custom'];
588 foreach (['email', 'postal', 'addressee'] as $key) {
589 $greeting = '_greeting';
590 if ($key == 'addressee') {
591 $greeting = '';
592 }
593
594 $formatParams = FALSE;
595 // Unset display value from params.
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;
613 $filter = [
614 'greeting_type' => "{$key}{$greeting}",
615 ];
616
617 $greetings = CRM_Core_PseudoConstant::greeting($filter);
618 $greetingId = $params["{$key}{$greeting}_id"] ?? NULL;
619 $greetingVal = $params["{$key}{$greeting}"] ?? NULL;
620 $customGreeting = $params["{$key}{$greeting}_custom"] ?? NULL;
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 ) {
629 throw new API_Exception(ts('Provide either %1 greeting id and/or %1 greeting or custom %1 greeting',
630 [1 => $key]
631 ));
632 }
633
634 if ($greetingVal && $greetingId &&
635 ($greetingId != CRM_Utils_Array::key($greetingVal, $greetings))
636 ) {
637 throw new API_Exception(ts('Mismatch in %1 greeting id and %1 greeting',
638 [1 => $key]
639 ));
640 }
641
642 if ($greetingId) {
643 if (!$customGreeting && ($greetingId == array_search('Customized', $greetings))) {
644 throw new API_Exception(ts('Please provide a custom value for %1 greeting',
645 [1 => $key]
646 ));
647 }
648 }
649 elseif ($greetingVal) {
650
651 if (!in_array($greetingVal, $greetings)) {
652 throw new API_Exception(ts('Invalid %1 greeting', [1 => $key]));
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
662 $customValue = isset($params['contact_id']) ? CRM_Core_DAO::getFieldValue(
663 'CRM_Contact_DAO_Contact',
664 $params['contact_id'],
665 "{$key}{$greeting}_custom"
666 ) : FALSE;
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
697 /**
698 * Adjust Metadata for Get action.
699 *
700 * @param array $params
701 * Array of parameters determined by getfields.
702 */
703 function _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');
709 $params['field']['options'] = [
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',
722 ];
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
728 /**
729 * Old Contact quick search api.
730 *
731 * @deprecated
732 *
733 * @param array $params
734 *
735 * @return array
736 * @throws \API_Exception
737 */
738 function civicrm_api3_contact_getquick($params) {
739 $name = CRM_Utils_Type::escape(CRM_Utils_Array::value('name', $params), 'String');
740 $table_name = CRM_Utils_String::munge($params['table_name']);
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
748 $table_names = [
749 'email' => 'eml',
750 'phone_numeric' => 'phe',
751 'street_address' => 'sts',
752 'city' => 'sts',
753 'postal_code' => 'sts',
754 ];
755
756 // get the option values for contact autocomplete
757 $acOptions = CRM_Core_OptionGroup::values('contact_autocomplete_options', FALSE, FALSE, FALSE, NULL, 'name');
758
759 $list = $from = [];
760 foreach ($acpref as $value) {
761 if ($value && !empty($acOptions[$value])) {
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'])) {
767 $field_name = CRM_Utils_String::munge($params['field_name']);
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 }
772 // Unique name contact_id = id
773 if ($field_name == 'contact_id') {
774 $field_name = 'id';
775 }
776 // core#1420 : trim non-numeric character from phone search string
777 elseif ($field_name == 'phone_numeric') {
778 $name = preg_replace('/[^\d]/', '', $name);
779 }
780 if (isset($table_names[$field_name])) {
781 $table_name = $table_names[$field_name];
782 }
783 elseif (strpos($field_name, 'custom_') === 0) {
784 $customField = civicrm_api3('CustomField', 'getsingle', [
785 'id' => substr($field_name, 7),
786 'return' => [
787 'custom_group_id.table_name',
788 'column_name',
789 'data_type',
790 'option_group_id',
791 'html_type',
792 ],
793 ]);
794 $field_name = $customField['column_name'];
795 $table_name = CRM_Utils_String::munge($customField['custom_group_id.table_name']);
796 $from[$field_name] = "LEFT JOIN `$table_name` ON cc.id = `$table_name`.entity_id";
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 }
808 }
809 // phone_numeric should be phone
810 $searchField = str_replace('_numeric', '', $field_name);
811 if (!in_array($searchField, $list)) {
812 $list[] = $searchField;
813 }
814 }
815 else {
816 // Set field name to first name for exact match checking.
817 $field_name = 'sort_name';
818 }
819
820 $select = $actualSelectElements = ['sort_name'];
821 $where = '';
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;
829 $value = "address";
830 $suffix = 'sts';
831 case 'phone':
832 case 'email':
833 $actualSelectElements[] = $select[] = ($value == 'address') ? $selectText : $value;
834 if ($value == 'phone') {
835 $actualSelectElements[] = $select[] = 'phone_ext';
836 }
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:
851 if ($value == 'id') {
852 $actualSelectElements[] = 'cc.id';
853 }
854 elseif ($value != 'sort_name') {
855 $suffix = 'cc';
856 if ($field_name == $value) {
857 $suffix = $table_name;
858 }
859 $actualSelectElements[] = $select[] = $suffix . '.' . $value;
860 }
861 break;
862 }
863 }
864
865 $config = CRM_Core_Config::singleton();
866 $as = $select;
867 $select = implode(', ', $select);
868 if (!empty($select)) {
869 $select = ", $select";
870 }
871 $actualSelectElements = implode(', ', $actualSelectElements);
872 $from = implode(' ', $from);
873 $limit = (int) ($params['limit'] ?? 0);
874 $limit = $limit > 0 ? $limit : Civi::settings()->get('search_autocomplete_count');
875
876 // add acl clause here
877 list($aclFrom, $aclWhere) = CRM_Contact_BAO_Contact_Permission::cacheClause('cc');
878
879 if ($aclWhere) {
880 $where .= " AND $aclWhere ";
881 }
882 $isPrependWildcard = \Civi::settings()->get('includeWildCardInName');
883
884 if (!empty($params['org'])) {
885 $where .= " AND contact_type = \"Organization\"";
886
887 // CRM-7157, hack: get current employer details when
888 // employee_id is present.
889 $currEmpDetails = [];
890 if (!empty($params['employee_id'])) {
891 if ($currentEmployer = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact',
892 (int) $params['employee_id'],
893 'employer_id'
894 )) {
895 if ($isPrependWildcard) {
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()) {
906 $currEmpDetails = [
907 'id' => $dao->id,
908 'data' => $dao->data,
909 ];
910 }
911 }
912 }
913 }
914
915 if (!empty($params['contact_sub_type'])) {
916 $contactSubType = CRM_Utils_Type::escape($params['contact_sub_type'], 'String');
917 $where .= " AND cc.contact_sub_type = '{$contactSubType}'";
918 }
919
920 if (!empty($params['contact_type'])) {
921 $contactType = CRM_Utils_Type::escape($params['contact_type'], 'String');
922 $where .= " AND cc.contact_type LIKE '{$contactType}'";
923 }
924
925 // Set default for current_employer or return contact with particular id
926 if (!empty($params['id'])) {
927 $where .= " AND cc.id = " . (int) $params['id'];
928 }
929
930 if (!empty($params['cid'])) {
931 $where .= " AND cc.id <> " . (int) $params['cid'];
932 }
933
934 // Contact's based of relationhip type
935 $relType = NULL;
936 if (!empty($params['rel'])) {
937 $relation = explode('_', $params['rel']);
938 $relType = CRM_Utils_Type::escape($relation[0], 'Integer');
939 $rel = CRM_Utils_Type::escape($relation[2], 'String');
940 }
941
942 if ($isPrependWildcard) {
943 $strSearch = "%$name%";
944 }
945 else {
946 $strSearch = "$name%";
947 }
948 $includeEmailFrom = $includeNickName = '';
949 if ($config->includeNickNameInName) {
950 $includeNickName = " OR nick_name LIKE '$strSearch'";
951 }
952
953 if (isset($customOptionsWhere)) {
954 $customOptionsWhere = $customOptionsWhere ?: [0];
955 $whereClause = " WHERE (" . implode(' OR ', $customOptionsWhere) . ") $where";
956 }
957 elseif (!empty($params['field_name']) && !empty($params['table_name']) && $params['field_name'] != 'sort_name') {
958 $whereClause = " WHERE ( $table_name.$field_name LIKE '$strSearch') {$where}";
959 // Search by id should be exact
960 if ($field_name == 'id' || $field_name == 'external_identifier') {
961 $whereClause = " WHERE ( $table_name.$field_name = '$name') {$where}";
962 }
963 }
964 else {
965 $whereClause = " WHERE ( sort_name LIKE '$strSearch' $includeNickName ) {$where} ";
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 }
970 $emailWhere = " WHERE email LIKE '$strSearch'";
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
985 if (!empty($params['cmsuser'])) {
986 $additionalFrom = "
987 INNER JOIN civicrm_uf_match um ON (um.contact_id=cc.id)
988 ";
989 }
990 $orderBy = _civicrm_api3_quicksearch_get_order_by($name, $isPrependWildcard, $field_name);
991
992 //CRM-5954
993 $query = "
994 SELECT DISTINCT(id), data, sort_name, exactFirst
995 FROM (
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}
1000 FROM civicrm_contact cc {$from}
1001 {$aclFrom}
1002 {$additionalFrom}
1003 {$whereClause}
1004 {$orderBy}
1005 LIMIT 0, {$limit} )
1006 ";
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}
1018 {$emailWhere} AND cc.is_deleted = 0 " . ($aclWhere ? " AND $aclWhere " : '') . "
1019 {$orderBy}
1020 LIMIT 0, {$limit}
1021 )
1022 ";
1023 }
1024 $query .= ") t
1025 {$orderBy}
1026 LIMIT 0, {$limit}
1027 ";
1028
1029 // send query to hook to be modified if needed
1030 CRM_Utils_Hook::contactListQuery($query,
1031 $name,
1032 empty($params['context']) ? NULL : CRM_Utils_Type::escape($params['context'], 'String'),
1033 empty($params['id']) ? NULL : $params['id']
1034 );
1035
1036 $dao = CRM_Core_DAO::executeQuery($query);
1037
1038 $contactList = [];
1039 $listCurrentEmployer = TRUE;
1040 while ($dao->fetch()) {
1041 $t = ['id' => $dao->id];
1042 foreach ($as as $k) {
1043 $t[$k] = $dao->$k ?? '';
1044 }
1045 $t['data'] = $dao->data;
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 }
1054 $contactList[] = $t;
1055 if (!empty($params['org']) &&
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)) {
1065 if (!empty($params['org'])) {
1066 if ($listCurrentEmployer && !empty($currEmpDetails)) {
1067 $contactList = [
1068 [
1069 'data' => $currEmpDetails['data'],
1070 'id' => $currEmpDetails['id'],
1071 ],
1072 ];
1073 }
1074 else {
1075 $contactList = [
1076 [
1077 'data' => $name,
1078 'id' => $name,
1079 ],
1080 ];
1081 }
1082 }
1083 }
1084
1085 return civicrm_api3_create_success($contactList, $params, 'Contact', 'getquick');
1086 }
1087
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 */
1122 function _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
1140 /**
1141 * Declare deprecated api functions.
1142 *
1143 * @deprecated api notice
1144 * @return array
1145 * Array of deprecated actions
1146 */
1147 function _civicrm_api3_contact_deprecation() {
1148 return ['getquick' => 'The "getquick" action is deprecated in favor of "getlist".'];
1149 }
1150
1151 /**
1152 * Merges given pair of duplicate contacts.
1153 *
1154 * @param array $params
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.
1159 *
1160 * @return array
1161 * API Result Array
1162 *
1163 * @throws API_Exception
1164 * @throws \CiviCRM_API3_Exception
1165 * @throws \CRM_Core_Exception
1166 */
1167 function civicrm_api3_contact_merge($params) {
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
1176 return civicrm_api3_create_success($result, $params);
1177 }
1178 throw new API_Exception('Merge failed');
1179 }
1180
1181 /**
1182 * Adjust metadata for contact_merge api function.
1183 *
1184 * @param array $params
1185 */
1186 function _civicrm_api3_contact_merge_spec(&$params) {
1187 $params['to_remove_id'] = [
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?'),
1190 'api.required' => 1,
1191 'type' => CRM_Utils_Type::T_INT,
1192 'api.aliases' => ['main_id'],
1193 ];
1194 $params['to_keep_id'] = [
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?'),
1197 'api.required' => 1,
1198 'type' => CRM_Utils_Type::T_INT,
1199 'api.aliases' => ['other_id'],
1200 ];
1201 $params['mode'] = [
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)"),
1204 'api.default' => 'safe',
1205 'options' => ['safe' => ts('Abort on unhandled conflict'), 'aggressive' => ts('Proceed on unhandled conflict. Note hooks may change handling here.')],
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
1223 * @throws \API_Exception
1224 */
1225 function civicrm_api3_contact_get_merge_conflicts($params) {
1226 $migrationInfo = [];
1227 $result = [];
1228 foreach ((array) $params['mode'] as $mode) {
1229 $result[$mode] = CRM_Dedupe_Merger::getConflicts(
1230 $migrationInfo,
1231 $params['to_remove_id'], $params['to_keep_id'],
1232 $mode
1233 );
1234 }
1235 return civicrm_api3_create_success($result, $params);
1236 }
1237
1238 /**
1239 * Adjust metadata for contact_merge api function.
1240 *
1241 * @param array $params
1242 */
1243 function _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 "),
1257 'api.default' => 'safe',
1258 ];
1259 }
1260
1261 /**
1262 * Get the ultimate contact a contact was merged to.
1263 *
1264 * @param array $params
1265 *
1266 * @return array
1267 * API Result Array
1268 *
1269 * @throws \CiviCRM_API3_Exception
1270 */
1271 function 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
1292 *
1293 * @throws \CiviCRM_API3_Exception
1294 */
1295 function _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,
1307 'sort' => 'activity_id.activity_date_time DESC',
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 */
1325 function _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
1345 *
1346 * @throws \CiviCRM_API3_Exception
1347 */
1348 function 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
1359 *
1360 * @throws \CiviCRM_API3_Exception
1361 */
1362 function _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 */
1397 function _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
1410 /**
1411 * Adjust metadata for contact_proximity api function.
1412 *
1413 * @param array $params
1414 */
1415 function _civicrm_api3_contact_proximity_spec(&$params) {
1416 $params['latitude'] = [
1417 'title' => 'Latitude',
1418 'api.required' => 1,
1419 'type' => CRM_Utils_Type::T_STRING,
1420 ];
1421 $params['longitude'] = [
1422 'title' => 'Longitude',
1423 'api.required' => 1,
1424 'type' => CRM_Utils_Type::T_STRING,
1425 ];
1426
1427 $params['unit'] = [
1428 'title' => 'Unit of Measurement',
1429 'api.default' => 'meter',
1430 'type' => CRM_Utils_Type::T_STRING,
1431 ];
1432 }
1433
1434 /**
1435 * Get contacts by proximity.
1436 *
1437 * @param array $params
1438 *
1439 * @return array
1440 * @throws Exception
1441 */
1442 function civicrm_api3_contact_proximity($params) {
1443 $latitude = $params['latitude'] ?? NULL;
1444 $longitude = $params['longitude'] ?? NULL;
1445 $distance = $params['distance'] ?? NULL;
1446
1447 $unit = $params['unit'] ?? NULL;
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 ) {
1455 throw new API_Exception(ts('Latitude, Longitude and Distance should exist and be numeric'));
1456 }
1457
1458 if ($unit === 'mile') {
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 = "
1470 SELECT civicrm_contact.id as contact_id,
1471 civicrm_contact.display_name as display_name
1472 FROM civicrm_contact
1473 LEFT JOIN civicrm_address ON civicrm_contact.id = civicrm_address.contact_id
1474 WHERE $whereClause
1475 ";
1476
1477 $dao = CRM_Core_DAO::executeQuery($query);
1478 $contacts = [];
1479 while ($dao->fetch()) {
1480 $contacts[] = $dao->toArray();
1481 }
1482
1483 return civicrm_api3_create_success($contacts, $params, 'Contact', 'get_by_location', $dao);
1484 }
1485
1486 /**
1487 * Get parameters for getlist function.
1488 *
1489 * @see _civicrm_api3_generic_getlist_params
1490 *
1491 * @param array $request
1492 */
1493 function _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
1504 $list = [];
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
1513 if ($field_name === 'contact_id') {
1514 $field_name = 'id';
1515 }
1516 // phone_numeric should be phone
1517 $searchField = str_replace('_numeric', '', $field_name);
1518 if (!in_array($searchField, $list)) {
1519 $list[] = $searchField;
1520 }
1521 $request['description_field'] = $list;
1522 $list[] = 'contact_type';
1523 $request['params']['return'] = array_unique(array_merge($list, $request['extra']));
1524 $request['params']['options']['sort'] = 'sort_name';
1525 // Contact api doesn't support array(LIKE => 'foo') syntax
1526 if (!empty($request['input'])) {
1527 $request['params'][$request['search_field']] = $request['input'];
1528 // Temporarily override wildcard setting
1529 if (Civi::settings()->get('includeWildCardInName') !== $request['add_wildcard']) {
1530 Civi::$statics['civicrm_api3_contact_getlist']['override_wildcard'] = !$request['add_wildcard'];
1531 Civi::settings()->set('includeWildCardInName', $request['add_wildcard']);
1532 }
1533 }
1534 }
1535
1536 /**
1537 * Get output for getlist function.
1538 *
1539 * @see _civicrm_api3_generic_getlist_output
1540 *
1541 * @param array $result
1542 * @param array $request
1543 *
1544 * @return array
1545 */
1546 function _civicrm_api3_contact_getlist_output($result, $request) {
1547 $output = [];
1548 if (!empty($result['values'])) {
1549 $addressFields = array_intersect([
1550 'street_address',
1551 'city',
1552 'state_province',
1553 'country',
1554 ],
1555 $request['params']['return']);
1556 foreach ($result['values'] as $row) {
1557 $data = [
1558 'id' => $row[$request['id_field']],
1559 'label' => $row[$request['label_field']],
1560 'description' => [],
1561 ];
1562 foreach ($request['description_field'] as $item) {
1563 if (!strpos($item, '_name') && !in_array($item, $addressFields) && !empty($row[$item])) {
1564 $data['description'][] = $row[$item];
1565 }
1566 }
1567 $address = [];
1568 foreach ($addressFields as $item) {
1569 if (!empty($row[$item])) {
1570 $address[] = $row[$item];
1571 }
1572 }
1573 if ($address) {
1574 $data['description'][] = implode(' ', $address);
1575 }
1576 if (!empty($request['image_field'])) {
1577 $data['image'] = $row[$request['image_field']] ?? '';
1578 }
1579 else {
1580 $data['icon_class'] = $row['contact_type'];
1581 }
1582 $output[] = $data;
1583 }
1584 }
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 }
1590 return $output;
1591 }
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
1601 *
1602 * @throws \CiviCRM_API3_Exception
1603 */
1604 function civicrm_api3_contact_duplicatecheck($params) {
1605 $dupes = CRM_Contact_BAO_Contact::getDuplicateContacts(
1606 $params['match'],
1607 $params['match']['contact_type'],
1608 $params['rule_type'],
1609 CRM_Utils_Array::value('exclude', $params, []),
1610 CRM_Utils_Array::value('check_permissions', $params),
1611 CRM_Utils_Array::value('dedupe_rule_id', $params)
1612 );
1613 $values = [];
1614 if ($dupes && !empty($params['return'])) {
1615 return civicrm_api3('Contact', 'get', [
1616 'return' => $params['return'],
1617 'id' => ['IN' => $dupes],
1618 'options' => $params['options'] ?? NULL,
1619 'sequential' => $params['sequential'] ?? NULL,
1620 'check_permissions' => $params['check_permissions'] ?? NULL,
1621 ]);
1622 }
1623 foreach ($dupes as $dupe) {
1624 $values[$dupe] = ['id' => $dupe];
1625 }
1626 return civicrm_api3_create_success($values, $params, 'Contact', 'duplicatecheck');
1627 }
1628
1629 /**
1630 * Declare metadata for contact dedupe function.
1631 *
1632 * @param array $params
1633 */
1634 function _civicrm_api3_contact_duplicatecheck_spec(&$params) {
1635 $params['dedupe_rule_id'] = [
1636 'title' => 'Dedupe Rule ID (optional)',
1637 'description' => 'This will default to the built in unsupervised rule',
1638 'type' => CRM_Utils_Type::T_INT,
1639 ];
1640 $params['rule_type'] = [
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',
1645 ];
1646 // @todo declare 'match' parameter. We don't have a standard for type = array yet.
1647 }