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