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['supplemental_address_3'] = array(
216 'title' => 'Primary Address Supplemental Address 3',
217 'type' => CRM_Utils_Type
::T_STRING
,
219 $params['current_employer'] = array(
220 'title' => 'Current Employer',
221 'type' => CRM_Utils_Type
::T_STRING
,
223 $params['city'] = array(
224 'title' => 'Primary Address City',
225 'type' => CRM_Utils_Type
::T_STRING
,
227 $params['postal_code_suffix'] = array(
228 'title' => 'Primary Address Post Code Suffix',
229 'type' => CRM_Utils_Type
::T_STRING
,
231 $params['postal_code'] = array(
232 'title' => 'Primary Address Post Code',
233 'type' => CRM_Utils_Type
::T_STRING
,
235 $params['geo_code_1'] = array(
236 'title' => 'Primary Address Latitude',
237 'type' => CRM_Utils_Type
::T_STRING
,
239 $params['geo_code_2'] = array(
240 'title' => 'Primary Address Longitude',
241 'type' => CRM_Utils_Type
::T_STRING
,
243 $params['state_province_id'] = array(
244 'title' => 'Primary Address State Province ID',
245 'type' => CRM_Utils_Type
::T_INT
,
246 'pseudoconstant' => array(
247 'table' => 'civicrm_state_province',
250 $params['state_province_name'] = array(
251 'title' => 'Primary Address State Province Name',
252 'type' => CRM_Utils_Type
::T_STRING
,
253 'pseudoconstant' => array(
254 'table' => 'civicrm_state_province',
257 $params['state_province'] = array(
258 'title' => 'Primary Address State Province',
259 'type' => CRM_Utils_Type
::T_STRING
,
260 'pseudoconstant' => array(
261 'table' => 'civicrm_state_province',
264 $params['country_id'] = array(
265 'title' => 'Primary Address Country ID',
266 'type' => CRM_Utils_Type
::T_INT
,
267 'pseudoconstant' => array(
268 'table' => 'civicrm_country',
271 $params['country'] = array(
272 'title' => 'Primary Address country',
273 'type' => CRM_Utils_Type
::T_STRING
,
274 'pseudoconstant' => array(
275 'table' => 'civicrm_country',
278 $params['worldregion_id'] = array(
279 'title' => 'Primary Address World Region ID',
280 'type' => CRM_Utils_Type
::T_INT
,
281 'pseudoconstant' => array(
282 'table' => 'civicrm_world_region',
285 $params['worldregion'] = array(
286 'title' => 'Primary Address World Region',
287 'type' => CRM_Utils_Type
::T_STRING
,
288 'pseudoconstant' => array(
289 'table' => 'civicrm_world_region',
292 $params['phone_id'] = array(
293 'title' => 'Primary Phone ID',
294 'type' => CRM_Utils_Type
::T_INT
,
296 $params['phone'] = array(
297 'title' => 'Primary Phone',
298 'type' => CRM_Utils_Type
::T_STRING
,
300 $params['phone_type_id'] = array(
301 'title' => 'Primary Phone Type ID',
302 'type' => CRM_Utils_Type
::T_INT
,
304 $params['provider_id'] = array(
305 'title' => 'Primary Phone Provider ID',
306 'type' => CRM_Utils_Type
::T_INT
,
308 $params['email_id'] = array(
309 'title' => 'Primary Email ID',
310 'type' => CRM_Utils_Type
::T_INT
,
312 $params['email'] = array(
313 'title' => 'Primary Email',
314 'type' => CRM_Utils_Type
::T_STRING
,
316 $params['on_hold'] = array(
317 'title' => 'Primary Email On Hold',
318 'type' => CRM_Utils_Type
::T_BOOLEAN
,
320 $params['im'] = array(
321 'title' => 'Primary Instant Messenger',
322 'type' => CRM_Utils_Type
::T_STRING
,
324 $params['im_id'] = array(
325 'title' => 'Primary Instant Messenger ID',
326 'type' => CRM_Utils_Type
::T_INT
,
328 $params['group'] = array(
330 'pseudoconstant' => array(
331 'table' => 'civicrm_group',
334 $params['tag'] = array(
336 'pseudoconstant' => array(
337 'table' => 'civicrm_tag',
340 $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'));
341 $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'));
342 $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'));
343 $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'));
347 * Support for historical oddities.
349 * We are supporting 'showAll' = 'all', 'trash' or 'active' for Contact get
351 * - hopefully some day we'll come up with a std syntax for the 3-way-boolean of
354 * We also support 'filter_group_id' & 'filter.group_id'
356 * @param array $params
357 * As passed into api get or getcount function.
358 * @param array $options
359 * Array of options (so we can modify the filter).
361 function _civicrm_api3_contact_get_supportanomalies(&$params, &$options) {
362 if (isset($params['showAll'])) {
363 if (strtolower($params['showAll']) == "active") {
364 $params['contact_is_deleted'] = 0;
366 if (strtolower($params['showAll']) == "trash") {
367 $params['contact_is_deleted'] = 1;
369 if (strtolower($params['showAll']) == "all" && isset($params['contact_is_deleted'])) {
370 unset($params['contact_is_deleted']);
373 // support for group filters
374 if (array_key_exists('filter_group_id', $params)) {
375 $params['filter.group_id'] = $params['filter_group_id'];
376 unset($params['filter_group_id']);
378 // filter.group_id works both for 1,2,3 and array (1,2,3)
379 if (array_key_exists('filter.group_id', $params)) {
380 if (is_array($params['filter.group_id'])) {
381 $groups = $params['filter.group_id'];
384 $groups = explode(',', $params['filter.group_id']);
386 unset($params['filter.group_id']);
387 $options['input_params']['group'] = $groups;
389 if (isset($params['group'])) {
390 $groups = $params['group'];
391 $allGroups = CRM_Core_PseudoConstant
::group();
392 if (is_array($groups) && in_array(key($groups), CRM_Core_DAO
::acceptedSQLOperators(), TRUE)) {
393 // Get the groups array.
394 $groupsArray = $groups[key($groups)];
395 foreach ($groupsArray as &$group) {
396 if (!is_numeric($group) && array_search($group, $allGroups)) {
397 $group = array_search($group, $allGroups);
400 // Now reset the $groups array with the ids not the titles.
401 $groups[key($groups)] = $groupsArray;
403 // handle format like 'group' => array('title1', 'title2').
404 elseif (is_array($groups)) {
405 foreach ($groups as $k => &$group) {
406 if (!is_numeric($group) && array_search($group, $allGroups)) {
407 $group = array_search($group, $allGroups);
409 if (!is_numeric($k) && array_search($k, $allGroups)) {
411 $groups[array_search($k, $allGroups)] = $group;
415 elseif (!is_numeric($groups) && array_search($groups, $allGroups)) {
416 $groups = array_search($groups, $allGroups);
418 $params['group'] = $groups;
423 * Delete a Contact with given contact_id.
425 * @param array $params
426 * input parameters per getfields
428 * @throws \Civi\API\Exception\UnauthorizedException
432 function civicrm_api3_contact_delete($params) {
433 $contactID = CRM_Utils_Array
::value('id', $params);
435 if (!empty($params['check_permissions']) && !CRM_Contact_BAO_Contact_Permission
::allow($contactID, CRM_Core_Permission
::DELETE
)) {
436 throw new \Civi\API\Exception\
UnauthorizedException('Permission denied to modify contact record');
439 $session = CRM_Core_Session
::singleton();
440 if ($contactID == $session->get('userID')) {
441 return civicrm_api3_create_error('This contact record is linked to the currently logged in user account - and cannot be deleted.');
443 $restore = !empty($params['restore']) ?
$params['restore'] : FALSE;
444 $skipUndelete = !empty($params['skip_undelete']) ?
$params['skip_undelete'] : FALSE;
447 // restrict permanent delete if a contact has financial trxn associated with it
449 if ($skipUndelete && CRM_Financial_BAO_FinancialItem
::checkContactPresent(array($contactID), $error)) {
450 return civicrm_api3_create_error($error['_qf_default']);
452 if (CRM_Contact_BAO_Contact
::deleteContact($contactID, $restore, $skipUndelete,
453 CRM_Utils_Array
::value('check_permissions', $params))) {
454 return civicrm_api3_create_success();
457 return civicrm_api3_create_error('Could not delete contact');
463 * Check parameters passed in.
465 * This function is on it's way out.
467 * @param array $params
470 * @throws API_Exception
471 * @throws CiviCRM_API3_Exception
473 function _civicrm_api3_contact_check_params(&$params) {
475 switch (strtolower(CRM_Utils_Array
::value('contact_type', $params))) {
477 civicrm_api3_verify_mandatory($params, NULL, array('household_name'));
481 civicrm_api3_verify_mandatory($params, NULL, array('organization_name'));
485 civicrm_api3_verify_one_mandatory($params, NULL, array(
495 // Fixme: This really needs to be handled at a lower level. @See CRM-13123
496 if (isset($params['preferred_communication_method'])) {
497 $params['preferred_communication_method'] = CRM_Utils_Array
::implodePadded($params['preferred_communication_method']);
500 if (!empty($params['contact_sub_type']) && !empty($params['contact_type'])) {
501 if (!(CRM_Contact_BAO_ContactType
::isExtendsContactType($params['contact_sub_type'], $params['contact_type']))) {
502 throw new API_Exception("Invalid or Mismatched Contact Subtype: " . implode(', ', (array) $params['contact_sub_type']));
506 // The BAO no longer supports the legacy param "current_employer" so here is a shim for api backward-compatability
507 if (!empty($params['current_employer'])) {
508 $organizationParams = array(
509 'organization_name' => $params['current_employer'],
512 $dupeIds = CRM_Contact_BAO_Contact
::getDuplicateContacts($organizationParams, 'Organization', 'Supervised', array(), FALSE);
514 // check for mismatch employer name and id
515 if (!empty($params['employer_id']) && !in_array($params['employer_id'], $dupeIds)) {
516 throw new API_Exception('Employer name and Employer id Mismatch');
519 // show error if multiple organisation with same name exist
520 if (empty($params['employer_id']) && (count($dupeIds) > 1)) {
521 throw new API_Exception('Found more than one Organisation with same Name.');
525 $params['employer_id'] = $dupeIds[0];
528 $result = civicrm_api3('Contact', 'create', array(
529 'organization_name' => $params['current_employer'],
530 'contact_type' => 'Organization',
532 $params['employer_id'] = $result['id'];
540 * Helper function for Contact create.
542 * @param array $params
543 * (reference ) an assoc array of name/value pairs.
544 * @param int $contactID
545 * If present the contact with that ID is updated.
547 * @return CRM_Contact_BAO_Contact|CRM_Core_Error
549 function _civicrm_api3_contact_update($params, $contactID = NULL) {
550 //@todo - doesn't contact create support 'id' which is already set- check & remove
552 $params['contact_id'] = $contactID;
555 return CRM_Contact_BAO_Contact
::create($params);
559 * Validate the addressee or email or postal greetings.
561 * @param array $params
562 * Array per getfields metadata.
564 * @throws API_Exception
566 function _civicrm_api3_greeting_format_params($params) {
567 $greetingParams = array('', '_id', '_custom');
568 foreach (array('email', 'postal', 'addressee') as $key) {
569 $greeting = '_greeting';
570 if ($key == 'addressee') {
574 $formatParams = FALSE;
575 // Unset display value from params.
576 if (isset($params["{$key}{$greeting}_display"])) {
577 unset($params["{$key}{$greeting}_display"]);
580 // check if greetings are present in present
581 foreach ($greetingParams as $greetingValues) {
582 if (array_key_exists("{$key}{$greeting}{$greetingValues}", $params)) {
583 $formatParams = TRUE;
588 if (!$formatParams) {
594 'contact_type' => $params['contact_type'],
595 'greeting_type' => "{$key}{$greeting}",
598 $greetings = CRM_Core_PseudoConstant
::greeting($filter);
599 $greetingId = CRM_Utils_Array
::value("{$key}{$greeting}_id", $params);
600 $greetingVal = CRM_Utils_Array
::value("{$key}{$greeting}", $params);
601 $customGreeting = CRM_Utils_Array
::value("{$key}{$greeting}_custom", $params);
603 if (!$greetingId && $greetingVal) {
604 $params["{$key}{$greeting}_id"] = CRM_Utils_Array
::key($params["{$key}{$greeting}"], $greetings);
607 if ($customGreeting && $greetingId &&
608 ($greetingId != array_search('Customized', $greetings))
610 throw new API_Exception(ts('Provide either %1 greeting id and/or %1 greeting or custom %1 greeting',
615 if ($greetingVal && $greetingId &&
616 ($greetingId != CRM_Utils_Array
::key($greetingVal, $greetings))
618 throw new API_Exception(ts('Mismatch in %1 greeting id and %1 greeting',
625 if (!array_key_exists($greetingId, $greetings)) {
626 throw new API_Exception(ts('Invalid %1 greeting Id', array(1 => $key)));
629 if (!$customGreeting && ($greetingId == array_search('Customized', $greetings))) {
630 throw new API_Exception(ts('Please provide a custom value for %1 greeting',
635 elseif ($greetingVal) {
637 if (!in_array($greetingVal, $greetings)) {
638 throw new API_Exception(ts('Invalid %1 greeting', array(1 => $key)));
641 $greetingId = CRM_Utils_Array
::key($greetingVal, $greetings);
644 if ($customGreeting) {
645 $greetingId = CRM_Utils_Array
::key('Customized', $greetings);
648 $customValue = isset($params['contact_id']) ? CRM_Core_DAO
::getFieldValue(
649 'CRM_Contact_DAO_Contact',
650 $params['contact_id'],
651 "{$key}{$greeting}_custom"
654 if (array_key_exists("{$key}{$greeting}_id", $params) && empty($params["{$key}{$greeting}_id"])) {
657 elseif (array_key_exists("{$key}{$greeting}", $params) && empty($params["{$key}{$greeting}"])) {
660 elseif ($customValue && array_key_exists("{$key}{$greeting}_custom", $params)
661 && empty($params["{$key}{$greeting}_custom"])
666 $params["{$key}{$greeting}_id"] = $greetingId;
668 if (!$customValue && !$customGreeting && array_key_exists("{$key}{$greeting}_custom", $params)) {
669 unset($params["{$key}{$greeting}_custom"]);
673 $params["{$key}{$greeting}_id"] = '';
674 $params["{$key}{$greeting}_custom"] = '';
677 if (isset($params["{$key}{$greeting}"])) {
678 unset($params["{$key}{$greeting}"]);
684 * Adjust Metadata for Get action.
686 * @param array $params
687 * Array of parameters determined by getfields.
689 function _civicrm_api3_contact_getquick_spec(&$params) {
690 $params['name']['api.required'] = TRUE;
691 $params['name']['title'] = ts('String to search on');
692 $params['name']['type'] = CRM_Utils_Type
::T_STRING
;
693 $params['field']['type'] = CRM_Utils_Type
::T_STRING
;
694 $params['field']['title'] = ts('Field to search on');
695 $params['field']['options'] = array(
699 'external_identifier',
709 $params['table_name']['type'] = CRM_Utils_Type
::T_STRING
;
710 $params['table_name']['title'] = ts('Table alias to search on');
711 $params['table_name']['api.default'] = 'cc';
715 * Old Contact quick search api.
719 * @param array $params
722 * @throws \API_Exception
724 function civicrm_api3_contact_getquick($params) {
725 $name = CRM_Utils_Type
::escape(CRM_Utils_Array
::value('name', $params), 'String');
726 $table_name = CRM_Utils_String
::munge($params['table_name']);
727 // get the autocomplete options from settings
728 $acpref = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
729 CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
,
730 'contact_autocomplete_options'
734 // get the option values for contact autocomplete
735 $acOptions = CRM_Core_OptionGroup
::values('contact_autocomplete_options', FALSE, FALSE, FALSE, NULL, 'name');
738 foreach ($acpref as $value) {
739 if ($value && !empty($acOptions[$value])) {
740 $list[$value] = $acOptions[$value];
743 // If we are doing quicksearch by a field other than name, make sure that field is added to results
744 if (!empty($params['field_name'])) {
745 $field_name = CRM_Utils_String
::munge($params['field_name']);
746 // Unique name contact_id = id
747 if ($field_name == 'contact_id') {
750 // phone_numeric should be phone
751 $searchField = str_replace('_numeric', '', $field_name);
752 if (!in_array($searchField, $list)) {
753 $list[] = $searchField;
757 // Set field name to first name for exact match checking.
758 $field_name = 'sort_name';
761 $select = $actualSelectElements = array('sort_name');
764 foreach ($list as $value) {
765 $suffix = substr($value, 0, 2) . substr($value, -1);
767 case 'street_address':
770 $selectText = $value;
775 $actualSelectElements[] = $select[] = ($value == 'address') ?
$selectText : $value;
776 if ($value == 'phone') {
777 $actualSelectElements[] = $select[] = 'phone_ext';
779 $from[$value] = "LEFT JOIN civicrm_{$value} {$suffix} ON ( cc.id = {$suffix}.contact_id AND {$suffix}.is_primary = 1 ) ";
783 case 'state_province':
784 $select[] = "{$suffix}.name as {$value}";
785 $actualSelectElements[] = "{$suffix}.name";
786 if (!in_array('address', $from)) {
787 $from['address'] = 'LEFT JOIN civicrm_address sts ON ( cc.id = sts.contact_id AND sts.is_primary = 1) ';
789 $from[$value] = " LEFT JOIN civicrm_{$value} {$suffix} ON ( sts.{$value}_id = {$suffix}.id ) ";
793 if ($value != 'id') {
795 if (!empty($params['field_name']) && $params['field_name'] == 'value') {
796 $suffix = CRM_Utils_String
::munge(CRM_Utils_Array
::value('table_name', $params, 'cc'));
798 $actualSelectElements[] = $select[] = $suffix . '.' . $value;
804 $config = CRM_Core_Config
::singleton();
806 $select = implode(', ', $select);
807 if (!empty($select)) {
808 $select = ", $select";
810 $actualSelectElements = implode(', ', $actualSelectElements);
811 $selectAliases = $from;
812 unset($selectAliases['address']);
813 $selectAliases = implode(', ', array_keys($selectAliases));
814 if (!empty($selectAliases)) {
815 $selectAliases = ", $selectAliases";
817 $from = implode(' ', $from);
818 $limit = (int) CRM_Utils_Array
::value('limit', $params);
819 $limit = $limit > 0 ?
$limit : Civi
::settings()->get('search_autocomplete_count');
821 // add acl clause here
822 list($aclFrom, $aclWhere) = CRM_Contact_BAO_Contact_Permission
::cacheClause('cc');
825 $where .= " AND $aclWhere ";
827 $isPrependWildcard = \Civi
::settings()->get('includeWildCardInName');
829 if (!empty($params['org'])) {
830 $where .= " AND contact_type = \"Organization\"";
832 // CRM-7157, hack: get current employer details when
833 // employee_id is present.
834 $currEmpDetails = array();
835 if (!empty($params['employee_id'])) {
836 if ($currentEmployer = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact',
837 (int) $params['employee_id'],
840 if ($isPrependWildcard) {
841 $strSearch = "%$name%";
844 $strSearch = "$name%";
847 // get current employer details
848 $dao = CRM_Core_DAO
::executeQuery("SELECT cc.id as id, CONCAT_WS( ' :: ', {$actualSelectElements} ) as data, sort_name
849 FROM civicrm_contact cc {$from} WHERE cc.contact_type = \"Organization\" AND cc.id = {$currentEmployer} AND cc.sort_name LIKE '$strSearch'");
851 $currEmpDetails = array(
853 'data' => $dao->data
,
860 if (!empty($params['contact_sub_type'])) {
861 $contactSubType = CRM_Utils_Type
::escape($params['contact_sub_type'], 'String');
862 $where .= " AND cc.contact_sub_type = '{$contactSubType}'";
865 if (!empty($params['contact_type'])) {
866 $contactType = CRM_Utils_Type
::escape($params['contact_type'], 'String');
867 $where .= " AND cc.contact_type LIKE '{$contactType}'";
870 // Set default for current_employer or return contact with particular id
871 if (!empty($params['id'])) {
872 $where .= " AND cc.id = " . (int) $params['id'];
875 if (!empty($params['cid'])) {
876 $where .= " AND cc.id <> " . (int) $params['cid'];
879 // Contact's based of relationhip type
881 if (!empty($params['rel'])) {
882 $relation = explode('_', CRM_Utils_Array
::value('rel', $params));
883 $relType = CRM_Utils_Type
::escape($relation[0], 'Integer');
884 $rel = CRM_Utils_Type
::escape($relation[2], 'String');
887 if ($isPrependWildcard) {
888 $strSearch = "%$name%";
891 $strSearch = "$name%";
893 $includeEmailFrom = $includeNickName = $exactIncludeNickName = '';
894 if ($config->includeNickNameInName
) {
895 $includeNickName = " OR nick_name LIKE '$strSearch'";
896 $exactIncludeNickName = " OR nick_name LIKE '$name'";
900 if (!empty($params['field_name']) && !empty($params['table_name'])) {
901 $whereClause = " WHERE ( $table_name.$field_name LIKE '$strSearch') {$where}";
902 // Search by id should be exact
903 if ($field_name == 'id' ||
$field_name == 'external_identifier') {
904 $whereClause = " WHERE ( $table_name.$field_name = '$name') {$where}";
908 $whereClause = " WHERE ( sort_name LIKE '$strSearch' $includeNickName ) {$where} ";
909 if ($config->includeEmailInName
) {
910 if (!in_array('email', $list)) {
911 $includeEmailFrom = "LEFT JOIN civicrm_email eml ON ( cc.id = eml.contact_id AND eml.is_primary = 1 )";
913 $emailWhere = " WHERE email LIKE '$strSearch'";
917 $additionalFrom = '';
920 INNER JOIN civicrm_relationship_type r ON (
922 AND ( cc.contact_type = r.contact_type_{$rel} OR r.contact_type_{$rel} IS NULL )
923 AND ( cc.contact_sub_type = r.contact_sub_type_{$rel} OR r.contact_sub_type_{$rel} IS NULL )
927 // check if only CMS users are requested
928 if (!empty($params['cmsuser'])) {
930 INNER JOIN civicrm_uf_match um ON (um.contact_id=cc.id)
933 $orderBy = _civicrm_api3_quicksearch_get_order_by($name, $isPrependWildcard, $field_name);
937 SELECT DISTINCT(id), data, sort_name {$selectAliases}, exactFirst
939 ( SELECT IF($table_name.$field_name = '{$name}', 0, 1) as exactFirst, cc.id as id, CONCAT_WS( ' :: ',
940 {$actualSelectElements} )
943 FROM civicrm_contact cc {$from}
951 if (!empty($emailWhere)) {
954 SELECT IF($table_name.$field_name = '{$name}', 0, 1) as exactFirst, cc.id as id, CONCAT_WS( ' :: ',
955 {$actualSelectElements} )
958 FROM civicrm_contact cc {$from}
960 {$additionalFrom} {$includeEmailFrom}
961 {$emailWhere} AND cc.is_deleted = 0 " . ($aclWhere ?
" AND $aclWhere " : '') . "
972 // send query to hook to be modified if needed
973 CRM_Utils_Hook
::contactListQuery($query,
975 empty($params['context']) ?
NULL : CRM_Utils_Type
::escape($params['context'], 'String'),
976 empty($params['id']) ?
NULL : $params['id']
979 $dao = CRM_Core_DAO
::executeQuery($query);
981 $contactList = array();
982 $listCurrentEmployer = TRUE;
983 while ($dao->fetch()) {
984 $t = array('id' => $dao->id
);
985 foreach ($as as $k) {
986 $t[$k] = isset($dao->$k) ?
$dao->$k : '';
988 $t['data'] = $dao->data
;
990 if (!empty($params['org']) &&
991 !empty($currEmpDetails) &&
992 $dao->id
== $currEmpDetails['id']
994 $listCurrentEmployer = FALSE;
998 //return organization name if doesn't exist in db
999 if (empty($contactList)) {
1000 if (!empty($params['org'])) {
1001 if ($listCurrentEmployer && !empty($currEmpDetails)) {
1002 $contactList = array(
1004 'data' => $currEmpDetails['data'],
1005 'id' => $currEmpDetails['id'],
1010 $contactList = array(
1020 return civicrm_api3_create_success($contactList, $params, 'Contact', 'getquick');
1024 * Get the order by string for the quicksearch query.
1026 * Get the order by string. The string might be
1027 * - sort name if there is no search value provided and the site is configured
1028 * to search by sort name
1029 * - empty if there is no search value provided and the site is not configured
1030 * to search by sort name
1031 * - exactFirst and then sort name if a search value is provided and the site is configured
1032 * to search by sort name
1033 * - exactFirst if a search value is provided and the site is not configured
1034 * to search by sort name
1036 * exactFirst means 'yes if the search value exactly matches the searched field. else no'.
1037 * It is intended to prioritise exact matches for the entered string so on a first name search
1038 * for 'kath' contacts with a first name of exactly Kath rise to the top.
1040 * On short strings it is expensive. Per CRM-19547 there is still an open question
1041 * as to whether we should only do exactMatch on a minimum length or on certain fields.
1043 * However, we have mitigated this somewhat by not doing an exact match search on
1044 * empty strings, non-wildcard sort-name searches and email searches where there is
1045 * no @ after the first character.
1047 * For the user it is further mitigated by the fact they just don't know the
1048 * slower queries are firing. If they type 'smit' slowly enough 4 queries will trigger
1049 * but if the first 3 are slow the first result they see may be off the 4th query.
1051 * @param string $name
1052 * @param bool $isPrependWildcard
1053 * @param string $field_name
1057 function _civicrm_api3_quicksearch_get_order_by($name, $isPrependWildcard, $field_name) {
1058 $skipExactMatch = ($name === '%');
1059 if ($field_name === 'email' && !strpos('@', $name)) {
1060 $skipExactMatch = TRUE;
1063 if (!\Civi
::settings()->get('includeOrderByClause')) {
1064 return $skipExactMatch ?
'' : "ORDER BY exactFirst";
1066 if ($skipExactMatch ||
(!$isPrependWildcard && $field_name === 'sort_name')) {
1067 // If there is no wildcard then sorting by exactFirst would have the same
1068 // effect as just a sort_name search, but slower.
1069 return "ORDER BY sort_name";
1072 return "ORDER BY exactFirst, sort_name";
1076 * Declare deprecated api functions.
1078 * @deprecated api notice
1080 * Array of deprecated actions
1082 function _civicrm_api3_contact_deprecation() {
1083 return array('getquick' => 'The "getquick" action is deprecated in favor of "getlist".');
1087 * Merges given pair of duplicate contacts.
1089 * @param array $params
1090 * Allowed array keys are:
1091 * -int main_id: main contact id with whom merge has to happen
1092 * -int other_id: duplicate contact which would be deleted after merge operation
1093 * -string mode: "safe" skips the merge if there are no conflicts. Does a force merge otherwise.
1097 * @throws API_Exception
1099 function civicrm_api3_contact_merge($params) {
1100 if (($result = CRM_Dedupe_Merger
::merge(array(
1102 'srcID' => $params['to_remove_id'],
1103 'dstID' => $params['to_keep_id'],
1105 ), array(), $params['mode'])) != FALSE) {
1106 return civicrm_api3_create_success($result, $params);
1108 throw new API_Exception('Merge failed');
1112 * Adjust metadata for contact_merge api function.
1114 * @param array $params
1116 function _civicrm_api3_contact_merge_spec(&$params) {
1117 $params['to_remove_id'] = array(
1118 'title' => 'ID of the contact to merge & remove',
1119 'description' => ts('Wow - these 2 params are the logical reverse of what I expect - but what to do?'),
1120 'api.required' => 1,
1121 'type' => CRM_Utils_Type
::T_INT
,
1122 'api.aliases' => array('main_id'),
1124 $params['to_keep_id'] = array(
1125 'title' => 'ID of the contact to keep',
1126 'description' => ts('Wow - these 2 params are the logical reverse of what I expect - but what to do?'),
1127 'api.required' => 1,
1128 'type' => CRM_Utils_Type
::T_INT
,
1129 'api.aliases' => array('other_id'),
1131 $params['mode'] = array(
1132 // @todo need more detail on what this means.
1133 'title' => 'Dedupe mode',
1134 'api.default' => 'safe',
1139 * Adjust metadata for contact_proximity api function.
1141 * @param array $params
1143 function _civicrm_api3_contact_proximity_spec(&$params) {
1144 $params['latitude'] = array(
1145 'title' => 'Latitude',
1146 'api.required' => 1,
1147 'type' => CRM_Utils_Type
::T_STRING
,
1149 $params['longitude'] = array(
1150 'title' => 'Longitude',
1151 'api.required' => 1,
1152 'type' => CRM_Utils_Type
::T_STRING
,
1155 $params['unit'] = array(
1156 'title' => 'Unit of Measurement',
1157 'api.default' => 'meter',
1158 'type' => CRM_Utils_Type
::T_STRING
,
1163 * Get contacts by proximity.
1165 * @param array $params
1170 function civicrm_api3_contact_proximity($params) {
1171 $latitude = CRM_Utils_Array
::value('latitude', $params);
1172 $longitude = CRM_Utils_Array
::value('longitude', $params);
1173 $distance = CRM_Utils_Array
::value('distance', $params);
1175 $unit = CRM_Utils_Array
::value('unit', $params);
1177 // check and ensure that lat/long and distance are floats
1179 !CRM_Utils_Rule
::numeric($latitude) ||
1180 !CRM_Utils_Rule
::numeric($longitude) ||
1181 !CRM_Utils_Rule
::numeric($distance)
1183 throw new Exception(ts('Latitude, Longitude and Distance should exist and be numeric'));
1186 if ($unit == "mile") {
1187 $conversionFactor = 1609.344;
1190 $conversionFactor = 1000;
1192 //Distance in meters
1193 $distance = $distance * $conversionFactor;
1195 $whereClause = CRM_Contact_BAO_ProximityQuery
::where($latitude, $longitude, $distance);
1198 SELECT civicrm_contact.id as contact_id,
1199 civicrm_contact.display_name as display_name
1200 FROM civicrm_contact
1201 LEFT JOIN civicrm_address ON civicrm_contact.id = civicrm_address.contact_id
1205 $dao = CRM_Core_DAO
::executeQuery($query);
1206 $contacts = array();
1207 while ($dao->fetch()) {
1208 $contacts[] = $dao->toArray();
1211 return civicrm_api3_create_success($contacts, $params, 'Contact', 'get_by_location', $dao);
1216 * Get parameters for getlist function.
1218 * @see _civicrm_api3_generic_getlist_params
1220 * @param array $request
1222 function _civicrm_api3_contact_getlist_params(&$request) {
1223 // get the autocomplete options from settings
1224 $acpref = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1225 CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
,
1226 'contact_autocomplete_options'
1230 // get the option values for contact autocomplete
1231 $acOptions = CRM_Core_OptionGroup
::values('contact_autocomplete_options', FALSE, FALSE, FALSE, NULL, 'name');
1234 foreach ($acpref as $value) {
1235 if ($value && !empty($acOptions[$value])) {
1236 $list[] = $acOptions[$value];
1239 // If we are doing quicksearch by a field other than name, make sure that field is added to results
1240 $field_name = CRM_Utils_String
::munge($request['search_field']);
1241 // Unique name contact_id = id
1242 if ($field_name == 'contact_id') {
1245 // phone_numeric should be phone
1246 $searchField = str_replace('_numeric', '', $field_name);
1247 if (!in_array($searchField, $list)) {
1248 $list[] = $searchField;
1250 $request['description_field'] = $list;
1251 $list[] = 'contact_type';
1252 $request['params']['return'] = array_unique(array_merge($list, $request['extra']));
1253 $request['params']['options']['sort'] = 'sort_name';
1254 // Contact api doesn't support array(LIKE => 'foo') syntax
1255 if (!empty($request['input'])) {
1256 $request['params'][$request['search_field']] = $request['input'];
1261 * Get output for getlist function.
1263 * @see _civicrm_api3_generic_getlist_output
1265 * @param array $result
1266 * @param array $request
1270 function _civicrm_api3_contact_getlist_output($result, $request) {
1272 if (!empty($result['values'])) {
1273 $addressFields = array_intersect(array(
1279 $request['params']['return']);
1280 foreach ($result['values'] as $row) {
1282 'id' => $row[$request['id_field']],
1283 'label' => $row[$request['label_field']],
1284 'description' => array(),
1286 foreach ($request['description_field'] as $item) {
1287 if (!strpos($item, '_name') && !in_array($item, $addressFields) && !empty($row[$item])) {
1288 $data['description'][] = $row[$item];
1292 foreach ($addressFields as $item) {
1293 if (!empty($row[$item])) {
1294 $address[] = $row[$item];
1298 $data['description'][] = implode(' ', $address);
1300 if (!empty($request['image_field'])) {
1301 $data['image'] = isset($row[$request['image_field']]) ?
$row[$request['image_field']] : '';
1304 $data['icon_class'] = $row['contact_type'];
1313 * Check for duplicate contacts.
1315 * @param array $params
1316 * Params per getfields metadata.
1319 * API formatted array
1321 function civicrm_api3_contact_duplicatecheck($params) {
1322 $dupes = CRM_Contact_BAO_Contact
::getDuplicateContacts(
1324 $params['match']['contact_type'],
1327 CRM_Utils_Array
::value('check_permissions', $params),
1328 CRM_Utils_Array
::value('dedupe_rule_id', $params)
1330 $values = empty($dupes) ?
array() : array_fill_keys($dupes, array());
1331 return civicrm_api3_create_success($values, $params, 'Contact', 'duplicatecheck');
1335 * Declare metadata for contact dedupe function.
1339 function _civicrm_api3_contact_duplicatecheck_spec(&$params) {
1340 $params['dedupe_rule_id'] = array(
1341 'title' => 'Dedupe Rule ID (optional)',
1342 'description' => 'This will default to the built in unsupervised rule',
1343 'type' => CRM_Utils_Type
::T_INT
,
1345 // @todo declare 'match' parameter. We don't have a standard for type = array yet.