Merge pull request #14252 from jitendrapurohit/core-961
[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 $result = [];
1215 foreach ((array) $params['mode'] as $mode) {
1216 $result[$mode]['conflicts'] = CRM_Dedupe_Merger::getConflicts(
1217 $migrationInfo,
1218 $params['to_remove_id'], $params['to_keep_id'],
1219 $mode
1220 );
1221 }
1222 return civicrm_api3_create_success($result, $params);
1223 }
1224
1225 /**
1226 * Adjust metadata for contact_merge api function.
1227 *
1228 * @param array $params
1229 */
1230 function _civicrm_api3_contact_get_merge_conflicts_spec(&$params) {
1231 $params['to_remove_id'] = [
1232 'title' => ts('ID of the contact to merge & remove'),
1233 'api.required' => 1,
1234 'type' => CRM_Utils_Type::T_INT,
1235 ];
1236 $params['to_keep_id'] = [
1237 'title' => ts('ID of the contact to keep'),
1238 'api.required' => 1,
1239 'type' => CRM_Utils_Type::T_INT,
1240 ];
1241 $params['mode'] = [
1242 'title' => ts('Dedupe mode'),
1243 'description' => ts("'safe' or 'aggressive' - these modes map to the merge actions & may affect resolution done by hooks "),
1244 'api.default' => 'safe',
1245 ];
1246 }
1247
1248 /**
1249 * Get the ultimate contact a contact was merged to.
1250 *
1251 * @param array $params
1252 *
1253 * @return array
1254 * API Result Array
1255 * @throws API_Exception
1256 */
1257 function civicrm_api3_contact_getmergedto($params) {
1258 $contactID = _civicrm_api3_contact_getmergedto($params);
1259 if ($contactID) {
1260 $values = [$contactID => ['id' => $contactID]];
1261 }
1262 else {
1263 $values = [];
1264 }
1265 return civicrm_api3_create_success($values, $params);
1266 }
1267
1268 /**
1269 * Get the contact our contact was finally merged to.
1270 *
1271 * If the contact has been merged multiple times the crucial parent activity will have
1272 * wound up on the ultimate contact so we can figure out the final resting place of the
1273 * contact with only 2 activities even if 50 merges took place.
1274 *
1275 * @param array $params
1276 *
1277 * @return int|false
1278 */
1279 function _civicrm_api3_contact_getmergedto($params) {
1280 $contactID = FALSE;
1281 $deleteActivity = civicrm_api3('ActivityContact', 'get', [
1282 'contact_id' => $params['contact_id'],
1283 'activity_id.activity_type_id' => 'Contact Deleted By Merge',
1284 'is_deleted' => 0,
1285 'is_test' => $params['is_test'],
1286 'record_type_id' => 'Activity Targets',
1287 'return' => ['activity_id.parent_id'],
1288 'sequential' => 1,
1289 'options' => [
1290 'limit' => 1,
1291 'sort' => 'activity_id.activity_date_time DESC',
1292 ],
1293 ])['values'];
1294 if (!empty($deleteActivity)) {
1295 $contactID = civicrm_api3('ActivityContact', 'getvalue', [
1296 'activity_id' => $deleteActivity[0]['activity_id.parent_id'],
1297 'record_type_id' => 'Activity Targets',
1298 'return' => 'contact_id',
1299 ]);
1300 }
1301 return $contactID;
1302 }
1303
1304 /**
1305 * Adjust metadata for contact_merge api function.
1306 *
1307 * @param array $params
1308 */
1309 function _civicrm_api3_contact_getmergedto_spec(&$params) {
1310 $params['contact_id'] = [
1311 'title' => ts('ID of contact to find ultimate contact for'),
1312 'type' => CRM_Utils_Type::T_INT,
1313 'api.required' => TRUE,
1314 ];
1315 $params['is_test'] = [
1316 'title' => ts('Get test deletions rather than live?'),
1317 'type' => CRM_Utils_Type::T_BOOLEAN,
1318 'api.default' => 0,
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_getmergedfrom($params) {
1332 $contacts = _civicrm_api3_contact_getmergedfrom($params);
1333 return civicrm_api3_create_success($contacts, $params);
1334 }
1335
1336 /**
1337 * Get all the contacts merged into our contact.
1338 *
1339 * @param array $params
1340 *
1341 * @return array
1342 */
1343 function _civicrm_api3_contact_getmergedfrom($params) {
1344 $activities = [];
1345 $deleteActivities = civicrm_api3('ActivityContact', 'get', [
1346 'contact_id' => $params['contact_id'],
1347 'activity_id.activity_type_id' => 'Contact Merged',
1348 'is_deleted' => 0,
1349 'is_test' => $params['is_test'],
1350 'record_type_id' => 'Activity Targets',
1351 'return' => 'activity_id',
1352 ])['values'];
1353
1354 foreach ($deleteActivities as $deleteActivity) {
1355 $activities[] = $deleteActivity['activity_id'];
1356 }
1357 if (empty($activities)) {
1358 return [];
1359 }
1360
1361 $activityContacts = civicrm_api3('ActivityContact', 'get', [
1362 'activity_id.parent_id' => ['IN' => $activities],
1363 'record_type_id' => 'Activity Targets',
1364 'return' => 'contact_id',
1365 ])['values'];
1366 $contacts = [];
1367 foreach ($activityContacts as $activityContact) {
1368 $contacts[$activityContact['contact_id']] = ['id' => $activityContact['contact_id']];
1369 }
1370 return $contacts;
1371 }
1372
1373 /**
1374 * Adjust metadata for contact_merge api function.
1375 *
1376 * @param array $params
1377 */
1378 function _civicrm_api3_contact_getmergedfrom_spec(&$params) {
1379 $params['contact_id'] = [
1380 'title' => ts('ID of contact to find ultimate contact for'),
1381 'type' => CRM_Utils_Type::T_INT,
1382 'api.required' => TRUE,
1383 ];
1384 $params['is_test'] = [
1385 'title' => ts('Get test deletions rather than live?'),
1386 'type' => CRM_Utils_Type::T_BOOLEAN,
1387 'api.default' => 0,
1388 ];
1389 }
1390
1391 /**
1392 * Adjust metadata for contact_proximity api function.
1393 *
1394 * @param array $params
1395 */
1396 function _civicrm_api3_contact_proximity_spec(&$params) {
1397 $params['latitude'] = [
1398 'title' => 'Latitude',
1399 'api.required' => 1,
1400 'type' => CRM_Utils_Type::T_STRING,
1401 ];
1402 $params['longitude'] = [
1403 'title' => 'Longitude',
1404 'api.required' => 1,
1405 'type' => CRM_Utils_Type::T_STRING,
1406 ];
1407
1408 $params['unit'] = [
1409 'title' => 'Unit of Measurement',
1410 'api.default' => 'meter',
1411 'type' => CRM_Utils_Type::T_STRING,
1412 ];
1413 }
1414
1415 /**
1416 * Get contacts by proximity.
1417 *
1418 * @param array $params
1419 *
1420 * @return array
1421 * @throws Exception
1422 */
1423 function civicrm_api3_contact_proximity($params) {
1424 $latitude = CRM_Utils_Array::value('latitude', $params);
1425 $longitude = CRM_Utils_Array::value('longitude', $params);
1426 $distance = CRM_Utils_Array::value('distance', $params);
1427
1428 $unit = CRM_Utils_Array::value('unit', $params);
1429
1430 // check and ensure that lat/long and distance are floats
1431 if (
1432 !CRM_Utils_Rule::numeric($latitude) ||
1433 !CRM_Utils_Rule::numeric($longitude) ||
1434 !CRM_Utils_Rule::numeric($distance)
1435 ) {
1436 throw new Exception(ts('Latitude, Longitude and Distance should exist and be numeric'));
1437 }
1438
1439 if ($unit == "mile") {
1440 $conversionFactor = 1609.344;
1441 }
1442 else {
1443 $conversionFactor = 1000;
1444 }
1445 //Distance in meters
1446 $distance = $distance * $conversionFactor;
1447
1448 $whereClause = CRM_Contact_BAO_ProximityQuery::where($latitude, $longitude, $distance);
1449
1450 $query = "
1451 SELECT civicrm_contact.id as contact_id,
1452 civicrm_contact.display_name as display_name
1453 FROM civicrm_contact
1454 LEFT JOIN civicrm_address ON civicrm_contact.id = civicrm_address.contact_id
1455 WHERE $whereClause
1456 ";
1457
1458 $dao = CRM_Core_DAO::executeQuery($query);
1459 $contacts = [];
1460 while ($dao->fetch()) {
1461 $contacts[] = $dao->toArray();
1462 }
1463
1464 return civicrm_api3_create_success($contacts, $params, 'Contact', 'get_by_location', $dao);
1465 }
1466
1467 /**
1468 * Get parameters for getlist function.
1469 *
1470 * @see _civicrm_api3_generic_getlist_params
1471 *
1472 * @param array $request
1473 */
1474 function _civicrm_api3_contact_getlist_params(&$request) {
1475 // get the autocomplete options from settings
1476 $acpref = explode(CRM_Core_DAO::VALUE_SEPARATOR,
1477 CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME,
1478 'contact_autocomplete_options'
1479 )
1480 );
1481
1482 // get the option values for contact autocomplete
1483 $acOptions = CRM_Core_OptionGroup::values('contact_autocomplete_options', FALSE, FALSE, FALSE, NULL, 'name');
1484
1485 $list = [];
1486 foreach ($acpref as $value) {
1487 if ($value && !empty($acOptions[$value])) {
1488 $list[] = $acOptions[$value];
1489 }
1490 }
1491 // If we are doing quicksearch by a field other than name, make sure that field is added to results
1492 $field_name = CRM_Utils_String::munge($request['search_field']);
1493 // Unique name contact_id = id
1494 if ($field_name == 'contact_id') {
1495 $field_name = 'id';
1496 }
1497 // phone_numeric should be phone
1498 $searchField = str_replace('_numeric', '', $field_name);
1499 if (!in_array($searchField, $list)) {
1500 $list[] = $searchField;
1501 }
1502 $request['description_field'] = $list;
1503 $list[] = 'contact_type';
1504 $request['params']['return'] = array_unique(array_merge($list, $request['extra']));
1505 $request['params']['options']['sort'] = 'sort_name';
1506 // Contact api doesn't support array(LIKE => 'foo') syntax
1507 if (!empty($request['input'])) {
1508 $request['params'][$request['search_field']] = $request['input'];
1509 // Temporarily override wildcard setting
1510 if (Civi::settings()->get('includeWildCardInName') != $request['add_wildcard']) {
1511 Civi::$statics['civicrm_api3_contact_getlist']['override_wildcard'] = !$request['add_wildcard'];
1512 Civi::settings()->set('includeWildCardInName', $request['add_wildcard']);
1513 }
1514 }
1515 }
1516
1517 /**
1518 * Get output for getlist function.
1519 *
1520 * @see _civicrm_api3_generic_getlist_output
1521 *
1522 * @param array $result
1523 * @param array $request
1524 *
1525 * @return array
1526 */
1527 function _civicrm_api3_contact_getlist_output($result, $request) {
1528 $output = [];
1529 if (!empty($result['values'])) {
1530 $addressFields = array_intersect([
1531 'street_address',
1532 'city',
1533 'state_province',
1534 'country',
1535 ],
1536 $request['params']['return']);
1537 foreach ($result['values'] as $row) {
1538 $data = [
1539 'id' => $row[$request['id_field']],
1540 'label' => $row[$request['label_field']],
1541 'description' => [],
1542 ];
1543 foreach ($request['description_field'] as $item) {
1544 if (!strpos($item, '_name') && !in_array($item, $addressFields) && !empty($row[$item])) {
1545 $data['description'][] = $row[$item];
1546 }
1547 }
1548 $address = [];
1549 foreach ($addressFields as $item) {
1550 if (!empty($row[$item])) {
1551 $address[] = $row[$item];
1552 }
1553 }
1554 if ($address) {
1555 $data['description'][] = implode(' ', $address);
1556 }
1557 if (!empty($request['image_field'])) {
1558 $data['image'] = isset($row[$request['image_field']]) ? $row[$request['image_field']] : '';
1559 }
1560 else {
1561 $data['icon_class'] = $row['contact_type'];
1562 }
1563 $output[] = $data;
1564 }
1565 }
1566 // Restore wildcard override by _civicrm_api3_contact_getlist_params
1567 if (isset(Civi::$statics['civicrm_api3_contact_getlist']['override_wildcard'])) {
1568 Civi::settings()->set('includeWildCardInName', Civi::$statics['civicrm_api3_contact_getlist']['override_wildcard']);
1569 unset(Civi::$statics['civicrm_api3_contact_getlist']['override_wildcard']);
1570 }
1571 return $output;
1572 }
1573
1574 /**
1575 * Check for duplicate contacts.
1576 *
1577 * @param array $params
1578 * Params per getfields metadata.
1579 *
1580 * @return array
1581 * API formatted array
1582 */
1583 function civicrm_api3_contact_duplicatecheck($params) {
1584 $dupes = CRM_Contact_BAO_Contact::getDuplicateContacts(
1585 $params['match'],
1586 $params['match']['contact_type'],
1587 $params['rule_type'],
1588 CRM_Utils_Array::value('exclude', $params, []),
1589 CRM_Utils_Array::value('check_permissions', $params),
1590 CRM_Utils_Array::value('dedupe_rule_id', $params)
1591 );
1592 $values = [];
1593 if ($dupes && !empty($params['return'])) {
1594 return civicrm_api3('Contact', 'get', [
1595 'return' => $params['return'],
1596 'id' => ['IN' => $dupes],
1597 'options' => CRM_Utils_Array::value('options', $params),
1598 'sequential' => CRM_Utils_Array::value('sequential', $params),
1599 'check_permissions' => CRM_Utils_Array::value('check_permissions', $params),
1600 ]);
1601 }
1602 foreach ($dupes as $dupe) {
1603 $values[$dupe] = ['id' => $dupe];
1604 }
1605 return civicrm_api3_create_success($values, $params, 'Contact', 'duplicatecheck');
1606 }
1607
1608 /**
1609 * Declare metadata for contact dedupe function.
1610 *
1611 * @param $params
1612 */
1613 function _civicrm_api3_contact_duplicatecheck_spec(&$params) {
1614 $params['dedupe_rule_id'] = [
1615 'title' => 'Dedupe Rule ID (optional)',
1616 'description' => 'This will default to the built in unsupervised rule',
1617 'type' => CRM_Utils_Type::T_INT,
1618 ];
1619 $params['rule_type'] = [
1620 'title' => 'Dedupe Rule Type',
1621 'description' => 'If no rule id specified, pass "Unsupervised" or "Supervised"',
1622 'type' => CRM_Utils_Type::T_STRING,
1623 'api.default' => 'Unsupervised',
1624 ];
1625 // @todo declare 'match' parameter. We don't have a standard for type = array yet.
1626 }