Merge pull request #13372 from eileenmcnaughton/activity_extract
[civicrm-core.git] / api / v3 / Contact.php
CommitLineData
6a488035 1<?php
6a488035
TO
2/*
3 +--------------------------------------------------------------------+
fee14197 4 | CiviCRM version 5 |
6a488035 5 +--------------------------------------------------------------------+
6b83d5bd 6 | Copyright CiviCRM LLC (c) 2004-2019 |
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 );
8d475ce9
CW
378 $params['uf_user'] = array(
379 'title' => 'CMS User',
380 'type' => CRM_Utils_Type::T_BOOLEAN,
381 );
c206647d
EM
382 $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'));
383 $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 384 $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 385 $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
386}
387
11e09c59 388/**
9d32e6f7
EM
389 * Support for historical oddities.
390 *
244bbdd8 391 * We are supporting 'showAll' = 'all', 'trash' or 'active' for Contact get
6a488035
TO
392 * and for getcount
393 * - hopefully some day we'll come up with a std syntax for the 3-way-boolean of
394 * 0, 1 or not set
395 *
396 * We also support 'filter_group_id' & 'filter.group_id'
397 *
cf470720
TO
398 * @param array $params
399 * As passed into api get or getcount function.
400 * @param array $options
401 * Array of options (so we can modify the filter).
6a488035
TO
402 */
403function _civicrm_api3_contact_get_supportanomalies(&$params, &$options) {
404 if (isset($params['showAll'])) {
405 if (strtolower($params['showAll']) == "active") {
406 $params['contact_is_deleted'] = 0;
407 }
408 if (strtolower($params['showAll']) == "trash") {
409 $params['contact_is_deleted'] = 1;
410 }
411 if (strtolower($params['showAll']) == "all" && isset($params['contact_is_deleted'])) {
412 unset($params['contact_is_deleted']);
413 }
414 }
415 // support for group filters
416 if (array_key_exists('filter_group_id', $params)) {
417 $params['filter.group_id'] = $params['filter_group_id'];
418 unset($params['filter_group_id']);
419 }
420 // filter.group_id works both for 1,2,3 and array (1,2,3)
421 if (array_key_exists('filter.group_id', $params)) {
422 if (is_array($params['filter.group_id'])) {
423 $groups = $params['filter.group_id'];
424 }
4f99ca55
TO
425 else {
426 $groups = explode(',', $params['filter.group_id']);
35671d00 427 }
6a488035 428 unset($params['filter.group_id']);
6a488035 429 $options['input_params']['group'] = $groups;
51c4748e
SL
430 }
431 if (isset($params['group'])) {
432 $groups = $params['group'];
433 $allGroups = CRM_Core_PseudoConstant::group();
434 if (is_array($groups) && in_array(key($groups), CRM_Core_DAO::acceptedSQLOperators(), TRUE)) {
0c66b30c 435 // Get the groups array.
51c4748e 436 $groupsArray = $groups[key($groups)];
0c66b30c 437 foreach ($groupsArray as &$group) {
51c4748e
SL
438 if (!is_numeric($group) && array_search($group, $allGroups)) {
439 $group = array_search($group, $allGroups);
440 }
441 }
0c66b30c 442 // Now reset the $groups array with the ids not the titles.
56272bee 443 $groups[key($groups)] = $groupsArray;
51c4748e 444 }
0c66b30c 445 // handle format like 'group' => array('title1', 'title2').
51c4748e
SL
446 elseif (is_array($groups)) {
447 foreach ($groups as $k => &$group) {
b6b28d93 448 if (!is_numeric($group) && array_search($group, $allGroups)) {
51c4748e
SL
449 $group = array_search($group, $allGroups);
450 }
b6b28d93
SL
451 if (!is_numeric($k) && array_search($k, $allGroups)) {
452 unset($groups[$k]);
453 $groups[array_search($k, $allGroups)] = $group;
454 }
51c4748e
SL
455 }
456 }
457 elseif (!is_numeric($groups) && array_search($groups, $allGroups)) {
458 $groups = array_search($groups, $allGroups);
459 }
460 $params['group'] = $groups;
6a488035
TO
461 }
462}
463
464/**
244bbdd8 465 * Delete a Contact with given contact_id.
6a488035 466 *
cf470720 467 * @param array $params
c23f45d3 468 * input parameters per getfields
6a488035 469 *
c16ed19b 470 * @throws \Civi\API\Exception\UnauthorizedException
a6c01b45 471 * @return array
72b3a70c 472 * API Result Array
6a488035
TO
473 */
474function civicrm_api3_contact_delete($params) {
6a488035
TO
475 $contactID = CRM_Utils_Array::value('id', $params);
476
c16ed19b
CW
477 if (!empty($params['check_permissions']) && !CRM_Contact_BAO_Contact_Permission::allow($contactID, CRM_Core_Permission::DELETE)) {
478 throw new \Civi\API\Exception\UnauthorizedException('Permission denied to modify contact record');
479 }
480
6a488035
TO
481 $session = CRM_Core_Session::singleton();
482 if ($contactID == $session->get('userID')) {
483 return civicrm_api3_create_error('This contact record is linked to the currently logged in user account - and cannot be deleted.');
484 }
0d8afee2
CW
485 $restore = !empty($params['restore']) ? $params['restore'] : FALSE;
486 $skipUndelete = !empty($params['skip_undelete']) ? $params['skip_undelete'] : FALSE;
f182074e
PN
487
488 // CRM-12929
489 // restrict permanent delete if a contact has financial trxn associated with it
490 $error = NULL;
491 if ($skipUndelete && CRM_Financial_BAO_FinancialItem::checkContactPresent(array($contactID), $error)) {
ad3f841d 492 return civicrm_api3_create_error($error['_qf_default']);
f182074e 493 }
fa6448fa
EM
494 if (CRM_Contact_BAO_Contact::deleteContact($contactID, $restore, $skipUndelete,
495 CRM_Utils_Array::value('check_permissions', $params))) {
6a488035
TO
496 return civicrm_api3_create_success();
497 }
498 else {
499 return civicrm_api3_create_error('Could not delete contact');
500 }
501}
502
503
aa1b1481 504/**
9d32e6f7
EM
505 * Check parameters passed in.
506 *
507 * This function is on it's way out.
508 *
c490a46a 509 * @param array $params
aa1b1481
EM
510 *
511 * @return null
512 * @throws API_Exception
513 * @throws CiviCRM_API3_Exception
514 */
fedc3428 515function _civicrm_api3_contact_check_params(&$params) {
6a488035
TO
516
517 switch (strtolower(CRM_Utils_Array::value('contact_type', $params))) {
518 case 'household':
35671d00 519 civicrm_api3_verify_mandatory($params, NULL, array('household_name'));
6a488035 520 break;
35671d00 521
6a488035 522 case 'organization':
35671d00 523 civicrm_api3_verify_mandatory($params, NULL, array('organization_name'));
6a488035 524 break;
35671d00 525
6a488035 526 case 'individual':
35671d00 527 civicrm_api3_verify_one_mandatory($params, NULL, array(
6a488035
TO
528 'first_name',
529 'last_name',
530 'email',
531 'display_name',
532 )
35671d00
TO
533 );
534 break;
6a488035
TO
535 }
536
8cc574cf 537 if (!empty($params['contact_sub_type']) && !empty($params['contact_type'])) {
35671d00
TO
538 if (!(CRM_Contact_BAO_ContactType::isExtendsContactType($params['contact_sub_type'], $params['contact_type']))) {
539 throw new API_Exception("Invalid or Mismatched Contact Subtype: " . implode(', ', (array) $params['contact_sub_type']));
6a488035 540 }
35671d00 541 }
6a488035 542
8d99ab37 543 // The BAO no longer supports the legacy param "current_employer" so here is a shim for api backward-compatability
6a488035 544 if (!empty($params['current_employer'])) {
8d99ab37
CW
545 $organizationParams = array(
546 'organization_name' => $params['current_employer'],
547 );
6a488035 548
fedc3428 549 $dupeIds = CRM_Contact_BAO_Contact::getDuplicateContacts($organizationParams, 'Organization', 'Supervised', array(), FALSE);
6a488035
TO
550
551 // check for mismatch employer name and id
552 if (!empty($params['employer_id']) && !in_array($params['employer_id'], $dupeIds)) {
553 throw new API_Exception('Employer name and Employer id Mismatch');
554 }
555
556 // show error if multiple organisation with same name exist
557 if (empty($params['employer_id']) && (count($dupeIds) > 1)) {
558 throw new API_Exception('Found more than one Organisation with same Name.');
559 }
8d99ab37
CW
560
561 if ($dupeIds) {
562 $params['employer_id'] = $dupeIds[0];
563 }
564 else {
244bbdd8 565 $result = civicrm_api3('Contact', 'create', array(
8d99ab37 566 'organization_name' => $params['current_employer'],
21dfd5f5 567 'contact_type' => 'Organization',
8d99ab37
CW
568 ));
569 $params['employer_id'] = $result['id'];
570 }
6a488035
TO
571 }
572
573 return NULL;
574}
575
576/**
244bbdd8 577 * Helper function for Contact create.
6a488035 578 *
cf470720
TO
579 * @param array $params
580 * (reference ) an assoc array of name/value pairs.
581 * @param int $contactID
582 * If present the contact with that ID is updated.
6a488035 583 *
54f1aa2a 584 * @return CRM_Contact_BAO_Contact|CRM_Core_Error
6a488035
TO
585 */
586function _civicrm_api3_contact_update($params, $contactID = NULL) {
6ecbca5b 587 //@todo - doesn't contact create support 'id' which is already set- check & remove
6a488035
TO
588 if ($contactID) {
589 $params['contact_id'] = $contactID;
590 }
591
6ecbca5b 592 return CRM_Contact_BAO_Contact::create($params);
6a488035
TO
593}
594
595/**
9d32e6f7 596 * Validate the addressee or email or postal greetings.
6a488035 597 *
cf470720 598 * @param array $params
9d32e6f7 599 * Array per getfields metadata.
6a488035 600 *
77b97be7 601 * @throws API_Exception
6a488035
TO
602 */
603function _civicrm_api3_greeting_format_params($params) {
604 $greetingParams = array('', '_id', '_custom');
605 foreach (array('email', 'postal', 'addressee') as $key) {
606 $greeting = '_greeting';
607 if ($key == 'addressee') {
608 $greeting = '';
609 }
610
611 $formatParams = FALSE;
22242c87 612 // Unset display value from params.
6a488035
TO
613 if (isset($params["{$key}{$greeting}_display"])) {
614 unset($params["{$key}{$greeting}_display"]);
615 }
616
617 // check if greetings are present in present
618 foreach ($greetingParams as $greetingValues) {
619 if (array_key_exists("{$key}{$greeting}{$greetingValues}", $params)) {
620 $formatParams = TRUE;
621 break;
622 }
623 }
624
625 if (!$formatParams) {
626 continue;
627 }
628
629 $nullValue = FALSE;
630 $filter = array(
6a488035
TO
631 'greeting_type' => "{$key}{$greeting}",
632 );
633
634 $greetings = CRM_Core_PseudoConstant::greeting($filter);
635 $greetingId = CRM_Utils_Array::value("{$key}{$greeting}_id", $params);
636 $greetingVal = CRM_Utils_Array::value("{$key}{$greeting}", $params);
637 $customGreeting = CRM_Utils_Array::value("{$key}{$greeting}_custom", $params);
638
639 if (!$greetingId && $greetingVal) {
640 $params["{$key}{$greeting}_id"] = CRM_Utils_Array::key($params["{$key}{$greeting}"], $greetings);
641 }
642
643 if ($customGreeting && $greetingId &&
644 ($greetingId != array_search('Customized', $greetings))
645 ) {
6ecbca5b 646 throw new API_Exception(ts('Provide either %1 greeting id and/or %1 greeting or custom %1 greeting',
6a488035
TO
647 array(1 => $key)
648 ));
649 }
650
651 if ($greetingVal && $greetingId &&
652 ($greetingId != CRM_Utils_Array::key($greetingVal, $greetings))
653 ) {
6ecbca5b 654 throw new API_Exception(ts('Mismatch in %1 greeting id and %1 greeting',
6a488035
TO
655 array(1 => $key)
656 ));
657 }
658
659 if ($greetingId) {
6a488035 660 if (!$customGreeting && ($greetingId == array_search('Customized', $greetings))) {
6ecbca5b 661 throw new API_Exception(ts('Please provide a custom value for %1 greeting',
6a488035
TO
662 array(1 => $key)
663 ));
664 }
665 }
666 elseif ($greetingVal) {
667
668 if (!in_array($greetingVal, $greetings)) {
6ecbca5b 669 throw new API_Exception(ts('Invalid %1 greeting', array(1 => $key)));
6a488035
TO
670 }
671
672 $greetingId = CRM_Utils_Array::key($greetingVal, $greetings);
673 }
674
675 if ($customGreeting) {
676 $greetingId = CRM_Utils_Array::key('Customized', $greetings);
677 }
678
35671d00 679 $customValue = isset($params['contact_id']) ? CRM_Core_DAO::getFieldValue(
ad3f841d
DL
680 'CRM_Contact_DAO_Contact',
681 $params['contact_id'],
682 "{$key}{$greeting}_custom"
35671d00 683 ) : FALSE;
6a488035
TO
684
685 if (array_key_exists("{$key}{$greeting}_id", $params) && empty($params["{$key}{$greeting}_id"])) {
686 $nullValue = TRUE;
687 }
688 elseif (array_key_exists("{$key}{$greeting}", $params) && empty($params["{$key}{$greeting}"])) {
689 $nullValue = TRUE;
690 }
691 elseif ($customValue && array_key_exists("{$key}{$greeting}_custom", $params)
692 && empty($params["{$key}{$greeting}_custom"])
693 ) {
694 $nullValue = TRUE;
695 }
696
697 $params["{$key}{$greeting}_id"] = $greetingId;
698
699 if (!$customValue && !$customGreeting && array_key_exists("{$key}{$greeting}_custom", $params)) {
700 unset($params["{$key}{$greeting}_custom"]);
701 }
702
703 if ($nullValue) {
704 $params["{$key}{$greeting}_id"] = '';
705 $params["{$key}{$greeting}_custom"] = '';
706 }
707
708 if (isset($params["{$key}{$greeting}"])) {
709 unset($params["{$key}{$greeting}"]);
710 }
711 }
712}
713
2baa1e00 714/**
715 * Adjust Metadata for Get action.
716 *
717 * @param array $params
718 * Array of parameters determined by getfields.
719 */
720function _civicrm_api3_contact_getquick_spec(&$params) {
721 $params['name']['api.required'] = TRUE;
722 $params['name']['title'] = ts('String to search on');
723 $params['name']['type'] = CRM_Utils_Type::T_STRING;
724 $params['field']['type'] = CRM_Utils_Type::T_STRING;
725 $params['field']['title'] = ts('Field to search on');
726 $params['field']['options'] = array(
727 '',
728 'id',
729 'contact_id',
730 'external_identifier',
731 'first_name',
732 'last_name',
733 'job_title',
734 'postal_code',
735 'street_address',
736 'email',
737 'city',
738 'phone_numeric',
739 );
740 $params['table_name']['type'] = CRM_Utils_Type::T_STRING;
741 $params['table_name']['title'] = ts('Table alias to search on');
742 $params['table_name']['api.default'] = 'cc';
743}
744
6a488035 745/**
244bbdd8 746 * Old Contact quick search api.
6a488035 747 *
03f32517 748 * @deprecated
6a488035 749 *
d0997921 750 * @param array $params
9d32e6f7 751 *
645ee340
EM
752 * @return array
753 * @throws \API_Exception
6a488035 754 */
6a488035 755function civicrm_api3_contact_getquick($params) {
aca85468 756 $name = CRM_Utils_Type::escape(CRM_Utils_Array::value('name', $params), 'String');
2baa1e00 757 $table_name = CRM_Utils_String::munge($params['table_name']);
6a488035
TO
758 // get the autocomplete options from settings
759 $acpref = explode(CRM_Core_DAO::VALUE_SEPARATOR,
760 CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME,
761 'contact_autocomplete_options'
762 )
763 );
764
4235341b
CW
765 $table_names = [
766 'email' => 'eml',
767 'phone_numeric' => 'phe',
768 'street_address' => 'sts',
769 'city' => 'sts',
770 'postal_code' => 'sts',
771 ];
772
6a488035
TO
773 // get the option values for contact autocomplete
774 $acOptions = CRM_Core_OptionGroup::values('contact_autocomplete_options', FALSE, FALSE, FALSE, NULL, 'name');
775
4235341b 776 $list = $from = array();
6a488035 777 foreach ($acpref as $value) {
8cc574cf 778 if ($value && !empty($acOptions[$value])) {
6a488035
TO
779 $list[$value] = $acOptions[$value];
780 }
781 }
782 // If we are doing quicksearch by a field other than name, make sure that field is added to results
783 if (!empty($params['field_name'])) {
1aba4d9a 784 $field_name = CRM_Utils_String::munge($params['field_name']);
5d8ba7a7 785 // Unique name contact_id = id
1aba4d9a
CW
786 if ($field_name == 'contact_id') {
787 $field_name = 'id';
5d8ba7a7 788 }
4235341b
CW
789 if (isset($table_names[$field_name])) {
790 $table_name = $table_names[$field_name];
791 }
792 elseif (strpos($field_name, 'custom_') === 0) {
1f8ac3d2 793 $customField = civicrm_api3('CustomField', 'getsingle', [
4235341b 794 'id' => substr($field_name, 7),
1f8ac3d2 795 'return' => ['custom_group_id.table_name', 'column_name', 'data_type', 'option_group_id', 'html_type'],
4235341b 796 ]);
1f8ac3d2
CW
797 $field_name = $customField['column_name'];
798 $table_name = CRM_Utils_String::munge($customField['custom_group_id.table_name']);
4235341b 799 $from[$field_name] = "LEFT JOIN `$table_name` ON cc.id = `$table_name`.entity_id";
1f8ac3d2
CW
800 if (CRM_Core_BAO_CustomField::hasOptions($customField)) {
801 $customOptionsWhere = [];
802 $customFieldOptions = CRM_Contact_BAO_Contact::buildOptions('custom_' . $customField['id'], 'search');
803 $isMultivalueField = CRM_Core_BAO_CustomField::isSerialized($customField);
804 $sep = CRM_Core_DAO::VALUE_SEPARATOR;
805 foreach ($customFieldOptions as $optionKey => $optionLabel) {
806 if (mb_stripos($optionLabel, $name) !== FALSE) {
807 $customOptionsWhere[$optionKey] = "$table_name.$field_name " . ($isMultivalueField ? "LIKE '%{$sep}{$optionKey}{$sep}%'" : "= '$optionKey'");
808 }
809 }
810 }
4235341b 811 }
6a488035 812 // phone_numeric should be phone
1aba4d9a 813 $searchField = str_replace('_numeric', '', $field_name);
22e263ad 814 if (!in_array($searchField, $list)) {
6a488035
TO
815 $list[] = $searchField;
816 }
817 }
2baa1e00 818 else {
819 // Set field name to first name for exact match checking.
820 $field_name = 'sort_name';
821 }
6a488035
TO
822
823 $select = $actualSelectElements = array('sort_name');
824 $where = '';
6a488035
TO
825 foreach ($list as $value) {
826 $suffix = substr($value, 0, 2) . substr($value, -1);
827 switch ($value) {
828 case 'street_address':
829 case 'city':
830 case 'postal_code':
831 $selectText = $value;
832 $value = "address";
833 $suffix = 'sts';
834 case 'phone':
835 case 'email':
836 $actualSelectElements[] = $select[] = ($value == 'address') ? $selectText : $value;
aebdef3c
JL
837 if ($value == 'phone') {
838 $actualSelectElements[] = $select[] = 'phone_ext';
839 }
6a488035
TO
840 $from[$value] = "LEFT JOIN civicrm_{$value} {$suffix} ON ( cc.id = {$suffix}.contact_id AND {$suffix}.is_primary = 1 ) ";
841 break;
842
843 case 'country':
844 case 'state_province':
845 $select[] = "{$suffix}.name as {$value}";
846 $actualSelectElements[] = "{$suffix}.name";
847 if (!in_array('address', $from)) {
848 $from['address'] = 'LEFT JOIN civicrm_address sts ON ( cc.id = sts.contact_id AND sts.is_primary = 1) ';
849 }
850 $from[$value] = " LEFT JOIN civicrm_{$value} {$suffix} ON ( sts.{$value}_id = {$suffix}.id ) ";
851 break;
852
853 default:
4235341b
CW
854 if ($value == 'id') {
855 $actualSelectElements[] = 'cc.id';
856 }
857 elseif ($value != 'sort_name') {
6a488035 858 $suffix = 'cc';
4235341b
CW
859 if ($field_name == $value) {
860 $suffix = $table_name;
6a488035
TO
861 }
862 $actualSelectElements[] = $select[] = $suffix . '.' . $value;
863 }
864 break;
865 }
866 }
867
868 $config = CRM_Core_Config::singleton();
869 $as = $select;
870 $select = implode(', ', $select);
871 if (!empty($select)) {
872 $select = ", $select";
873 }
874 $actualSelectElements = implode(', ', $actualSelectElements);
6a488035 875 $from = implode(' ', $from);
133da98d 876 $limit = (int) CRM_Utils_Array::value('limit', $params);
89595c92 877 $limit = $limit > 0 ? $limit : Civi::settings()->get('search_autocomplete_count');
6a488035
TO
878
879 // add acl clause here
880 list($aclFrom, $aclWhere) = CRM_Contact_BAO_Contact_Permission::cacheClause('cc');
881
882 if ($aclWhere) {
883 $where .= " AND $aclWhere ";
884 }
613643e0 885 $isPrependWildcard = \Civi::settings()->get('includeWildCardInName');
6a488035 886
a7488080 887 if (!empty($params['org'])) {
6a488035
TO
888 $where .= " AND contact_type = \"Organization\"";
889
890 // CRM-7157, hack: get current employer details when
891 // employee_id is present.
892 $currEmpDetails = array();
a7488080 893 if (!empty($params['employee_id'])) {
6a488035 894 if ($currentEmployer = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact',
133da98d 895 (int) $params['employee_id'],
6a488035
TO
896 'employer_id'
897 )) {
613643e0 898 if ($isPrependWildcard) {
6a488035
TO
899 $strSearch = "%$name%";
900 }
901 else {
902 $strSearch = "$name%";
903 }
904
905 // get current employer details
906 $dao = CRM_Core_DAO::executeQuery("SELECT cc.id as id, CONCAT_WS( ' :: ', {$actualSelectElements} ) as data, sort_name
907 FROM civicrm_contact cc {$from} WHERE cc.contact_type = \"Organization\" AND cc.id = {$currentEmployer} AND cc.sort_name LIKE '$strSearch'");
908 if ($dao->fetch()) {
909 $currEmpDetails = array(
910 'id' => $dao->id,
911 'data' => $dao->data,
912 );
913 }
914 }
915 }
916 }
917
a7488080 918 if (!empty($params['contact_sub_type'])) {
69164898
N
919 $contactSubType = CRM_Utils_Type::escape($params['contact_sub_type'], 'String');
920 $where .= " AND cc.contact_sub_type = '{$contactSubType}'";
921 }
922
e1b717cb
P
923 if (!empty($params['contact_type'])) {
924 $contactType = CRM_Utils_Type::escape($params['contact_type'], 'String');
925 $where .= " AND cc.contact_type LIKE '{$contactType}'";
926 }
927
244bbdd8 928 // Set default for current_employer or return contact with particular id
a7488080 929 if (!empty($params['id'])) {
1aba4d9a 930 $where .= " AND cc.id = " . (int) $params['id'];
6a488035
TO
931 }
932
a7488080 933 if (!empty($params['cid'])) {
1aba4d9a 934 $where .= " AND cc.id <> " . (int) $params['cid'];
6a488035
TO
935 }
936
244bbdd8 937 // Contact's based of relationhip type
6a488035 938 $relType = NULL;
a7488080 939 if (!empty($params['rel'])) {
6a488035
TO
940 $relation = explode('_', CRM_Utils_Array::value('rel', $params));
941 $relType = CRM_Utils_Type::escape($relation[0], 'Integer');
942 $rel = CRM_Utils_Type::escape($relation[2], 'String');
943 }
944
613643e0 945 if ($isPrependWildcard) {
6a488035
TO
946 $strSearch = "%$name%";
947 }
948 else {
949 $strSearch = "$name%";
950 }
1f8ac3d2 951 $includeEmailFrom = $includeNickName = '';
6a488035
TO
952 if ($config->includeNickNameInName) {
953 $includeNickName = " OR nick_name LIKE '$strSearch'";
6a488035
TO
954 }
955
1f8ac3d2
CW
956 if (isset($customOptionsWhere)) {
957 $customOptionsWhere = $customOptionsWhere ?: [0];
958 $whereClause = " WHERE (" . implode(' OR ', $customOptionsWhere) . ") $where";
959 }
d976e590 960 elseif (!empty($params['field_name']) && !empty($params['table_name']) && $params['field_name'] != 'sort_name') {
8d3b1aa6 961 $whereClause = " WHERE ( $table_name.$field_name LIKE '$strSearch') {$where}";
6a488035
TO
962 // Search by id should be exact
963 if ($field_name == 'id' || $field_name == 'external_identifier') {
613643e0 964 $whereClause = " WHERE ( $table_name.$field_name = '$name') {$where}";
6a488035
TO
965 }
966 }
967 else {
a5728a28 968 $whereClause = " WHERE ( sort_name LIKE '$strSearch' $includeNickName ) {$where} ";
6a488035
TO
969 if ($config->includeEmailInName) {
970 if (!in_array('email', $list)) {
971 $includeEmailFrom = "LEFT JOIN civicrm_email eml ON ( cc.id = eml.contact_id AND eml.is_primary = 1 )";
972 }
36575b09 973 $emailWhere = " WHERE email LIKE '$strSearch'";
6a488035
TO
974 }
975 }
976
977 $additionalFrom = '';
978 if ($relType) {
979 $additionalFrom = "
980 INNER JOIN civicrm_relationship_type r ON (
981 r.id = {$relType}
982 AND ( cc.contact_type = r.contact_type_{$rel} OR r.contact_type_{$rel} IS NULL )
983 AND ( cc.contact_sub_type = r.contact_sub_type_{$rel} OR r.contact_sub_type_{$rel} IS NULL )
984 )";
985 }
986
987 // check if only CMS users are requested
a7488080 988 if (!empty($params['cmsuser'])) {
6a488035
TO
989 $additionalFrom = "
990 INNER JOIN civicrm_uf_match um ON (um.contact_id=cc.id)
991 ";
992 }
613643e0 993 $orderBy = _civicrm_api3_quicksearch_get_order_by($name, $isPrependWildcard, $field_name);
51e61eae 994
6a488035
TO
995 //CRM-5954
996 $query = "
1f8ac3d2 997 SELECT DISTINCT(id), data, sort_name, exactFirst
6a488035 998 FROM (
2baa1e00 999 ( SELECT IF($table_name.$field_name = '{$name}', 0, 1) as exactFirst, cc.id as id, CONCAT_WS( ' :: ',
1000 {$actualSelectElements} )
1001 as data
1002 {$select}
6a488035
TO
1003 FROM civicrm_contact cc {$from}
1004 {$aclFrom}
a5728a28 1005 {$additionalFrom}
6a488035 1006 {$whereClause}
613643e0 1007 {$orderBy}
6a488035 1008 LIMIT 0, {$limit} )
6a488035 1009 ";
a5728a28 1010
1011 if (!empty($emailWhere)) {
1012 $query .= "
1013 UNION (
1014 SELECT IF($table_name.$field_name = '{$name}', 0, 1) as exactFirst, cc.id as id, CONCAT_WS( ' :: ',
1015 {$actualSelectElements} )
1016 as data
1017 {$select}
1018 FROM civicrm_contact cc {$from}
1019 {$aclFrom}
1020 {$additionalFrom} {$includeEmailFrom}
c37a2d66 1021 {$emailWhere} AND cc.is_deleted = 0 " . ($aclWhere ? " AND $aclWhere " : '') . "
613643e0 1022 {$orderBy}
a5728a28 1023 LIMIT 0, {$limit}
1024 )
1025 ";
1026 }
36575b09 1027 $query .= ") t
613643e0 1028 {$orderBy}
2baa1e00 1029 LIMIT 0, {$limit}
1030 ";
1031
6a488035
TO
1032 // send query to hook to be modified if needed
1033 CRM_Utils_Hook::contactListQuery($query,
1034 $name,
133da98d
CW
1035 empty($params['context']) ? NULL : CRM_Utils_Type::escape($params['context'], 'String'),
1036 empty($params['id']) ? NULL : $params['id']
6a488035
TO
1037 );
1038
1039 $dao = CRM_Core_DAO::executeQuery($query);
1040
1041 $contactList = array();
1042 $listCurrentEmployer = TRUE;
1043 while ($dao->fetch()) {
1044 $t = array('id' => $dao->id);
1045 foreach ($as as $k) {
35671d00 1046 $t[$k] = isset($dao->$k) ? $dao->$k : '';
6a488035
TO
1047 }
1048 $t['data'] = $dao->data;
1f8ac3d2
CW
1049 // Replace keys with values when displaying fields from an option list
1050 if (!empty($customOptionsWhere)) {
1051 $data = explode(' :: ', $dao->data);
1052 $pos = count($data) - 1;
1053 $customValue = array_intersect(CRM_Utils_Array::explodePadded($data[$pos]), array_keys($customOptionsWhere));
1054 $data[$pos] = implode(', ', array_intersect_key($customFieldOptions, array_flip($customValue)));
1055 $t['data'] = implode(' :: ', $data);
1056 }
6a488035 1057 $contactList[] = $t;
a7488080 1058 if (!empty($params['org']) &&
6a488035
TO
1059 !empty($currEmpDetails) &&
1060 $dao->id == $currEmpDetails['id']
1061 ) {
1062 $listCurrentEmployer = FALSE;
1063 }
1064 }
1065
1066 //return organization name if doesn't exist in db
1067 if (empty($contactList)) {
a7488080 1068 if (!empty($params['org'])) {
6a488035
TO
1069 if ($listCurrentEmployer && !empty($currEmpDetails)) {
1070 $contactList = array(
1071 array(
d5cc0fc2 1072 'data' => $currEmpDetails['data'],
21dfd5f5
TO
1073 'id' => $currEmpDetails['id'],
1074 ),
6a488035
TO
1075 );
1076 }
1077 else {
1078 $contactList = array(
1079 array(
1080 'data' => $name,
21dfd5f5
TO
1081 'id' => $name,
1082 ),
6a488035
TO
1083 );
1084 }
1085 }
1086 }
1087
244bbdd8 1088 return civicrm_api3_create_success($contactList, $params, 'Contact', 'getquick');
a14e9d08
CW
1089}
1090
613643e0 1091/**
1092 * Get the order by string for the quicksearch query.
1093 *
1094 * Get the order by string. The string might be
1095 * - sort name if there is no search value provided and the site is configured
1096 * to search by sort name
1097 * - empty if there is no search value provided and the site is not configured
1098 * to search by sort name
1099 * - exactFirst and then sort name if a search value is provided and the site is configured
1100 * to search by sort name
1101 * - exactFirst if a search value is provided and the site is not configured
1102 * to search by sort name
1103 *
1104 * exactFirst means 'yes if the search value exactly matches the searched field. else no'.
1105 * It is intended to prioritise exact matches for the entered string so on a first name search
1106 * for 'kath' contacts with a first name of exactly Kath rise to the top.
1107 *
1108 * On short strings it is expensive. Per CRM-19547 there is still an open question
1109 * as to whether we should only do exactMatch on a minimum length or on certain fields.
1110 *
1111 * However, we have mitigated this somewhat by not doing an exact match search on
1112 * empty strings, non-wildcard sort-name searches and email searches where there is
1113 * no @ after the first character.
1114 *
1115 * For the user it is further mitigated by the fact they just don't know the
1116 * slower queries are firing. If they type 'smit' slowly enough 4 queries will trigger
1117 * but if the first 3 are slow the first result they see may be off the 4th query.
1118 *
1119 * @param string $name
1120 * @param bool $isPrependWildcard
1121 * @param string $field_name
1122 *
1123 * @return string
1124 */
1125function _civicrm_api3_quicksearch_get_order_by($name, $isPrependWildcard, $field_name) {
1126 $skipExactMatch = ($name === '%');
1127 if ($field_name === 'email' && !strpos('@', $name)) {
1128 $skipExactMatch = TRUE;
1129 }
1130
1131 if (!\Civi::settings()->get('includeOrderByClause')) {
1132 return $skipExactMatch ? '' : "ORDER BY exactFirst";
1133 }
1134 if ($skipExactMatch || (!$isPrependWildcard && $field_name === 'sort_name')) {
1135 // If there is no wildcard then sorting by exactFirst would have the same
1136 // effect as just a sort_name search, but slower.
1137 return "ORDER BY sort_name";
1138 }
1139
1140 return "ORDER BY exactFirst, sort_name";
1141}
1142
a14e9d08 1143/**
35823763
EM
1144 * Declare deprecated api functions.
1145 *
a14e9d08 1146 * @deprecated api notice
a6c01b45 1147 * @return array
16b10e64 1148 * Array of deprecated actions
a14e9d08
CW
1149 */
1150function _civicrm_api3_contact_deprecation() {
1151 return array('getquick' => 'The "getquick" action is deprecated in favor of "getlist".');
6a488035
TO
1152}
1153
1154/**
1155 * Merges given pair of duplicate contacts.
1156 *
cf470720 1157 * @param array $params
b081365f
CW
1158 * Allowed array keys are:
1159 * -int main_id: main contact id with whom merge has to happen
1160 * -int other_id: duplicate contact which would be deleted after merge operation
1161 * -string mode: "safe" skips the merge if there are no conflicts. Does a force merge otherwise.
6a488035 1162 *
a6c01b45 1163 * @return array
72b3a70c 1164 * API Result Array
fedc3428 1165 * @throws API_Exception
6a488035
TO
1166 */
1167function civicrm_api3_contact_merge($params) {
5ea06a7b 1168 if (($result = CRM_Dedupe_Merger::merge(array(
1169 array(
1170 'srcID' => $params['to_remove_id'],
1171 'dstID' => $params['to_keep_id'],
1172 ),
d238756a 1173 ), array(), $params['mode'])) != FALSE) {
12d73bba 1174 return civicrm_api3_create_success($result, $params);
6a488035 1175 }
fedc3428 1176 throw new API_Exception('Merge failed');
12d73bba 1177}
1178
1179/**
5ea06a7b 1180 * Adjust metadata for contact_merge api function.
12d73bba 1181 *
1182 * @param array $params
1183 */
1184function _civicrm_api3_contact_merge_spec(&$params) {
5ea06a7b 1185 $params['to_remove_id'] = array(
12d73bba 1186 'title' => 'ID of the contact to merge & remove',
1187 'description' => ts('Wow - these 2 params are the logical reverse of what I expect - but what to do?'),
1188 'api.required' => 1,
1189 'type' => CRM_Utils_Type::T_INT,
5ea06a7b 1190 'api.aliases' => array('main_id'),
12d73bba 1191 );
5ea06a7b 1192 $params['to_keep_id'] = array(
12d73bba 1193 'title' => 'ID of the contact to keep',
1194 'description' => ts('Wow - these 2 params are the logical reverse of what I expect - but what to do?'),
1195 'api.required' => 1,
1196 'type' => CRM_Utils_Type::T_INT,
5ea06a7b 1197 'api.aliases' => array('other_id'),
1198 );
5ea06a7b 1199 $params['mode'] = array(
1200 // @todo need more detail on what this means.
1201 'title' => 'Dedupe mode',
1202 'api.default' => 'safe',
12d73bba 1203 );
6a488035
TO
1204}
1205
734cd0d5 1206/**
1207 * Get the ultimate contact a contact was merged to.
1208 *
1209 * @param array $params
1210 *
1211 * @return array
1212 * API Result Array
1213 * @throws API_Exception
1214 */
1215function civicrm_api3_contact_getmergedto($params) {
1216 $contactID = _civicrm_api3_contact_getmergedto($params);
1217 if ($contactID) {
1218 $values = [$contactID => ['id' => $contactID]];
1219 }
1220 else {
1221 $values = [];
1222 }
1223 return civicrm_api3_create_success($values, $params);
1224}
1225
1226/**
1227 * Get the contact our contact was finally merged to.
1228 *
1229 * If the contact has been merged multiple times the crucial parent activity will have
1230 * wound up on the ultimate contact so we can figure out the final resting place of the
1231 * contact with only 2 activities even if 50 merges took place.
1232 *
1233 * @param array $params
1234 *
1235 * @return int|false
1236 */
1237function _civicrm_api3_contact_getmergedto($params) {
1238 $contactID = FALSE;
1239 $deleteActivity = civicrm_api3('ActivityContact', 'get', [
1240 'contact_id' => $params['contact_id'],
1241 'activity_id.activity_type_id' => 'Contact Deleted By Merge',
1242 'is_deleted' => 0,
1243 'is_test' => $params['is_test'],
1244 'record_type_id' => 'Activity Targets',
1245 'return' => ['activity_id.parent_id'],
1246 'sequential' => 1,
1247 'options' => [
1248 'limit' => 1,
1249 'sort' => 'activity_id.activity_date_time DESC'
1250 ],
1251 ])['values'];
1252 if (!empty($deleteActivity)) {
1253 $contactID = civicrm_api3('ActivityContact', 'getvalue', [
1254 'activity_id' => $deleteActivity[0]['activity_id.parent_id'],
1255 'record_type_id' => 'Activity Targets',
1256 'return' => 'contact_id',
1257 ]);
1258 }
1259 return $contactID;
1260}
1261
1262/**
1263 * Adjust metadata for contact_merge api function.
1264 *
1265 * @param array $params
1266 */
1267function _civicrm_api3_contact_getmergedto_spec(&$params) {
1268 $params['contact_id'] = [
1269 'title' => ts('ID of contact to find ultimate contact for'),
1270 'type' => CRM_Utils_Type::T_INT,
1271 'api.required' => TRUE,
1272 ];
1273 $params['is_test'] = [
1274 'title' => ts('Get test deletions rather than live?'),
1275 'type' => CRM_Utils_Type::T_BOOLEAN,
1276 'api.default' => 0,
1277 ];
1278}
1279
1280/**
1281 * Get the ultimate contact a contact was merged to.
1282 *
1283 * @param array $params
1284 *
1285 * @return array
1286 * API Result Array
1287 * @throws API_Exception
1288 */
1289function civicrm_api3_contact_getmergedfrom($params) {
1290 $contacts = _civicrm_api3_contact_getmergedfrom($params);
1291 return civicrm_api3_create_success($contacts, $params);
1292}
1293
1294/**
1295 * Get all the contacts merged into our contact.
1296 *
1297 * @param array $params
1298 *
1299 * @return array
1300 */
1301function _civicrm_api3_contact_getmergedfrom($params) {
1302 $activities = [];
1303 $deleteActivities = civicrm_api3('ActivityContact', 'get', [
1304 'contact_id' => $params['contact_id'],
1305 'activity_id.activity_type_id' => 'Contact Merged',
1306 'is_deleted' => 0,
1307 'is_test' => $params['is_test'],
1308 'record_type_id' => 'Activity Targets',
1309 'return' => 'activity_id',
1310 ])['values'];
1311
1312 foreach ($deleteActivities as $deleteActivity) {
1313 $activities[] = $deleteActivity['activity_id'];
1314 }
1315 if (empty($activities)) {
1316 return [];
1317 }
1318
1319 $activityContacts = civicrm_api3('ActivityContact', 'get', [
1320 'activity_id.parent_id' => ['IN' => $activities],
1321 'record_type_id' => 'Activity Targets',
1322 'return' => 'contact_id',
1323 ])['values'];
1324 $contacts = [];
1325 foreach ($activityContacts as $activityContact) {
1326 $contacts[$activityContact['contact_id']] = ['id' => $activityContact['contact_id']];
1327 }
1328 return $contacts;
1329}
1330
1331/**
1332 * Adjust metadata for contact_merge api function.
1333 *
1334 * @param array $params
1335 */
1336function _civicrm_api3_contact_getmergedfrom_spec(&$params) {
1337 $params['contact_id'] = [
1338 'title' => ts('ID of contact to find ultimate contact for'),
1339 'type' => CRM_Utils_Type::T_INT,
1340 'api.required' => TRUE,
1341 ];
1342 $params['is_test'] = [
1343 'title' => ts('Get test deletions rather than live?'),
1344 'type' => CRM_Utils_Type::T_BOOLEAN,
1345 'api.default' => 0,
1346 ];
1347}
1348
aa1b1481 1349/**
9d32e6f7
EM
1350 * Adjust metadata for contact_proximity api function.
1351 *
c490a46a 1352 * @param array $params
aa1b1481 1353 */
6a488035 1354function _civicrm_api3_contact_proximity_spec(&$params) {
d142432b
EM
1355 $params['latitude'] = array(
1356 'title' => 'Latitude',
1357 'api.required' => 1,
1358 'type' => CRM_Utils_Type::T_STRING,
1359 );
1360 $params['longitude'] = array(
1361 'title' => 'Longitude',
1362 'api.required' => 1,
1363 'type' => CRM_Utils_Type::T_STRING,
1364 );
1365
1366 $params['unit'] = array(
1367 'title' => 'Unit of Measurement',
1368 'api.default' => 'meter',
1369 'type' => CRM_Utils_Type::T_STRING,
1370 );
6a488035
TO
1371}
1372
aa1b1481 1373/**
9d32e6f7
EM
1374 * Get contacts by proximity.
1375 *
c490a46a 1376 * @param array $params
aa1b1481
EM
1377 *
1378 * @return array
1379 * @throws Exception
1380 */
6a488035
TO
1381function civicrm_api3_contact_proximity($params) {
1382 $latitude = CRM_Utils_Array::value('latitude', $params);
1383 $longitude = CRM_Utils_Array::value('longitude', $params);
1384 $distance = CRM_Utils_Array::value('distance', $params);
1385
1386 $unit = CRM_Utils_Array::value('unit', $params);
1387
1388 // check and ensure that lat/long and distance are floats
1389 if (
1390 !CRM_Utils_Rule::numeric($latitude) ||
1391 !CRM_Utils_Rule::numeric($longitude) ||
1392 !CRM_Utils_Rule::numeric($distance)
1393 ) {
1394 throw new Exception(ts('Latitude, Longitude and Distance should exist and be numeric'));
1395 }
1396
1397 if ($unit == "mile") {
1398 $conversionFactor = 1609.344;
1399 }
1400 else {
1401 $conversionFactor = 1000;
1402 }
1403 //Distance in meters
1404 $distance = $distance * $conversionFactor;
1405
1406 $whereClause = CRM_Contact_BAO_ProximityQuery::where($latitude, $longitude, $distance);
1407
1408 $query = "
1409SELECT civicrm_contact.id as contact_id,
1410 civicrm_contact.display_name as display_name
1411FROM civicrm_contact
1412LEFT JOIN civicrm_address ON civicrm_contact.id = civicrm_address.contact_id
1413WHERE $whereClause
1414";
1415
1416 $dao = CRM_Core_DAO::executeQuery($query);
1417 $contacts = array();
1418 while ($dao->fetch()) {
1419 $contacts[] = $dao->toArray();
1420 }
1421
244bbdd8 1422 return civicrm_api3_create_success($contacts, $params, 'Contact', 'get_by_location', $dao);
6a488035
TO
1423}
1424
ff88d165
CW
1425
1426/**
22242c87
EM
1427 * Get parameters for getlist function.
1428 *
a6c6059d 1429 * @see _civicrm_api3_generic_getlist_params
ff88d165 1430 *
8c6b335b 1431 * @param array $request
ff88d165
CW
1432 */
1433function _civicrm_api3_contact_getlist_params(&$request) {
1434 // get the autocomplete options from settings
1435 $acpref = explode(CRM_Core_DAO::VALUE_SEPARATOR,
1436 CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME,
1437 'contact_autocomplete_options'
1438 )
1439 );
1440
1441 // get the option values for contact autocomplete
1442 $acOptions = CRM_Core_OptionGroup::values('contact_autocomplete_options', FALSE, FALSE, FALSE, NULL, 'name');
1443
1444 $list = array();
1445 foreach ($acpref as $value) {
1446 if ($value && !empty($acOptions[$value])) {
1447 $list[] = $acOptions[$value];
1448 }
1449 }
1450 // If we are doing quicksearch by a field other than name, make sure that field is added to results
1451 $field_name = CRM_Utils_String::munge($request['search_field']);
1452 // Unique name contact_id = id
1453 if ($field_name == 'contact_id') {
1454 $field_name = 'id';
1455 }
1456 // phone_numeric should be phone
1457 $searchField = str_replace('_numeric', '', $field_name);
22e263ad 1458 if (!in_array($searchField, $list)) {
ff88d165
CW
1459 $list[] = $searchField;
1460 }
8250601e 1461 $request['description_field'] = $list;
54bee7df 1462 $list[] = 'contact_type';
8250601e 1463 $request['params']['return'] = array_unique(array_merge($list, $request['extra']));
ff88d165
CW
1464 $request['params']['options']['sort'] = 'sort_name';
1465 // Contact api doesn't support array(LIKE => 'foo') syntax
609a8c53 1466 if (!empty($request['input'])) {
fd816db5 1467 $request['params'][$request['search_field']] = $request['input'];
81b7bb6f
CW
1468 // Temporarily override wildcard setting
1469 if (Civi::settings()->get('includeWildCardInName') != $request['add_wildcard']) {
1470 Civi::$statics['civicrm_api3_contact_getlist']['override_wildcard'] = !$request['add_wildcard'];
1471 Civi::settings()->set('includeWildCardInName', $request['add_wildcard']);
1472 }
609a8c53 1473 }
ff88d165
CW
1474}
1475
1476/**
22242c87
EM
1477 * Get output for getlist function.
1478 *
a6c6059d 1479 * @see _civicrm_api3_generic_getlist_output
ff88d165 1480 *
8c6b335b
CW
1481 * @param array $result
1482 * @param array $request
ff88d165
CW
1483 *
1484 * @return array
1485 */
1486function _civicrm_api3_contact_getlist_output($result, $request) {
1487 $output = array();
1488 if (!empty($result['values'])) {
dc64d047
EM
1489 $addressFields = array_intersect(array(
1490 'street_address',
1491 'city',
1492 'state_province',
1493 'country',
1494 ),
1495 $request['params']['return']);
ff88d165
CW
1496 foreach ($result['values'] as $row) {
1497 $data = array(
1498 'id' => $row[$request['id_field']],
1499 'label' => $row[$request['label_field']],
88881f79 1500 'description' => array(),
ff88d165 1501 );
8250601e
CW
1502 foreach ($request['description_field'] as $item) {
1503 if (!strpos($item, '_name') && !in_array($item, $addressFields) && !empty($row[$item])) {
88881f79 1504 $data['description'][] = $row[$item];
ff88d165
CW
1505 }
1506 }
88881f79 1507 $address = array();
22e263ad 1508 foreach ($addressFields as $item) {
88881f79
CW
1509 if (!empty($row[$item])) {
1510 $address[] = $row[$item];
1511 }
1512 }
1513 if ($address) {
1514 $data['description'][] = implode(' ', $address);
1515 }
ff88d165
CW
1516 if (!empty($request['image_field'])) {
1517 $data['image'] = isset($row[$request['image_field']]) ? $row[$request['image_field']] : '';
54bee7df
CW
1518 }
1519 else {
1520 $data['icon_class'] = $row['contact_type'];
1521 }
ff88d165
CW
1522 $output[] = $data;
1523 }
1524 }
81b7bb6f
CW
1525 // Restore wildcard override by _civicrm_api3_contact_getlist_params
1526 if (isset(Civi::$statics['civicrm_api3_contact_getlist']['override_wildcard'])) {
1527 Civi::settings()->set('includeWildCardInName', Civi::$statics['civicrm_api3_contact_getlist']['override_wildcard']);
1528 unset(Civi::$statics['civicrm_api3_contact_getlist']['override_wildcard']);
1529 }
ff88d165
CW
1530 return $output;
1531}
eb5f7260 1532
1533/**
1534 * Check for duplicate contacts.
1535 *
1536 * @param array $params
1537 * Params per getfields metadata.
1538 *
1539 * @return array
1540 * API formatted array
1541 */
1542function civicrm_api3_contact_duplicatecheck($params) {
fedc3428 1543 $dupes = CRM_Contact_BAO_Contact::getDuplicateContacts(
1544 $params['match'],
1545 $params['match']['contact_type'],
d6def514 1546 $params['rule_type'],
1e8be62b 1547 CRM_Utils_Array::value('exclude', $params, []),
fedc3428 1548 CRM_Utils_Array::value('check_permissions', $params),
1549 CRM_Utils_Array::value('dedupe_rule_id', $params)
1550 );
d6def514
CW
1551 $values = array();
1552 if ($dupes && !empty($params['return'])) {
1553 return civicrm_api3('Contact', 'get', array(
1554 'return' => $params['return'],
1555 'id' => array('IN' => $dupes),
1556 'options' => CRM_Utils_Array::value('options', $params),
1557 'sequential' => CRM_Utils_Array::value('sequential', $params),
1558 'check_permissions' => CRM_Utils_Array::value('check_permissions', $params),
1559 ));
1560 }
1561 foreach ($dupes as $dupe) {
1562 $values[$dupe] = array('id' => $dupe);
1563 }
eb5f7260 1564 return civicrm_api3_create_success($values, $params, 'Contact', 'duplicatecheck');
1565}
1566
1567/**
1568 * Declare metadata for contact dedupe function.
1569 *
1570 * @param $params
1571 */
1572function _civicrm_api3_contact_duplicatecheck_spec(&$params) {
1573 $params['dedupe_rule_id'] = array(
1574 'title' => 'Dedupe Rule ID (optional)',
1575 'description' => 'This will default to the built in unsupervised rule',
1576 'type' => CRM_Utils_Type::T_INT,
1577 );
d6def514
CW
1578 $params['rule_type'] = array(
1579 'title' => 'Dedupe Rule Type',
1580 'description' => 'If no rule id specified, pass "Unsupervised" or "Supervised"',
1581 'type' => CRM_Utils_Type::T_STRING,
1582 'api.default' => 'Unsupervised',
1583 );
eb5f7260 1584 // @todo declare 'match' parameter. We don't have a standard for type = array yet.
1585}