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