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