3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2016 |
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);
64 if (array_key_exists('api_key', $params) && !empty($params['check_permissions'])) {
65 if (CRM_Core_Permission
::check('edit api keys') || CRM_Core_Permission
::check('administer CiviCRM')) {
68 elseif ($contactID && CRM_Core_Permission
::check('edit own api keys') && CRM_Core_Session
::singleton()->get('userID') == $contactID) {
72 throw new \Civi\API\Exception\
UnauthorizedException('Permission denied to modify api key');
77 // If we get here, we're ready to create a new contact
78 if (($email = CRM_Utils_Array
::value('email', $params)) && !is_array($params['email'])) {
79 $defLocType = CRM_Core_BAO_LocationType
::getDefault();
80 $params['email'] = array(
84 'location_type_id' => ($defLocType->id
) ?
$defLocType->id
: 1,
90 if (!empty($params['home_url'])) {
91 $websiteTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Website', 'website_type_id');
92 $params['website'] = array(
94 'website_type_id' => key($websiteTypes),
95 'url' => $params['home_url'],
100 _civicrm_api3_greeting_format_params($params);
104 if (empty($params['contact_type']) && $contactID) {
105 $params['contact_type'] = CRM_Contact_BAO_Contact
::getContactType($contactID);
108 if (!isset($params['contact_sub_type']) && $contactID) {
109 $params['contact_sub_type'] = CRM_Contact_BAO_Contact
::getContactSubType($contactID);
112 _civicrm_api3_custom_format_params($params, $values, $params['contact_type'], $contactID);
114 $params = array_merge($params, $values);
115 //@todo we should just call basic_create here - but need to make contact:create accept 'id' on the bao
116 $contact = _civicrm_api3_contact_update($params, $contactID);
118 if (is_a($contact, 'CRM_Core_Error')) {
119 throw new API_Exception($contact->_errors
[0]['message']);
123 _civicrm_api3_object_to_array_unique_fields($contact, $values[$contact->id
]);
126 return civicrm_api3_create_success($values, $params, 'Contact', 'create');
130 * Adjust Metadata for Create action.
132 * @param array $params
133 * Array of parameters determined by getfields.
135 function _civicrm_api3_contact_create_spec(&$params) {
136 $params['contact_type']['api.required'] = 1;
137 $params['id']['api.aliases'] = array('contact_id');
138 $params['current_employer'] = array(
139 'title' => 'Current Employer',
140 'description' => 'Name of Current Employer',
141 'type' => CRM_Utils_Type
::T_STRING
,
143 $params['dupe_check'] = array(
144 'title' => 'Check for Duplicates',
145 'description' => 'Throw error if contact create matches dedupe rule',
146 'type' => CRM_Utils_Type
::T_BOOLEAN
,
148 $params['prefix_id']['api.aliases'] = array('individual_prefix', 'individual_prefix_id');
149 $params['suffix_id']['api.aliases'] = array('individual_suffix', 'individual_suffix_id');
150 $params['gender_id']['api.aliases'] = array('gender');
154 * Retrieve one or more contacts, given a set of search params.
156 * @param array $params
161 function civicrm_api3_contact_get($params) {
163 _civicrm_api3_contact_get_supportanomalies($params, $options);
164 $contacts = _civicrm_api3_get_using_query_object('Contact', $params, $options);
165 return civicrm_api3_create_success($contacts, $params, 'Contact');
169 * Get number of contacts matching the supplied criteria.
171 * @param array $params
175 function civicrm_api3_contact_getcount($params) {
177 _civicrm_api3_contact_get_supportanomalies($params, $options);
178 $count = _civicrm_api3_get_using_query_object('Contact', $params, $options, 1);
183 * Adjust Metadata for Get action.
185 * @param array $params
186 * Array of parameters determined by getfields.
188 function _civicrm_api3_contact_get_spec(&$params) {
189 $params['contact_is_deleted']['api.default'] = 0;
191 // We declare all these pseudoFields as there are other undocumented fields accessible
192 // via the api - but if check permissions is set we only allow declared fields
193 $params['address_id'] = array(
194 'title' => 'Primary Address ID',
195 'type' => CRM_Utils_Type
::T_INT
,
197 $params['street_address'] = array(
198 'title' => 'Primary Address Street Address',
199 'type' => CRM_Utils_Type
::T_STRING
,
201 $params['supplemental_address_1'] = array(
202 'title' => 'Primary Address Supplemental Address 1',
203 'type' => CRM_Utils_Type
::T_STRING
,
205 $params['supplemental_address_2'] = array(
206 'title' => 'Primary Address Supplemental Address 2',
207 'type' => CRM_Utils_Type
::T_STRING
,
209 $params['current_employer'] = array(
210 'title' => 'Current Employer',
211 'type' => CRM_Utils_Type
::T_STRING
,
213 $params['city'] = array(
214 'title' => 'Primary Address City',
215 'type' => CRM_Utils_Type
::T_STRING
,
217 $params['postal_code_suffix'] = array(
218 'title' => 'Primary Address Post Code Suffix',
219 'type' => CRM_Utils_Type
::T_STRING
,
221 $params['postal_code'] = array(
222 'title' => 'Primary Address Post Code',
223 'type' => CRM_Utils_Type
::T_STRING
,
225 $params['geo_code_1'] = array(
226 'title' => 'Primary Address Latitude',
227 'type' => CRM_Utils_Type
::T_STRING
,
229 $params['geo_code_2'] = array(
230 'title' => 'Primary Address Longitude',
231 'type' => CRM_Utils_Type
::T_STRING
,
233 $params['state_province_id'] = array(
234 'title' => 'Primary Address State Province ID',
235 'type' => CRM_Utils_Type
::T_INT
,
236 'pseudoconstant' => array(
237 'table' => 'civicrm_state_province',
240 $params['state_province_name'] = array(
241 'title' => 'Primary Address State Province Name',
242 'type' => CRM_Utils_Type
::T_STRING
,
243 'pseudoconstant' => array(
244 'table' => 'civicrm_state_province',
247 $params['state_province'] = array(
248 'title' => 'Primary Address State Province',
249 'type' => CRM_Utils_Type
::T_STRING
,
250 'pseudoconstant' => array(
251 'table' => 'civicrm_state_province',
254 $params['country_id'] = array(
255 'title' => 'Primary Address Country ID',
256 'type' => CRM_Utils_Type
::T_INT
,
257 'pseudoconstant' => array(
258 'table' => 'civicrm_country',
261 $params['country'] = array(
262 'title' => 'Primary Address country',
263 'type' => CRM_Utils_Type
::T_STRING
,
264 'pseudoconstant' => array(
265 'table' => 'civicrm_country',
268 $params['worldregion_id'] = array(
269 'title' => 'Primary Address World Region ID',
270 'type' => CRM_Utils_Type
::T_INT
,
271 'pseudoconstant' => array(
272 'table' => 'civicrm_world_region',
275 $params['worldregion'] = array(
276 'title' => 'Primary Address World Region',
277 'type' => CRM_Utils_Type
::T_STRING
,
278 'pseudoconstant' => array(
279 'table' => 'civicrm_world_region',
282 $params['phone_id'] = array(
283 'title' => 'Primary Phone ID',
284 'type' => CRM_Utils_Type
::T_INT
,
286 $params['phone'] = array(
287 'title' => 'Primary Phone',
288 'type' => CRM_Utils_Type
::T_STRING
,
290 $params['phone_type_id'] = array(
291 'title' => 'Primary Phone Type ID',
292 'type' => CRM_Utils_Type
::T_INT
,
294 $params['provider_id'] = array(
295 'title' => 'Primary Phone Provider ID',
296 'type' => CRM_Utils_Type
::T_INT
,
298 $params['email_id'] = array(
299 'title' => 'Primary Email ID',
300 'type' => CRM_Utils_Type
::T_INT
,
302 $params['email'] = array(
303 'title' => 'Primary Email',
304 'type' => CRM_Utils_Type
::T_STRING
,
306 $params['on_hold'] = array(
307 'title' => 'Primary Email On Hold',
308 'type' => CRM_Utils_Type
::T_BOOLEAN
,
310 $params['im'] = array(
311 'title' => 'Primary Instant Messenger',
312 'type' => CRM_Utils_Type
::T_STRING
,
314 $params['im_id'] = array(
315 'title' => 'Primary Instant Messenger ID',
316 'type' => CRM_Utils_Type
::T_INT
,
318 $params['group'] = array(
320 'pseudoconstant' => array(
321 'table' => 'civicrm_group',
324 $params['tag'] = array(
326 'pseudoconstant' => array(
327 'table' => 'civicrm_tag',
330 $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'));
331 $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'));
332 $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'));
333 $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'));
337 * Support for historical oddities.
339 * We are supporting 'showAll' = 'all', 'trash' or 'active' for Contact get
341 * - hopefully some day we'll come up with a std syntax for the 3-way-boolean of
344 * We also support 'filter_group_id' & 'filter.group_id'
346 * @param array $params
347 * As passed into api get or getcount function.
348 * @param array $options
349 * Array of options (so we can modify the filter).
351 function _civicrm_api3_contact_get_supportanomalies(&$params, &$options) {
352 if (isset($params['showAll'])) {
353 if (strtolower($params['showAll']) == "active") {
354 $params['contact_is_deleted'] = 0;
356 if (strtolower($params['showAll']) == "trash") {
357 $params['contact_is_deleted'] = 1;
359 if (strtolower($params['showAll']) == "all" && isset($params['contact_is_deleted'])) {
360 unset($params['contact_is_deleted']);
363 // support for group filters
364 if (array_key_exists('filter_group_id', $params)) {
365 $params['filter.group_id'] = $params['filter_group_id'];
366 unset($params['filter_group_id']);
368 // filter.group_id works both for 1,2,3 and array (1,2,3)
369 if (array_key_exists('filter.group_id', $params)) {
370 if (is_array($params['filter.group_id'])) {
371 $groups = $params['filter.group_id'];
374 $groups = explode(',', $params['filter.group_id']);
376 unset($params['filter.group_id']);
377 $options['input_params']['group'] = $groups;
382 * Delete a Contact with given contact_id.
384 * @param array $params
385 * input parameters per getfields
387 * @throws \Civi\API\Exception\UnauthorizedException
391 function civicrm_api3_contact_delete($params) {
392 $contactID = CRM_Utils_Array
::value('id', $params);
394 if (!empty($params['check_permissions']) && !CRM_Contact_BAO_Contact_Permission
::allow($contactID, CRM_Core_Permission
::DELETE
)) {
395 throw new \Civi\API\Exception\
UnauthorizedException('Permission denied to modify contact record');
398 $session = CRM_Core_Session
::singleton();
399 if ($contactID == $session->get('userID')) {
400 return civicrm_api3_create_error('This contact record is linked to the currently logged in user account - and cannot be deleted.');
402 $restore = !empty($params['restore']) ?
$params['restore'] : FALSE;
403 $skipUndelete = !empty($params['skip_undelete']) ?
$params['skip_undelete'] : FALSE;
406 // restrict permanent delete if a contact has financial trxn associated with it
408 if ($skipUndelete && CRM_Financial_BAO_FinancialItem
::checkContactPresent(array($contactID), $error)) {
409 return civicrm_api3_create_error($error['_qf_default']);
411 if (CRM_Contact_BAO_Contact
::deleteContact($contactID, $restore, $skipUndelete)) {
412 return civicrm_api3_create_success();
415 return civicrm_api3_create_error('Could not delete contact');
421 * Check parameters passed in.
423 * This function is on it's way out.
425 * @param array $params
426 * @param bool $dupeCheck
429 * @throws API_Exception
430 * @throws CiviCRM_API3_Exception
432 function _civicrm_api3_contact_check_params(&$params, $dupeCheck) {
434 switch (strtolower(CRM_Utils_Array
::value('contact_type', $params))) {
436 civicrm_api3_verify_mandatory($params, NULL, array('household_name'));
440 civicrm_api3_verify_mandatory($params, NULL, array('organization_name'));
444 civicrm_api3_verify_one_mandatory($params, NULL, array(
454 // Fixme: This really needs to be handled at a lower level. @See CRM-13123
455 if (isset($params['preferred_communication_method'])) {
456 $params['preferred_communication_method'] = CRM_Utils_Array
::implodePadded($params['preferred_communication_method']);
459 if (!empty($params['contact_sub_type']) && !empty($params['contact_type'])) {
460 if (!(CRM_Contact_BAO_ContactType
::isExtendsContactType($params['contact_sub_type'], $params['contact_type']))) {
461 throw new API_Exception("Invalid or Mismatched Contact Subtype: " . implode(', ', (array) $params['contact_sub_type']));
466 // check for record already existing
467 $dedupeParams = CRM_Dedupe_Finder
::formatParams($params, $params['contact_type']);
470 // setting 'check_permission' here means that the dedupe checking will be carried out even if the
471 // person does not have permission to carry out de-dupes
472 // this is similar to the front end form
473 if (isset($params['check_permission'])) {
474 $dedupeParams['check_permission'] = $params['check_permission'];
477 $ids = CRM_Dedupe_Finder
::dupesByParams($dedupeParams, $params['contact_type'], 'Unsupervised', array());
479 if (count($ids) > 0) {
480 throw new API_Exception("Found matching contacts: " . implode(',', $ids), "duplicate", array("ids" => $ids));
484 // The BAO no longer supports the legacy param "current_employer" so here is a shim for api backward-compatability
485 if (!empty($params['current_employer'])) {
486 $organizationParams = array(
487 'organization_name' => $params['current_employer'],
490 $dedupParams = CRM_Dedupe_Finder
::formatParams($organizationParams, 'Organization');
492 $dedupParams['check_permission'] = FALSE;
493 $dupeIds = CRM_Dedupe_Finder
::dupesByParams($dedupParams, 'Organization', 'Supervised');
495 // check for mismatch employer name and id
496 if (!empty($params['employer_id']) && !in_array($params['employer_id'], $dupeIds)) {
497 throw new API_Exception('Employer name and Employer id Mismatch');
500 // show error if multiple organisation with same name exist
501 if (empty($params['employer_id']) && (count($dupeIds) > 1)) {
502 throw new API_Exception('Found more than one Organisation with same Name.');
506 $params['employer_id'] = $dupeIds[0];
509 $result = civicrm_api3('Contact', 'create', array(
510 'organization_name' => $params['current_employer'],
511 'contact_type' => 'Organization',
513 $params['employer_id'] = $result['id'];
521 * Helper function for Contact create.
523 * @param array $params
524 * (reference ) an assoc array of name/value pairs.
525 * @param int $contactID
526 * If present the contact with that ID is updated.
528 * @return CRM_Contact_BAO_Contact|CRM_Core_Error
530 function _civicrm_api3_contact_update($params, $contactID = NULL) {
531 //@todo - doesn't contact create support 'id' which is already set- check & remove
533 $params['contact_id'] = $contactID;
536 return CRM_Contact_BAO_Contact
::create($params);
540 * Validate the addressee or email or postal greetings.
542 * @param array $params
543 * Array per getfields metadata.
545 * @throws API_Exception
547 function _civicrm_api3_greeting_format_params($params) {
548 $greetingParams = array('', '_id', '_custom');
549 foreach (array('email', 'postal', 'addressee') as $key) {
550 $greeting = '_greeting';
551 if ($key == 'addressee') {
555 $formatParams = FALSE;
556 // Unset display value from params.
557 if (isset($params["{$key}{$greeting}_display"])) {
558 unset($params["{$key}{$greeting}_display"]);
561 // check if greetings are present in present
562 foreach ($greetingParams as $greetingValues) {
563 if (array_key_exists("{$key}{$greeting}{$greetingValues}", $params)) {
564 $formatParams = TRUE;
569 if (!$formatParams) {
575 'contact_type' => $params['contact_type'],
576 'greeting_type' => "{$key}{$greeting}",
579 $greetings = CRM_Core_PseudoConstant
::greeting($filter);
580 $greetingId = CRM_Utils_Array
::value("{$key}{$greeting}_id", $params);
581 $greetingVal = CRM_Utils_Array
::value("{$key}{$greeting}", $params);
582 $customGreeting = CRM_Utils_Array
::value("{$key}{$greeting}_custom", $params);
584 if (!$greetingId && $greetingVal) {
585 $params["{$key}{$greeting}_id"] = CRM_Utils_Array
::key($params["{$key}{$greeting}"], $greetings);
588 if ($customGreeting && $greetingId &&
589 ($greetingId != array_search('Customized', $greetings))
591 throw new API_Exception(ts('Provide either %1 greeting id and/or %1 greeting or custom %1 greeting',
596 if ($greetingVal && $greetingId &&
597 ($greetingId != CRM_Utils_Array
::key($greetingVal, $greetings))
599 throw new API_Exception(ts('Mismatch in %1 greeting id and %1 greeting',
606 if (!array_key_exists($greetingId, $greetings)) {
607 throw new API_Exception(ts('Invalid %1 greeting Id', array(1 => $key)));
610 if (!$customGreeting && ($greetingId == array_search('Customized', $greetings))) {
611 throw new API_Exception(ts('Please provide a custom value for %1 greeting',
616 elseif ($greetingVal) {
618 if (!in_array($greetingVal, $greetings)) {
619 throw new API_Exception(ts('Invalid %1 greeting', array(1 => $key)));
622 $greetingId = CRM_Utils_Array
::key($greetingVal, $greetings);
625 if ($customGreeting) {
626 $greetingId = CRM_Utils_Array
::key('Customized', $greetings);
629 $customValue = isset($params['contact_id']) ? CRM_Core_DAO
::getFieldValue(
630 'CRM_Contact_DAO_Contact',
631 $params['contact_id'],
632 "{$key}{$greeting}_custom"
635 if (array_key_exists("{$key}{$greeting}_id", $params) && empty($params["{$key}{$greeting}_id"])) {
638 elseif (array_key_exists("{$key}{$greeting}", $params) && empty($params["{$key}{$greeting}"])) {
641 elseif ($customValue && array_key_exists("{$key}{$greeting}_custom", $params)
642 && empty($params["{$key}{$greeting}_custom"])
647 $params["{$key}{$greeting}_id"] = $greetingId;
649 if (!$customValue && !$customGreeting && array_key_exists("{$key}{$greeting}_custom", $params)) {
650 unset($params["{$key}{$greeting}_custom"]);
654 $params["{$key}{$greeting}_id"] = '';
655 $params["{$key}{$greeting}_custom"] = '';
658 if (isset($params["{$key}{$greeting}"])) {
659 unset($params["{$key}{$greeting}"]);
665 * Adjust Metadata for Get action.
667 * @param array $params
668 * Array of parameters determined by getfields.
670 function _civicrm_api3_contact_getquick_spec(&$params) {
671 $params['name']['api.required'] = TRUE;
672 $params['name']['title'] = ts('String to search on');
673 $params['name']['type'] = CRM_Utils_Type
::T_STRING
;
674 $params['field']['type'] = CRM_Utils_Type
::T_STRING
;
675 $params['field']['title'] = ts('Field to search on');
676 $params['field']['options'] = array(
680 'external_identifier',
690 $params['table_name']['type'] = CRM_Utils_Type
::T_STRING
;
691 $params['table_name']['title'] = ts('Table alias to search on');
692 $params['table_name']['api.default'] = 'cc';
696 * Old Contact quick search api.
700 * @param array $params
703 * @throws \API_Exception
705 function civicrm_api3_contact_getquick($params) {
706 $name = CRM_Utils_Type
::escape(CRM_Utils_Array
::value('name', $params), 'String');
707 $table_name = CRM_Utils_String
::munge($params['table_name']);
708 // get the autocomplete options from settings
709 $acpref = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
710 CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
,
711 'contact_autocomplete_options'
715 // get the option values for contact autocomplete
716 $acOptions = CRM_Core_OptionGroup
::values('contact_autocomplete_options', FALSE, FALSE, FALSE, NULL, 'name');
719 foreach ($acpref as $value) {
720 if ($value && !empty($acOptions[$value])) {
721 $list[$value] = $acOptions[$value];
724 // If we are doing quicksearch by a field other than name, make sure that field is added to results
725 if (!empty($params['field_name'])) {
726 $field_name = CRM_Utils_String
::munge($params['field_name']);
727 // Unique name contact_id = id
728 if ($field_name == 'contact_id') {
731 // phone_numeric should be phone
732 $searchField = str_replace('_numeric', '', $field_name);
733 if (!in_array($searchField, $list)) {
734 $list[] = $searchField;
738 // Set field name to first name for exact match checking.
739 $field_name = 'sort_name';
742 $select = $actualSelectElements = array('sort_name');
745 foreach ($list as $value) {
746 $suffix = substr($value, 0, 2) . substr($value, -1);
748 case 'street_address':
751 $selectText = $value;
756 $actualSelectElements[] = $select[] = ($value == 'address') ?
$selectText : $value;
757 if ($value == 'phone') {
758 $actualSelectElements[] = $select[] = 'phone_ext';
760 $from[$value] = "LEFT JOIN civicrm_{$value} {$suffix} ON ( cc.id = {$suffix}.contact_id AND {$suffix}.is_primary = 1 ) ";
764 case 'state_province':
765 $select[] = "{$suffix}.name as {$value}";
766 $actualSelectElements[] = "{$suffix}.name";
767 if (!in_array('address', $from)) {
768 $from['address'] = 'LEFT JOIN civicrm_address sts ON ( cc.id = sts.contact_id AND sts.is_primary = 1) ';
770 $from[$value] = " LEFT JOIN civicrm_{$value} {$suffix} ON ( sts.{$value}_id = {$suffix}.id ) ";
774 if ($value != 'id') {
776 if (!empty($params['field_name']) && $params['field_name'] == 'value') {
777 $suffix = CRM_Utils_String
::munge(CRM_Utils_Array
::value('table_name', $params, 'cc'));
779 $actualSelectElements[] = $select[] = $suffix . '.' . $value;
785 $config = CRM_Core_Config
::singleton();
787 $select = implode(', ', $select);
788 if (!empty($select)) {
789 $select = ", $select";
791 $actualSelectElements = implode(', ', $actualSelectElements);
792 $selectAliases = $from;
793 unset($selectAliases['address']);
794 $selectAliases = implode(', ', array_keys($selectAliases));
795 if (!empty($selectAliases)) {
796 $selectAliases = ", $selectAliases";
798 $from = implode(' ', $from);
799 $limit = (int) CRM_Utils_Array
::value('limit', $params);
800 $limit = $limit > 0 ?
$limit : Civi
::settings()->get('search_autocomplete_count');
802 // add acl clause here
803 list($aclFrom, $aclWhere) = CRM_Contact_BAO_Contact_Permission
::cacheClause('cc');
806 $where .= " AND $aclWhere ";
809 if (!empty($params['org'])) {
810 $where .= " AND contact_type = \"Organization\"";
812 // CRM-7157, hack: get current employer details when
813 // employee_id is present.
814 $currEmpDetails = array();
815 if (!empty($params['employee_id'])) {
816 if ($currentEmployer = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact',
817 (int) $params['employee_id'],
820 if ($config->includeWildCardInName
) {
821 $strSearch = "%$name%";
824 $strSearch = "$name%";
827 // get current employer details
828 $dao = CRM_Core_DAO
::executeQuery("SELECT cc.id as id, CONCAT_WS( ' :: ', {$actualSelectElements} ) as data, sort_name
829 FROM civicrm_contact cc {$from} WHERE cc.contact_type = \"Organization\" AND cc.id = {$currentEmployer} AND cc.sort_name LIKE '$strSearch'");
831 $currEmpDetails = array(
833 'data' => $dao->data
,
840 if (!empty($params['contact_sub_type'])) {
841 $contactSubType = CRM_Utils_Type
::escape($params['contact_sub_type'], 'String');
842 $where .= " AND cc.contact_sub_type = '{$contactSubType}'";
845 if (!empty($params['contact_type'])) {
846 $contactType = CRM_Utils_Type
::escape($params['contact_type'], 'String');
847 $where .= " AND cc.contact_type LIKE '{$contactType}'";
850 // Set default for current_employer or return contact with particular id
851 if (!empty($params['id'])) {
852 $where .= " AND cc.id = " . (int) $params['id'];
855 if (!empty($params['cid'])) {
856 $where .= " AND cc.id <> " . (int) $params['cid'];
859 // Contact's based of relationhip type
861 if (!empty($params['rel'])) {
862 $relation = explode('_', CRM_Utils_Array
::value('rel', $params));
863 $relType = CRM_Utils_Type
::escape($relation[0], 'Integer');
864 $rel = CRM_Utils_Type
::escape($relation[2], 'String');
867 if ($config->includeWildCardInName
) {
868 $strSearch = "%$name%";
871 $strSearch = "$name%";
873 $includeEmailFrom = $includeNickName = $exactIncludeNickName = '';
874 if ($config->includeNickNameInName
) {
875 $includeNickName = " OR nick_name LIKE '$strSearch'";
876 $exactIncludeNickName = " OR nick_name LIKE '$name'";
880 if (!empty($params['field_name']) && !empty($params['table_name'])) {
881 $whereClause = " WHERE ( $table_name.$field_name LIKE '$strSearch') {$where}";
882 $exactWhereClause = " WHERE ( $table_name.$field_name = '$name') {$where}";
883 // Search by id should be exact
884 if ($field_name == 'id' ||
$field_name == 'external_identifier') {
885 $whereClause = $exactWhereClause;
889 $whereClause = " WHERE ( sort_name LIKE '$strSearch' $includeNickName ) {$where} ";
890 $exactWhereClause = " WHERE ( sort_name LIKE '$name' $exactIncludeNickName ) {$where} ";
891 if ($config->includeEmailInName
) {
892 if (!in_array('email', $list)) {
893 $includeEmailFrom = "LEFT JOIN civicrm_email eml ON ( cc.id = eml.contact_id AND eml.is_primary = 1 )";
895 $emailWhere = " WHERE email LIKE '$strSearch'";
899 $additionalFrom = '';
902 INNER JOIN civicrm_relationship_type r ON (
904 AND ( cc.contact_type = r.contact_type_{$rel} OR r.contact_type_{$rel} IS NULL )
905 AND ( cc.contact_sub_type = r.contact_sub_type_{$rel} OR r.contact_sub_type_{$rel} IS NULL )
909 // check if only CMS users are requested
910 if (!empty($params['cmsuser'])) {
912 INNER JOIN civicrm_uf_match um ON (um.contact_id=cc.id)
916 $orderByInner = $orderByOuter = "ORDER BY exactFirst";
917 if ($config->includeOrderByClause
) {
918 $orderByInner = "ORDER BY exactFirst, sort_name";
919 $orderByOuter .= ", sort_name";
924 SELECT DISTINCT(id), data, sort_name {$selectAliases}, exactFirst
926 ( SELECT IF($table_name.$field_name = '{$name}', 0, 1) as exactFirst, cc.id as id, CONCAT_WS( ' :: ',
927 {$actualSelectElements} )
930 FROM civicrm_contact cc {$from}
938 if (!empty($emailWhere)) {
941 SELECT IF($table_name.$field_name = '{$name}', 0, 1) as exactFirst, cc.id as id, CONCAT_WS( ' :: ',
942 {$actualSelectElements} )
945 FROM civicrm_contact cc {$from}
947 {$additionalFrom} {$includeEmailFrom}
948 {$emailWhere} AND cc.is_deleted = 0 " . ($aclWhere ?
" AND $aclWhere " : '') . "
959 // send query to hook to be modified if needed
960 CRM_Utils_Hook
::contactListQuery($query,
962 empty($params['context']) ?
NULL : CRM_Utils_Type
::escape($params['context'], 'String'),
963 empty($params['id']) ?
NULL : $params['id']
966 $dao = CRM_Core_DAO
::executeQuery($query);
968 $contactList = array();
969 $listCurrentEmployer = TRUE;
970 while ($dao->fetch()) {
971 $t = array('id' => $dao->id
);
972 foreach ($as as $k) {
973 $t[$k] = isset($dao->$k) ?
$dao->$k : '';
975 $t['data'] = $dao->data
;
977 if (!empty($params['org']) &&
978 !empty($currEmpDetails) &&
979 $dao->id
== $currEmpDetails['id']
981 $listCurrentEmployer = FALSE;
985 //return organization name if doesn't exist in db
986 if (empty($contactList)) {
987 if (!empty($params['org'])) {
988 if ($listCurrentEmployer && !empty($currEmpDetails)) {
989 $contactList = array(
991 'data' => $currEmpDetails['data'],
992 'id' => $currEmpDetails['id'],
997 $contactList = array(
1007 return civicrm_api3_create_success($contactList, $params, 'Contact', 'getquick');
1011 * Declare deprecated api functions.
1013 * @deprecated api notice
1015 * Array of deprecated actions
1017 function _civicrm_api3_contact_deprecation() {
1018 return array('getquick' => 'The "getquick" action is deprecated in favor of "getlist".');
1022 * Merges given pair of duplicate contacts.
1024 * @param array $params
1025 * Allowed array keys are:
1026 * -int main_id: main contact id with whom merge has to happen
1027 * -int other_id: duplicate contact which would be deleted after merge operation
1028 * -string mode: "safe" skips the merge if there are no conflicts. Does a force merge otherwise.
1029 * -boolean auto_flip: whether to let api decide which contact to retain and which to delete.
1033 * @throws CiviCRM_API3_Exception
1035 function civicrm_api3_contact_merge($params) {
1036 if (($result = CRM_Dedupe_Merger
::merge(array(
1038 'srcID' => $params['to_remove_id'],
1039 'dstID' => $params['to_keep_id'],
1041 ), array(), $params['mode'], $params['auto_flip'])) != FALSE) {
1042 return civicrm_api3_create_success($result, $params);
1044 throw new CiviCRM_API3_Exception('Merge failed');
1048 * Adjust metadata for contact_merge api function.
1050 * @param array $params
1052 function _civicrm_api3_contact_merge_spec(&$params) {
1053 $params['to_remove_id'] = array(
1054 'title' => 'ID of the contact to merge & remove',
1055 'description' => ts('Wow - these 2 params are the logical reverse of what I expect - but what to do?'),
1056 'api.required' => 1,
1057 'type' => CRM_Utils_Type
::T_INT
,
1058 'api.aliases' => array('main_id'),
1060 $params['to_keep_id'] = array(
1061 'title' => 'ID of the contact to keep',
1062 'description' => ts('Wow - these 2 params are the logical reverse of what I expect - but what to do?'),
1063 'api.required' => 1,
1064 'type' => CRM_Utils_Type
::T_INT
,
1065 'api.aliases' => array('other_id'),
1067 $params['auto_flip'] = array(
1068 'title' => 'Swap destination and source to retain lowest id?',
1069 'api.default' => TRUE,
1071 $params['mode'] = array(
1072 // @todo need more detail on what this means.
1073 'title' => 'Dedupe mode',
1074 'api.default' => 'safe',
1079 * Adjust metadata for contact_proximity api function.
1081 * @param array $params
1083 function _civicrm_api3_contact_proximity_spec(&$params) {
1084 $params['latitude'] = array(
1085 'title' => 'Latitude',
1086 'api.required' => 1,
1087 'type' => CRM_Utils_Type
::T_STRING
,
1089 $params['longitude'] = array(
1090 'title' => 'Longitude',
1091 'api.required' => 1,
1092 'type' => CRM_Utils_Type
::T_STRING
,
1095 $params['unit'] = array(
1096 'title' => 'Unit of Measurement',
1097 'api.default' => 'meter',
1098 'type' => CRM_Utils_Type
::T_STRING
,
1103 * Get contacts by proximity.
1105 * @param array $params
1110 function civicrm_api3_contact_proximity($params) {
1111 $latitude = CRM_Utils_Array
::value('latitude', $params);
1112 $longitude = CRM_Utils_Array
::value('longitude', $params);
1113 $distance = CRM_Utils_Array
::value('distance', $params);
1115 $unit = CRM_Utils_Array
::value('unit', $params);
1117 // check and ensure that lat/long and distance are floats
1119 !CRM_Utils_Rule
::numeric($latitude) ||
1120 !CRM_Utils_Rule
::numeric($longitude) ||
1121 !CRM_Utils_Rule
::numeric($distance)
1123 throw new Exception(ts('Latitude, Longitude and Distance should exist and be numeric'));
1126 if ($unit == "mile") {
1127 $conversionFactor = 1609.344;
1130 $conversionFactor = 1000;
1132 //Distance in meters
1133 $distance = $distance * $conversionFactor;
1135 $whereClause = CRM_Contact_BAO_ProximityQuery
::where($latitude, $longitude, $distance);
1138 SELECT civicrm_contact.id as contact_id,
1139 civicrm_contact.display_name as display_name
1140 FROM civicrm_contact
1141 LEFT JOIN civicrm_address ON civicrm_contact.id = civicrm_address.contact_id
1145 $dao = CRM_Core_DAO
::executeQuery($query);
1146 $contacts = array();
1147 while ($dao->fetch()) {
1148 $contacts[] = $dao->toArray();
1151 return civicrm_api3_create_success($contacts, $params, 'Contact', 'get_by_location', $dao);
1156 * Get parameters for getlist function.
1158 * @see _civicrm_api3_generic_getlist_params
1160 * @param array $request
1162 function _civicrm_api3_contact_getlist_params(&$request) {
1163 // get the autocomplete options from settings
1164 $acpref = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1165 CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
,
1166 'contact_autocomplete_options'
1170 // get the option values for contact autocomplete
1171 $acOptions = CRM_Core_OptionGroup
::values('contact_autocomplete_options', FALSE, FALSE, FALSE, NULL, 'name');
1174 foreach ($acpref as $value) {
1175 if ($value && !empty($acOptions[$value])) {
1176 $list[] = $acOptions[$value];
1179 // If we are doing quicksearch by a field other than name, make sure that field is added to results
1180 $field_name = CRM_Utils_String
::munge($request['search_field']);
1181 // Unique name contact_id = id
1182 if ($field_name == 'contact_id') {
1185 // phone_numeric should be phone
1186 $searchField = str_replace('_numeric', '', $field_name);
1187 if (!in_array($searchField, $list)) {
1188 $list[] = $searchField;
1190 $request['description_field'] = $list;
1191 $list[] = 'contact_type';
1192 $request['params']['return'] = array_unique(array_merge($list, $request['extra']));
1193 $request['params']['options']['sort'] = 'sort_name';
1194 // Contact api doesn't support array(LIKE => 'foo') syntax
1195 if (!empty($request['input'])) {
1196 $request['params'][$request['search_field']] = $request['input'];
1201 * Get output for getlist function.
1203 * @see _civicrm_api3_generic_getlist_output
1205 * @param array $result
1206 * @param array $request
1210 function _civicrm_api3_contact_getlist_output($result, $request) {
1212 if (!empty($result['values'])) {
1213 $addressFields = array_intersect(array(
1219 $request['params']['return']);
1220 foreach ($result['values'] as $row) {
1222 'id' => $row[$request['id_field']],
1223 'label' => $row[$request['label_field']],
1224 'description' => array(),
1226 foreach ($request['description_field'] as $item) {
1227 if (!strpos($item, '_name') && !in_array($item, $addressFields) && !empty($row[$item])) {
1228 $data['description'][] = $row[$item];
1232 foreach ($addressFields as $item) {
1233 if (!empty($row[$item])) {
1234 $address[] = $row[$item];
1238 $data['description'][] = implode(' ', $address);
1240 if (!empty($request['image_field'])) {
1241 $data['image'] = isset($row[$request['image_field']]) ?
$row[$request['image_field']] : '';
1244 $data['icon_class'] = $row['contact_type'];
1253 * Check for duplicate contacts.
1255 * @param array $params
1256 * Params per getfields metadata.
1259 * API formatted array
1261 function civicrm_api3_contact_duplicatecheck($params) {
1262 $dedupeParams = CRM_Dedupe_Finder
::formatParams($params['match'], $params['match']['contact_type']);
1265 // setting 'check_permission' here means that the dedupe checking will be carried out even if the
1266 // person does not have permission to carry out de-dupes
1267 // this is similar to the front end form
1268 if (isset($params['check_permission'])) {
1269 $dedupeParams['check_permission'] = $params['check_permission'];
1272 $dupes = CRM_Dedupe_Finder
::dupesByParams($dedupeParams, $params['match']['contact_type'], 'Unsupervised', array(), CRM_Utils_Array
::value('dedupe_rule_id', $params));
1273 $values = empty($dupes) ?
array() : array_fill_keys($dupes, array());
1274 return civicrm_api3_create_success($values, $params, 'Contact', 'duplicatecheck');
1278 * Declare metadata for contact dedupe function.
1282 function _civicrm_api3_contact_duplicatecheck_spec(&$params) {
1283 $params['dedupe_rule_id'] = array(
1284 'title' => 'Dedupe Rule ID (optional)',
1285 'description' => 'This will default to the built in unsupervised rule',
1286 'type' => CRM_Utils_Type
::T_INT
,
1288 // @todo declare 'match' parameter. We don't have a standard for type = array yet.