3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2015 |
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 $dupeCheck = CRM_Utils_Array
::value('dupe_check', $params, FALSE);
59 $values = _civicrm_api3_contact_check_params($params, $dupeCheck);
65 // If we get here, we're ready to create a new contact
66 if (($email = CRM_Utils_Array
::value('email', $params)) && !is_array($params['email'])) {
67 $defLocType = CRM_Core_BAO_LocationType
::getDefault();
68 $params['email'] = array(
72 'location_type_id' => ($defLocType->id
) ?
$defLocType->id
: 1,
78 if (!empty($params['home_url'])) {
79 $websiteTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Website', 'website_type_id');
80 $params['website'] = array(
82 'website_type_id' => key($websiteTypes),
83 'url' => $params['home_url'],
88 _civicrm_api3_greeting_format_params($params);
92 if (empty($params['contact_type']) && $contactID) {
93 $params['contact_type'] = CRM_Contact_BAO_Contact
::getContactType($contactID);
96 if (!isset($params['contact_sub_type']) && $contactID) {
97 $params['contact_sub_type'] = CRM_Contact_BAO_Contact
::getContactSubType($contactID);
100 _civicrm_api3_custom_format_params($params, $values, $params['contact_type'], $contactID);
102 $params = array_merge($params, $values);
103 //@todo we should just call basic_create here - but need to make contact:create accept 'id' on the bao
104 $contact = _civicrm_api3_contact_update($params, $contactID);
106 if (is_a($contact, 'CRM_Core_Error')) {
107 throw new API_Exception($contact->_errors
[0]['message']);
111 _civicrm_api3_object_to_array_unique_fields($contact, $values[$contact->id
]);
114 return civicrm_api3_create_success($values, $params, 'Contact', 'create');
118 * Adjust Metadata for Create action.
120 * @param array $params
121 * Array of parameters determined by getfields.
123 function _civicrm_api3_contact_create_spec(&$params) {
124 $params['contact_type']['api.required'] = 1;
125 $params['id']['api.aliases'] = array('contact_id');
126 $params['current_employer'] = array(
127 'title' => 'Current Employer',
128 'description' => 'Name of Current Employer',
129 'type' => CRM_Utils_Type
::T_STRING
,
131 $params['dupe_check'] = array(
132 'title' => 'Check for Duplicates',
133 'description' => 'Throw error if contact create matches dedupe rule',
134 'type' => CRM_Utils_Type
::T_BOOLEAN
,
136 $params['prefix_id']['api.aliases'] = array('individual_prefix', 'individual_prefix_id');
137 $params['suffix_id']['api.aliases'] = array('individual_suffix', 'individual_suffix_id');
138 $params['gender_id']['api.aliases'] = array('gender');
142 * Retrieve one or more contacts, given a set of search params.
144 * @param array $params
149 function civicrm_api3_contact_get($params) {
151 _civicrm_api3_contact_get_supportanomalies($params, $options);
152 $contacts = _civicrm_api3_get_using_query_object('Contact', $params, $options);
153 return civicrm_api3_create_success($contacts, $params, 'Contact');
157 * Get number of contacts matching the supplied criteria.
159 * @param array $params
163 function civicrm_api3_contact_getcount($params) {
165 _civicrm_api3_contact_get_supportanomalies($params, $options);
166 $count = _civicrm_api3_get_using_query_object('Contact', $params, $options, 1);
171 * Adjust Metadata for Get action.
173 * @param array $params
174 * Array of parameters determined by getfields.
176 function _civicrm_api3_contact_get_spec(&$params) {
177 $params['contact_is_deleted']['api.default'] = 0;
179 // We declare all these pseudoFields as there are other undocumented fields accessible
180 // via the api - but if check permissions is set we only allow declared fields
181 $params['address_id'] = array(
182 'title' => 'Primary Address ID',
183 'type' => CRM_Utils_Type
::T_INT
,
185 $params['street_address'] = array(
186 'title' => 'Primary Address Street Address',
187 'type' => CRM_Utils_Type
::T_STRING
,
189 $params['supplemental_address_1'] = array(
190 'title' => 'Primary Address Supplemental Address 1',
191 'type' => CRM_Utils_Type
::T_STRING
,
193 $params['supplemental_address_2'] = array(
194 'title' => 'Primary Address Supplemental Address 2',
195 'type' => CRM_Utils_Type
::T_STRING
,
197 $params['current_employer'] = array(
198 'title' => 'Current Employer',
199 'type' => CRM_Utils_Type
::T_STRING
,
201 $params['city'] = array(
202 'title' => 'Primary Address City',
203 'type' => CRM_Utils_Type
::T_STRING
,
205 $params['postal_code_suffix'] = array(
206 'title' => 'Primary Address Post Code Suffix',
207 'type' => CRM_Utils_Type
::T_STRING
,
209 $params['postal_code'] = array(
210 'title' => 'Primary Address Post Code',
211 'type' => CRM_Utils_Type
::T_STRING
,
213 $params['geo_code_1'] = array(
214 'title' => 'Primary Address Latitude',
215 'type' => CRM_Utils_Type
::T_STRING
,
217 $params['geo_code_2'] = array(
218 'title' => 'Primary Address Longitude',
219 'type' => CRM_Utils_Type
::T_STRING
,
221 $params['state_province_id'] = array(
222 'title' => 'Primary Address State Province ID',
223 'type' => CRM_Utils_Type
::T_INT
,
224 'pseudoconstant' => array(
225 'table' => 'civicrm_state_province',
228 $params['state_province_name'] = array(
229 'title' => 'Primary Address State Province Name',
230 'type' => CRM_Utils_Type
::T_STRING
,
231 'pseudoconstant' => array(
232 'table' => 'civicrm_state_province',
235 $params['state_province'] = array(
236 'title' => 'Primary Address State Province',
237 'type' => CRM_Utils_Type
::T_STRING
,
238 'pseudoconstant' => array(
239 'table' => 'civicrm_state_province',
242 $params['country_id'] = array(
243 'title' => 'Primary Address Country ID',
244 'type' => CRM_Utils_Type
::T_INT
,
245 'pseudoconstant' => array(
246 'table' => 'civicrm_country',
249 $params['country'] = array(
250 'title' => 'Primary Address country',
251 'type' => CRM_Utils_Type
::T_STRING
,
252 'pseudoconstant' => array(
253 'table' => 'civicrm_country',
256 $params['worldregion_id'] = array(
257 'title' => 'Primary Address World Region ID',
258 'type' => CRM_Utils_Type
::T_INT
,
259 'pseudoconstant' => array(
260 'table' => 'civicrm_world_region',
263 $params['worldregion'] = array(
264 'title' => 'Primary Address World Region',
265 'type' => CRM_Utils_Type
::T_STRING
,
266 'pseudoconstant' => array(
267 'table' => 'civicrm_world_region',
270 $params['phone_id'] = array(
271 'title' => 'Primary Phone ID',
272 'type' => CRM_Utils_Type
::T_INT
,
274 $params['phone'] = array(
275 'title' => 'Primary Phone',
276 'type' => CRM_Utils_Type
::T_STRING
,
278 $params['phone_type_id'] = array(
279 'title' => 'Primary Phone Type ID',
280 'type' => CRM_Utils_Type
::T_INT
,
282 $params['provider_id'] = array(
283 'title' => 'Primary Phone Provider ID',
284 'type' => CRM_Utils_Type
::T_INT
,
286 $params['email_id'] = array(
287 'title' => 'Primary Email ID',
288 'type' => CRM_Utils_Type
::T_INT
,
290 $params['email'] = array(
291 'title' => 'Primary Email',
292 'type' => CRM_Utils_Type
::T_STRING
,
294 $params['on_hold'] = array(
295 'title' => 'Primary Email On Hold',
296 'type' => CRM_Utils_Type
::T_BOOLEAN
,
298 $params['im'] = array(
299 'title' => 'Primary Instant Messenger',
300 'type' => CRM_Utils_Type
::T_STRING
,
302 $params['im_id'] = array(
303 'title' => 'Primary Instant Messenger ID',
304 'type' => CRM_Utils_Type
::T_INT
,
306 $params['group'] = array(
308 'pseudoconstant' => array(
309 'table' => 'civicrm_group',
312 $params['tag'] = array(
314 'pseudoconstant' => array(
315 'table' => 'civicrm_tag',
318 $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'));
319 $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'));
320 $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'));
321 $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'));
325 * Support for historical oddities.
327 * We are supporting 'showAll' = 'all', 'trash' or 'active' for Contact get
329 * - hopefully some day we'll come up with a std syntax for the 3-way-boolean of
332 * We also support 'filter_group_id' & 'filter.group_id'
334 * @param array $params
335 * As passed into api get or getcount function.
336 * @param array $options
337 * Array of options (so we can modify the filter).
339 function _civicrm_api3_contact_get_supportanomalies(&$params, &$options) {
340 if (isset($params['showAll'])) {
341 if (strtolower($params['showAll']) == "active") {
342 $params['contact_is_deleted'] = 0;
344 if (strtolower($params['showAll']) == "trash") {
345 $params['contact_is_deleted'] = 1;
347 if (strtolower($params['showAll']) == "all" && isset($params['contact_is_deleted'])) {
348 unset($params['contact_is_deleted']);
351 // support for group filters
352 if (array_key_exists('filter_group_id', $params)) {
353 $params['filter.group_id'] = $params['filter_group_id'];
354 unset($params['filter_group_id']);
356 // filter.group_id works both for 1,2,3 and array (1,2,3)
357 if (array_key_exists('filter.group_id', $params)) {
358 if (is_array($params['filter.group_id'])) {
359 $groups = $params['filter.group_id'];
362 $groups = explode(',', $params['filter.group_id']);
364 unset($params['filter.group_id']);
365 $options['input_params']['group'] = $groups;
370 * Delete a Contact with given contact_id.
372 * @param array $params
373 * input parameters per getfields
375 * @throws \Civi\API\Exception\UnauthorizedException
379 function civicrm_api3_contact_delete($params) {
380 $contactID = CRM_Utils_Array
::value('id', $params);
382 if (!empty($params['check_permissions']) && !CRM_Contact_BAO_Contact_Permission
::allow($contactID, CRM_Core_Permission
::DELETE
)) {
383 throw new \Civi\API\Exception\
UnauthorizedException('Permission denied to modify contact record');
386 $session = CRM_Core_Session
::singleton();
387 if ($contactID == $session->get('userID')) {
388 return civicrm_api3_create_error('This contact record is linked to the currently logged in user account - and cannot be deleted.');
390 $restore = !empty($params['restore']) ?
$params['restore'] : FALSE;
391 $skipUndelete = !empty($params['skip_undelete']) ?
$params['skip_undelete'] : FALSE;
394 // restrict permanent delete if a contact has financial trxn associated with it
396 if ($skipUndelete && CRM_Financial_BAO_FinancialItem
::checkContactPresent(array($contactID), $error)) {
397 return civicrm_api3_create_error($error['_qf_default']);
399 if (CRM_Contact_BAO_Contact
::deleteContact($contactID, $restore, $skipUndelete)) {
400 return civicrm_api3_create_success();
403 return civicrm_api3_create_error('Could not delete contact');
409 * Check parameters passed in.
411 * This function is on it's way out.
413 * @param array $params
414 * @param bool $dupeCheck
417 * @throws API_Exception
418 * @throws CiviCRM_API3_Exception
420 function _civicrm_api3_contact_check_params(&$params, $dupeCheck) {
422 switch (strtolower(CRM_Utils_Array
::value('contact_type', $params))) {
424 civicrm_api3_verify_mandatory($params, NULL, array('household_name'));
428 civicrm_api3_verify_mandatory($params, NULL, array('organization_name'));
432 civicrm_api3_verify_one_mandatory($params, NULL, array(
442 // Fixme: This really needs to be handled at a lower level. @See CRM-13123
443 if (isset($params['preferred_communication_method'])) {
444 $params['preferred_communication_method'] = CRM_Utils_Array
::implodePadded($params['preferred_communication_method']);
447 if (!empty($params['contact_sub_type']) && !empty($params['contact_type'])) {
448 if (!(CRM_Contact_BAO_ContactType
::isExtendsContactType($params['contact_sub_type'], $params['contact_type']))) {
449 throw new API_Exception("Invalid or Mismatched Contact Subtype: " . implode(', ', (array) $params['contact_sub_type']));
454 // check for record already existing
455 $dedupeParams = CRM_Dedupe_Finder
::formatParams($params, $params['contact_type']);
458 // setting 'check_permission' here means that the dedupe checking will be carried out even if the
459 // person does not have permission to carry out de-dupes
460 // this is similar to the front end form
461 if (isset($params['check_permission'])) {
462 $dedupeParams['check_permission'] = $params['check_permission'];
465 $ids = CRM_Dedupe_Finder
::dupesByParams($dedupeParams, $params['contact_type'], 'Unsupervised', array());
467 if (count($ids) > 0) {
468 throw new API_Exception("Found matching contacts: " . implode(',', $ids), "duplicate", array("ids" => $ids));
472 // The BAO no longer supports the legacy param "current_employer" so here is a shim for api backward-compatability
473 if (!empty($params['current_employer'])) {
474 $organizationParams = array(
475 'organization_name' => $params['current_employer'],
478 $dedupParams = CRM_Dedupe_Finder
::formatParams($organizationParams, 'Organization');
480 $dedupParams['check_permission'] = FALSE;
481 $dupeIds = CRM_Dedupe_Finder
::dupesByParams($dedupParams, 'Organization', 'Supervised');
483 // check for mismatch employer name and id
484 if (!empty($params['employer_id']) && !in_array($params['employer_id'], $dupeIds)) {
485 throw new API_Exception('Employer name and Employer id Mismatch');
488 // show error if multiple organisation with same name exist
489 if (empty($params['employer_id']) && (count($dupeIds) > 1)) {
490 throw new API_Exception('Found more than one Organisation with same Name.');
494 $params['employer_id'] = $dupeIds[0];
497 $result = civicrm_api3('Contact', 'create', array(
498 'organization_name' => $params['current_employer'],
499 'contact_type' => 'Organization',
501 $params['employer_id'] = $result['id'];
509 * Helper function for Contact create.
511 * @param array $params
512 * (reference ) an assoc array of name/value pairs.
513 * @param int $contactID
514 * If present the contact with that ID is updated.
516 * @return CRM_Contact_BAO_Contact|CRM_Core_Error
518 function _civicrm_api3_contact_update($params, $contactID = NULL) {
519 //@todo - doesn't contact create support 'id' which is already set- check & remove
521 $params['contact_id'] = $contactID;
524 return CRM_Contact_BAO_Contact
::create($params);
528 * Validate the addressee or email or postal greetings.
530 * @param array $params
531 * Array per getfields metadata.
533 * @throws API_Exception
535 function _civicrm_api3_greeting_format_params($params) {
536 $greetingParams = array('', '_id', '_custom');
537 foreach (array('email', 'postal', 'addressee') as $key) {
538 $greeting = '_greeting';
539 if ($key == 'addressee') {
543 $formatParams = FALSE;
544 // Unset display value from params.
545 if (isset($params["{$key}{$greeting}_display"])) {
546 unset($params["{$key}{$greeting}_display"]);
549 // check if greetings are present in present
550 foreach ($greetingParams as $greetingValues) {
551 if (array_key_exists("{$key}{$greeting}{$greetingValues}", $params)) {
552 $formatParams = TRUE;
557 if (!$formatParams) {
563 'contact_type' => $params['contact_type'],
564 'greeting_type' => "{$key}{$greeting}",
567 $greetings = CRM_Core_PseudoConstant
::greeting($filter);
568 $greetingId = CRM_Utils_Array
::value("{$key}{$greeting}_id", $params);
569 $greetingVal = CRM_Utils_Array
::value("{$key}{$greeting}", $params);
570 $customGreeting = CRM_Utils_Array
::value("{$key}{$greeting}_custom", $params);
572 if (!$greetingId && $greetingVal) {
573 $params["{$key}{$greeting}_id"] = CRM_Utils_Array
::key($params["{$key}{$greeting}"], $greetings);
576 if ($customGreeting && $greetingId &&
577 ($greetingId != array_search('Customized', $greetings))
579 throw new API_Exception(ts('Provide either %1 greeting id and/or %1 greeting or custom %1 greeting',
584 if ($greetingVal && $greetingId &&
585 ($greetingId != CRM_Utils_Array
::key($greetingVal, $greetings))
587 throw new API_Exception(ts('Mismatch in %1 greeting id and %1 greeting',
594 if (!array_key_exists($greetingId, $greetings)) {
595 throw new API_Exception(ts('Invalid %1 greeting Id', array(1 => $key)));
598 if (!$customGreeting && ($greetingId == array_search('Customized', $greetings))) {
599 throw new API_Exception(ts('Please provide a custom value for %1 greeting',
604 elseif ($greetingVal) {
606 if (!in_array($greetingVal, $greetings)) {
607 throw new API_Exception(ts('Invalid %1 greeting', array(1 => $key)));
610 $greetingId = CRM_Utils_Array
::key($greetingVal, $greetings);
613 if ($customGreeting) {
614 $greetingId = CRM_Utils_Array
::key('Customized', $greetings);
617 $customValue = isset($params['contact_id']) ? CRM_Core_DAO
::getFieldValue(
618 'CRM_Contact_DAO_Contact',
619 $params['contact_id'],
620 "{$key}{$greeting}_custom"
623 if (array_key_exists("{$key}{$greeting}_id", $params) && empty($params["{$key}{$greeting}_id"])) {
626 elseif (array_key_exists("{$key}{$greeting}", $params) && empty($params["{$key}{$greeting}"])) {
629 elseif ($customValue && array_key_exists("{$key}{$greeting}_custom", $params)
630 && empty($params["{$key}{$greeting}_custom"])
635 $params["{$key}{$greeting}_id"] = $greetingId;
637 if (!$customValue && !$customGreeting && array_key_exists("{$key}{$greeting}_custom", $params)) {
638 unset($params["{$key}{$greeting}_custom"]);
642 $params["{$key}{$greeting}_id"] = '';
643 $params["{$key}{$greeting}_custom"] = '';
646 if (isset($params["{$key}{$greeting}"])) {
647 unset($params["{$key}{$greeting}"]);
653 * Adjust Metadata for Get action.
655 * @param array $params
656 * Array of parameters determined by getfields.
658 function _civicrm_api3_contact_getquick_spec(&$params) {
659 $params['name']['api.required'] = TRUE;
660 $params['name']['title'] = ts('String to search on');
661 $params['name']['type'] = CRM_Utils_Type
::T_STRING
;
662 $params['field']['type'] = CRM_Utils_Type
::T_STRING
;
663 $params['field']['title'] = ts('Field to search on');
664 $params['field']['options'] = array(
668 'external_identifier',
678 $params['table_name']['type'] = CRM_Utils_Type
::T_STRING
;
679 $params['table_name']['title'] = ts('Table alias to search on');
680 $params['table_name']['api.default'] = 'cc';
684 * Old Contact quick search api.
688 * @param array $params
691 * @throws \API_Exception
693 function civicrm_api3_contact_getquick($params) {
694 $name = CRM_Utils_Type
::escape(CRM_Utils_Array
::value('name', $params), 'String');
695 $table_name = CRM_Utils_String
::munge($params['table_name']);
696 // get the autocomplete options from settings
697 $acpref = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
698 CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
,
699 'contact_autocomplete_options'
703 // get the option values for contact autocomplete
704 $acOptions = CRM_Core_OptionGroup
::values('contact_autocomplete_options', FALSE, FALSE, FALSE, NULL, 'name');
707 foreach ($acpref as $value) {
708 if ($value && !empty($acOptions[$value])) {
709 $list[$value] = $acOptions[$value];
712 // If we are doing quicksearch by a field other than name, make sure that field is added to results
713 if (!empty($params['field_name'])) {
714 $field_name = CRM_Utils_String
::munge($params['field_name']);
715 // Unique name contact_id = id
716 if ($field_name == 'contact_id') {
719 // phone_numeric should be phone
720 $searchField = str_replace('_numeric', '', $field_name);
721 if (!in_array($searchField, $list)) {
722 $list[] = $searchField;
726 // Set field name to first name for exact match checking.
727 $field_name = 'sort_name';
730 $select = $actualSelectElements = array('sort_name');
733 foreach ($list as $value) {
734 $suffix = substr($value, 0, 2) . substr($value, -1);
736 case 'street_address':
739 $selectText = $value;
744 $actualSelectElements[] = $select[] = ($value == 'address') ?
$selectText : $value;
745 if ($value == 'phone') {
746 $actualSelectElements[] = $select[] = 'phone_ext';
748 $from[$value] = "LEFT JOIN civicrm_{$value} {$suffix} ON ( cc.id = {$suffix}.contact_id AND {$suffix}.is_primary = 1 ) ";
752 case 'state_province':
753 $select[] = "{$suffix}.name as {$value}";
754 $actualSelectElements[] = "{$suffix}.name";
755 if (!in_array('address', $from)) {
756 $from['address'] = 'LEFT JOIN civicrm_address sts ON ( cc.id = sts.contact_id AND sts.is_primary = 1) ';
758 $from[$value] = " LEFT JOIN civicrm_{$value} {$suffix} ON ( sts.{$value}_id = {$suffix}.id ) ";
762 if ($value != 'id') {
764 if (!empty($params['field_name']) && $params['field_name'] == 'value') {
765 $suffix = CRM_Utils_String
::munge(CRM_Utils_Array
::value('table_name', $params, 'cc'));
767 $actualSelectElements[] = $select[] = $suffix . '.' . $value;
773 $config = CRM_Core_Config
::singleton();
775 $select = implode(', ', $select);
776 if (!empty($select)) {
777 $select = ", $select";
779 $actualSelectElements = implode(', ', $actualSelectElements);
780 $selectAliases = $from;
781 unset($selectAliases['address']);
782 $selectAliases = implode(', ', array_keys($selectAliases));
783 if (!empty($selectAliases)) {
784 $selectAliases = ", $selectAliases";
786 $from = implode(' ', $from);
787 $limit = (int) CRM_Utils_Array
::value('limit', $params);
788 $limit = $limit > 0 ?
$limit : Civi
::settings()->get('search_autocomplete_count');
790 // add acl clause here
791 list($aclFrom, $aclWhere) = CRM_Contact_BAO_Contact_Permission
::cacheClause('cc');
794 $where .= " AND $aclWhere ";
797 if (!empty($params['org'])) {
798 $where .= " AND contact_type = \"Organization\"";
800 // CRM-7157, hack: get current employer details when
801 // employee_id is present.
802 $currEmpDetails = array();
803 if (!empty($params['employee_id'])) {
804 if ($currentEmployer = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact',
805 (int) $params['employee_id'],
808 if ($config->includeWildCardInName
) {
809 $strSearch = "%$name%";
812 $strSearch = "$name%";
815 // get current employer details
816 $dao = CRM_Core_DAO
::executeQuery("SELECT cc.id as id, CONCAT_WS( ' :: ', {$actualSelectElements} ) as data, sort_name
817 FROM civicrm_contact cc {$from} WHERE cc.contact_type = \"Organization\" AND cc.id = {$currentEmployer} AND cc.sort_name LIKE '$strSearch'");
819 $currEmpDetails = array(
821 'data' => $dao->data
,
828 if (!empty($params['contact_sub_type'])) {
829 $contactSubType = CRM_Utils_Type
::escape($params['contact_sub_type'], 'String');
830 $where .= " AND cc.contact_sub_type = '{$contactSubType}'";
833 if (!empty($params['contact_type'])) {
834 $contactType = CRM_Utils_Type
::escape($params['contact_type'], 'String');
835 $where .= " AND cc.contact_type LIKE '{$contactType}'";
838 // Set default for current_employer or return contact with particular id
839 if (!empty($params['id'])) {
840 $where .= " AND cc.id = " . (int) $params['id'];
843 if (!empty($params['cid'])) {
844 $where .= " AND cc.id <> " . (int) $params['cid'];
847 // Contact's based of relationhip type
849 if (!empty($params['rel'])) {
850 $relation = explode('_', CRM_Utils_Array
::value('rel', $params));
851 $relType = CRM_Utils_Type
::escape($relation[0], 'Integer');
852 $rel = CRM_Utils_Type
::escape($relation[2], 'String');
855 if ($config->includeWildCardInName
) {
856 $strSearch = "%$name%";
859 $strSearch = "$name%";
861 $includeEmailFrom = $includeNickName = $exactIncludeNickName = '';
862 if ($config->includeNickNameInName
) {
863 $includeNickName = " OR nick_name LIKE '$strSearch'";
864 $exactIncludeNickName = " OR nick_name LIKE '$name'";
868 if (!empty($params['field_name']) && !empty($params['table_name'])) {
869 $whereClause = " WHERE ( $table_name.$field_name LIKE '$strSearch') {$where}";
870 $exactWhereClause = " WHERE ( $table_name.$field_name = '$name') {$where}";
871 // Search by id should be exact
872 if ($field_name == 'id' ||
$field_name == 'external_identifier') {
873 $whereClause = $exactWhereClause;
877 $whereClause = " WHERE ( sort_name LIKE '$strSearch' $includeNickName ) {$where} ";
878 $exactWhereClause = " WHERE ( sort_name LIKE '$name' $exactIncludeNickName ) {$where} ";
879 if ($config->includeEmailInName
) {
880 if (!in_array('email', $list)) {
881 $includeEmailFrom = "LEFT JOIN civicrm_email eml ON ( cc.id = eml.contact_id AND eml.is_primary = 1 )";
883 $emailWhere = " WHERE email LIKE '$strSearch'";
887 $additionalFrom = '';
890 INNER JOIN civicrm_relationship_type r ON (
892 AND ( cc.contact_type = r.contact_type_{$rel} OR r.contact_type_{$rel} IS NULL )
893 AND ( cc.contact_sub_type = r.contact_sub_type_{$rel} OR r.contact_sub_type_{$rel} IS NULL )
897 // check if only CMS users are requested
898 if (!empty($params['cmsuser'])) {
900 INNER JOIN civicrm_uf_match um ON (um.contact_id=cc.id)
904 $orderByInner = $orderByOuter = "ORDER BY exactFirst";
905 if ($config->includeOrderByClause
) {
906 $orderByInner = "ORDER BY exactFirst, sort_name";
907 $orderByOuter .= ", sort_name";
912 SELECT DISTINCT(id), data, sort_name {$selectAliases}, exactFirst
914 ( SELECT IF($table_name.$field_name = '{$name}', 0, 1) as exactFirst, cc.id as id, CONCAT_WS( ' :: ',
915 {$actualSelectElements} )
918 FROM civicrm_contact cc {$from}
926 if (!empty($emailWhere)) {
929 SELECT IF($table_name.$field_name = '{$name}', 0, 1) as exactFirst, cc.id as id, CONCAT_WS( ' :: ',
930 {$actualSelectElements} )
933 FROM civicrm_contact cc {$from}
935 {$additionalFrom} {$includeEmailFrom}
936 {$emailWhere} AND cc.is_deleted = 0 " . ($aclWhere ?
" AND $aclWhere " : '') . "
947 // send query to hook to be modified if needed
948 CRM_Utils_Hook
::contactListQuery($query,
950 empty($params['context']) ?
NULL : CRM_Utils_Type
::escape($params['context'], 'String'),
951 empty($params['id']) ?
NULL : $params['id']
954 $dao = CRM_Core_DAO
::executeQuery($query);
956 $contactList = array();
957 $listCurrentEmployer = TRUE;
958 while ($dao->fetch()) {
959 $t = array('id' => $dao->id
);
960 foreach ($as as $k) {
961 $t[$k] = isset($dao->$k) ?
$dao->$k : '';
963 $t['data'] = $dao->data
;
965 if (!empty($params['org']) &&
966 !empty($currEmpDetails) &&
967 $dao->id
== $currEmpDetails['id']
969 $listCurrentEmployer = FALSE;
973 //return organization name if doesn't exist in db
974 if (empty($contactList)) {
975 if (!empty($params['org'])) {
976 if ($listCurrentEmployer && !empty($currEmpDetails)) {
977 $contactList = array(
979 'data' => $currEmpDetails['data'],
980 'id' => $currEmpDetails['id'],
985 $contactList = array(
995 return civicrm_api3_create_success($contactList, $params, 'Contact', 'getquick');
999 * Declare deprecated api functions.
1001 * @deprecated api notice
1003 * Array of deprecated actions
1005 function _civicrm_api3_contact_deprecation() {
1006 return array('getquick' => 'The "getquick" action is deprecated in favor of "getlist".');
1010 * Merges given pair of duplicate contacts.
1012 * @param array $params
1013 * Allowed array keys are:
1014 * -int main_id: main contact id with whom merge has to happen
1015 * -int other_id: duplicate contact which would be deleted after merge operation
1016 * -string mode: "safe" skips the merge if there are no conflicts. Does a force merge otherwise.
1017 * -boolean auto_flip: whether to let api decide which contact to retain and which to delete.
1021 * @throws CiviCRM_API3_Exception
1023 function civicrm_api3_contact_merge($params) {
1024 $mode = CRM_Utils_Array
::value('mode', $params, 'safe');
1025 $autoFlip = CRM_Utils_Array
::value('auto_flip', $params, TRUE);
1029 'srcID' => CRM_Utils_Array
::value('main_id', $params),
1030 'dstID' => CRM_Utils_Array
::value('other_id', $params),
1034 if (($result = CRM_Dedupe_Merger
::merge($dupePairs, array(), $mode, $autoFlip)) != FALSE) {
1035 return civicrm_api3_create_success($result, $params);
1037 throw new CiviCRM_API3_Exception('Merge failed');
1041 * Adjust metadata for contact_proximity api function.
1043 * @param array $params
1045 function _civicrm_api3_contact_merge_spec(&$params) {
1046 $params['main_id'] = array(
1047 'title' => 'ID of the contact to merge & remove',
1048 'description' => ts('Wow - these 2 params are the logical reverse of what I expect - but what to do?'),
1049 'api.required' => 1,
1050 'type' => CRM_Utils_Type
::T_INT
,
1052 $params['other_id'] = array(
1053 'title' => 'ID of the contact to keep',
1054 'description' => ts('Wow - these 2 params are the logical reverse of what I expect - but what to do?'),
1055 'api.required' => 1,
1056 'type' => CRM_Utils_Type
::T_INT
,
1061 * Adjust metadata for contact_proximity api function.
1063 * @param array $params
1065 function _civicrm_api3_contact_proximity_spec(&$params) {
1066 $params['latitude'] = array(
1067 'title' => 'Latitude',
1068 'api.required' => 1,
1069 'type' => CRM_Utils_Type
::T_STRING
,
1071 $params['longitude'] = array(
1072 'title' => 'Longitude',
1073 'api.required' => 1,
1074 'type' => CRM_Utils_Type
::T_STRING
,
1077 $params['unit'] = array(
1078 'title' => 'Unit of Measurement',
1079 'api.default' => 'meter',
1080 'type' => CRM_Utils_Type
::T_STRING
,
1085 * Get contacts by proximity.
1087 * @param array $params
1092 function civicrm_api3_contact_proximity($params) {
1093 $latitude = CRM_Utils_Array
::value('latitude', $params);
1094 $longitude = CRM_Utils_Array
::value('longitude', $params);
1095 $distance = CRM_Utils_Array
::value('distance', $params);
1097 $unit = CRM_Utils_Array
::value('unit', $params);
1099 // check and ensure that lat/long and distance are floats
1101 !CRM_Utils_Rule
::numeric($latitude) ||
1102 !CRM_Utils_Rule
::numeric($longitude) ||
1103 !CRM_Utils_Rule
::numeric($distance)
1105 throw new Exception(ts('Latitude, Longitude and Distance should exist and be numeric'));
1108 if ($unit == "mile") {
1109 $conversionFactor = 1609.344;
1112 $conversionFactor = 1000;
1114 //Distance in meters
1115 $distance = $distance * $conversionFactor;
1117 $whereClause = CRM_Contact_BAO_ProximityQuery
::where($latitude, $longitude, $distance);
1120 SELECT civicrm_contact.id as contact_id,
1121 civicrm_contact.display_name as display_name
1122 FROM civicrm_contact
1123 LEFT JOIN civicrm_address ON civicrm_contact.id = civicrm_address.contact_id
1127 $dao = CRM_Core_DAO
::executeQuery($query);
1128 $contacts = array();
1129 while ($dao->fetch()) {
1130 $contacts[] = $dao->toArray();
1133 return civicrm_api3_create_success($contacts, $params, 'Contact', 'get_by_location', $dao);
1138 * Get parameters for getlist function.
1140 * @see _civicrm_api3_generic_getlist_params
1142 * @param array $request
1144 function _civicrm_api3_contact_getlist_params(&$request) {
1145 // get the autocomplete options from settings
1146 $acpref = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1147 CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
,
1148 'contact_autocomplete_options'
1152 // get the option values for contact autocomplete
1153 $acOptions = CRM_Core_OptionGroup
::values('contact_autocomplete_options', FALSE, FALSE, FALSE, NULL, 'name');
1156 foreach ($acpref as $value) {
1157 if ($value && !empty($acOptions[$value])) {
1158 $list[] = $acOptions[$value];
1161 // If we are doing quicksearch by a field other than name, make sure that field is added to results
1162 $field_name = CRM_Utils_String
::munge($request['search_field']);
1163 // Unique name contact_id = id
1164 if ($field_name == 'contact_id') {
1167 // phone_numeric should be phone
1168 $searchField = str_replace('_numeric', '', $field_name);
1169 if (!in_array($searchField, $list)) {
1170 $list[] = $searchField;
1172 $request['description_field'] = $list;
1173 $list[] = 'contact_type';
1174 $request['params']['return'] = array_unique(array_merge($list, $request['extra']));
1175 $request['params']['options']['sort'] = 'sort_name';
1176 // Contact api doesn't support array(LIKE => 'foo') syntax
1177 if (!empty($request['input'])) {
1178 $request['params'][$request['search_field']] = $request['input'];
1183 * Get output for getlist function.
1185 * @see _civicrm_api3_generic_getlist_output
1187 * @param array $result
1188 * @param array $request
1192 function _civicrm_api3_contact_getlist_output($result, $request) {
1194 if (!empty($result['values'])) {
1195 $addressFields = array_intersect(array(
1201 $request['params']['return']);
1202 foreach ($result['values'] as $row) {
1204 'id' => $row[$request['id_field']],
1205 'label' => $row[$request['label_field']],
1206 'description' => array(),
1208 foreach ($request['description_field'] as $item) {
1209 if (!strpos($item, '_name') && !in_array($item, $addressFields) && !empty($row[$item])) {
1210 $data['description'][] = $row[$item];
1214 foreach ($addressFields as $item) {
1215 if (!empty($row[$item])) {
1216 $address[] = $row[$item];
1220 $data['description'][] = implode(' ', $address);
1222 if (!empty($request['image_field'])) {
1223 $data['image'] = isset($row[$request['image_field']]) ?
$row[$request['image_field']] : '';
1226 $data['icon_class'] = $row['contact_type'];
1235 * Check for duplicate contacts.
1237 * @param array $params
1238 * Params per getfields metadata.
1241 * API formatted array
1243 function civicrm_api3_contact_duplicatecheck($params) {
1244 $dedupeParams = CRM_Dedupe_Finder
::formatParams($params['match'], $params['match']['contact_type']);
1247 // setting 'check_permission' here means that the dedupe checking will be carried out even if the
1248 // person does not have permission to carry out de-dupes
1249 // this is similar to the front end form
1250 if (isset($params['check_permission'])) {
1251 $dedupeParams['check_permission'] = $params['check_permission'];
1254 $dupes = CRM_Dedupe_Finder
::dupesByParams($dedupeParams, $params['match']['contact_type'], 'Unsupervised', array(), CRM_Utils_Array
::value('dedupe_rule_id', $params));
1255 $values = empty($dupes) ?
array() : array_fill_keys($dupes, array());
1256 return civicrm_api3_create_success($values, $params, 'Contact', 'duplicatecheck');
1260 * Declare metadata for contact dedupe function.
1264 function _civicrm_api3_contact_duplicatecheck_spec(&$params) {
1265 $params['dedupe_rule_id'] = array(
1266 'title' => 'Dedupe Rule ID (optional)',
1267 'description' => 'This will default to the built in unsupervised rule',
1268 'type' => CRM_Utils_Type
::T_INT
,
1270 // @todo declare 'match' parameter. We don't have a standard for type = array yet.