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