3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2017 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
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. |
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. |
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 +--------------------------------------------------------------------+
29 * This api exposes CiviCRM contacts.
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.
37 * @package CiviCRM_APIv3
41 * Create or update a Contact.
43 * @param array $params
46 * @throws API_Exception
51 function civicrm_api3_contact_create($params) {
52 $contactID = CRM_Utils_Array
::value('contact_id', $params, CRM_Utils_Array
::value('id', $params));
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');
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));
65 $values = _civicrm_api3_contact_check_params($params);
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')) {
74 elseif ($contactID && CRM_Core_Permission
::check('edit own api keys') && CRM_Core_Session
::singleton()->get('userID') == $contactID) {
78 throw new \Civi\API\Exception\
UnauthorizedException('Permission denied to modify api key');
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(
90 'location_type_id' => ($defLocType->id
) ?
$defLocType->id
: 1,
96 if (!empty($params['home_url'])) {
97 $websiteTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Website', 'website_type_id');
98 $params['website'] = array(
100 'website_type_id' => key($websiteTypes),
101 'url' => $params['home_url'],
106 _civicrm_api3_greeting_format_params($params);
110 if (empty($params['contact_type']) && $contactID) {
111 $params['contact_type'] = CRM_Contact_BAO_Contact
::getContactType($contactID);
114 if (!isset($params['contact_sub_type']) && $contactID) {
115 $params['contact_sub_type'] = CRM_Contact_BAO_Contact
::getContactSubType($contactID);
118 _civicrm_api3_custom_format_params($params, $values, $params['contact_type'], $contactID);
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);
124 if (is_a($contact, 'CRM_Core_Error')) {
125 throw new API_Exception($contact->_errors
[0]['message']);
129 _civicrm_api3_object_to_array_unique_fields($contact, $values[$contact->id
]);
132 return civicrm_api3_create_success($values, $params, 'Contact', 'create');
136 * Adjust Metadata for Create action.
138 * @param array $params
139 * Array of parameters determined by getfields.
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
,
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
,
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');
160 * Retrieve one or more contacts, given a set of search params.
162 * @param array $params
167 function civicrm_api3_contact_get($params) {
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');
175 * Get number of contacts matching the supplied criteria.
177 * @param array $params
181 function civicrm_api3_contact_getcount($params) {
183 _civicrm_api3_contact_get_supportanomalies($params, $options);
184 $count = _civicrm_api3_get_using_query_object('Contact', $params, $options, 1);
189 * Adjust Metadata for Get action.
191 * @param array $params
192 * Array of parameters determined by getfields.
194 function _civicrm_api3_contact_get_spec(&$params) {
195 $params['contact_is_deleted']['api.default'] = 0;
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
,
203 $params['street_address'] = array(
204 'title' => 'Primary Address Street Address',
205 'type' => CRM_Utils_Type
::T_STRING
,
207 $params['supplemental_address_1'] = array(
208 'title' => 'Primary Address Supplemental Address 1',
209 'type' => CRM_Utils_Type
::T_STRING
,
211 $params['supplemental_address_2'] = array(
212 'title' => 'Primary Address Supplemental Address 2',
213 'type' => CRM_Utils_Type
::T_STRING
,
215 $params['current_employer'] = array(
216 'title' => 'Current Employer',
217 'type' => CRM_Utils_Type
::T_STRING
,
219 $params['city'] = array(
220 'title' => 'Primary Address City',
221 'type' => CRM_Utils_Type
::T_STRING
,
223 $params['postal_code_suffix'] = array(
224 'title' => 'Primary Address Post Code Suffix',
225 'type' => CRM_Utils_Type
::T_STRING
,
227 $params['postal_code'] = array(
228 'title' => 'Primary Address Post Code',
229 'type' => CRM_Utils_Type
::T_STRING
,
231 $params['geo_code_1'] = array(
232 'title' => 'Primary Address Latitude',
233 'type' => CRM_Utils_Type
::T_STRING
,
235 $params['geo_code_2'] = array(
236 'title' => 'Primary Address Longitude',
237 'type' => CRM_Utils_Type
::T_STRING
,
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',
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',
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',
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',
267 $params['country'] = array(
268 'title' => 'Primary Address country',
269 'type' => CRM_Utils_Type
::T_STRING
,
270 'pseudoconstant' => array(
271 'table' => 'civicrm_country',
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',
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',
288 $params['phone_id'] = array(
289 'title' => 'Primary Phone ID',
290 'type' => CRM_Utils_Type
::T_INT
,
292 $params['phone'] = array(
293 'title' => 'Primary Phone',
294 'type' => CRM_Utils_Type
::T_STRING
,
296 $params['phone_type_id'] = array(
297 'title' => 'Primary Phone Type ID',
298 'type' => CRM_Utils_Type
::T_INT
,
300 $params['provider_id'] = array(
301 'title' => 'Primary Phone Provider ID',
302 'type' => CRM_Utils_Type
::T_INT
,
304 $params['email_id'] = array(
305 'title' => 'Primary Email ID',
306 'type' => CRM_Utils_Type
::T_INT
,
308 $params['email'] = array(
309 'title' => 'Primary Email',
310 'type' => CRM_Utils_Type
::T_STRING
,
312 $params['on_hold'] = array(
313 'title' => 'Primary Email On Hold',
314 'type' => CRM_Utils_Type
::T_BOOLEAN
,
316 $params['im'] = array(
317 'title' => 'Primary Instant Messenger',
318 'type' => CRM_Utils_Type
::T_STRING
,
320 $params['im_id'] = array(
321 'title' => 'Primary Instant Messenger ID',
322 'type' => CRM_Utils_Type
::T_INT
,
324 $params['group'] = array(
326 'pseudoconstant' => array(
327 'table' => 'civicrm_group',
330 $params['tag'] = array(
332 'pseudoconstant' => array(
333 'table' => 'civicrm_tag',
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'));
343 * Support for historical oddities.
345 * We are supporting 'showAll' = 'all', 'trash' or 'active' for Contact get
347 * - hopefully some day we'll come up with a std syntax for the 3-way-boolean of
350 * We also support 'filter_group_id' & 'filter.group_id'
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).
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;
362 if (strtolower($params['showAll']) == "trash") {
363 $params['contact_is_deleted'] = 1;
365 if (strtolower($params['showAll']) == "all" && isset($params['contact_is_deleted'])) {
366 unset($params['contact_is_deleted']);
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']);
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'];
380 $groups = explode(',', $params['filter.group_id']);
382 unset($params['filter.group_id']);
383 $options['input_params']['group'] = $groups;
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);
396 // Now reset the $groups array with the ids not the titles.
397 $groups[key($groups)] = $groupsArray;
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);
405 if (!is_numeric($k) && array_search($k, $allGroups)) {
407 $groups[array_search($k, $allGroups)] = $group;
411 elseif (!is_numeric($groups) && array_search($groups, $allGroups)) {
412 $groups = array_search($groups, $allGroups);
414 $params['group'] = $groups;
419 * Delete a Contact with given contact_id.
421 * @param array $params
422 * input parameters per getfields
424 * @throws \Civi\API\Exception\UnauthorizedException
428 function civicrm_api3_contact_delete($params) {
429 $contactID = CRM_Utils_Array
::value('id', $params);
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');
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.');
439 $restore = !empty($params['restore']) ?
$params['restore'] : FALSE;
440 $skipUndelete = !empty($params['skip_undelete']) ?
$params['skip_undelete'] : FALSE;
443 // restrict permanent delete if a contact has financial trxn associated with it
445 if ($skipUndelete && CRM_Financial_BAO_FinancialItem
::checkContactPresent(array($contactID), $error)) {
446 return civicrm_api3_create_error($error['_qf_default']);
448 if (CRM_Contact_BAO_Contact
::deleteContact($contactID, $restore, $skipUndelete,
449 CRM_Utils_Array
::value('check_permissions', $params))) {
450 return civicrm_api3_create_success();
453 return civicrm_api3_create_error('Could not delete contact');
459 * Check parameters passed in.
461 * This function is on it's way out.
463 * @param array $params
466 * @throws API_Exception
467 * @throws CiviCRM_API3_Exception
469 function _civicrm_api3_contact_check_params(&$params) {
471 switch (strtolower(CRM_Utils_Array
::value('contact_type', $params))) {
473 civicrm_api3_verify_mandatory($params, NULL, array('household_name'));
477 civicrm_api3_verify_mandatory($params, NULL, array('organization_name'));
481 civicrm_api3_verify_one_mandatory($params, NULL, array(
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']);
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']));
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'],
508 $dupeIds = CRM_Contact_BAO_Contact
::getDuplicateContacts($organizationParams, 'Organization', 'Supervised', array(), FALSE);
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');
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.');
521 $params['employer_id'] = $dupeIds[0];
524 $result = civicrm_api3('Contact', 'create', array(
525 'organization_name' => $params['current_employer'],
526 'contact_type' => 'Organization',
528 $params['employer_id'] = $result['id'];
536 * Helper function for Contact create.
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.
543 * @return CRM_Contact_BAO_Contact|CRM_Core_Error
545 function _civicrm_api3_contact_update($params, $contactID = NULL) {
546 //@todo - doesn't contact create support 'id' which is already set- check & remove
548 $params['contact_id'] = $contactID;
551 return CRM_Contact_BAO_Contact
::create($params);
555 * Validate the addressee or email or postal greetings.
557 * @param array $params
558 * Array per getfields metadata.
560 * @throws API_Exception
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') {
570 $formatParams = FALSE;
571 // Unset display value from params.
572 if (isset($params["{$key}{$greeting}_display"])) {
573 unset($params["{$key}{$greeting}_display"]);
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;
584 if (!$formatParams) {
590 'contact_type' => $params['contact_type'],
591 'greeting_type' => "{$key}{$greeting}",
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);
599 if (!$greetingId && $greetingVal) {
600 $params["{$key}{$greeting}_id"] = CRM_Utils_Array
::key($params["{$key}{$greeting}"], $greetings);
603 if ($customGreeting && $greetingId &&
604 ($greetingId != array_search('Customized', $greetings))
606 throw new API_Exception(ts('Provide either %1 greeting id and/or %1 greeting or custom %1 greeting',
611 if ($greetingVal && $greetingId &&
612 ($greetingId != CRM_Utils_Array
::key($greetingVal, $greetings))
614 throw new API_Exception(ts('Mismatch in %1 greeting id and %1 greeting',
621 if (!array_key_exists($greetingId, $greetings)) {
622 throw new API_Exception(ts('Invalid %1 greeting Id', array(1 => $key)));
625 if (!$customGreeting && ($greetingId == array_search('Customized', $greetings))) {
626 throw new API_Exception(ts('Please provide a custom value for %1 greeting',
631 elseif ($greetingVal) {
633 if (!in_array($greetingVal, $greetings)) {
634 throw new API_Exception(ts('Invalid %1 greeting', array(1 => $key)));
637 $greetingId = CRM_Utils_Array
::key($greetingVal, $greetings);
640 if ($customGreeting) {
641 $greetingId = CRM_Utils_Array
::key('Customized', $greetings);
644 $customValue = isset($params['contact_id']) ? CRM_Core_DAO
::getFieldValue(
645 'CRM_Contact_DAO_Contact',
646 $params['contact_id'],
647 "{$key}{$greeting}_custom"
650 if (array_key_exists("{$key}{$greeting}_id", $params) && empty($params["{$key}{$greeting}_id"])) {
653 elseif (array_key_exists("{$key}{$greeting}", $params) && empty($params["{$key}{$greeting}"])) {
656 elseif ($customValue && array_key_exists("{$key}{$greeting}_custom", $params)
657 && empty($params["{$key}{$greeting}_custom"])
662 $params["{$key}{$greeting}_id"] = $greetingId;
664 if (!$customValue && !$customGreeting && array_key_exists("{$key}{$greeting}_custom", $params)) {
665 unset($params["{$key}{$greeting}_custom"]);
669 $params["{$key}{$greeting}_id"] = '';
670 $params["{$key}{$greeting}_custom"] = '';
673 if (isset($params["{$key}{$greeting}"])) {
674 unset($params["{$key}{$greeting}"]);
680 * Adjust Metadata for Get action.
682 * @param array $params
683 * Array of parameters determined by getfields.
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(
695 'external_identifier',
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';
711 * Old Contact quick search api.
715 * @param array $params
718 * @throws \API_Exception
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'
730 // get the option values for contact autocomplete
731 $acOptions = CRM_Core_OptionGroup
::values('contact_autocomplete_options', FALSE, FALSE, FALSE, NULL, 'name');
734 foreach ($acpref as $value) {
735 if ($value && !empty($acOptions[$value])) {
736 $list[$value] = $acOptions[$value];
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') {
746 // phone_numeric should be phone
747 $searchField = str_replace('_numeric', '', $field_name);
748 if (!in_array($searchField, $list)) {
749 $list[] = $searchField;
753 // Set field name to first name for exact match checking.
754 $field_name = 'sort_name';
757 $select = $actualSelectElements = array('sort_name');
760 foreach ($list as $value) {
761 $suffix = substr($value, 0, 2) . substr($value, -1);
763 case 'street_address':
766 $selectText = $value;
771 $actualSelectElements[] = $select[] = ($value == 'address') ?
$selectText : $value;
772 if ($value == 'phone') {
773 $actualSelectElements[] = $select[] = 'phone_ext';
775 $from[$value] = "LEFT JOIN civicrm_{$value} {$suffix} ON ( cc.id = {$suffix}.contact_id AND {$suffix}.is_primary = 1 ) ";
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) ';
785 $from[$value] = " LEFT JOIN civicrm_{$value} {$suffix} ON ( sts.{$value}_id = {$suffix}.id ) ";
789 if ($value != 'id') {
791 if (!empty($params['field_name']) && $params['field_name'] == 'value') {
792 $suffix = CRM_Utils_String
::munge(CRM_Utils_Array
::value('table_name', $params, 'cc'));
794 $actualSelectElements[] = $select[] = $suffix . '.' . $value;
800 $config = CRM_Core_Config
::singleton();
802 $select = implode(', ', $select);
803 if (!empty($select)) {
804 $select = ", $select";
806 $actualSelectElements = implode(', ', $actualSelectElements);
807 $selectAliases = $from;
808 unset($selectAliases['address']);
809 $selectAliases = implode(', ', array_keys($selectAliases));
810 if (!empty($selectAliases)) {
811 $selectAliases = ", $selectAliases";
813 $from = implode(' ', $from);
814 $limit = (int) CRM_Utils_Array
::value('limit', $params);
815 $limit = $limit > 0 ?
$limit : Civi
::settings()->get('search_autocomplete_count');
817 // add acl clause here
818 list($aclFrom, $aclWhere) = CRM_Contact_BAO_Contact_Permission
::cacheClause('cc');
821 $where .= " AND $aclWhere ";
823 $isPrependWildcard = \Civi
::settings()->get('includeWildCardInName');
825 if (!empty($params['org'])) {
826 $where .= " AND contact_type = \"Organization\"";
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'],
836 if ($isPrependWildcard) {
837 $strSearch = "%$name%";
840 $strSearch = "$name%";
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'");
847 $currEmpDetails = array(
849 'data' => $dao->data
,
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}'";
861 if (!empty($params['contact_type'])) {
862 $contactType = CRM_Utils_Type
::escape($params['contact_type'], 'String');
863 $where .= " AND cc.contact_type LIKE '{$contactType}'";
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'];
871 if (!empty($params['cid'])) {
872 $where .= " AND cc.id <> " . (int) $params['cid'];
875 // Contact's based of relationhip type
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');
883 if ($isPrependWildcard) {
884 $strSearch = "%$name%";
887 $strSearch = "$name%";
889 $includeEmailFrom = $includeNickName = $exactIncludeNickName = '';
890 if ($config->includeNickNameInName
) {
891 $includeNickName = " OR nick_name LIKE '$strSearch'";
892 $exactIncludeNickName = " OR nick_name LIKE '$name'";
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}";
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 )";
909 $emailWhere = " WHERE email LIKE '$strSearch'";
913 $additionalFrom = '';
916 INNER JOIN civicrm_relationship_type r ON (
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 )
923 // check if only CMS users are requested
924 if (!empty($params['cmsuser'])) {
926 INNER JOIN civicrm_uf_match um ON (um.contact_id=cc.id)
929 $orderBy = _civicrm_api3_quicksearch_get_order_by($name, $isPrependWildcard, $field_name);
933 SELECT DISTINCT(id), data, sort_name {$selectAliases}, exactFirst
935 ( SELECT IF($table_name.$field_name = '{$name}', 0, 1) as exactFirst, cc.id as id, CONCAT_WS( ' :: ',
936 {$actualSelectElements} )
939 FROM civicrm_contact cc {$from}
947 if (!empty($emailWhere)) {
950 SELECT IF($table_name.$field_name = '{$name}', 0, 1) as exactFirst, cc.id as id, CONCAT_WS( ' :: ',
951 {$actualSelectElements} )
954 FROM civicrm_contact cc {$from}
956 {$additionalFrom} {$includeEmailFrom}
957 {$emailWhere} AND cc.is_deleted = 0 " . ($aclWhere ?
" AND $aclWhere " : '') . "
968 // send query to hook to be modified if needed
969 CRM_Utils_Hook
::contactListQuery($query,
971 empty($params['context']) ?
NULL : CRM_Utils_Type
::escape($params['context'], 'String'),
972 empty($params['id']) ?
NULL : $params['id']
975 $dao = CRM_Core_DAO
::executeQuery($query);
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 : '';
984 $t['data'] = $dao->data
;
986 if (!empty($params['org']) &&
987 !empty($currEmpDetails) &&
988 $dao->id
== $currEmpDetails['id']
990 $listCurrentEmployer = FALSE;
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(
1000 'data' => $currEmpDetails['data'],
1001 'id' => $currEmpDetails['id'],
1006 $contactList = array(
1016 return civicrm_api3_create_success($contactList, $params, 'Contact', 'getquick');
1020 * Get the order by string for the quicksearch query.
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
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.
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.
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.
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.
1047 * @param string $name
1048 * @param bool $isPrependWildcard
1049 * @param string $field_name
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;
1059 if (!\Civi
::settings()->get('includeOrderByClause')) {
1060 return $skipExactMatch ?
'' : "ORDER BY exactFirst";
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";
1068 return "ORDER BY exactFirst, sort_name";
1072 * Declare deprecated api functions.
1074 * @deprecated api notice
1076 * Array of deprecated actions
1078 function _civicrm_api3_contact_deprecation() {
1079 return array('getquick' => 'The "getquick" action is deprecated in favor of "getlist".');
1083 * Merges given pair of duplicate contacts.
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.
1093 * @throws API_Exception
1095 function civicrm_api3_contact_merge($params) {
1096 if (($result = CRM_Dedupe_Merger
::merge(array(
1098 'srcID' => $params['to_remove_id'],
1099 'dstID' => $params['to_keep_id'],
1101 ), array(), $params['mode'])) != FALSE) {
1102 return civicrm_api3_create_success($result, $params);
1104 throw new API_Exception('Merge failed');
1108 * Adjust metadata for contact_merge api function.
1110 * @param array $params
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'),
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'),
1127 $params['mode'] = array(
1128 // @todo need more detail on what this means.
1129 'title' => 'Dedupe mode',
1130 'api.default' => 'safe',
1135 * Adjust metadata for contact_proximity api function.
1137 * @param array $params
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
,
1145 $params['longitude'] = array(
1146 'title' => 'Longitude',
1147 'api.required' => 1,
1148 'type' => CRM_Utils_Type
::T_STRING
,
1151 $params['unit'] = array(
1152 'title' => 'Unit of Measurement',
1153 'api.default' => 'meter',
1154 'type' => CRM_Utils_Type
::T_STRING
,
1159 * Get contacts by proximity.
1161 * @param array $params
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);
1171 $unit = CRM_Utils_Array
::value('unit', $params);
1173 // check and ensure that lat/long and distance are floats
1175 !CRM_Utils_Rule
::numeric($latitude) ||
1176 !CRM_Utils_Rule
::numeric($longitude) ||
1177 !CRM_Utils_Rule
::numeric($distance)
1179 throw new Exception(ts('Latitude, Longitude and Distance should exist and be numeric'));
1182 if ($unit == "mile") {
1183 $conversionFactor = 1609.344;
1186 $conversionFactor = 1000;
1188 //Distance in meters
1189 $distance = $distance * $conversionFactor;
1191 $whereClause = CRM_Contact_BAO_ProximityQuery
::where($latitude, $longitude, $distance);
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
1201 $dao = CRM_Core_DAO
::executeQuery($query);
1202 $contacts = array();
1203 while ($dao->fetch()) {
1204 $contacts[] = $dao->toArray();
1207 return civicrm_api3_create_success($contacts, $params, 'Contact', 'get_by_location', $dao);
1212 * Get parameters for getlist function.
1214 * @see _civicrm_api3_generic_getlist_params
1216 * @param array $request
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'
1226 // get the option values for contact autocomplete
1227 $acOptions = CRM_Core_OptionGroup
::values('contact_autocomplete_options', FALSE, FALSE, FALSE, NULL, 'name');
1230 foreach ($acpref as $value) {
1231 if ($value && !empty($acOptions[$value])) {
1232 $list[] = $acOptions[$value];
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') {
1241 // phone_numeric should be phone
1242 $searchField = str_replace('_numeric', '', $field_name);
1243 if (!in_array($searchField, $list)) {
1244 $list[] = $searchField;
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'];
1257 * Get output for getlist function.
1259 * @see _civicrm_api3_generic_getlist_output
1261 * @param array $result
1262 * @param array $request
1266 function _civicrm_api3_contact_getlist_output($result, $request) {
1268 if (!empty($result['values'])) {
1269 $addressFields = array_intersect(array(
1275 $request['params']['return']);
1276 foreach ($result['values'] as $row) {
1278 'id' => $row[$request['id_field']],
1279 'label' => $row[$request['label_field']],
1280 'description' => array(),
1282 foreach ($request['description_field'] as $item) {
1283 if (!strpos($item, '_name') && !in_array($item, $addressFields) && !empty($row[$item])) {
1284 $data['description'][] = $row[$item];
1288 foreach ($addressFields as $item) {
1289 if (!empty($row[$item])) {
1290 $address[] = $row[$item];
1294 $data['description'][] = implode(' ', $address);
1296 if (!empty($request['image_field'])) {
1297 $data['image'] = isset($row[$request['image_field']]) ?
$row[$request['image_field']] : '';
1300 $data['icon_class'] = $row['contact_type'];
1309 * Check for duplicate contacts.
1311 * @param array $params
1312 * Params per getfields metadata.
1315 * API formatted array
1317 function civicrm_api3_contact_duplicatecheck($params) {
1318 $dupes = CRM_Contact_BAO_Contact
::getDuplicateContacts(
1320 $params['match']['contact_type'],
1323 CRM_Utils_Array
::value('check_permissions', $params),
1324 CRM_Utils_Array
::value('dedupe_rule_id', $params)
1326 $values = empty($dupes) ?
array() : array_fill_keys($dupes, array());
1327 return civicrm_api3_create_success($values, $params, 'Contact', 'duplicatecheck');
1331 * Declare metadata for contact dedupe function.
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
,
1341 // @todo declare 'match' parameter. We don't have a standard for type = array yet.