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