CRM-13072 - Fix typo in api getfields sequential
[civicrm-core.git] / api / v3 / Contact.php
CommitLineData
6a488035 1<?php
6a488035
TO
2/*
3 +--------------------------------------------------------------------+
39de6fd5 4 | CiviCRM version 4.6 |
6a488035 5 +--------------------------------------------------------------------+
731a0992 6 | Copyright CiviCRM LLC (c) 2004-2014 |
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',
130 );
6ecbca5b 131 $params['prefix_id']['api.aliases'] = array('individual_prefix', 'individual_prefix_id');
132 $params['suffix_id']['api.aliases'] = array('individual_suffix', 'individual_suffix_id');
6a488035
TO
133}
134
135/**
61fe4988
EM
136 * Retrieve one or more contacts, given a set of search params.
137 *
138 * @param array $params
6a488035 139 *
a6c01b45 140 * @return array
72b3a70c 141 * API Result Array
6a488035
TO
142 */
143function civicrm_api3_contact_get($params) {
144 $options = array();
145 _civicrm_api3_contact_get_supportanomalies($params, $options);
244bbdd8
CW
146 $contacts = _civicrm_api3_get_using_query_object('Contact', $params, $options);
147 return civicrm_api3_create_success($contacts, $params, 'Contact');
6a488035
TO
148}
149
aa1b1481 150/**
244bbdd8 151 * Get number of contacts matching the supplied criteria.
61fe4988 152 *
c490a46a 153 * @param array $params
aa1b1481
EM
154 *
155 * @return int
156 */
6a488035
TO
157function civicrm_api3_contact_getcount($params) {
158 $options = array();
159 _civicrm_api3_contact_get_supportanomalies($params, $options);
244bbdd8 160 $count = _civicrm_api3_get_using_query_object('Contact', $params, $options, 1);
972322c5 161 return (int) $count;
6a488035 162}
11e09c59
TO
163
164/**
9d32e6f7 165 * Adjust Metadata for Get action.
6a488035 166 *
cf470720 167 * @param array $params
b081365f 168 * Array of parameters determined by getfields.
6a488035
TO
169 */
170function _civicrm_api3_contact_get_spec(&$params) {
171 $params['contact_is_deleted']['api.default'] = 0;
172
9d32e6f7 173 // We declare all these pseudoFields as there are other undocumented fields accessible
6a488035
TO
174 // via the api - but if check permissions is set we only allow declared fields
175 $params['address_id']['title'] = 'Primary Address ID';
176 $params['street_address']['title'] = 'Primary Address Street Address';
177 $params['supplemental_address_1']['title'] = 'Primary Address Supplemental Address 1';
178 $params['supplemental_address_2']['title'] = 'Primary Address Supplemental Address 2';
23c2fe57 179 $params['current_employer']['title'] = 'Current Employer';
6a488035
TO
180 $params['city']['title'] = 'Primary Address City';
181 $params['postal_code_suffix']['title'] = 'Primary Address Post Code Suffix';
182 $params['postal_code']['title'] = 'Primary Address Post Code';
183 $params['geo_code_1']['title'] = 'Primary Address Latitude';
184 $params['geo_code_2']['title'] = 'Primary Address Longitude';
185 $params['state_province_id']['title'] = 'Primary Address State Province ID';
186 $params['state_province_name']['title'] = 'Primary Address State Province Name';
187 $params['state_province']['title'] = 'Primary Address State Province';
41847fb4 188 $params['country_id']['title'] = 'Primary Address Country ID';
6a488035
TO
189 $params['country']['title'] = 'Primary Address country';
190 $params['worldregion_id']['title'] = 'Primary Address World Region ID';
191 $params['worldregion']['title'] = 'Primary Address World Region';
192 $params['phone_id']['title'] = 'Primary Phone ID';
7d4ceb59 193 $params['phone']['title'] = 'Primary Phone';
6a488035
TO
194 $params['phone_type_id']['title'] = 'Primary Phone Type ID';
195 $params['provider_id']['title'] = 'Primary Phone Provider ID';
196 $params['email_id']['title'] = 'Primary Email ID';
197 $params['email']['title'] = 'Primary Email';
c2280651 198 $params['gender_id']['title'] = 'Gender ID';
199 $params['gender']['title'] = 'Gender';
6a488035 200 $params['on_hold']['title'] = 'Primary Email On Hold';
c206647d
EM
201 $params['im']['title'] = 'Primary Instant Messenger';
202 $params['im_id']['title'] = 'Primary Instant Messenger ID';
6a488035
TO
203 $params['group_id']['title'] = 'Group Memberships (filter)';
204 $params['group']['title'] = 'Group Memberships (filter, array)';
205 $params['tag']['title'] = 'Assigned tags (filter, array)';
c206647d
EM
206 $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'));
207 $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 208 $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 209 $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
210}
211
11e09c59 212/**
9d32e6f7
EM
213 * Support for historical oddities.
214 *
244bbdd8 215 * We are supporting 'showAll' = 'all', 'trash' or 'active' for Contact get
6a488035
TO
216 * and for getcount
217 * - hopefully some day we'll come up with a std syntax for the 3-way-boolean of
218 * 0, 1 or not set
219 *
220 * We also support 'filter_group_id' & 'filter.group_id'
221 *
cf470720
TO
222 * @param array $params
223 * As passed into api get or getcount function.
224 * @param array $options
225 * Array of options (so we can modify the filter).
6a488035
TO
226 */
227function _civicrm_api3_contact_get_supportanomalies(&$params, &$options) {
228 if (isset($params['showAll'])) {
229 if (strtolower($params['showAll']) == "active") {
230 $params['contact_is_deleted'] = 0;
231 }
232 if (strtolower($params['showAll']) == "trash") {
233 $params['contact_is_deleted'] = 1;
234 }
235 if (strtolower($params['showAll']) == "all" && isset($params['contact_is_deleted'])) {
236 unset($params['contact_is_deleted']);
237 }
238 }
239 // support for group filters
240 if (array_key_exists('filter_group_id', $params)) {
241 $params['filter.group_id'] = $params['filter_group_id'];
242 unset($params['filter_group_id']);
243 }
244 // filter.group_id works both for 1,2,3 and array (1,2,3)
245 if (array_key_exists('filter.group_id', $params)) {
246 if (is_array($params['filter.group_id'])) {
247 $groups = $params['filter.group_id'];
248 }
4f99ca55
TO
249 else {
250 $groups = explode(',', $params['filter.group_id']);
35671d00 251 }
6a488035
TO
252 unset($params['filter.group_id']);
253 $groups = array_flip($groups);
254 $groups[key($groups)] = 1;
255 $options['input_params']['group'] = $groups;
256 }
257}
258
259/**
244bbdd8 260 * Delete a Contact with given contact_id.
6a488035 261 *
cf470720 262 * @param array $params
c23f45d3 263 * input parameters per getfields
6a488035 264 *
a6c01b45 265 * @return array
72b3a70c 266 * API Result Array
6a488035
TO
267 */
268function civicrm_api3_contact_delete($params) {
269
270 $contactID = CRM_Utils_Array::value('id', $params);
271
272 $session = CRM_Core_Session::singleton();
273 if ($contactID == $session->get('userID')) {
274 return civicrm_api3_create_error('This contact record is linked to the currently logged in user account - and cannot be deleted.');
275 }
0d8afee2
CW
276 $restore = !empty($params['restore']) ? $params['restore'] : FALSE;
277 $skipUndelete = !empty($params['skip_undelete']) ? $params['skip_undelete'] : FALSE;
f182074e
PN
278
279 // CRM-12929
280 // restrict permanent delete if a contact has financial trxn associated with it
281 $error = NULL;
282 if ($skipUndelete && CRM_Financial_BAO_FinancialItem::checkContactPresent(array($contactID), $error)) {
ad3f841d 283 return civicrm_api3_create_error($error['_qf_default']);
f182074e 284 }
6a488035
TO
285 if (CRM_Contact_BAO_Contact::deleteContact($contactID, $restore, $skipUndelete)) {
286 return civicrm_api3_create_success();
287 }
288 else {
289 return civicrm_api3_create_error('Could not delete contact');
290 }
291}
292
293
aa1b1481 294/**
9d32e6f7
EM
295 * Check parameters passed in.
296 *
297 * This function is on it's way out.
298 *
c490a46a 299 * @param array $params
aa1b1481 300 * @param bool $dupeCheck
aa1b1481
EM
301 *
302 * @return null
303 * @throws API_Exception
304 * @throws CiviCRM_API3_Exception
305 */
c1d12cc0 306function _civicrm_api3_contact_check_params(&$params, $dupeCheck) {
6a488035
TO
307
308 switch (strtolower(CRM_Utils_Array::value('contact_type', $params))) {
309 case 'household':
35671d00 310 civicrm_api3_verify_mandatory($params, NULL, array('household_name'));
6a488035 311 break;
35671d00 312
6a488035 313 case 'organization':
35671d00 314 civicrm_api3_verify_mandatory($params, NULL, array('organization_name'));
6a488035 315 break;
35671d00 316
6a488035 317 case 'individual':
35671d00 318 civicrm_api3_verify_one_mandatory($params, NULL, array(
6a488035
TO
319 'first_name',
320 'last_name',
321 'email',
322 'display_name',
323 )
35671d00
TO
324 );
325 break;
6a488035
TO
326 }
327
fe18a93c
CW
328 // Fixme: This really needs to be handled at a lower level. @See CRM-13123
329 if (isset($params['preferred_communication_method'])) {
330 $params['preferred_communication_method'] = CRM_Utils_Array::implodePadded($params['preferred_communication_method']);
331 }
332
8cc574cf 333 if (!empty($params['contact_sub_type']) && !empty($params['contact_type'])) {
35671d00
TO
334 if (!(CRM_Contact_BAO_ContactType::isExtendsContactType($params['contact_sub_type'], $params['contact_type']))) {
335 throw new API_Exception("Invalid or Mismatched Contact Subtype: " . implode(', ', (array) $params['contact_sub_type']));
6a488035 336 }
35671d00 337 }
6a488035
TO
338
339 if ($dupeCheck) {
340 // check for record already existing
341 $dedupeParams = CRM_Dedupe_Finder::formatParams($params, $params['contact_type']);
342
343 // CRM-6431
344 // setting 'check_permission' here means that the dedupe checking will be carried out even if the
345 // person does not have permission to carry out de-dupes
346 // this is similar to the front end form
347 if (isset($params['check_permission'])) {
348 $dedupeParams['check_permission'] = $params['check_permission'];
349 }
350
67cfa333 351 $ids = CRM_Dedupe_Finder::dupesByParams($dedupeParams, $params['contact_type'], 'Unsupervised', array());
6a488035 352
35671d00 353 if (count($ids) > 0) {
86bfa4f6 354 throw new API_Exception("Found matching contacts: " . implode(',', $ids), "duplicate", array("ids" => $ids));
6a488035
TO
355 }
356 }
357
8d99ab37 358 // The BAO no longer supports the legacy param "current_employer" so here is a shim for api backward-compatability
6a488035 359 if (!empty($params['current_employer'])) {
8d99ab37
CW
360 $organizationParams = array(
361 'organization_name' => $params['current_employer'],
362 );
6a488035
TO
363
364 $dedupParams = CRM_Dedupe_Finder::formatParams($organizationParams, 'Organization');
365
366 $dedupParams['check_permission'] = FALSE;
367 $dupeIds = CRM_Dedupe_Finder::dupesByParams($dedupParams, 'Organization', 'Supervised');
368
369 // check for mismatch employer name and id
370 if (!empty($params['employer_id']) && !in_array($params['employer_id'], $dupeIds)) {
371 throw new API_Exception('Employer name and Employer id Mismatch');
372 }
373
374 // show error if multiple organisation with same name exist
375 if (empty($params['employer_id']) && (count($dupeIds) > 1)) {
376 throw new API_Exception('Found more than one Organisation with same Name.');
377 }
8d99ab37
CW
378
379 if ($dupeIds) {
380 $params['employer_id'] = $dupeIds[0];
381 }
382 else {
244bbdd8 383 $result = civicrm_api3('Contact', 'create', array(
8d99ab37 384 'organization_name' => $params['current_employer'],
21dfd5f5 385 'contact_type' => 'Organization',
8d99ab37
CW
386 ));
387 $params['employer_id'] = $result['id'];
388 }
6a488035
TO
389 }
390
391 return NULL;
392}
393
394/**
244bbdd8 395 * Helper function for Contact create.
6a488035 396 *
cf470720
TO
397 * @param array $params
398 * (reference ) an assoc array of name/value pairs.
399 * @param int $contactID
400 * If present the contact with that ID is updated.
6a488035 401 *
54f1aa2a 402 * @return CRM_Contact_BAO_Contact|CRM_Core_Error
6a488035
TO
403 */
404function _civicrm_api3_contact_update($params, $contactID = NULL) {
6ecbca5b 405 //@todo - doesn't contact create support 'id' which is already set- check & remove
6a488035
TO
406 if ($contactID) {
407 $params['contact_id'] = $contactID;
408 }
409
6ecbca5b 410 return CRM_Contact_BAO_Contact::create($params);
6a488035
TO
411}
412
413/**
9d32e6f7 414 * Validate the addressee or email or postal greetings.
6a488035 415 *
cf470720 416 * @param array $params
9d32e6f7 417 * Array per getfields metadata.
6a488035 418 *
77b97be7 419 * @throws API_Exception
6a488035
TO
420 */
421function _civicrm_api3_greeting_format_params($params) {
422 $greetingParams = array('', '_id', '_custom');
423 foreach (array('email', 'postal', 'addressee') as $key) {
424 $greeting = '_greeting';
425 if ($key == 'addressee') {
426 $greeting = '';
427 }
428
429 $formatParams = FALSE;
22242c87 430 // Unset display value from params.
6a488035
TO
431 if (isset($params["{$key}{$greeting}_display"])) {
432 unset($params["{$key}{$greeting}_display"]);
433 }
434
435 // check if greetings are present in present
436 foreach ($greetingParams as $greetingValues) {
437 if (array_key_exists("{$key}{$greeting}{$greetingValues}", $params)) {
438 $formatParams = TRUE;
439 break;
440 }
441 }
442
443 if (!$formatParams) {
444 continue;
445 }
446
447 $nullValue = FALSE;
448 $filter = array(
449 'contact_type' => $params['contact_type'],
450 'greeting_type' => "{$key}{$greeting}",
451 );
452
453 $greetings = CRM_Core_PseudoConstant::greeting($filter);
454 $greetingId = CRM_Utils_Array::value("{$key}{$greeting}_id", $params);
455 $greetingVal = CRM_Utils_Array::value("{$key}{$greeting}", $params);
456 $customGreeting = CRM_Utils_Array::value("{$key}{$greeting}_custom", $params);
457
458 if (!$greetingId && $greetingVal) {
459 $params["{$key}{$greeting}_id"] = CRM_Utils_Array::key($params["{$key}{$greeting}"], $greetings);
460 }
461
462 if ($customGreeting && $greetingId &&
463 ($greetingId != array_search('Customized', $greetings))
464 ) {
6ecbca5b 465 throw new API_Exception(ts('Provide either %1 greeting id and/or %1 greeting or custom %1 greeting',
6a488035
TO
466 array(1 => $key)
467 ));
468 }
469
470 if ($greetingVal && $greetingId &&
471 ($greetingId != CRM_Utils_Array::key($greetingVal, $greetings))
472 ) {
6ecbca5b 473 throw new API_Exception(ts('Mismatch in %1 greeting id and %1 greeting',
6a488035
TO
474 array(1 => $key)
475 ));
476 }
477
478 if ($greetingId) {
479
480 if (!array_key_exists($greetingId, $greetings)) {
6ecbca5b 481 throw new API_Exception(ts('Invalid %1 greeting Id', array(1 => $key)));
6a488035
TO
482 }
483
484 if (!$customGreeting && ($greetingId == array_search('Customized', $greetings))) {
6ecbca5b 485 throw new API_Exception(ts('Please provide a custom value for %1 greeting',
6a488035
TO
486 array(1 => $key)
487 ));
488 }
489 }
490 elseif ($greetingVal) {
491
492 if (!in_array($greetingVal, $greetings)) {
6ecbca5b 493 throw new API_Exception(ts('Invalid %1 greeting', array(1 => $key)));
6a488035
TO
494 }
495
496 $greetingId = CRM_Utils_Array::key($greetingVal, $greetings);
497 }
498
499 if ($customGreeting) {
500 $greetingId = CRM_Utils_Array::key('Customized', $greetings);
501 }
502
35671d00 503 $customValue = isset($params['contact_id']) ? CRM_Core_DAO::getFieldValue(
ad3f841d
DL
504 'CRM_Contact_DAO_Contact',
505 $params['contact_id'],
506 "{$key}{$greeting}_custom"
35671d00 507 ) : FALSE;
6a488035
TO
508
509 if (array_key_exists("{$key}{$greeting}_id", $params) && empty($params["{$key}{$greeting}_id"])) {
510 $nullValue = TRUE;
511 }
512 elseif (array_key_exists("{$key}{$greeting}", $params) && empty($params["{$key}{$greeting}"])) {
513 $nullValue = TRUE;
514 }
515 elseif ($customValue && array_key_exists("{$key}{$greeting}_custom", $params)
516 && empty($params["{$key}{$greeting}_custom"])
517 ) {
518 $nullValue = TRUE;
519 }
520
521 $params["{$key}{$greeting}_id"] = $greetingId;
522
523 if (!$customValue && !$customGreeting && array_key_exists("{$key}{$greeting}_custom", $params)) {
524 unset($params["{$key}{$greeting}_custom"]);
525 }
526
527 if ($nullValue) {
528 $params["{$key}{$greeting}_id"] = '';
529 $params["{$key}{$greeting}_custom"] = '';
530 }
531
532 if (isset($params["{$key}{$greeting}"])) {
533 unset($params["{$key}{$greeting}"]);
534 }
535 }
536}
537
538/**
244bbdd8 539 * Old Contact quick search api.
6a488035 540 *
03f32517 541 * @deprecated
6a488035 542 *
d0997921 543 * @param array $params
9d32e6f7 544 *
645ee340
EM
545 * @return array
546 * @throws \API_Exception
6a488035 547 */
6a488035
TO
548function civicrm_api3_contact_getquick($params) {
549 civicrm_api3_verify_mandatory($params, NULL, array('name'));
aca85468 550 $name = CRM_Utils_Type::escape(CRM_Utils_Array::value('name', $params), 'String');
6a488035
TO
551
552 // get the autocomplete options from settings
553 $acpref = explode(CRM_Core_DAO::VALUE_SEPARATOR,
554 CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME,
555 'contact_autocomplete_options'
556 )
557 );
558
559 // get the option values for contact autocomplete
560 $acOptions = CRM_Core_OptionGroup::values('contact_autocomplete_options', FALSE, FALSE, FALSE, NULL, 'name');
561
562 $list = array();
563 foreach ($acpref as $value) {
8cc574cf 564 if ($value && !empty($acOptions[$value])) {
6a488035
TO
565 $list[$value] = $acOptions[$value];
566 }
567 }
568 // If we are doing quicksearch by a field other than name, make sure that field is added to results
569 if (!empty($params['field_name'])) {
1aba4d9a 570 $field_name = CRM_Utils_String::munge($params['field_name']);
5d8ba7a7 571 // Unique name contact_id = id
1aba4d9a
CW
572 if ($field_name == 'contact_id') {
573 $field_name = 'id';
5d8ba7a7 574 }
6a488035 575 // phone_numeric should be phone
1aba4d9a 576 $searchField = str_replace('_numeric', '', $field_name);
22e263ad 577 if (!in_array($searchField, $list)) {
6a488035
TO
578 $list[] = $searchField;
579 }
580 }
581
582 $select = $actualSelectElements = array('sort_name');
583 $where = '';
584 $from = array();
585 foreach ($list as $value) {
586 $suffix = substr($value, 0, 2) . substr($value, -1);
587 switch ($value) {
588 case 'street_address':
589 case 'city':
590 case 'postal_code':
591 $selectText = $value;
592 $value = "address";
593 $suffix = 'sts';
594 case 'phone':
595 case 'email':
596 $actualSelectElements[] = $select[] = ($value == 'address') ? $selectText : $value;
aebdef3c
JL
597 if ($value == 'phone') {
598 $actualSelectElements[] = $select[] = 'phone_ext';
599 }
6a488035
TO
600 $from[$value] = "LEFT JOIN civicrm_{$value} {$suffix} ON ( cc.id = {$suffix}.contact_id AND {$suffix}.is_primary = 1 ) ";
601 break;
602
603 case 'country':
604 case 'state_province':
605 $select[] = "{$suffix}.name as {$value}";
606 $actualSelectElements[] = "{$suffix}.name";
607 if (!in_array('address', $from)) {
608 $from['address'] = 'LEFT JOIN civicrm_address sts ON ( cc.id = sts.contact_id AND sts.is_primary = 1) ';
609 }
610 $from[$value] = " LEFT JOIN civicrm_{$value} {$suffix} ON ( sts.{$value}_id = {$suffix}.id ) ";
611 break;
612
613 default:
614 if ($value != 'id') {
615 $suffix = 'cc';
616 if (!empty($params['field_name']) && $params['field_name'] == 'value') {
133da98d 617 $suffix = CRM_Utils_String::munge(CRM_Utils_Array::value('table_name', $params, 'cc'));
6a488035
TO
618 }
619 $actualSelectElements[] = $select[] = $suffix . '.' . $value;
620 }
621 break;
622 }
623 }
624
625 $config = CRM_Core_Config::singleton();
626 $as = $select;
627 $select = implode(', ', $select);
628 if (!empty($select)) {
629 $select = ", $select";
630 }
631 $actualSelectElements = implode(', ', $actualSelectElements);
632 $selectAliases = $from;
633 unset($selectAliases['address']);
634 $selectAliases = implode(', ', array_keys($selectAliases));
635 if (!empty($selectAliases)) {
636 $selectAliases = ", $selectAliases";
637 }
638 $from = implode(' ', $from);
133da98d
CW
639 $limit = (int) CRM_Utils_Array::value('limit', $params);
640 $limit = $limit > 0 ? $limit : 10;
6a488035
TO
641
642 // add acl clause here
643 list($aclFrom, $aclWhere) = CRM_Contact_BAO_Contact_Permission::cacheClause('cc');
644
645 if ($aclWhere) {
646 $where .= " AND $aclWhere ";
647 }
648
a7488080 649 if (!empty($params['org'])) {
6a488035
TO
650 $where .= " AND contact_type = \"Organization\"";
651
652 // CRM-7157, hack: get current employer details when
653 // employee_id is present.
654 $currEmpDetails = array();
a7488080 655 if (!empty($params['employee_id'])) {
6a488035 656 if ($currentEmployer = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact',
133da98d 657 (int) $params['employee_id'],
6a488035
TO
658 'employer_id'
659 )) {
660 if ($config->includeWildCardInName) {
661 $strSearch = "%$name%";
662 }
663 else {
664 $strSearch = "$name%";
665 }
666
667 // get current employer details
668 $dao = CRM_Core_DAO::executeQuery("SELECT cc.id as id, CONCAT_WS( ' :: ', {$actualSelectElements} ) as data, sort_name
669 FROM civicrm_contact cc {$from} WHERE cc.contact_type = \"Organization\" AND cc.id = {$currentEmployer} AND cc.sort_name LIKE '$strSearch'");
670 if ($dao->fetch()) {
671 $currEmpDetails = array(
672 'id' => $dao->id,
673 'data' => $dao->data,
674 );
675 }
676 }
677 }
678 }
679
a7488080 680 if (!empty($params['contact_sub_type'])) {
69164898
N
681 $contactSubType = CRM_Utils_Type::escape($params['contact_sub_type'], 'String');
682 $where .= " AND cc.contact_sub_type = '{$contactSubType}'";
683 }
684
e1b717cb
P
685 if (!empty($params['contact_type'])) {
686 $contactType = CRM_Utils_Type::escape($params['contact_type'], 'String');
687 $where .= " AND cc.contact_type LIKE '{$contactType}'";
688 }
689
244bbdd8 690 // Set default for current_employer or return contact with particular id
a7488080 691 if (!empty($params['id'])) {
1aba4d9a 692 $where .= " AND cc.id = " . (int) $params['id'];
6a488035
TO
693 }
694
a7488080 695 if (!empty($params['cid'])) {
1aba4d9a 696 $where .= " AND cc.id <> " . (int) $params['cid'];
6a488035
TO
697 }
698
244bbdd8 699 // Contact's based of relationhip type
6a488035 700 $relType = NULL;
a7488080 701 if (!empty($params['rel'])) {
6a488035
TO
702 $relation = explode('_', CRM_Utils_Array::value('rel', $params));
703 $relType = CRM_Utils_Type::escape($relation[0], 'Integer');
704 $rel = CRM_Utils_Type::escape($relation[2], 'String');
705 }
706
707 if ($config->includeWildCardInName) {
708 $strSearch = "%$name%";
709 }
710 else {
711 $strSearch = "$name%";
712 }
713 $includeEmailFrom = $includeNickName = $exactIncludeNickName = '';
714 if ($config->includeNickNameInName) {
715 $includeNickName = " OR nick_name LIKE '$strSearch'";
716 $exactIncludeNickName = " OR nick_name LIKE '$name'";
717 }
718
719 //CRM-10687
720 if (!empty($params['field_name']) && !empty($params['table_name'])) {
1aba4d9a 721 $table_name = CRM_Utils_String::munge($params['table_name']);
8d3b1aa6
PC
722 $whereClause = " WHERE ( $table_name.$field_name LIKE '$strSearch') {$where}";
723 $exactWhereClause = " WHERE ( $table_name.$field_name = '$name') {$where}";
6a488035
TO
724 // Search by id should be exact
725 if ($field_name == 'id' || $field_name == 'external_identifier') {
726 $whereClause = $exactWhereClause;
727 }
728 }
729 else {
730 if ($config->includeEmailInName) {
731 if (!in_array('email', $list)) {
732 $includeEmailFrom = "LEFT JOIN civicrm_email eml ON ( cc.id = eml.contact_id AND eml.is_primary = 1 )";
733 }
734 $whereClause = " WHERE ( email LIKE '$strSearch' OR sort_name LIKE '$strSearch' $includeNickName ) {$where} ";
735 $exactWhereClause = " WHERE ( email LIKE '$name' OR sort_name LIKE '$name' $exactIncludeNickName ) {$where} ";
736 }
737 else {
738 $whereClause = " WHERE ( sort_name LIKE '$strSearch' $includeNickName ) {$where} ";
739 $exactWhereClause = " WHERE ( sort_name LIKE '$name' $exactIncludeNickName ) {$where} ";
740 }
741 }
742
743 $additionalFrom = '';
744 if ($relType) {
745 $additionalFrom = "
746 INNER JOIN civicrm_relationship_type r ON (
747 r.id = {$relType}
748 AND ( cc.contact_type = r.contact_type_{$rel} OR r.contact_type_{$rel} IS NULL )
749 AND ( cc.contact_sub_type = r.contact_sub_type_{$rel} OR r.contact_sub_type_{$rel} IS NULL )
750 )";
751 }
752
753 // check if only CMS users are requested
a7488080 754 if (!empty($params['cmsuser'])) {
6a488035
TO
755 $additionalFrom = "
756 INNER JOIN civicrm_uf_match um ON (um.contact_id=cc.id)
757 ";
758 }
759
51e61eae
ARW
760 $orderByInner = "";
761 $orderByOuter = "ORDER BY exactFirst";
762 if ($config->includeOrderByClause) {
763 $orderByInner = "ORDER BY sort_name";
764 $orderByOuter .= ", sort_name";
765 }
766
6a488035
TO
767 //CRM-5954
768 $query = "
769 SELECT DISTINCT(id), data, sort_name {$selectAliases}
770 FROM (
771 ( SELECT 0 as exactFirst, cc.id as id, CONCAT_WS( ' :: ', {$actualSelectElements} ) as data {$select}
772 FROM civicrm_contact cc {$from}
773 {$aclFrom}
774 {$additionalFrom} {$includeEmailFrom}
775 {$exactWhereClause}
776 LIMIT 0, {$limit} )
777 UNION
778 ( SELECT 1 as exactFirst, cc.id as id, CONCAT_WS( ' :: ', {$actualSelectElements} ) as data {$select}
779 FROM civicrm_contact cc {$from}
780 {$aclFrom}
781 {$additionalFrom} {$includeEmailFrom}
782 {$whereClause}
51e61eae 783 {$orderByInner}
6a488035
TO
784 LIMIT 0, {$limit} )
785) t
51e61eae 786{$orderByOuter}
6a488035
TO
787LIMIT 0, {$limit}
788 ";
789 // send query to hook to be modified if needed
790 CRM_Utils_Hook::contactListQuery($query,
791 $name,
133da98d
CW
792 empty($params['context']) ? NULL : CRM_Utils_Type::escape($params['context'], 'String'),
793 empty($params['id']) ? NULL : $params['id']
6a488035
TO
794 );
795
796 $dao = CRM_Core_DAO::executeQuery($query);
797
798 $contactList = array();
799 $listCurrentEmployer = TRUE;
800 while ($dao->fetch()) {
801 $t = array('id' => $dao->id);
802 foreach ($as as $k) {
35671d00 803 $t[$k] = isset($dao->$k) ? $dao->$k : '';
6a488035
TO
804 }
805 $t['data'] = $dao->data;
806 $contactList[] = $t;
a7488080 807 if (!empty($params['org']) &&
6a488035
TO
808 !empty($currEmpDetails) &&
809 $dao->id == $currEmpDetails['id']
810 ) {
811 $listCurrentEmployer = FALSE;
812 }
813 }
814
815 //return organization name if doesn't exist in db
816 if (empty($contactList)) {
a7488080 817 if (!empty($params['org'])) {
6a488035
TO
818 if ($listCurrentEmployer && !empty($currEmpDetails)) {
819 $contactList = array(
820 array(
d5cc0fc2 821 'data' => $currEmpDetails['data'],
21dfd5f5
TO
822 'id' => $currEmpDetails['id'],
823 ),
6a488035
TO
824 );
825 }
826 else {
827 $contactList = array(
828 array(
829 'data' => $name,
21dfd5f5
TO
830 'id' => $name,
831 ),
6a488035
TO
832 );
833 }
834 }
835 }
836
244bbdd8 837 return civicrm_api3_create_success($contactList, $params, 'Contact', 'getquick');
a14e9d08
CW
838}
839
840/**
35823763
EM
841 * Declare deprecated api functions.
842 *
a14e9d08 843 * @deprecated api notice
a6c01b45 844 * @return array
16b10e64 845 * Array of deprecated actions
a14e9d08
CW
846 */
847function _civicrm_api3_contact_deprecation() {
848 return array('getquick' => 'The "getquick" action is deprecated in favor of "getlist".');
6a488035
TO
849}
850
851/**
852 * Merges given pair of duplicate contacts.
853 *
cf470720 854 * @param array $params
b081365f
CW
855 * Allowed array keys are:
856 * -int main_id: main contact id with whom merge has to happen
857 * -int other_id: duplicate contact which would be deleted after merge operation
858 * -string mode: "safe" skips the merge if there are no conflicts. Does a force merge otherwise.
859 * -boolean auto_flip: whether to let api decide which contact to retain and which to delete.
6a488035 860 *
a6c01b45 861 * @return array
72b3a70c 862 * API Result Array
6a488035
TO
863 */
864function civicrm_api3_contact_merge($params) {
865 $mode = CRM_Utils_Array::value('mode', $params, 'safe');
866 $autoFlip = CRM_Utils_Array::value('auto_flip', $params, TRUE);
867
35671d00
TO
868 $dupePairs = array(array(
869 'srcID' => CRM_Utils_Array::value('main_id', $params),
6a488035
TO
870 'dstID' => CRM_Utils_Array::value('other_id', $params),
871 ));
872 $result = CRM_Dedupe_Merger::merge($dupePairs, array(), $mode, $autoFlip);
873
874 if ($result['is_error'] == 0) {
875 return civicrm_api3_create_success();
876 }
877 else {
878 return civicrm_api3_create_error($result['messages']);
879 }
880}
881
aa1b1481 882/**
9d32e6f7
EM
883 * Adjust metadata for contact_proximity api function.
884 *
c490a46a 885 * @param array $params
aa1b1481 886 */
6a488035
TO
887function _civicrm_api3_contact_proximity_spec(&$params) {
888 $params['latitude']['api.required'] = 1;
4c41ecb2 889 $params['latitude']['title'] = 'Latitude';
6a488035 890 $params['longitude']['api.required'] = 1;
4c41ecb2 891 $params['longitude']['title'] = 'Longitude';
6a488035 892 $params['unit']['api.default'] = 'meter';
4c41ecb2 893 $params['unit']['title'] = 'Unit of Measurement';
6a488035
TO
894}
895
aa1b1481 896/**
9d32e6f7
EM
897 * Get contacts by proximity.
898 *
c490a46a 899 * @param array $params
aa1b1481
EM
900 *
901 * @return array
902 * @throws Exception
903 */
6a488035
TO
904function civicrm_api3_contact_proximity($params) {
905 $latitude = CRM_Utils_Array::value('latitude', $params);
906 $longitude = CRM_Utils_Array::value('longitude', $params);
907 $distance = CRM_Utils_Array::value('distance', $params);
908
909 $unit = CRM_Utils_Array::value('unit', $params);
910
911 // check and ensure that lat/long and distance are floats
912 if (
913 !CRM_Utils_Rule::numeric($latitude) ||
914 !CRM_Utils_Rule::numeric($longitude) ||
915 !CRM_Utils_Rule::numeric($distance)
916 ) {
917 throw new Exception(ts('Latitude, Longitude and Distance should exist and be numeric'));
918 }
919
920 if ($unit == "mile") {
921 $conversionFactor = 1609.344;
922 }
923 else {
924 $conversionFactor = 1000;
925 }
926 //Distance in meters
927 $distance = $distance * $conversionFactor;
928
929 $whereClause = CRM_Contact_BAO_ProximityQuery::where($latitude, $longitude, $distance);
930
931 $query = "
932SELECT civicrm_contact.id as contact_id,
933 civicrm_contact.display_name as display_name
934FROM civicrm_contact
935LEFT JOIN civicrm_address ON civicrm_contact.id = civicrm_address.contact_id
936WHERE $whereClause
937";
938
939 $dao = CRM_Core_DAO::executeQuery($query);
940 $contacts = array();
941 while ($dao->fetch()) {
942 $contacts[] = $dao->toArray();
943 }
944
244bbdd8 945 return civicrm_api3_create_success($contacts, $params, 'Contact', 'get_by_location', $dao);
6a488035
TO
946}
947
ff88d165
CW
948
949/**
22242c87
EM
950 * Get parameters for getlist function.
951 *
a6c6059d 952 * @see _civicrm_api3_generic_getlist_params
ff88d165 953 *
8c6b335b 954 * @param array $request
ff88d165
CW
955 */
956function _civicrm_api3_contact_getlist_params(&$request) {
957 // get the autocomplete options from settings
958 $acpref = explode(CRM_Core_DAO::VALUE_SEPARATOR,
959 CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME,
960 'contact_autocomplete_options'
961 )
962 );
963
964 // get the option values for contact autocomplete
965 $acOptions = CRM_Core_OptionGroup::values('contact_autocomplete_options', FALSE, FALSE, FALSE, NULL, 'name');
966
967 $list = array();
968 foreach ($acpref as $value) {
969 if ($value && !empty($acOptions[$value])) {
970 $list[] = $acOptions[$value];
971 }
972 }
973 // If we are doing quicksearch by a field other than name, make sure that field is added to results
974 $field_name = CRM_Utils_String::munge($request['search_field']);
975 // Unique name contact_id = id
976 if ($field_name == 'contact_id') {
977 $field_name = 'id';
978 }
979 // phone_numeric should be phone
980 $searchField = str_replace('_numeric', '', $field_name);
22e263ad 981 if (!in_array($searchField, $list)) {
ff88d165
CW
982 $list[] = $searchField;
983 }
8250601e 984 $request['description_field'] = $list;
54bee7df 985 $list[] = 'contact_type';
8250601e 986 $request['params']['return'] = array_unique(array_merge($list, $request['extra']));
ff88d165
CW
987 $request['params']['options']['sort'] = 'sort_name';
988 // Contact api doesn't support array(LIKE => 'foo') syntax
609a8c53 989 if (!empty($request['input'])) {
fd816db5 990 $request['params'][$request['search_field']] = $request['input'];
609a8c53 991 }
ff88d165
CW
992}
993
994/**
22242c87
EM
995 * Get output for getlist function.
996 *
a6c6059d 997 * @see _civicrm_api3_generic_getlist_output
ff88d165 998 *
8c6b335b
CW
999 * @param array $result
1000 * @param array $request
ff88d165
CW
1001 *
1002 * @return array
1003 */
1004function _civicrm_api3_contact_getlist_output($result, $request) {
1005 $output = array();
1006 if (!empty($result['values'])) {
dc64d047
EM
1007 $addressFields = array_intersect(array(
1008 'street_address',
1009 'city',
1010 'state_province',
1011 'country',
1012 ),
1013 $request['params']['return']);
ff88d165
CW
1014 foreach ($result['values'] as $row) {
1015 $data = array(
1016 'id' => $row[$request['id_field']],
1017 'label' => $row[$request['label_field']],
88881f79 1018 'description' => array(),
ff88d165 1019 );
8250601e
CW
1020 foreach ($request['description_field'] as $item) {
1021 if (!strpos($item, '_name') && !in_array($item, $addressFields) && !empty($row[$item])) {
88881f79 1022 $data['description'][] = $row[$item];
ff88d165
CW
1023 }
1024 }
88881f79 1025 $address = array();
22e263ad 1026 foreach ($addressFields as $item) {
88881f79
CW
1027 if (!empty($row[$item])) {
1028 $address[] = $row[$item];
1029 }
1030 }
1031 if ($address) {
1032 $data['description'][] = implode(' ', $address);
1033 }
ff88d165
CW
1034 if (!empty($request['image_field'])) {
1035 $data['image'] = isset($row[$request['image_field']]) ? $row[$request['image_field']] : '';
54bee7df
CW
1036 }
1037 else {
1038 $data['icon_class'] = $row['contact_type'];
1039 }
8250601e
CW
1040 foreach ($request['extra'] as $field) {
1041 $data['extra'][$field] = isset($row[$field]) ? $row[$field] : NULL;
1042 }
ff88d165
CW
1043 $output[] = $data;
1044 }
1045 }
1046 return $output;
1047}