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