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