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