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