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) {
53 $contactID = CRM_Utils_Array
::value('contact_id', $params, CRM_Utils_Array
::value('id', $params));
54 $dupeCheck = CRM_Utils_Array
::value('dupe_check', $params, FALSE);
55 $values = _civicrm_api3_contact_check_params($params, $dupeCheck);
61 // If we get here, we're ready to create a new contact
62 if (($email = CRM_Utils_Array
::value('email', $params)) && !is_array($params['email'])) {
63 $defLocType = CRM_Core_BAO_LocationType
::getDefault();
64 $params['email'] = array(
68 'location_type_id' => ($defLocType->id
) ?
$defLocType->id
: 1,
74 if (!empty($params['home_url'])) {
75 $websiteTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Website', 'website_type_id');
76 $params['website'] = array(
78 'website_type_id' => key($websiteTypes),
79 'url' => $params['home_url'],
84 _civicrm_api3_greeting_format_params($params);
88 if (empty($params['contact_type']) && $contactID) {
89 $params['contact_type'] = CRM_Contact_BAO_Contact
::getContactType($contactID);
92 if (!isset($params['contact_sub_type']) && $contactID) {
93 $params['contact_sub_type'] = CRM_Contact_BAO_Contact
::getContactSubType($contactID);
96 _civicrm_api3_custom_format_params($params, $values, $params['contact_type'], $contactID);
98 $params = array_merge($params, $values);
99 //@todo we should just call basic_create here - but need to make contact:create accept 'id' on the bao
100 $contact = _civicrm_api3_contact_update($params, $contactID);
102 if (is_a($contact, 'CRM_Core_Error')) {
103 throw new API_Exception($contact->_errors
[0]['message']);
107 _civicrm_api3_object_to_array_unique_fields($contact, $values[$contact->id
]);
110 return civicrm_api3_create_success($values, $params, 'Contact', 'create');
114 * Adjust Metadata for Create action.
116 * @param array $params
117 * Array of parameters determined by getfields.
119 function _civicrm_api3_contact_create_spec(&$params) {
120 $params['contact_type']['api.required'] = 1;
121 $params['id']['api.aliases'] = array('contact_id');
122 $params['current_employer'] = array(
123 'title' => 'Current Employer',
124 'description' => 'Name of Current Employer',
125 'type' => CRM_Utils_Type
::T_STRING
,
127 $params['dupe_check'] = array(
128 'title' => 'Check for Duplicates',
129 'description' => 'Throw error if contact create matches dedupe rule',
130 'type' => CRM_Utils_Type
::T_BOOLEAN
,
132 $params['prefix_id']['api.aliases'] = array('individual_prefix', 'individual_prefix_id');
133 $params['suffix_id']['api.aliases'] = array('individual_suffix', 'individual_suffix_id');
134 $params['gender_id']['api.aliases'] = array('gender');
138 * Retrieve one or more contacts, given a set of search params.
140 * @param array $params
145 function civicrm_api3_contact_get($params) {
147 _civicrm_api3_contact_get_supportanomalies($params, $options);
148 $contacts = _civicrm_api3_get_using_query_object('Contact', $params, $options);
149 return civicrm_api3_create_success($contacts, $params, 'Contact');
153 * Get number of contacts matching the supplied criteria.
155 * @param array $params
159 function civicrm_api3_contact_getcount($params) {
161 _civicrm_api3_contact_get_supportanomalies($params, $options);
162 $count = _civicrm_api3_get_using_query_object('Contact', $params, $options, 1);
167 * Adjust Metadata for Get action.
169 * @param array $params
170 * Array of parameters determined by getfields.
172 function _civicrm_api3_contact_get_spec(&$params) {
173 $params['contact_is_deleted']['api.default'] = 0;
175 // We declare all these pseudoFields as there are other undocumented fields accessible
176 // via the api - but if check permissions is set we only allow declared fields
177 $params['address_id'] = array(
178 'title' => 'Primary Address ID',
179 'type' => CRM_Utils_Type
::T_INT
,
181 $params['street_address'] = array(
182 'title' => 'Primary Address Street Address',
183 'type' => CRM_Utils_Type
::T_STRING
,
185 $params['supplemental_address_1'] = array(
186 'title' => 'Primary Address Supplemental Address 1',
187 'type' => CRM_Utils_Type
::T_STRING
,
189 $params['supplemental_address_2'] = array(
190 'title' => 'Primary Address Supplemental Address 2',
191 'type' => CRM_Utils_Type
::T_STRING
,
193 $params['current_employer'] = array(
194 'title' => 'Current Employer',
195 'type' => CRM_Utils_Type
::T_STRING
,
197 $params['city'] = array(
198 'title' => 'Primary Address City',
199 'type' => CRM_Utils_Type
::T_STRING
,
201 $params['postal_code_suffix'] = array(
202 'title' => 'Primary Address Post Code Suffix',
203 'type' => CRM_Utils_Type
::T_STRING
,
205 $params['postal_code'] = array(
206 'title' => 'Primary Address Post Code',
207 'type' => CRM_Utils_Type
::T_STRING
,
209 $params['geo_code_1'] = array(
210 'title' => 'Primary Address Latitude',
211 'type' => CRM_Utils_Type
::T_STRING
,
213 $params['geo_code_2'] = array(
214 'title' => 'Primary Address Longitude',
215 'type' => CRM_Utils_Type
::T_STRING
,
217 $params['state_province_id'] = array(
218 'title' => 'Primary Address State Province ID',
219 'type' => CRM_Utils_Type
::T_INT
,
220 'pseudoconstant' => array(
221 'table' => 'civicrm_state_province',
224 $params['state_province_name'] = array(
225 'title' => 'Primary Address State Province Name',
226 'type' => CRM_Utils_Type
::T_STRING
,
227 'pseudoconstant' => array(
228 'table' => 'civicrm_state_province',
231 $params['state_province'] = array(
232 'title' => 'Primary Address State Province',
233 'type' => CRM_Utils_Type
::T_STRING
,
234 'pseudoconstant' => array(
235 'table' => 'civicrm_state_province',
238 $params['country_id'] = array(
239 'title' => 'Primary Address Country ID',
240 'type' => CRM_Utils_Type
::T_INT
,
241 'pseudoconstant' => array(
242 'table' => 'civicrm_country',
245 $params['country'] = array(
246 'title' => 'Primary Address country',
247 'type' => CRM_Utils_Type
::T_STRING
,
248 'pseudoconstant' => array(
249 'table' => 'civicrm_country',
252 $params['worldregion_id'] = array(
253 'title' => 'Primary Address World Region ID',
254 'type' => CRM_Utils_Type
::T_INT
,
255 'pseudoconstant' => array(
256 'table' => 'civicrm_world_region',
259 $params['worldregion'] = array(
260 'title' => 'Primary Address World Region',
261 'type' => CRM_Utils_Type
::T_STRING
,
262 'pseudoconstant' => array(
263 'table' => 'civicrm_world_region',
266 $params['phone_id'] = array(
267 'title' => 'Primary Phone ID',
268 'type' => CRM_Utils_Type
::T_INT
,
270 $params['phone'] = array(
271 'title' => 'Primary Phone',
272 'type' => CRM_Utils_Type
::T_STRING
,
274 $params['phone_type_id'] = array(
275 'title' => 'Primary Phone Type ID',
276 'type' => CRM_Utils_Type
::T_INT
,
278 $params['provider_id'] = array(
279 'title' => 'Primary Phone Provider ID',
280 'type' => CRM_Utils_Type
::T_INT
,
282 $params['email_id'] = array(
283 'title' => 'Primary Email ID',
284 'type' => CRM_Utils_Type
::T_INT
,
286 $params['email'] = array(
287 'title' => 'Primary Email',
288 'type' => CRM_Utils_Type
::T_STRING
,
290 $params['on_hold'] = array(
291 'title' => 'Primary Email On Hold',
292 'type' => CRM_Utils_Type
::T_BOOLEAN
,
294 $params['im'] = array(
295 'title' => 'Primary Instant Messenger',
296 'type' => CRM_Utils_Type
::T_STRING
,
298 $params['im_id'] = array(
299 'title' => 'Primary Instant Messenger ID',
300 'type' => CRM_Utils_Type
::T_INT
,
302 $params['group'] = array(
304 'pseudoconstant' => array(
305 'table' => 'civicrm_group',
308 $params['tag'] = array(
310 'pseudoconstant' => array(
311 'table' => 'civicrm_tag',
314 $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'));
315 $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'));
316 $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'));
317 $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'));
321 * Support for historical oddities.
323 * We are supporting 'showAll' = 'all', 'trash' or 'active' for Contact get
325 * - hopefully some day we'll come up with a std syntax for the 3-way-boolean of
328 * We also support 'filter_group_id' & 'filter.group_id'
330 * @param array $params
331 * As passed into api get or getcount function.
332 * @param array $options
333 * Array of options (so we can modify the filter).
335 function _civicrm_api3_contact_get_supportanomalies(&$params, &$options) {
336 if (isset($params['showAll'])) {
337 if (strtolower($params['showAll']) == "active") {
338 $params['contact_is_deleted'] = 0;
340 if (strtolower($params['showAll']) == "trash") {
341 $params['contact_is_deleted'] = 1;
343 if (strtolower($params['showAll']) == "all" && isset($params['contact_is_deleted'])) {
344 unset($params['contact_is_deleted']);
347 // support for group filters
348 if (array_key_exists('filter_group_id', $params)) {
349 $params['filter.group_id'] = $params['filter_group_id'];
350 unset($params['filter_group_id']);
352 // filter.group_id works both for 1,2,3 and array (1,2,3)
353 if (array_key_exists('filter.group_id', $params)) {
354 if (is_array($params['filter.group_id'])) {
355 $groups = $params['filter.group_id'];
358 $groups = explode(',', $params['filter.group_id']);
360 unset($params['filter.group_id']);
361 $options['input_params']['group'] = $groups;
366 * Delete a Contact with given contact_id.
368 * @param array $params
369 * input parameters per getfields
374 function civicrm_api3_contact_delete($params) {
376 $contactID = CRM_Utils_Array
::value('id', $params);
378 $session = CRM_Core_Session
::singleton();
379 if ($contactID == $session->get('userID')) {
380 return civicrm_api3_create_error('This contact record is linked to the currently logged in user account - and cannot be deleted.');
382 $restore = !empty($params['restore']) ?
$params['restore'] : FALSE;
383 $skipUndelete = !empty($params['skip_undelete']) ?
$params['skip_undelete'] : FALSE;
386 // restrict permanent delete if a contact has financial trxn associated with it
388 if ($skipUndelete && CRM_Financial_BAO_FinancialItem
::checkContactPresent(array($contactID), $error)) {
389 return civicrm_api3_create_error($error['_qf_default']);
391 if (CRM_Contact_BAO_Contact
::deleteContact($contactID, $restore, $skipUndelete)) {
392 return civicrm_api3_create_success();
395 return civicrm_api3_create_error('Could not delete contact');
401 * Check parameters passed in.
403 * This function is on it's way out.
405 * @param array $params
406 * @param bool $dupeCheck
409 * @throws API_Exception
410 * @throws CiviCRM_API3_Exception
412 function _civicrm_api3_contact_check_params(&$params, $dupeCheck) {
414 switch (strtolower(CRM_Utils_Array
::value('contact_type', $params))) {
416 civicrm_api3_verify_mandatory($params, NULL, array('household_name'));
420 civicrm_api3_verify_mandatory($params, NULL, array('organization_name'));
424 civicrm_api3_verify_one_mandatory($params, NULL, array(
434 // Fixme: This really needs to be handled at a lower level. @See CRM-13123
435 if (isset($params['preferred_communication_method'])) {
436 $params['preferred_communication_method'] = CRM_Utils_Array
::implodePadded($params['preferred_communication_method']);
439 if (!empty($params['contact_sub_type']) && !empty($params['contact_type'])) {
440 if (!(CRM_Contact_BAO_ContactType
::isExtendsContactType($params['contact_sub_type'], $params['contact_type']))) {
441 throw new API_Exception("Invalid or Mismatched Contact Subtype: " . implode(', ', (array) $params['contact_sub_type']));
446 // check for record already existing
447 $dedupeParams = CRM_Dedupe_Finder
::formatParams($params, $params['contact_type']);
450 // setting 'check_permission' here means that the dedupe checking will be carried out even if the
451 // person does not have permission to carry out de-dupes
452 // this is similar to the front end form
453 if (isset($params['check_permission'])) {
454 $dedupeParams['check_permission'] = $params['check_permission'];
457 $ids = CRM_Dedupe_Finder
::dupesByParams($dedupeParams, $params['contact_type'], 'Unsupervised', array());
459 if (count($ids) > 0) {
460 throw new API_Exception("Found matching contacts: " . implode(',', $ids), "duplicate", array("ids" => $ids));
464 // The BAO no longer supports the legacy param "current_employer" so here is a shim for api backward-compatability
465 if (!empty($params['current_employer'])) {
466 $organizationParams = array(
467 'organization_name' => $params['current_employer'],
470 $dedupParams = CRM_Dedupe_Finder
::formatParams($organizationParams, 'Organization');
472 $dedupParams['check_permission'] = FALSE;
473 $dupeIds = CRM_Dedupe_Finder
::dupesByParams($dedupParams, 'Organization', 'Supervised');
475 // check for mismatch employer name and id
476 if (!empty($params['employer_id']) && !in_array($params['employer_id'], $dupeIds)) {
477 throw new API_Exception('Employer name and Employer id Mismatch');
480 // show error if multiple organisation with same name exist
481 if (empty($params['employer_id']) && (count($dupeIds) > 1)) {
482 throw new API_Exception('Found more than one Organisation with same Name.');
486 $params['employer_id'] = $dupeIds[0];
489 $result = civicrm_api3('Contact', 'create', array(
490 'organization_name' => $params['current_employer'],
491 'contact_type' => 'Organization',
493 $params['employer_id'] = $result['id'];
501 * Helper function for Contact create.
503 * @param array $params
504 * (reference ) an assoc array of name/value pairs.
505 * @param int $contactID
506 * If present the contact with that ID is updated.
508 * @return CRM_Contact_BAO_Contact|CRM_Core_Error
510 function _civicrm_api3_contact_update($params, $contactID = NULL) {
511 //@todo - doesn't contact create support 'id' which is already set- check & remove
513 $params['contact_id'] = $contactID;
516 return CRM_Contact_BAO_Contact
::create($params);
520 * Validate the addressee or email or postal greetings.
522 * @param array $params
523 * Array per getfields metadata.
525 * @throws API_Exception
527 function _civicrm_api3_greeting_format_params($params) {
528 $greetingParams = array('', '_id', '_custom');
529 foreach (array('email', 'postal', 'addressee') as $key) {
530 $greeting = '_greeting';
531 if ($key == 'addressee') {
535 $formatParams = FALSE;
536 // Unset display value from params.
537 if (isset($params["{$key}{$greeting}_display"])) {
538 unset($params["{$key}{$greeting}_display"]);
541 // check if greetings are present in present
542 foreach ($greetingParams as $greetingValues) {
543 if (array_key_exists("{$key}{$greeting}{$greetingValues}", $params)) {
544 $formatParams = TRUE;
549 if (!$formatParams) {
555 'contact_type' => $params['contact_type'],
556 'greeting_type' => "{$key}{$greeting}",
559 $greetings = CRM_Core_PseudoConstant
::greeting($filter);
560 $greetingId = CRM_Utils_Array
::value("{$key}{$greeting}_id", $params);
561 $greetingVal = CRM_Utils_Array
::value("{$key}{$greeting}", $params);
562 $customGreeting = CRM_Utils_Array
::value("{$key}{$greeting}_custom", $params);
564 if (!$greetingId && $greetingVal) {
565 $params["{$key}{$greeting}_id"] = CRM_Utils_Array
::key($params["{$key}{$greeting}"], $greetings);
568 if ($customGreeting && $greetingId &&
569 ($greetingId != array_search('Customized', $greetings))
571 throw new API_Exception(ts('Provide either %1 greeting id and/or %1 greeting or custom %1 greeting',
576 if ($greetingVal && $greetingId &&
577 ($greetingId != CRM_Utils_Array
::key($greetingVal, $greetings))
579 throw new API_Exception(ts('Mismatch in %1 greeting id and %1 greeting',
586 if (!array_key_exists($greetingId, $greetings)) {
587 throw new API_Exception(ts('Invalid %1 greeting Id', array(1 => $key)));
590 if (!$customGreeting && ($greetingId == array_search('Customized', $greetings))) {
591 throw new API_Exception(ts('Please provide a custom value for %1 greeting',
596 elseif ($greetingVal) {
598 if (!in_array($greetingVal, $greetings)) {
599 throw new API_Exception(ts('Invalid %1 greeting', array(1 => $key)));
602 $greetingId = CRM_Utils_Array
::key($greetingVal, $greetings);
605 if ($customGreeting) {
606 $greetingId = CRM_Utils_Array
::key('Customized', $greetings);
609 $customValue = isset($params['contact_id']) ? CRM_Core_DAO
::getFieldValue(
610 'CRM_Contact_DAO_Contact',
611 $params['contact_id'],
612 "{$key}{$greeting}_custom"
615 if (array_key_exists("{$key}{$greeting}_id", $params) && empty($params["{$key}{$greeting}_id"])) {
618 elseif (array_key_exists("{$key}{$greeting}", $params) && empty($params["{$key}{$greeting}"])) {
621 elseif ($customValue && array_key_exists("{$key}{$greeting}_custom", $params)
622 && empty($params["{$key}{$greeting}_custom"])
627 $params["{$key}{$greeting}_id"] = $greetingId;
629 if (!$customValue && !$customGreeting && array_key_exists("{$key}{$greeting}_custom", $params)) {
630 unset($params["{$key}{$greeting}_custom"]);
634 $params["{$key}{$greeting}_id"] = '';
635 $params["{$key}{$greeting}_custom"] = '';
638 if (isset($params["{$key}{$greeting}"])) {
639 unset($params["{$key}{$greeting}"]);
645 * Adjust Metadata for Get action.
647 * @param array $params
648 * Array of parameters determined by getfields.
650 function _civicrm_api3_contact_getquick_spec(&$params) {
651 $params['name']['api.required'] = TRUE;
652 $params['name']['title'] = ts('String to search on');
653 $params['name']['type'] = CRM_Utils_Type
::T_STRING
;
654 $params['field']['type'] = CRM_Utils_Type
::T_STRING
;
655 $params['field']['title'] = ts('Field to search on');
656 $params['field']['options'] = array(
660 'external_identifier',
670 $params['table_name']['type'] = CRM_Utils_Type
::T_STRING
;
671 $params['table_name']['title'] = ts('Table alias to search on');
672 $params['table_name']['api.default'] = 'cc';
676 * Old Contact quick search api.
680 * @param array $params
683 * @throws \API_Exception
685 function civicrm_api3_contact_getquick($params) {
686 $name = CRM_Utils_Type
::escape(CRM_Utils_Array
::value('name', $params), 'String');
687 $table_name = CRM_Utils_String
::munge($params['table_name']);
688 // get the autocomplete options from settings
689 $acpref = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
690 CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
,
691 'contact_autocomplete_options'
695 // get the option values for contact autocomplete
696 $acOptions = CRM_Core_OptionGroup
::values('contact_autocomplete_options', FALSE, FALSE, FALSE, NULL, 'name');
699 foreach ($acpref as $value) {
700 if ($value && !empty($acOptions[$value])) {
701 $list[$value] = $acOptions[$value];
704 // If we are doing quicksearch by a field other than name, make sure that field is added to results
705 if (!empty($params['field_name'])) {
706 $field_name = CRM_Utils_String
::munge($params['field_name']);
707 // Unique name contact_id = id
708 if ($field_name == 'contact_id') {
711 // phone_numeric should be phone
712 $searchField = str_replace('_numeric', '', $field_name);
713 if (!in_array($searchField, $list)) {
714 $list[] = $searchField;
718 // Set field name to first name for exact match checking.
719 $field_name = 'sort_name';
722 $select = $actualSelectElements = array('sort_name');
725 foreach ($list as $value) {
726 $suffix = substr($value, 0, 2) . substr($value, -1);
728 case 'street_address':
731 $selectText = $value;
736 $actualSelectElements[] = $select[] = ($value == 'address') ?
$selectText : $value;
737 if ($value == 'phone') {
738 $actualSelectElements[] = $select[] = 'phone_ext';
740 $from[$value] = "LEFT JOIN civicrm_{$value} {$suffix} ON ( cc.id = {$suffix}.contact_id AND {$suffix}.is_primary = 1 ) ";
744 case 'state_province':
745 $select[] = "{$suffix}.name as {$value}";
746 $actualSelectElements[] = "{$suffix}.name";
747 if (!in_array('address', $from)) {
748 $from['address'] = 'LEFT JOIN civicrm_address sts ON ( cc.id = sts.contact_id AND sts.is_primary = 1) ';
750 $from[$value] = " LEFT JOIN civicrm_{$value} {$suffix} ON ( sts.{$value}_id = {$suffix}.id ) ";
754 if ($value != 'id') {
756 if (!empty($params['field_name']) && $params['field_name'] == 'value') {
757 $suffix = CRM_Utils_String
::munge(CRM_Utils_Array
::value('table_name', $params, 'cc'));
759 $actualSelectElements[] = $select[] = $suffix . '.' . $value;
765 $config = CRM_Core_Config
::singleton();
767 $select = implode(', ', $select);
768 if (!empty($select)) {
769 $select = ", $select";
771 $actualSelectElements = implode(', ', $actualSelectElements);
772 $selectAliases = $from;
773 unset($selectAliases['address']);
774 $selectAliases = implode(', ', array_keys($selectAliases));
775 if (!empty($selectAliases)) {
776 $selectAliases = ", $selectAliases";
778 $from = implode(' ', $from);
779 $limit = (int) CRM_Utils_Array
::value('limit', $params);
780 $limit = $limit > 0 ?
$limit : Civi
::settings()->get('search_autocomplete_count');
782 // add acl clause here
783 list($aclFrom, $aclWhere) = CRM_Contact_BAO_Contact_Permission
::cacheClause('cc');
786 $where .= " AND $aclWhere ";
789 if (!empty($params['org'])) {
790 $where .= " AND contact_type = \"Organization\"";
792 // CRM-7157, hack: get current employer details when
793 // employee_id is present.
794 $currEmpDetails = array();
795 if (!empty($params['employee_id'])) {
796 if ($currentEmployer = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact',
797 (int) $params['employee_id'],
800 if ($config->includeWildCardInName
) {
801 $strSearch = "%$name%";
804 $strSearch = "$name%";
807 // get current employer details
808 $dao = CRM_Core_DAO
::executeQuery("SELECT cc.id as id, CONCAT_WS( ' :: ', {$actualSelectElements} ) as data, sort_name
809 FROM civicrm_contact cc {$from} WHERE cc.contact_type = \"Organization\" AND cc.id = {$currentEmployer} AND cc.sort_name LIKE '$strSearch'");
811 $currEmpDetails = array(
813 'data' => $dao->data
,
820 if (!empty($params['contact_sub_type'])) {
821 $contactSubType = CRM_Utils_Type
::escape($params['contact_sub_type'], 'String');
822 $where .= " AND cc.contact_sub_type = '{$contactSubType}'";
825 if (!empty($params['contact_type'])) {
826 $contactType = CRM_Utils_Type
::escape($params['contact_type'], 'String');
827 $where .= " AND cc.contact_type LIKE '{$contactType}'";
830 // Set default for current_employer or return contact with particular id
831 if (!empty($params['id'])) {
832 $where .= " AND cc.id = " . (int) $params['id'];
835 if (!empty($params['cid'])) {
836 $where .= " AND cc.id <> " . (int) $params['cid'];
839 // Contact's based of relationhip type
841 if (!empty($params['rel'])) {
842 $relation = explode('_', CRM_Utils_Array
::value('rel', $params));
843 $relType = CRM_Utils_Type
::escape($relation[0], 'Integer');
844 $rel = CRM_Utils_Type
::escape($relation[2], 'String');
847 if ($config->includeWildCardInName
) {
848 $strSearch = "%$name%";
851 $strSearch = "$name%";
853 $includeEmailFrom = $includeNickName = $exactIncludeNickName = '';
854 if ($config->includeNickNameInName
) {
855 $includeNickName = " OR nick_name LIKE '$strSearch'";
856 $exactIncludeNickName = " OR nick_name LIKE '$name'";
860 if (!empty($params['field_name']) && !empty($params['table_name'])) {
861 $whereClause = " WHERE ( $table_name.$field_name LIKE '$strSearch') {$where}";
862 $exactWhereClause = " WHERE ( $table_name.$field_name = '$name') {$where}";
863 // Search by id should be exact
864 if ($field_name == 'id' ||
$field_name == 'external_identifier') {
865 $whereClause = $exactWhereClause;
869 $whereClause = " WHERE ( sort_name LIKE '$strSearch' $includeNickName ) {$where} ";
870 $exactWhereClause = " WHERE ( sort_name LIKE '$name' $exactIncludeNickName ) {$where} ";
871 if ($config->includeEmailInName
) {
872 if (!in_array('email', $list)) {
873 $includeEmailFrom = "LEFT JOIN civicrm_email eml ON ( cc.id = eml.contact_id AND eml.is_primary = 1 )";
875 $emailWhere = " WHERE email LIKE '$strSearch'";
879 $additionalFrom = '';
882 INNER JOIN civicrm_relationship_type r ON (
884 AND ( cc.contact_type = r.contact_type_{$rel} OR r.contact_type_{$rel} IS NULL )
885 AND ( cc.contact_sub_type = r.contact_sub_type_{$rel} OR r.contact_sub_type_{$rel} IS NULL )
889 // check if only CMS users are requested
890 if (!empty($params['cmsuser'])) {
892 INNER JOIN civicrm_uf_match um ON (um.contact_id=cc.id)
896 $orderByInner = $orderByOuter = "ORDER BY exactFirst";
897 if ($config->includeOrderByClause
) {
898 $orderByInner = "ORDER BY exactFirst, sort_name";
899 $orderByOuter .= ", sort_name";
904 SELECT DISTINCT(id), data, sort_name {$selectAliases}, exactFirst
906 ( SELECT IF($table_name.$field_name = '{$name}', 0, 1) as exactFirst, cc.id as id, CONCAT_WS( ' :: ',
907 {$actualSelectElements} )
910 FROM civicrm_contact cc {$from}
918 if (!empty($emailWhere)) {
921 SELECT IF($table_name.$field_name = '{$name}', 0, 1) as exactFirst, cc.id as id, CONCAT_WS( ' :: ',
922 {$actualSelectElements} )
925 FROM civicrm_contact cc {$from}
927 {$additionalFrom} {$includeEmailFrom}
928 {$emailWhere} AND cc.is_deleted = 0 " . ($aclWhere ?
" AND $aclWhere " : '') . "
939 // send query to hook to be modified if needed
940 CRM_Utils_Hook
::contactListQuery($query,
942 empty($params['context']) ?
NULL : CRM_Utils_Type
::escape($params['context'], 'String'),
943 empty($params['id']) ?
NULL : $params['id']
946 $dao = CRM_Core_DAO
::executeQuery($query);
948 $contactList = array();
949 $listCurrentEmployer = TRUE;
950 while ($dao->fetch()) {
951 $t = array('id' => $dao->id
);
952 foreach ($as as $k) {
953 $t[$k] = isset($dao->$k) ?
$dao->$k : '';
955 $t['data'] = $dao->data
;
957 if (!empty($params['org']) &&
958 !empty($currEmpDetails) &&
959 $dao->id
== $currEmpDetails['id']
961 $listCurrentEmployer = FALSE;
965 //return organization name if doesn't exist in db
966 if (empty($contactList)) {
967 if (!empty($params['org'])) {
968 if ($listCurrentEmployer && !empty($currEmpDetails)) {
969 $contactList = array(
971 'data' => $currEmpDetails['data'],
972 'id' => $currEmpDetails['id'],
977 $contactList = array(
987 return civicrm_api3_create_success($contactList, $params, 'Contact', 'getquick');
991 * Declare deprecated api functions.
993 * @deprecated api notice
995 * Array of deprecated actions
997 function _civicrm_api3_contact_deprecation() {
998 return array('getquick' => 'The "getquick" action is deprecated in favor of "getlist".');
1002 * Merges given pair of duplicate contacts.
1004 * @param array $params
1005 * Allowed array keys are:
1006 * -int main_id: main contact id with whom merge has to happen
1007 * -int other_id: duplicate contact which would be deleted after merge operation
1008 * -string mode: "safe" skips the merge if there are no conflicts. Does a force merge otherwise.
1009 * -boolean auto_flip: whether to let api decide which contact to retain and which to delete.
1014 function civicrm_api3_contact_merge($params) {
1015 $mode = CRM_Utils_Array
::value('mode', $params, 'safe');
1016 $autoFlip = CRM_Utils_Array
::value('auto_flip', $params, TRUE);
1018 $dupePairs = array(array(
1019 'srcID' => CRM_Utils_Array
::value('main_id', $params),
1020 'dstID' => CRM_Utils_Array
::value('other_id', $params),
1022 $result = CRM_Dedupe_Merger
::merge($dupePairs, array(), $mode, $autoFlip);
1024 if ($result['is_error'] == 0) {
1025 return civicrm_api3_create_success();
1028 return civicrm_api3_create_error($result['messages']);
1033 * Adjust metadata for contact_proximity api function.
1035 * @param array $params
1037 function _civicrm_api3_contact_proximity_spec(&$params) {
1038 $params['latitude'] = array(
1039 'title' => 'Latitude',
1040 'api.required' => 1,
1041 'type' => CRM_Utils_Type
::T_STRING
,
1043 $params['longitude'] = array(
1044 'title' => 'Longitude',
1045 'api.required' => 1,
1046 'type' => CRM_Utils_Type
::T_STRING
,
1049 $params['unit'] = array(
1050 'title' => 'Unit of Measurement',
1051 'api.default' => 'meter',
1052 'type' => CRM_Utils_Type
::T_STRING
,
1057 * Get contacts by proximity.
1059 * @param array $params
1064 function civicrm_api3_contact_proximity($params) {
1065 $latitude = CRM_Utils_Array
::value('latitude', $params);
1066 $longitude = CRM_Utils_Array
::value('longitude', $params);
1067 $distance = CRM_Utils_Array
::value('distance', $params);
1069 $unit = CRM_Utils_Array
::value('unit', $params);
1071 // check and ensure that lat/long and distance are floats
1073 !CRM_Utils_Rule
::numeric($latitude) ||
1074 !CRM_Utils_Rule
::numeric($longitude) ||
1075 !CRM_Utils_Rule
::numeric($distance)
1077 throw new Exception(ts('Latitude, Longitude and Distance should exist and be numeric'));
1080 if ($unit == "mile") {
1081 $conversionFactor = 1609.344;
1084 $conversionFactor = 1000;
1086 //Distance in meters
1087 $distance = $distance * $conversionFactor;
1089 $whereClause = CRM_Contact_BAO_ProximityQuery
::where($latitude, $longitude, $distance);
1092 SELECT civicrm_contact.id as contact_id,
1093 civicrm_contact.display_name as display_name
1094 FROM civicrm_contact
1095 LEFT JOIN civicrm_address ON civicrm_contact.id = civicrm_address.contact_id
1099 $dao = CRM_Core_DAO
::executeQuery($query);
1100 $contacts = array();
1101 while ($dao->fetch()) {
1102 $contacts[] = $dao->toArray();
1105 return civicrm_api3_create_success($contacts, $params, 'Contact', 'get_by_location', $dao);
1110 * Get parameters for getlist function.
1112 * @see _civicrm_api3_generic_getlist_params
1114 * @param array $request
1116 function _civicrm_api3_contact_getlist_params(&$request) {
1117 // get the autocomplete options from settings
1118 $acpref = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1119 CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
,
1120 'contact_autocomplete_options'
1124 // get the option values for contact autocomplete
1125 $acOptions = CRM_Core_OptionGroup
::values('contact_autocomplete_options', FALSE, FALSE, FALSE, NULL, 'name');
1128 foreach ($acpref as $value) {
1129 if ($value && !empty($acOptions[$value])) {
1130 $list[] = $acOptions[$value];
1133 // If we are doing quicksearch by a field other than name, make sure that field is added to results
1134 $field_name = CRM_Utils_String
::munge($request['search_field']);
1135 // Unique name contact_id = id
1136 if ($field_name == 'contact_id') {
1139 // phone_numeric should be phone
1140 $searchField = str_replace('_numeric', '', $field_name);
1141 if (!in_array($searchField, $list)) {
1142 $list[] = $searchField;
1144 $request['description_field'] = $list;
1145 $list[] = 'contact_type';
1146 $request['params']['return'] = array_unique(array_merge($list, $request['extra']));
1147 $request['params']['options']['sort'] = 'sort_name';
1148 // Contact api doesn't support array(LIKE => 'foo') syntax
1149 if (!empty($request['input'])) {
1150 $request['params'][$request['search_field']] = $request['input'];
1155 * Get output for getlist function.
1157 * @see _civicrm_api3_generic_getlist_output
1159 * @param array $result
1160 * @param array $request
1164 function _civicrm_api3_contact_getlist_output($result, $request) {
1166 if (!empty($result['values'])) {
1167 $addressFields = array_intersect(array(
1173 $request['params']['return']);
1174 foreach ($result['values'] as $row) {
1176 'id' => $row[$request['id_field']],
1177 'label' => $row[$request['label_field']],
1178 'description' => array(),
1180 foreach ($request['description_field'] as $item) {
1181 if (!strpos($item, '_name') && !in_array($item, $addressFields) && !empty($row[$item])) {
1182 $data['description'][] = $row[$item];
1186 foreach ($addressFields as $item) {
1187 if (!empty($row[$item])) {
1188 $address[] = $row[$item];
1192 $data['description'][] = implode(' ', $address);
1194 if (!empty($request['image_field'])) {
1195 $data['image'] = isset($row[$request['image_field']]) ?
$row[$request['image_field']] : '';
1198 $data['icon_class'] = $row['contact_type'];
1207 * Check for duplicate contacts.
1209 * @param array $params
1210 * Params per getfields metadata.
1213 * API formatted array
1215 function civicrm_api3_contact_duplicatecheck($params) {
1216 $dedupeParams = CRM_Dedupe_Finder
::formatParams($params['match'], $params['match']['contact_type']);
1219 // setting 'check_permission' here means that the dedupe checking will be carried out even if the
1220 // person does not have permission to carry out de-dupes
1221 // this is similar to the front end form
1222 if (isset($params['check_permission'])) {
1223 $dedupeParams['check_permission'] = $params['check_permission'];
1226 $dupes = CRM_Dedupe_Finder
::dupesByParams($dedupeParams, $params['match']['contact_type'], 'Unsupervised', array(), CRM_Utils_Array
::value('dedupe_rule_id', $params));
1227 $values = empty($dupes) ?
array() : array_fill_keys($dupes, array());
1228 return civicrm_api3_create_success($values, $params, 'Contact', 'duplicatecheck');
1232 * Declare metadata for contact dedupe function.
1236 function _civicrm_api3_contact_duplicatecheck_spec(&$params) {
1237 $params['dedupe_rule_id'] = array(
1238 'title' => 'Dedupe Rule ID (optional)',
1239 'description' => 'This will default to the built in unsupervised rule',
1240 'type' => CRM_Utils_Type
::T_INT
,
1242 // @todo declare 'match' parameter. We don't have a standard for type = array yet.