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