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 $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;
379 if (isset($params['group'])) {
380 $groups = $params['group'];
381 $allGroups = CRM_Core_PseudoConstant
::group();
382 if (is_array($groups) && in_array(key($groups), CRM_Core_DAO
::acceptedSQLOperators(), TRUE)) {
383 // Get the groups array.
384 $groupsArray = $groups[key($groups)];
385 foreach ($groupsArray as &$group) {
386 if (!is_numeric($group) && array_search($group, $allGroups)) {
387 $group = array_search($group, $allGroups);
390 // Now reset the $groups array with the ids not the titles.
391 $groups[key($groups)] = $groupsArray;
393 // handle format like 'group' => array('title1', 'title2').
394 elseif (is_array($groups)) {
395 foreach ($groups as $k => &$group) {
396 if (!is_numeric($group) && array_search($group, $allGroups)) {
397 $group = array_search($group, $allGroups);
399 if (!is_numeric($k) && array_search($k, $allGroups)) {
401 $groups[array_search($k, $allGroups)] = $group;
405 elseif (!is_numeric($groups) && array_search($groups, $allGroups)) {
406 $groups = array_search($groups, $allGroups);
408 $params['group'] = $groups;
413 * Delete a Contact with given contact_id.
415 * @param array $params
416 * input parameters per getfields
418 * @throws \Civi\API\Exception\UnauthorizedException
422 function civicrm_api3_contact_delete($params) {
423 $contactID = CRM_Utils_Array
::value('id', $params);
425 if (!empty($params['check_permissions']) && !CRM_Contact_BAO_Contact_Permission
::allow($contactID, CRM_Core_Permission
::DELETE
)) {
426 throw new \Civi\API\Exception\
UnauthorizedException('Permission denied to modify contact record');
429 $session = CRM_Core_Session
::singleton();
430 if ($contactID == $session->get('userID')) {
431 return civicrm_api3_create_error('This contact record is linked to the currently logged in user account - and cannot be deleted.');
433 $restore = !empty($params['restore']) ?
$params['restore'] : FALSE;
434 $skipUndelete = !empty($params['skip_undelete']) ?
$params['skip_undelete'] : FALSE;
437 // restrict permanent delete if a contact has financial trxn associated with it
439 if ($skipUndelete && CRM_Financial_BAO_FinancialItem
::checkContactPresent(array($contactID), $error)) {
440 return civicrm_api3_create_error($error['_qf_default']);
442 if (CRM_Contact_BAO_Contact
::deleteContact($contactID, $restore, $skipUndelete,
443 CRM_Utils_Array
::value('check_permissions', $params))) {
444 return civicrm_api3_create_success();
447 return civicrm_api3_create_error('Could not delete contact');
453 * Check parameters passed in.
455 * This function is on it's way out.
457 * @param array $params
458 * @param bool $dupeCheck
461 * @throws API_Exception
462 * @throws CiviCRM_API3_Exception
464 function _civicrm_api3_contact_check_params(&$params, $dupeCheck) {
466 switch (strtolower(CRM_Utils_Array
::value('contact_type', $params))) {
468 civicrm_api3_verify_mandatory($params, NULL, array('household_name'));
472 civicrm_api3_verify_mandatory($params, NULL, array('organization_name'));
476 civicrm_api3_verify_one_mandatory($params, NULL, array(
486 // Fixme: This really needs to be handled at a lower level. @See CRM-13123
487 if (isset($params['preferred_communication_method'])) {
488 $params['preferred_communication_method'] = CRM_Utils_Array
::implodePadded($params['preferred_communication_method']);
491 if (!empty($params['contact_sub_type']) && !empty($params['contact_type'])) {
492 if (!(CRM_Contact_BAO_ContactType
::isExtendsContactType($params['contact_sub_type'], $params['contact_type']))) {
493 throw new API_Exception("Invalid or Mismatched Contact Subtype: " . implode(', ', (array) $params['contact_sub_type']));
498 // check for record already existing
499 $dedupeParams = CRM_Dedupe_Finder
::formatParams($params, $params['contact_type']);
502 // setting 'check_permission' here means that the dedupe checking will be carried out even if the
503 // person does not have permission to carry out de-dupes
504 // this is similar to the front end form
505 if (isset($params['check_permission'])) {
506 $dedupeParams['check_permission'] = $params['check_permission'];
509 $ids = CRM_Dedupe_Finder
::dupesByParams($dedupeParams, $params['contact_type'], 'Unsupervised', array());
511 if (count($ids) > 0) {
512 throw new API_Exception("Found matching contacts: " . implode(',', $ids), "duplicate", array("ids" => $ids));
516 // The BAO no longer supports the legacy param "current_employer" so here is a shim for api backward-compatability
517 if (!empty($params['current_employer'])) {
518 $organizationParams = array(
519 'organization_name' => $params['current_employer'],
522 $dedupParams = CRM_Dedupe_Finder
::formatParams($organizationParams, 'Organization');
524 $dedupParams['check_permission'] = FALSE;
525 $dupeIds = CRM_Dedupe_Finder
::dupesByParams($dedupParams, 'Organization', 'Supervised');
527 // check for mismatch employer name and id
528 if (!empty($params['employer_id']) && !in_array($params['employer_id'], $dupeIds)) {
529 throw new API_Exception('Employer name and Employer id Mismatch');
532 // show error if multiple organisation with same name exist
533 if (empty($params['employer_id']) && (count($dupeIds) > 1)) {
534 throw new API_Exception('Found more than one Organisation with same Name.');
538 $params['employer_id'] = $dupeIds[0];
541 $result = civicrm_api3('Contact', 'create', array(
542 'organization_name' => $params['current_employer'],
543 'contact_type' => 'Organization',
545 $params['employer_id'] = $result['id'];
553 * Helper function for Contact create.
555 * @param array $params
556 * (reference ) an assoc array of name/value pairs.
557 * @param int $contactID
558 * If present the contact with that ID is updated.
560 * @return CRM_Contact_BAO_Contact|CRM_Core_Error
562 function _civicrm_api3_contact_update($params, $contactID = NULL) {
563 //@todo - doesn't contact create support 'id' which is already set- check & remove
565 $params['contact_id'] = $contactID;
568 return CRM_Contact_BAO_Contact
::create($params);
572 * Validate the addressee or email or postal greetings.
574 * @param array $params
575 * Array per getfields metadata.
577 * @throws API_Exception
579 function _civicrm_api3_greeting_format_params($params) {
580 $greetingParams = array('', '_id', '_custom');
581 foreach (array('email', 'postal', 'addressee') as $key) {
582 $greeting = '_greeting';
583 if ($key == 'addressee') {
587 $formatParams = FALSE;
588 // Unset display value from params.
589 if (isset($params["{$key}{$greeting}_display"])) {
590 unset($params["{$key}{$greeting}_display"]);
593 // check if greetings are present in present
594 foreach ($greetingParams as $greetingValues) {
595 if (array_key_exists("{$key}{$greeting}{$greetingValues}", $params)) {
596 $formatParams = TRUE;
601 if (!$formatParams) {
607 'contact_type' => $params['contact_type'],
608 'greeting_type' => "{$key}{$greeting}",
611 $greetings = CRM_Core_PseudoConstant
::greeting($filter);
612 $greetingId = CRM_Utils_Array
::value("{$key}{$greeting}_id", $params);
613 $greetingVal = CRM_Utils_Array
::value("{$key}{$greeting}", $params);
614 $customGreeting = CRM_Utils_Array
::value("{$key}{$greeting}_custom", $params);
616 if (!$greetingId && $greetingVal) {
617 $params["{$key}{$greeting}_id"] = CRM_Utils_Array
::key($params["{$key}{$greeting}"], $greetings);
620 if ($customGreeting && $greetingId &&
621 ($greetingId != array_search('Customized', $greetings))
623 throw new API_Exception(ts('Provide either %1 greeting id and/or %1 greeting or custom %1 greeting',
628 if ($greetingVal && $greetingId &&
629 ($greetingId != CRM_Utils_Array
::key($greetingVal, $greetings))
631 throw new API_Exception(ts('Mismatch in %1 greeting id and %1 greeting',
638 if (!array_key_exists($greetingId, $greetings)) {
639 throw new API_Exception(ts('Invalid %1 greeting Id', array(1 => $key)));
642 if (!$customGreeting && ($greetingId == array_search('Customized', $greetings))) {
643 throw new API_Exception(ts('Please provide a custom value for %1 greeting',
648 elseif ($greetingVal) {
650 if (!in_array($greetingVal, $greetings)) {
651 throw new API_Exception(ts('Invalid %1 greeting', array(1 => $key)));
654 $greetingId = CRM_Utils_Array
::key($greetingVal, $greetings);
657 if ($customGreeting) {
658 $greetingId = CRM_Utils_Array
::key('Customized', $greetings);
661 $customValue = isset($params['contact_id']) ? CRM_Core_DAO
::getFieldValue(
662 'CRM_Contact_DAO_Contact',
663 $params['contact_id'],
664 "{$key}{$greeting}_custom"
667 if (array_key_exists("{$key}{$greeting}_id", $params) && empty($params["{$key}{$greeting}_id"])) {
670 elseif (array_key_exists("{$key}{$greeting}", $params) && empty($params["{$key}{$greeting}"])) {
673 elseif ($customValue && array_key_exists("{$key}{$greeting}_custom", $params)
674 && empty($params["{$key}{$greeting}_custom"])
679 $params["{$key}{$greeting}_id"] = $greetingId;
681 if (!$customValue && !$customGreeting && array_key_exists("{$key}{$greeting}_custom", $params)) {
682 unset($params["{$key}{$greeting}_custom"]);
686 $params["{$key}{$greeting}_id"] = '';
687 $params["{$key}{$greeting}_custom"] = '';
690 if (isset($params["{$key}{$greeting}"])) {
691 unset($params["{$key}{$greeting}"]);
697 * Adjust Metadata for Get action.
699 * @param array $params
700 * Array of parameters determined by getfields.
702 function _civicrm_api3_contact_getquick_spec(&$params) {
703 $params['name']['api.required'] = TRUE;
704 $params['name']['title'] = ts('String to search on');
705 $params['name']['type'] = CRM_Utils_Type
::T_STRING
;
706 $params['field']['type'] = CRM_Utils_Type
::T_STRING
;
707 $params['field']['title'] = ts('Field to search on');
708 $params['field']['options'] = array(
712 'external_identifier',
722 $params['table_name']['type'] = CRM_Utils_Type
::T_STRING
;
723 $params['table_name']['title'] = ts('Table alias to search on');
724 $params['table_name']['api.default'] = 'cc';
728 * Old Contact quick search api.
732 * @param array $params
735 * @throws \API_Exception
737 function civicrm_api3_contact_getquick($params) {
738 $name = CRM_Utils_Type
::escape(CRM_Utils_Array
::value('name', $params), 'String');
739 $table_name = CRM_Utils_String
::munge($params['table_name']);
740 // get the autocomplete options from settings
741 $acpref = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
742 CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
,
743 'contact_autocomplete_options'
747 // get the option values for contact autocomplete
748 $acOptions = CRM_Core_OptionGroup
::values('contact_autocomplete_options', FALSE, FALSE, FALSE, NULL, 'name');
751 foreach ($acpref as $value) {
752 if ($value && !empty($acOptions[$value])) {
753 $list[$value] = $acOptions[$value];
756 // If we are doing quicksearch by a field other than name, make sure that field is added to results
757 if (!empty($params['field_name'])) {
758 $field_name = CRM_Utils_String
::munge($params['field_name']);
759 // Unique name contact_id = id
760 if ($field_name == 'contact_id') {
763 // phone_numeric should be phone
764 $searchField = str_replace('_numeric', '', $field_name);
765 if (!in_array($searchField, $list)) {
766 $list[] = $searchField;
770 // Set field name to first name for exact match checking.
771 $field_name = 'sort_name';
774 $select = $actualSelectElements = array('sort_name');
777 foreach ($list as $value) {
778 $suffix = substr($value, 0, 2) . substr($value, -1);
780 case 'street_address':
783 $selectText = $value;
788 $actualSelectElements[] = $select[] = ($value == 'address') ?
$selectText : $value;
789 if ($value == 'phone') {
790 $actualSelectElements[] = $select[] = 'phone_ext';
792 $from[$value] = "LEFT JOIN civicrm_{$value} {$suffix} ON ( cc.id = {$suffix}.contact_id AND {$suffix}.is_primary = 1 ) ";
796 case 'state_province':
797 $select[] = "{$suffix}.name as {$value}";
798 $actualSelectElements[] = "{$suffix}.name";
799 if (!in_array('address', $from)) {
800 $from['address'] = 'LEFT JOIN civicrm_address sts ON ( cc.id = sts.contact_id AND sts.is_primary = 1) ';
802 $from[$value] = " LEFT JOIN civicrm_{$value} {$suffix} ON ( sts.{$value}_id = {$suffix}.id ) ";
806 if ($value != 'id') {
808 if (!empty($params['field_name']) && $params['field_name'] == 'value') {
809 $suffix = CRM_Utils_String
::munge(CRM_Utils_Array
::value('table_name', $params, 'cc'));
811 $actualSelectElements[] = $select[] = $suffix . '.' . $value;
817 $config = CRM_Core_Config
::singleton();
819 $select = implode(', ', $select);
820 if (!empty($select)) {
821 $select = ", $select";
823 $actualSelectElements = implode(', ', $actualSelectElements);
824 $selectAliases = $from;
825 unset($selectAliases['address']);
826 $selectAliases = implode(', ', array_keys($selectAliases));
827 if (!empty($selectAliases)) {
828 $selectAliases = ", $selectAliases";
830 $from = implode(' ', $from);
831 $limit = (int) CRM_Utils_Array
::value('limit', $params);
832 $limit = $limit > 0 ?
$limit : Civi
::settings()->get('search_autocomplete_count');
834 // add acl clause here
835 list($aclFrom, $aclWhere) = CRM_Contact_BAO_Contact_Permission
::cacheClause('cc');
838 $where .= " AND $aclWhere ";
840 $isPrependWildcard = \Civi
::settings()->get('includeWildCardInName');
842 if (!empty($params['org'])) {
843 $where .= " AND contact_type = \"Organization\"";
845 // CRM-7157, hack: get current employer details when
846 // employee_id is present.
847 $currEmpDetails = array();
848 if (!empty($params['employee_id'])) {
849 if ($currentEmployer = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact',
850 (int) $params['employee_id'],
853 if ($isPrependWildcard) {
854 $strSearch = "%$name%";
857 $strSearch = "$name%";
860 // get current employer details
861 $dao = CRM_Core_DAO
::executeQuery("SELECT cc.id as id, CONCAT_WS( ' :: ', {$actualSelectElements} ) as data, sort_name
862 FROM civicrm_contact cc {$from} WHERE cc.contact_type = \"Organization\" AND cc.id = {$currentEmployer} AND cc.sort_name LIKE '$strSearch'");
864 $currEmpDetails = array(
866 'data' => $dao->data
,
873 if (!empty($params['contact_sub_type'])) {
874 $contactSubType = CRM_Utils_Type
::escape($params['contact_sub_type'], 'String');
875 $where .= " AND cc.contact_sub_type = '{$contactSubType}'";
878 if (!empty($params['contact_type'])) {
879 $contactType = CRM_Utils_Type
::escape($params['contact_type'], 'String');
880 $where .= " AND cc.contact_type LIKE '{$contactType}'";
883 // Set default for current_employer or return contact with particular id
884 if (!empty($params['id'])) {
885 $where .= " AND cc.id = " . (int) $params['id'];
888 if (!empty($params['cid'])) {
889 $where .= " AND cc.id <> " . (int) $params['cid'];
892 // Contact's based of relationhip type
894 if (!empty($params['rel'])) {
895 $relation = explode('_', CRM_Utils_Array
::value('rel', $params));
896 $relType = CRM_Utils_Type
::escape($relation[0], 'Integer');
897 $rel = CRM_Utils_Type
::escape($relation[2], 'String');
900 if ($isPrependWildcard) {
901 $strSearch = "%$name%";
904 $strSearch = "$name%";
906 $includeEmailFrom = $includeNickName = $exactIncludeNickName = '';
907 if ($config->includeNickNameInName
) {
908 $includeNickName = " OR nick_name LIKE '$strSearch'";
909 $exactIncludeNickName = " OR nick_name LIKE '$name'";
913 if (!empty($params['field_name']) && !empty($params['table_name'])) {
914 $whereClause = " WHERE ( $table_name.$field_name LIKE '$strSearch') {$where}";
915 // Search by id should be exact
916 if ($field_name == 'id' ||
$field_name == 'external_identifier') {
917 $whereClause = " WHERE ( $table_name.$field_name = '$name') {$where}";
921 $whereClause = " WHERE ( sort_name LIKE '$strSearch' $includeNickName ) {$where} ";
922 if ($config->includeEmailInName
) {
923 if (!in_array('email', $list)) {
924 $includeEmailFrom = "LEFT JOIN civicrm_email eml ON ( cc.id = eml.contact_id AND eml.is_primary = 1 )";
926 $emailWhere = " WHERE email LIKE '$strSearch'";
930 $additionalFrom = '';
933 INNER JOIN civicrm_relationship_type r ON (
935 AND ( cc.contact_type = r.contact_type_{$rel} OR r.contact_type_{$rel} IS NULL )
936 AND ( cc.contact_sub_type = r.contact_sub_type_{$rel} OR r.contact_sub_type_{$rel} IS NULL )
940 // check if only CMS users are requested
941 if (!empty($params['cmsuser'])) {
943 INNER JOIN civicrm_uf_match um ON (um.contact_id=cc.id)
946 $orderBy = _civicrm_api3_quicksearch_get_order_by($name, $isPrependWildcard, $field_name);
950 SELECT DISTINCT(id), data, sort_name {$selectAliases}, exactFirst
952 ( SELECT IF($table_name.$field_name = '{$name}', 0, 1) as exactFirst, cc.id as id, CONCAT_WS( ' :: ',
953 {$actualSelectElements} )
956 FROM civicrm_contact cc {$from}
964 if (!empty($emailWhere)) {
967 SELECT IF($table_name.$field_name = '{$name}', 0, 1) as exactFirst, cc.id as id, CONCAT_WS( ' :: ',
968 {$actualSelectElements} )
971 FROM civicrm_contact cc {$from}
973 {$additionalFrom} {$includeEmailFrom}
974 {$emailWhere} AND cc.is_deleted = 0 " . ($aclWhere ?
" AND $aclWhere " : '') . "
985 // send query to hook to be modified if needed
986 CRM_Utils_Hook
::contactListQuery($query,
988 empty($params['context']) ?
NULL : CRM_Utils_Type
::escape($params['context'], 'String'),
989 empty($params['id']) ?
NULL : $params['id']
992 $dao = CRM_Core_DAO
::executeQuery($query);
994 $contactList = array();
995 $listCurrentEmployer = TRUE;
996 while ($dao->fetch()) {
997 $t = array('id' => $dao->id
);
998 foreach ($as as $k) {
999 $t[$k] = isset($dao->$k) ?
$dao->$k : '';
1001 $t['data'] = $dao->data
;
1002 $contactList[] = $t;
1003 if (!empty($params['org']) &&
1004 !empty($currEmpDetails) &&
1005 $dao->id
== $currEmpDetails['id']
1007 $listCurrentEmployer = FALSE;
1011 //return organization name if doesn't exist in db
1012 if (empty($contactList)) {
1013 if (!empty($params['org'])) {
1014 if ($listCurrentEmployer && !empty($currEmpDetails)) {
1015 $contactList = array(
1017 'data' => $currEmpDetails['data'],
1018 'id' => $currEmpDetails['id'],
1023 $contactList = array(
1033 return civicrm_api3_create_success($contactList, $params, 'Contact', 'getquick');
1037 * Get the order by string for the quicksearch query.
1039 * Get the order by string. The string might be
1040 * - sort name if there is no search value provided and the site is configured
1041 * to search by sort name
1042 * - empty if there is no search value provided and the site is not configured
1043 * to search by sort name
1044 * - exactFirst and then sort name if a search value is provided and the site is configured
1045 * to search by sort name
1046 * - exactFirst if a search value is provided and the site is not configured
1047 * to search by sort name
1049 * exactFirst means 'yes if the search value exactly matches the searched field. else no'.
1050 * It is intended to prioritise exact matches for the entered string so on a first name search
1051 * for 'kath' contacts with a first name of exactly Kath rise to the top.
1053 * On short strings it is expensive. Per CRM-19547 there is still an open question
1054 * as to whether we should only do exactMatch on a minimum length or on certain fields.
1056 * However, we have mitigated this somewhat by not doing an exact match search on
1057 * empty strings, non-wildcard sort-name searches and email searches where there is
1058 * no @ after the first character.
1060 * For the user it is further mitigated by the fact they just don't know the
1061 * slower queries are firing. If they type 'smit' slowly enough 4 queries will trigger
1062 * but if the first 3 are slow the first result they see may be off the 4th query.
1064 * @param string $name
1065 * @param bool $isPrependWildcard
1066 * @param string $field_name
1070 function _civicrm_api3_quicksearch_get_order_by($name, $isPrependWildcard, $field_name) {
1071 $skipExactMatch = ($name === '%');
1072 if ($field_name === 'email' && !strpos('@', $name)) {
1073 $skipExactMatch = TRUE;
1076 if (!\Civi
::settings()->get('includeOrderByClause')) {
1077 return $skipExactMatch ?
'' : "ORDER BY exactFirst";
1079 if ($skipExactMatch ||
(!$isPrependWildcard && $field_name === 'sort_name')) {
1080 // If there is no wildcard then sorting by exactFirst would have the same
1081 // effect as just a sort_name search, but slower.
1082 return "ORDER BY sort_name";
1085 return "ORDER BY exactFirst, sort_name";
1089 * Declare deprecated api functions.
1091 * @deprecated api notice
1093 * Array of deprecated actions
1095 function _civicrm_api3_contact_deprecation() {
1096 return array('getquick' => 'The "getquick" action is deprecated in favor of "getlist".');
1100 * Merges given pair of duplicate contacts.
1102 * @param array $params
1103 * Allowed array keys are:
1104 * -int main_id: main contact id with whom merge has to happen
1105 * -int other_id: duplicate contact which would be deleted after merge operation
1106 * -string mode: "safe" skips the merge if there are no conflicts. Does a force merge otherwise.
1107 * -boolean auto_flip: whether to let api decide which contact to retain and which to delete.
1111 * @throws CiviCRM_API3_Exception
1113 function civicrm_api3_contact_merge($params) {
1114 if (($result = CRM_Dedupe_Merger
::merge(array(
1116 'srcID' => $params['to_remove_id'],
1117 'dstID' => $params['to_keep_id'],
1119 ), array(), $params['mode'])) != FALSE) {
1120 return civicrm_api3_create_success($result, $params);
1122 throw new CiviCRM_API3_Exception('Merge failed');
1126 * Adjust metadata for contact_merge api function.
1128 * @param array $params
1130 function _civicrm_api3_contact_merge_spec(&$params) {
1131 $params['to_remove_id'] = array(
1132 'title' => 'ID of the contact to merge & remove',
1133 'description' => ts('Wow - these 2 params are the logical reverse of what I expect - but what to do?'),
1134 'api.required' => 1,
1135 'type' => CRM_Utils_Type
::T_INT
,
1136 'api.aliases' => array('main_id'),
1138 $params['to_keep_id'] = array(
1139 'title' => 'ID of the contact to keep',
1140 'description' => ts('Wow - these 2 params are the logical reverse of what I expect - but what to do?'),
1141 'api.required' => 1,
1142 'type' => CRM_Utils_Type
::T_INT
,
1143 'api.aliases' => array('other_id'),
1145 $params['mode'] = array(
1146 // @todo need more detail on what this means.
1147 'title' => 'Dedupe mode',
1148 'api.default' => 'safe',
1153 * Adjust metadata for contact_proximity api function.
1155 * @param array $params
1157 function _civicrm_api3_contact_proximity_spec(&$params) {
1158 $params['latitude'] = array(
1159 'title' => 'Latitude',
1160 'api.required' => 1,
1161 'type' => CRM_Utils_Type
::T_STRING
,
1163 $params['longitude'] = array(
1164 'title' => 'Longitude',
1165 'api.required' => 1,
1166 'type' => CRM_Utils_Type
::T_STRING
,
1169 $params['unit'] = array(
1170 'title' => 'Unit of Measurement',
1171 'api.default' => 'meter',
1172 'type' => CRM_Utils_Type
::T_STRING
,
1177 * Get contacts by proximity.
1179 * @param array $params
1184 function civicrm_api3_contact_proximity($params) {
1185 $latitude = CRM_Utils_Array
::value('latitude', $params);
1186 $longitude = CRM_Utils_Array
::value('longitude', $params);
1187 $distance = CRM_Utils_Array
::value('distance', $params);
1189 $unit = CRM_Utils_Array
::value('unit', $params);
1191 // check and ensure that lat/long and distance are floats
1193 !CRM_Utils_Rule
::numeric($latitude) ||
1194 !CRM_Utils_Rule
::numeric($longitude) ||
1195 !CRM_Utils_Rule
::numeric($distance)
1197 throw new Exception(ts('Latitude, Longitude and Distance should exist and be numeric'));
1200 if ($unit == "mile") {
1201 $conversionFactor = 1609.344;
1204 $conversionFactor = 1000;
1206 //Distance in meters
1207 $distance = $distance * $conversionFactor;
1209 $whereClause = CRM_Contact_BAO_ProximityQuery
::where($latitude, $longitude, $distance);
1212 SELECT civicrm_contact.id as contact_id,
1213 civicrm_contact.display_name as display_name
1214 FROM civicrm_contact
1215 LEFT JOIN civicrm_address ON civicrm_contact.id = civicrm_address.contact_id
1219 $dao = CRM_Core_DAO
::executeQuery($query);
1220 $contacts = array();
1221 while ($dao->fetch()) {
1222 $contacts[] = $dao->toArray();
1225 return civicrm_api3_create_success($contacts, $params, 'Contact', 'get_by_location', $dao);
1230 * Get parameters for getlist function.
1232 * @see _civicrm_api3_generic_getlist_params
1234 * @param array $request
1236 function _civicrm_api3_contact_getlist_params(&$request) {
1237 // get the autocomplete options from settings
1238 $acpref = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1239 CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
,
1240 'contact_autocomplete_options'
1244 // get the option values for contact autocomplete
1245 $acOptions = CRM_Core_OptionGroup
::values('contact_autocomplete_options', FALSE, FALSE, FALSE, NULL, 'name');
1248 foreach ($acpref as $value) {
1249 if ($value && !empty($acOptions[$value])) {
1250 $list[] = $acOptions[$value];
1253 // If we are doing quicksearch by a field other than name, make sure that field is added to results
1254 $field_name = CRM_Utils_String
::munge($request['search_field']);
1255 // Unique name contact_id = id
1256 if ($field_name == 'contact_id') {
1259 // phone_numeric should be phone
1260 $searchField = str_replace('_numeric', '', $field_name);
1261 if (!in_array($searchField, $list)) {
1262 $list[] = $searchField;
1264 $request['description_field'] = $list;
1265 $list[] = 'contact_type';
1266 $request['params']['return'] = array_unique(array_merge($list, $request['extra']));
1267 $request['params']['options']['sort'] = 'sort_name';
1268 // Contact api doesn't support array(LIKE => 'foo') syntax
1269 if (!empty($request['input'])) {
1270 $request['params'][$request['search_field']] = $request['input'];
1275 * Get output for getlist function.
1277 * @see _civicrm_api3_generic_getlist_output
1279 * @param array $result
1280 * @param array $request
1284 function _civicrm_api3_contact_getlist_output($result, $request) {
1286 if (!empty($result['values'])) {
1287 $addressFields = array_intersect(array(
1293 $request['params']['return']);
1294 foreach ($result['values'] as $row) {
1296 'id' => $row[$request['id_field']],
1297 'label' => $row[$request['label_field']],
1298 'description' => array(),
1300 foreach ($request['description_field'] as $item) {
1301 if (!strpos($item, '_name') && !in_array($item, $addressFields) && !empty($row[$item])) {
1302 $data['description'][] = $row[$item];
1306 foreach ($addressFields as $item) {
1307 if (!empty($row[$item])) {
1308 $address[] = $row[$item];
1312 $data['description'][] = implode(' ', $address);
1314 if (!empty($request['image_field'])) {
1315 $data['image'] = isset($row[$request['image_field']]) ?
$row[$request['image_field']] : '';
1318 $data['icon_class'] = $row['contact_type'];
1327 * Check for duplicate contacts.
1329 * @param array $params
1330 * Params per getfields metadata.
1333 * API formatted array
1335 function civicrm_api3_contact_duplicatecheck($params) {
1336 $dedupeParams = CRM_Dedupe_Finder
::formatParams($params['match'], $params['match']['contact_type']);
1339 // setting 'check_permission' here means that the dedupe checking will be carried out even if the
1340 // person does not have permission to carry out de-dupes
1341 // this is similar to the front end form
1342 if (isset($params['check_permission'])) {
1343 $dedupeParams['check_permission'] = $params['check_permission'];
1346 $dupes = CRM_Dedupe_Finder
::dupesByParams($dedupeParams, $params['match']['contact_type'], 'Unsupervised', array(), CRM_Utils_Array
::value('dedupe_rule_id', $params));
1347 $values = empty($dupes) ?
array() : array_fill_keys($dupes, array());
1348 return civicrm_api3_create_success($values, $params, 'Contact', 'duplicatecheck');
1352 * Declare metadata for contact dedupe function.
1356 function _civicrm_api3_contact_duplicatecheck_spec(&$params) {
1357 $params['dedupe_rule_id'] = array(
1358 'title' => 'Dedupe Rule ID (optional)',
1359 'description' => 'This will default to the built in unsupervised rule',
1360 'type' => CRM_Utils_Type
::T_INT
,
1362 // @todo declare 'match' parameter. We don't have a standard for type = array yet.