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