Merge pull request #16800 from pradpnayak/notifyEmail
[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 // Unique name contact_id = id
769 if ($field_name == 'contact_id') {
770 $field_name = 'id';
771 }
772 // core#1420 : trim non-numeric character from phone search string
773 elseif ($field_name == 'phone_numeric') {
774 $name = preg_replace('/[^\d]/', '', $name);
775 }
776 if (isset($table_names[$field_name])) {
777 $table_name = $table_names[$field_name];
778 }
779 elseif (strpos($field_name, 'custom_') === 0) {
780 $customField = civicrm_api3('CustomField', 'getsingle', [
781 'id' => substr($field_name, 7),
782 'return' => [
783 'custom_group_id.table_name',
784 'column_name',
785 'data_type',
786 'option_group_id',
787 'html_type',
788 ],
789 ]);
790 $field_name = $customField['column_name'];
791 $table_name = CRM_Utils_String::munge($customField['custom_group_id.table_name']);
792 $from[$field_name] = "LEFT JOIN `$table_name` ON cc.id = `$table_name`.entity_id";
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 }
804 }
805 // phone_numeric should be phone
806 $searchField = str_replace('_numeric', '', $field_name);
807 if (!in_array($searchField, $list)) {
808 $list[] = $searchField;
809 }
810 }
811 else {
812 // Set field name to first name for exact match checking.
813 $field_name = 'sort_name';
814 }
815
816 $select = $actualSelectElements = ['sort_name'];
817 $where = '';
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;
825 $value = "address";
826 $suffix = 'sts';
827 case 'phone':
828 case 'email':
829 $actualSelectElements[] = $select[] = ($value == 'address') ? $selectText : $value;
830 if ($value == 'phone') {
831 $actualSelectElements[] = $select[] = 'phone_ext';
832 }
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:
847 if ($value == 'id') {
848 $actualSelectElements[] = 'cc.id';
849 }
850 elseif ($value != 'sort_name') {
851 $suffix = 'cc';
852 if ($field_name == $value) {
853 $suffix = $table_name;
854 }
855 $actualSelectElements[] = $select[] = $suffix . '.' . $value;
856 }
857 break;
858 }
859 }
860
861 $config = CRM_Core_Config::singleton();
862 $as = $select;
863 $select = implode(', ', $select);
864 if (!empty($select)) {
865 $select = ", $select";
866 }
867 $actualSelectElements = implode(', ', $actualSelectElements);
868 $from = implode(' ', $from);
869 $limit = (int) ($params['limit'] ?? 0);
870 $limit = $limit > 0 ? $limit : Civi::settings()->get('search_autocomplete_count');
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 }
878 $isPrependWildcard = \Civi::settings()->get('includeWildCardInName');
879
880 if (!empty($params['org'])) {
881 $where .= " AND contact_type = \"Organization\"";
882
883 // CRM-7157, hack: get current employer details when
884 // employee_id is present.
885 $currEmpDetails = [];
886 if (!empty($params['employee_id'])) {
887 if ($currentEmployer = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact',
888 (int) $params['employee_id'],
889 'employer_id'
890 )) {
891 if ($isPrependWildcard) {
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()) {
902 $currEmpDetails = [
903 'id' => $dao->id,
904 'data' => $dao->data,
905 ];
906 }
907 }
908 }
909 }
910
911 if (!empty($params['contact_sub_type'])) {
912 $contactSubType = CRM_Utils_Type::escape($params['contact_sub_type'], 'String');
913 $where .= " AND cc.contact_sub_type = '{$contactSubType}'";
914 }
915
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
921 // Set default for current_employer or return contact with particular id
922 if (!empty($params['id'])) {
923 $where .= " AND cc.id = " . (int) $params['id'];
924 }
925
926 if (!empty($params['cid'])) {
927 $where .= " AND cc.id <> " . (int) $params['cid'];
928 }
929
930 // Contact's based of relationhip type
931 $relType = NULL;
932 if (!empty($params['rel'])) {
933 $relation = explode('_', CRM_Utils_Array::value('rel', $params));
934 $relType = CRM_Utils_Type::escape($relation[0], 'Integer');
935 $rel = CRM_Utils_Type::escape($relation[2], 'String');
936 }
937
938 if ($isPrependWildcard) {
939 $strSearch = "%$name%";
940 }
941 else {
942 $strSearch = "$name%";
943 }
944 $includeEmailFrom = $includeNickName = '';
945 if ($config->includeNickNameInName) {
946 $includeNickName = " OR nick_name LIKE '$strSearch'";
947 }
948
949 if (isset($customOptionsWhere)) {
950 $customOptionsWhere = $customOptionsWhere ?: [0];
951 $whereClause = " WHERE (" . implode(' OR ', $customOptionsWhere) . ") $where";
952 }
953 elseif (!empty($params['field_name']) && !empty($params['table_name']) && $params['field_name'] != 'sort_name') {
954 $whereClause = " WHERE ( $table_name.$field_name LIKE '$strSearch') {$where}";
955 // Search by id should be exact
956 if ($field_name == 'id' || $field_name == 'external_identifier') {
957 $whereClause = " WHERE ( $table_name.$field_name = '$name') {$where}";
958 }
959 }
960 else {
961 $whereClause = " WHERE ( sort_name LIKE '$strSearch' $includeNickName ) {$where} ";
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 }
966 $emailWhere = " WHERE email LIKE '$strSearch'";
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
981 if (!empty($params['cmsuser'])) {
982 $additionalFrom = "
983 INNER JOIN civicrm_uf_match um ON (um.contact_id=cc.id)
984 ";
985 }
986 $orderBy = _civicrm_api3_quicksearch_get_order_by($name, $isPrependWildcard, $field_name);
987
988 //CRM-5954
989 $query = "
990 SELECT DISTINCT(id), data, sort_name, exactFirst
991 FROM (
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}
996 FROM civicrm_contact cc {$from}
997 {$aclFrom}
998 {$additionalFrom}
999 {$whereClause}
1000 {$orderBy}
1001 LIMIT 0, {$limit} )
1002 ";
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}
1014 {$emailWhere} AND cc.is_deleted = 0 " . ($aclWhere ? " AND $aclWhere " : '') . "
1015 {$orderBy}
1016 LIMIT 0, {$limit}
1017 )
1018 ";
1019 }
1020 $query .= ") t
1021 {$orderBy}
1022 LIMIT 0, {$limit}
1023 ";
1024
1025 // send query to hook to be modified if needed
1026 CRM_Utils_Hook::contactListQuery($query,
1027 $name,
1028 empty($params['context']) ? NULL : CRM_Utils_Type::escape($params['context'], 'String'),
1029 empty($params['id']) ? NULL : $params['id']
1030 );
1031
1032 $dao = CRM_Core_DAO::executeQuery($query);
1033
1034 $contactList = [];
1035 $listCurrentEmployer = TRUE;
1036 while ($dao->fetch()) {
1037 $t = ['id' => $dao->id];
1038 foreach ($as as $k) {
1039 $t[$k] = isset($dao->$k) ? $dao->$k : '';
1040 }
1041 $t['data'] = $dao->data;
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 }
1050 $contactList[] = $t;
1051 if (!empty($params['org']) &&
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)) {
1061 if (!empty($params['org'])) {
1062 if ($listCurrentEmployer && !empty($currEmpDetails)) {
1063 $contactList = [
1064 [
1065 'data' => $currEmpDetails['data'],
1066 'id' => $currEmpDetails['id'],
1067 ],
1068 ];
1069 }
1070 else {
1071 $contactList = [
1072 [
1073 'data' => $name,
1074 'id' => $name,
1075 ],
1076 ];
1077 }
1078 }
1079 }
1080
1081 return civicrm_api3_create_success($contactList, $params, 'Contact', 'getquick');
1082 }
1083
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 */
1118 function _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
1136 /**
1137 * Declare deprecated api functions.
1138 *
1139 * @deprecated api notice
1140 * @return array
1141 * Array of deprecated actions
1142 */
1143 function _civicrm_api3_contact_deprecation() {
1144 return ['getquick' => 'The "getquick" action is deprecated in favor of "getlist".'];
1145 }
1146
1147 /**
1148 * Merges given pair of duplicate contacts.
1149 *
1150 * @param array $params
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.
1155 *
1156 * @return array
1157 * API Result Array
1158 *
1159 * @throws API_Exception
1160 * @throws \CiviCRM_API3_Exception
1161 * @throws \CRM_Core_Exception
1162 */
1163 function civicrm_api3_contact_merge($params) {
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
1172 return civicrm_api3_create_success($result, $params);
1173 }
1174 throw new API_Exception('Merge failed');
1175 }
1176
1177 /**
1178 * Adjust metadata for contact_merge api function.
1179 *
1180 * @param array $params
1181 */
1182 function _civicrm_api3_contact_merge_spec(&$params) {
1183 $params['to_remove_id'] = [
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?'),
1186 'api.required' => 1,
1187 'type' => CRM_Utils_Type::T_INT,
1188 'api.aliases' => ['main_id'],
1189 ];
1190 $params['to_keep_id'] = [
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?'),
1193 'api.required' => 1,
1194 'type' => CRM_Utils_Type::T_INT,
1195 'api.aliases' => ['other_id'],
1196 ];
1197 $params['mode'] = [
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)"),
1200 'api.default' => 'safe',
1201 'options' => ['safe' => ts('Abort on unhandled conflict'), 'aggressive' => ts('Proceed on unhandled conflict. Note hooks may change handling here.')],
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
1219 * @throws \API_Exception
1220 */
1221 function civicrm_api3_contact_get_merge_conflicts($params) {
1222 $migrationInfo = [];
1223 $result = [];
1224 foreach ((array) $params['mode'] as $mode) {
1225 $result[$mode] = CRM_Dedupe_Merger::getConflicts(
1226 $migrationInfo,
1227 $params['to_remove_id'], $params['to_keep_id'],
1228 $mode
1229 );
1230 }
1231 return civicrm_api3_create_success($result, $params);
1232 }
1233
1234 /**
1235 * Adjust metadata for contact_merge api function.
1236 *
1237 * @param array $params
1238 */
1239 function _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 "),
1253 'api.default' => 'safe',
1254 ];
1255 }
1256
1257 /**
1258 * Get the ultimate contact a contact was merged to.
1259 *
1260 * @param array $params
1261 *
1262 * @return array
1263 * API Result Array
1264 *
1265 * @throws \CiviCRM_API3_Exception
1266 */
1267 function 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
1288 *
1289 * @throws \CiviCRM_API3_Exception
1290 */
1291 function _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,
1303 'sort' => 'activity_id.activity_date_time DESC',
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 */
1321 function _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
1341 *
1342 * @throws \CiviCRM_API3_Exception
1343 */
1344 function 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
1355 *
1356 * @throws \CiviCRM_API3_Exception
1357 */
1358 function _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 */
1393 function _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
1406 /**
1407 * Adjust metadata for contact_proximity api function.
1408 *
1409 * @param array $params
1410 */
1411 function _civicrm_api3_contact_proximity_spec(&$params) {
1412 $params['latitude'] = [
1413 'title' => 'Latitude',
1414 'api.required' => 1,
1415 'type' => CRM_Utils_Type::T_STRING,
1416 ];
1417 $params['longitude'] = [
1418 'title' => 'Longitude',
1419 'api.required' => 1,
1420 'type' => CRM_Utils_Type::T_STRING,
1421 ];
1422
1423 $params['unit'] = [
1424 'title' => 'Unit of Measurement',
1425 'api.default' => 'meter',
1426 'type' => CRM_Utils_Type::T_STRING,
1427 ];
1428 }
1429
1430 /**
1431 * Get contacts by proximity.
1432 *
1433 * @param array $params
1434 *
1435 * @return array
1436 * @throws Exception
1437 */
1438 function civicrm_api3_contact_proximity($params) {
1439 $latitude = $params['latitude'] ?? NULL;
1440 $longitude = $params['longitude'] ?? NULL;
1441 $distance = $params['distance'] ?? NULL;
1442
1443 $unit = $params['unit'] ?? NULL;
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 ) {
1451 throw new API_Exception(ts('Latitude, Longitude and Distance should exist and be numeric'));
1452 }
1453
1454 if ($unit === 'mile') {
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 = "
1466 SELECT civicrm_contact.id as contact_id,
1467 civicrm_contact.display_name as display_name
1468 FROM civicrm_contact
1469 LEFT JOIN civicrm_address ON civicrm_contact.id = civicrm_address.contact_id
1470 WHERE $whereClause
1471 ";
1472
1473 $dao = CRM_Core_DAO::executeQuery($query);
1474 $contacts = [];
1475 while ($dao->fetch()) {
1476 $contacts[] = $dao->toArray();
1477 }
1478
1479 return civicrm_api3_create_success($contacts, $params, 'Contact', 'get_by_location', $dao);
1480 }
1481
1482 /**
1483 * Get parameters for getlist function.
1484 *
1485 * @see _civicrm_api3_generic_getlist_params
1486 *
1487 * @param array $request
1488 */
1489 function _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
1500 $list = [];
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
1509 if ($field_name === 'contact_id') {
1510 $field_name = 'id';
1511 }
1512 // phone_numeric should be phone
1513 $searchField = str_replace('_numeric', '', $field_name);
1514 if (!in_array($searchField, $list)) {
1515 $list[] = $searchField;
1516 }
1517 $request['description_field'] = $list;
1518 $list[] = 'contact_type';
1519 $request['params']['return'] = array_unique(array_merge($list, $request['extra']));
1520 $request['params']['options']['sort'] = 'sort_name';
1521 // Contact api doesn't support array(LIKE => 'foo') syntax
1522 if (!empty($request['input'])) {
1523 $request['params'][$request['search_field']] = $request['input'];
1524 // Temporarily override wildcard setting
1525 if (Civi::settings()->get('includeWildCardInName') !== $request['add_wildcard']) {
1526 Civi::$statics['civicrm_api3_contact_getlist']['override_wildcard'] = !$request['add_wildcard'];
1527 Civi::settings()->set('includeWildCardInName', $request['add_wildcard']);
1528 }
1529 }
1530 }
1531
1532 /**
1533 * Get output for getlist function.
1534 *
1535 * @see _civicrm_api3_generic_getlist_output
1536 *
1537 * @param array $result
1538 * @param array $request
1539 *
1540 * @return array
1541 */
1542 function _civicrm_api3_contact_getlist_output($result, $request) {
1543 $output = [];
1544 if (!empty($result['values'])) {
1545 $addressFields = array_intersect([
1546 'street_address',
1547 'city',
1548 'state_province',
1549 'country',
1550 ],
1551 $request['params']['return']);
1552 foreach ($result['values'] as $row) {
1553 $data = [
1554 'id' => $row[$request['id_field']],
1555 'label' => $row[$request['label_field']],
1556 'description' => [],
1557 ];
1558 foreach ($request['description_field'] as $item) {
1559 if (!strpos($item, '_name') && !in_array($item, $addressFields) && !empty($row[$item])) {
1560 $data['description'][] = $row[$item];
1561 }
1562 }
1563 $address = [];
1564 foreach ($addressFields as $item) {
1565 if (!empty($row[$item])) {
1566 $address[] = $row[$item];
1567 }
1568 }
1569 if ($address) {
1570 $data['description'][] = implode(' ', $address);
1571 }
1572 if (!empty($request['image_field'])) {
1573 $data['image'] = isset($row[$request['image_field']]) ? $row[$request['image_field']] : '';
1574 }
1575 else {
1576 $data['icon_class'] = $row['contact_type'];
1577 }
1578 $output[] = $data;
1579 }
1580 }
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 }
1586 return $output;
1587 }
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
1597 *
1598 * @throws \CiviCRM_API3_Exception
1599 */
1600 function civicrm_api3_contact_duplicatecheck($params) {
1601 $dupes = CRM_Contact_BAO_Contact::getDuplicateContacts(
1602 $params['match'],
1603 $params['match']['contact_type'],
1604 $params['rule_type'],
1605 CRM_Utils_Array::value('exclude', $params, []),
1606 CRM_Utils_Array::value('check_permissions', $params),
1607 CRM_Utils_Array::value('dedupe_rule_id', $params)
1608 );
1609 $values = [];
1610 if ($dupes && !empty($params['return'])) {
1611 return civicrm_api3('Contact', 'get', [
1612 'return' => $params['return'],
1613 'id' => ['IN' => $dupes],
1614 'options' => $params['options'] ?? NULL,
1615 'sequential' => $params['sequential'] ?? NULL,
1616 'check_permissions' => $params['check_permissions'] ?? NULL,
1617 ]);
1618 }
1619 foreach ($dupes as $dupe) {
1620 $values[$dupe] = ['id' => $dupe];
1621 }
1622 return civicrm_api3_create_success($values, $params, 'Contact', 'duplicatecheck');
1623 }
1624
1625 /**
1626 * Declare metadata for contact dedupe function.
1627 *
1628 * @param array $params
1629 */
1630 function _civicrm_api3_contact_duplicatecheck_spec(&$params) {
1631 $params['dedupe_rule_id'] = [
1632 'title' => 'Dedupe Rule ID (optional)',
1633 'description' => 'This will default to the built in unsupervised rule',
1634 'type' => CRM_Utils_Type::T_INT,
1635 ];
1636 $params['rule_type'] = [
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',
1641 ];
1642 // @todo declare 'match' parameter. We don't have a standard for type = array yet.
1643 }