3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
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
,
221 $params['state_province_name'] = array(
222 'title' => 'Primary Address State Province Name',
223 'type' => CRM_Utils_Type
::T_STRING
,
225 $params['state_province'] = array(
226 'title' => 'Primary Address State Province',
227 'type' => CRM_Utils_Type
::T_STRING
,
229 $params['country_id'] = array(
230 'title' => 'Primary Address Country ID',
231 'type' => CRM_Utils_Type
::T_INT
,
233 $params['country'] = array(
234 'title' => 'Primary Address country',
235 'type' => CRM_Utils_Type
::T_STRING
,
237 $params['worldregion_id'] = array(
238 'title' => 'Primary Address World Region ID',
239 'type' => CRM_Utils_Type
::T_INT
,
241 $params['worldregion'] = array(
242 'title' => 'Primary Address World Region',
243 'type' => CRM_Utils_Type
::T_STRING
,
245 $params['phone_id'] = array(
246 'title' => 'Primary Phone ID',
247 'type' => CRM_Utils_Type
::T_INT
,
249 $params['phone'] = array(
250 'title' => 'Primary Phone',
251 'type' => CRM_Utils_Type
::T_STRING
,
253 $params['phone_type_id'] = array(
254 'title' => 'Primary Phone Type ID',
255 'type' => CRM_Utils_Type
::T_INT
,
257 $params['provider_id'] = array(
258 'title' => 'Primary Phone Provider ID',
259 'type' => CRM_Utils_Type
::T_INT
,
261 $params['email_id'] = array(
262 'title' => 'Primary Email ID',
263 'type' => CRM_Utils_Type
::T_INT
,
265 $params['email'] = array(
266 'title' => 'Primary Email',
267 'type' => CRM_Utils_Type
::T_STRING
,
269 $params['on_hold'] = array(
270 'title' => 'Primary Email On Hold',
271 'type' => CRM_Utils_Type
::T_BOOLEAN
,
273 $params['im'] = array(
274 'title' => 'Primary Instant Messenger',
275 'type' => CRM_Utils_Type
::T_STRING
,
277 $params['im_id'] = array(
278 'title' => 'Primary Instant Messenger ID',
279 'type' => CRM_Utils_Type
::T_INT
,
281 $params['group'] = array(
283 'pseudoconstant' => array(
284 'table' => 'civicrm_group',
287 $params['tag'] = array(
289 'pseudoconstant' => array(
290 'table' => 'civicrm_tag',
293 $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'));
294 $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'));
295 $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'));
296 $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'));
300 * Support for historical oddities.
302 * We are supporting 'showAll' = 'all', 'trash' or 'active' for Contact get
304 * - hopefully some day we'll come up with a std syntax for the 3-way-boolean of
307 * We also support 'filter_group_id' & 'filter.group_id'
309 * @param array $params
310 * As passed into api get or getcount function.
311 * @param array $options
312 * Array of options (so we can modify the filter).
314 function _civicrm_api3_contact_get_supportanomalies(&$params, &$options) {
315 if (isset($params['showAll'])) {
316 if (strtolower($params['showAll']) == "active") {
317 $params['contact_is_deleted'] = 0;
319 if (strtolower($params['showAll']) == "trash") {
320 $params['contact_is_deleted'] = 1;
322 if (strtolower($params['showAll']) == "all" && isset($params['contact_is_deleted'])) {
323 unset($params['contact_is_deleted']);
326 // support for group filters
327 if (array_key_exists('filter_group_id', $params)) {
328 $params['filter.group_id'] = $params['filter_group_id'];
329 unset($params['filter_group_id']);
331 // filter.group_id works both for 1,2,3 and array (1,2,3)
332 if (array_key_exists('filter.group_id', $params)) {
333 if (is_array($params['filter.group_id'])) {
334 $groups = $params['filter.group_id'];
337 $groups = explode(',', $params['filter.group_id']);
339 unset($params['filter.group_id']);
340 $groups = array_flip($groups);
341 $groups[key($groups)] = 1;
342 $options['input_params']['group'] = $groups;
347 * Delete a Contact with given contact_id.
349 * @param array $params
350 * input parameters per getfields
355 function civicrm_api3_contact_delete($params) {
357 $contactID = CRM_Utils_Array
::value('id', $params);
359 $session = CRM_Core_Session
::singleton();
360 if ($contactID == $session->get('userID')) {
361 return civicrm_api3_create_error('This contact record is linked to the currently logged in user account - and cannot be deleted.');
363 $restore = !empty($params['restore']) ?
$params['restore'] : FALSE;
364 $skipUndelete = !empty($params['skip_undelete']) ?
$params['skip_undelete'] : FALSE;
367 // restrict permanent delete if a contact has financial trxn associated with it
369 if ($skipUndelete && CRM_Financial_BAO_FinancialItem
::checkContactPresent(array($contactID), $error)) {
370 return civicrm_api3_create_error($error['_qf_default']);
372 if (CRM_Contact_BAO_Contact
::deleteContact($contactID, $restore, $skipUndelete)) {
373 return civicrm_api3_create_success();
376 return civicrm_api3_create_error('Could not delete contact');
382 * Check parameters passed in.
384 * This function is on it's way out.
386 * @param array $params
387 * @param bool $dupeCheck
390 * @throws API_Exception
391 * @throws CiviCRM_API3_Exception
393 function _civicrm_api3_contact_check_params(&$params, $dupeCheck) {
395 switch (strtolower(CRM_Utils_Array
::value('contact_type', $params))) {
397 civicrm_api3_verify_mandatory($params, NULL, array('household_name'));
401 civicrm_api3_verify_mandatory($params, NULL, array('organization_name'));
405 civicrm_api3_verify_one_mandatory($params, NULL, array(
415 // Fixme: This really needs to be handled at a lower level. @See CRM-13123
416 if (isset($params['preferred_communication_method'])) {
417 $params['preferred_communication_method'] = CRM_Utils_Array
::implodePadded($params['preferred_communication_method']);
420 if (!empty($params['contact_sub_type']) && !empty($params['contact_type'])) {
421 if (!(CRM_Contact_BAO_ContactType
::isExtendsContactType($params['contact_sub_type'], $params['contact_type']))) {
422 throw new API_Exception("Invalid or Mismatched Contact Subtype: " . implode(', ', (array) $params['contact_sub_type']));
427 // check for record already existing
428 $dedupeParams = CRM_Dedupe_Finder
::formatParams($params, $params['contact_type']);
431 // setting 'check_permission' here means that the dedupe checking will be carried out even if the
432 // person does not have permission to carry out de-dupes
433 // this is similar to the front end form
434 if (isset($params['check_permission'])) {
435 $dedupeParams['check_permission'] = $params['check_permission'];
438 $ids = CRM_Dedupe_Finder
::dupesByParams($dedupeParams, $params['contact_type'], 'Unsupervised', array());
440 if (count($ids) > 0) {
441 throw new API_Exception("Found matching contacts: " . implode(',', $ids), "duplicate", array("ids" => $ids));
445 // The BAO no longer supports the legacy param "current_employer" so here is a shim for api backward-compatability
446 if (!empty($params['current_employer'])) {
447 $organizationParams = array(
448 'organization_name' => $params['current_employer'],
451 $dedupParams = CRM_Dedupe_Finder
::formatParams($organizationParams, 'Organization');
453 $dedupParams['check_permission'] = FALSE;
454 $dupeIds = CRM_Dedupe_Finder
::dupesByParams($dedupParams, 'Organization', 'Supervised');
456 // check for mismatch employer name and id
457 if (!empty($params['employer_id']) && !in_array($params['employer_id'], $dupeIds)) {
458 throw new API_Exception('Employer name and Employer id Mismatch');
461 // show error if multiple organisation with same name exist
462 if (empty($params['employer_id']) && (count($dupeIds) > 1)) {
463 throw new API_Exception('Found more than one Organisation with same Name.');
467 $params['employer_id'] = $dupeIds[0];
470 $result = civicrm_api3('Contact', 'create', array(
471 'organization_name' => $params['current_employer'],
472 'contact_type' => 'Organization',
474 $params['employer_id'] = $result['id'];
482 * Helper function for Contact create.
484 * @param array $params
485 * (reference ) an assoc array of name/value pairs.
486 * @param int $contactID
487 * If present the contact with that ID is updated.
489 * @return CRM_Contact_BAO_Contact|CRM_Core_Error
491 function _civicrm_api3_contact_update($params, $contactID = NULL) {
492 //@todo - doesn't contact create support 'id' which is already set- check & remove
494 $params['contact_id'] = $contactID;
497 return CRM_Contact_BAO_Contact
::create($params);
501 * Validate the addressee or email or postal greetings.
503 * @param array $params
504 * Array per getfields metadata.
506 * @throws API_Exception
508 function _civicrm_api3_greeting_format_params($params) {
509 $greetingParams = array('', '_id', '_custom');
510 foreach (array('email', 'postal', 'addressee') as $key) {
511 $greeting = '_greeting';
512 if ($key == 'addressee') {
516 $formatParams = FALSE;
517 // Unset display value from params.
518 if (isset($params["{$key}{$greeting}_display"])) {
519 unset($params["{$key}{$greeting}_display"]);
522 // check if greetings are present in present
523 foreach ($greetingParams as $greetingValues) {
524 if (array_key_exists("{$key}{$greeting}{$greetingValues}", $params)) {
525 $formatParams = TRUE;
530 if (!$formatParams) {
536 'contact_type' => $params['contact_type'],
537 'greeting_type' => "{$key}{$greeting}",
540 $greetings = CRM_Core_PseudoConstant
::greeting($filter);
541 $greetingId = CRM_Utils_Array
::value("{$key}{$greeting}_id", $params);
542 $greetingVal = CRM_Utils_Array
::value("{$key}{$greeting}", $params);
543 $customGreeting = CRM_Utils_Array
::value("{$key}{$greeting}_custom", $params);
545 if (!$greetingId && $greetingVal) {
546 $params["{$key}{$greeting}_id"] = CRM_Utils_Array
::key($params["{$key}{$greeting}"], $greetings);
549 if ($customGreeting && $greetingId &&
550 ($greetingId != array_search('Customized', $greetings))
552 throw new API_Exception(ts('Provide either %1 greeting id and/or %1 greeting or custom %1 greeting',
557 if ($greetingVal && $greetingId &&
558 ($greetingId != CRM_Utils_Array
::key($greetingVal, $greetings))
560 throw new API_Exception(ts('Mismatch in %1 greeting id and %1 greeting',
567 if (!array_key_exists($greetingId, $greetings)) {
568 throw new API_Exception(ts('Invalid %1 greeting Id', array(1 => $key)));
571 if (!$customGreeting && ($greetingId == array_search('Customized', $greetings))) {
572 throw new API_Exception(ts('Please provide a custom value for %1 greeting',
577 elseif ($greetingVal) {
579 if (!in_array($greetingVal, $greetings)) {
580 throw new API_Exception(ts('Invalid %1 greeting', array(1 => $key)));
583 $greetingId = CRM_Utils_Array
::key($greetingVal, $greetings);
586 if ($customGreeting) {
587 $greetingId = CRM_Utils_Array
::key('Customized', $greetings);
590 $customValue = isset($params['contact_id']) ? CRM_Core_DAO
::getFieldValue(
591 'CRM_Contact_DAO_Contact',
592 $params['contact_id'],
593 "{$key}{$greeting}_custom"
596 if (array_key_exists("{$key}{$greeting}_id", $params) && empty($params["{$key}{$greeting}_id"])) {
599 elseif (array_key_exists("{$key}{$greeting}", $params) && empty($params["{$key}{$greeting}"])) {
602 elseif ($customValue && array_key_exists("{$key}{$greeting}_custom", $params)
603 && empty($params["{$key}{$greeting}_custom"])
608 $params["{$key}{$greeting}_id"] = $greetingId;
610 if (!$customValue && !$customGreeting && array_key_exists("{$key}{$greeting}_custom", $params)) {
611 unset($params["{$key}{$greeting}_custom"]);
615 $params["{$key}{$greeting}_id"] = '';
616 $params["{$key}{$greeting}_custom"] = '';
619 if (isset($params["{$key}{$greeting}"])) {
620 unset($params["{$key}{$greeting}"]);
626 * Old Contact quick search api.
630 * @param array $params
633 * @throws \API_Exception
635 function civicrm_api3_contact_getquick($params) {
636 civicrm_api3_verify_mandatory($params, NULL, array('name'));
637 $name = CRM_Utils_Type
::escape(CRM_Utils_Array
::value('name', $params), 'String');
639 // get the autocomplete options from settings
640 $acpref = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
641 CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
,
642 'contact_autocomplete_options'
646 // get the option values for contact autocomplete
647 $acOptions = CRM_Core_OptionGroup
::values('contact_autocomplete_options', FALSE, FALSE, FALSE, NULL, 'name');
650 foreach ($acpref as $value) {
651 if ($value && !empty($acOptions[$value])) {
652 $list[$value] = $acOptions[$value];
655 // If we are doing quicksearch by a field other than name, make sure that field is added to results
656 if (!empty($params['field_name'])) {
657 $field_name = CRM_Utils_String
::munge($params['field_name']);
658 // Unique name contact_id = id
659 if ($field_name == 'contact_id') {
662 // phone_numeric should be phone
663 $searchField = str_replace('_numeric', '', $field_name);
664 if (!in_array($searchField, $list)) {
665 $list[] = $searchField;
669 $select = $actualSelectElements = array('sort_name');
672 foreach ($list as $value) {
673 $suffix = substr($value, 0, 2) . substr($value, -1);
675 case 'street_address':
678 $selectText = $value;
683 $actualSelectElements[] = $select[] = ($value == 'address') ?
$selectText : $value;
684 if ($value == 'phone') {
685 $actualSelectElements[] = $select[] = 'phone_ext';
687 $from[$value] = "LEFT JOIN civicrm_{$value} {$suffix} ON ( cc.id = {$suffix}.contact_id AND {$suffix}.is_primary = 1 ) ";
691 case 'state_province':
692 $select[] = "{$suffix}.name as {$value}";
693 $actualSelectElements[] = "{$suffix}.name";
694 if (!in_array('address', $from)) {
695 $from['address'] = 'LEFT JOIN civicrm_address sts ON ( cc.id = sts.contact_id AND sts.is_primary = 1) ';
697 $from[$value] = " LEFT JOIN civicrm_{$value} {$suffix} ON ( sts.{$value}_id = {$suffix}.id ) ";
701 if ($value != 'id') {
703 if (!empty($params['field_name']) && $params['field_name'] == 'value') {
704 $suffix = CRM_Utils_String
::munge(CRM_Utils_Array
::value('table_name', $params, 'cc'));
706 $actualSelectElements[] = $select[] = $suffix . '.' . $value;
712 $config = CRM_Core_Config
::singleton();
714 $select = implode(', ', $select);
715 if (!empty($select)) {
716 $select = ", $select";
718 $actualSelectElements = implode(', ', $actualSelectElements);
719 $selectAliases = $from;
720 unset($selectAliases['address']);
721 $selectAliases = implode(', ', array_keys($selectAliases));
722 if (!empty($selectAliases)) {
723 $selectAliases = ", $selectAliases";
725 $from = implode(' ', $from);
726 $limit = (int) CRM_Utils_Array
::value('limit', $params);
727 $limit = $limit > 0 ?
$limit : CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::SEARCH_PREFERENCES_NAME
, 'search_autocomplete_count', NULL, 10);
729 // add acl clause here
730 list($aclFrom, $aclWhere) = CRM_Contact_BAO_Contact_Permission
::cacheClause('cc');
733 $where .= " AND $aclWhere ";
736 if (!empty($params['org'])) {
737 $where .= " AND contact_type = \"Organization\"";
739 // CRM-7157, hack: get current employer details when
740 // employee_id is present.
741 $currEmpDetails = array();
742 if (!empty($params['employee_id'])) {
743 if ($currentEmployer = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact',
744 (int) $params['employee_id'],
747 if ($config->includeWildCardInName
) {
748 $strSearch = "%$name%";
751 $strSearch = "$name%";
754 // get current employer details
755 $dao = CRM_Core_DAO
::executeQuery("SELECT cc.id as id, CONCAT_WS( ' :: ', {$actualSelectElements} ) as data, sort_name
756 FROM civicrm_contact cc {$from} WHERE cc.contact_type = \"Organization\" AND cc.id = {$currentEmployer} AND cc.sort_name LIKE '$strSearch'");
758 $currEmpDetails = array(
760 'data' => $dao->data
,
767 if (!empty($params['contact_sub_type'])) {
768 $contactSubType = CRM_Utils_Type
::escape($params['contact_sub_type'], 'String');
769 $where .= " AND cc.contact_sub_type = '{$contactSubType}'";
772 if (!empty($params['contact_type'])) {
773 $contactType = CRM_Utils_Type
::escape($params['contact_type'], 'String');
774 $where .= " AND cc.contact_type LIKE '{$contactType}'";
777 // Set default for current_employer or return contact with particular id
778 if (!empty($params['id'])) {
779 $where .= " AND cc.id = " . (int) $params['id'];
782 if (!empty($params['cid'])) {
783 $where .= " AND cc.id <> " . (int) $params['cid'];
786 // Contact's based of relationhip type
788 if (!empty($params['rel'])) {
789 $relation = explode('_', CRM_Utils_Array
::value('rel', $params));
790 $relType = CRM_Utils_Type
::escape($relation[0], 'Integer');
791 $rel = CRM_Utils_Type
::escape($relation[2], 'String');
794 if ($config->includeWildCardInName
) {
795 $strSearch = "%$name%";
798 $strSearch = "$name%";
800 $includeEmailFrom = $includeNickName = $exactIncludeNickName = '';
801 if ($config->includeNickNameInName
) {
802 $includeNickName = " OR nick_name LIKE '$strSearch'";
803 $exactIncludeNickName = " OR nick_name LIKE '$name'";
807 if (!empty($params['field_name']) && !empty($params['table_name'])) {
808 $table_name = CRM_Utils_String
::munge($params['table_name']);
809 $whereClause = " WHERE ( $table_name.$field_name LIKE '$strSearch') {$where}";
810 $exactWhereClause = " WHERE ( $table_name.$field_name = '$name') {$where}";
811 // Search by id should be exact
812 if ($field_name == 'id' ||
$field_name == 'external_identifier') {
813 $whereClause = $exactWhereClause;
817 if ($config->includeEmailInName
) {
818 if (!in_array('email', $list)) {
819 $includeEmailFrom = "LEFT JOIN civicrm_email eml ON ( cc.id = eml.contact_id AND eml.is_primary = 1 )";
821 $whereClause = " WHERE ( email LIKE '$strSearch' OR sort_name LIKE '$strSearch' $includeNickName ) {$where} ";
822 $exactWhereClause = " WHERE ( email LIKE '$name' OR sort_name LIKE '$name' $exactIncludeNickName ) {$where} ";
825 $whereClause = " WHERE ( sort_name LIKE '$strSearch' $includeNickName ) {$where} ";
826 $exactWhereClause = " WHERE ( sort_name LIKE '$name' $exactIncludeNickName ) {$where} ";
830 $additionalFrom = '';
833 INNER JOIN civicrm_relationship_type r ON (
835 AND ( cc.contact_type = r.contact_type_{$rel} OR r.contact_type_{$rel} IS NULL )
836 AND ( cc.contact_sub_type = r.contact_sub_type_{$rel} OR r.contact_sub_type_{$rel} IS NULL )
840 // check if only CMS users are requested
841 if (!empty($params['cmsuser'])) {
843 INNER JOIN civicrm_uf_match um ON (um.contact_id=cc.id)
848 $orderByOuter = "ORDER BY exactFirst";
849 if ($config->includeOrderByClause
) {
850 $orderByInner = "ORDER BY sort_name";
851 $orderByOuter .= ", sort_name";
856 SELECT DISTINCT(id), data, sort_name {$selectAliases}
858 ( SELECT 0 as exactFirst, cc.id as id, CONCAT_WS( ' :: ', {$actualSelectElements} ) as data {$select}
859 FROM civicrm_contact cc {$from}
861 {$additionalFrom} {$includeEmailFrom}
865 ( SELECT 1 as exactFirst, cc.id as id, CONCAT_WS( ' :: ', {$actualSelectElements} ) as data {$select}
866 FROM civicrm_contact cc {$from}
868 {$additionalFrom} {$includeEmailFrom}
876 // send query to hook to be modified if needed
877 CRM_Utils_Hook
::contactListQuery($query,
879 empty($params['context']) ?
NULL : CRM_Utils_Type
::escape($params['context'], 'String'),
880 empty($params['id']) ?
NULL : $params['id']
883 $dao = CRM_Core_DAO
::executeQuery($query);
885 $contactList = array();
886 $listCurrentEmployer = TRUE;
887 while ($dao->fetch()) {
888 $t = array('id' => $dao->id
);
889 foreach ($as as $k) {
890 $t[$k] = isset($dao->$k) ?
$dao->$k : '';
892 $t['data'] = $dao->data
;
894 if (!empty($params['org']) &&
895 !empty($currEmpDetails) &&
896 $dao->id
== $currEmpDetails['id']
898 $listCurrentEmployer = FALSE;
902 //return organization name if doesn't exist in db
903 if (empty($contactList)) {
904 if (!empty($params['org'])) {
905 if ($listCurrentEmployer && !empty($currEmpDetails)) {
906 $contactList = array(
908 'data' => $currEmpDetails['data'],
909 'id' => $currEmpDetails['id'],
914 $contactList = array(
924 return civicrm_api3_create_success($contactList, $params, 'Contact', 'getquick');
928 * Declare deprecated api functions.
930 * @deprecated api notice
932 * Array of deprecated actions
934 function _civicrm_api3_contact_deprecation() {
935 return array('getquick' => 'The "getquick" action is deprecated in favor of "getlist".');
939 * Merges given pair of duplicate contacts.
941 * @param array $params
942 * Allowed array keys are:
943 * -int main_id: main contact id with whom merge has to happen
944 * -int other_id: duplicate contact which would be deleted after merge operation
945 * -string mode: "safe" skips the merge if there are no conflicts. Does a force merge otherwise.
946 * -boolean auto_flip: whether to let api decide which contact to retain and which to delete.
951 function civicrm_api3_contact_merge($params) {
952 $mode = CRM_Utils_Array
::value('mode', $params, 'safe');
953 $autoFlip = CRM_Utils_Array
::value('auto_flip', $params, TRUE);
955 $dupePairs = array(array(
956 'srcID' => CRM_Utils_Array
::value('main_id', $params),
957 'dstID' => CRM_Utils_Array
::value('other_id', $params),
959 $result = CRM_Dedupe_Merger
::merge($dupePairs, array(), $mode, $autoFlip);
961 if ($result['is_error'] == 0) {
962 return civicrm_api3_create_success();
965 return civicrm_api3_create_error($result['messages']);
970 * Adjust metadata for contact_proximity api function.
972 * @param array $params
974 function _civicrm_api3_contact_proximity_spec(&$params) {
975 $params['latitude'] = array(
976 'title' => 'Latitude',
978 'type' => CRM_Utils_Type
::T_STRING
,
980 $params['longitude'] = array(
981 'title' => 'Longitude',
983 'type' => CRM_Utils_Type
::T_STRING
,
986 $params['unit'] = array(
987 'title' => 'Unit of Measurement',
988 'api.default' => 'meter',
989 'type' => CRM_Utils_Type
::T_STRING
,
994 * Get contacts by proximity.
996 * @param array $params
1001 function civicrm_api3_contact_proximity($params) {
1002 $latitude = CRM_Utils_Array
::value('latitude', $params);
1003 $longitude = CRM_Utils_Array
::value('longitude', $params);
1004 $distance = CRM_Utils_Array
::value('distance', $params);
1006 $unit = CRM_Utils_Array
::value('unit', $params);
1008 // check and ensure that lat/long and distance are floats
1010 !CRM_Utils_Rule
::numeric($latitude) ||
1011 !CRM_Utils_Rule
::numeric($longitude) ||
1012 !CRM_Utils_Rule
::numeric($distance)
1014 throw new Exception(ts('Latitude, Longitude and Distance should exist and be numeric'));
1017 if ($unit == "mile") {
1018 $conversionFactor = 1609.344;
1021 $conversionFactor = 1000;
1023 //Distance in meters
1024 $distance = $distance * $conversionFactor;
1026 $whereClause = CRM_Contact_BAO_ProximityQuery
::where($latitude, $longitude, $distance);
1029 SELECT civicrm_contact.id as contact_id,
1030 civicrm_contact.display_name as display_name
1031 FROM civicrm_contact
1032 LEFT JOIN civicrm_address ON civicrm_contact.id = civicrm_address.contact_id
1036 $dao = CRM_Core_DAO
::executeQuery($query);
1037 $contacts = array();
1038 while ($dao->fetch()) {
1039 $contacts[] = $dao->toArray();
1042 return civicrm_api3_create_success($contacts, $params, 'Contact', 'get_by_location', $dao);
1047 * Get parameters for getlist function.
1049 * @see _civicrm_api3_generic_getlist_params
1051 * @param array $request
1053 function _civicrm_api3_contact_getlist_params(&$request) {
1054 // get the autocomplete options from settings
1055 $acpref = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1056 CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
,
1057 'contact_autocomplete_options'
1061 // get the option values for contact autocomplete
1062 $acOptions = CRM_Core_OptionGroup
::values('contact_autocomplete_options', FALSE, FALSE, FALSE, NULL, 'name');
1065 foreach ($acpref as $value) {
1066 if ($value && !empty($acOptions[$value])) {
1067 $list[] = $acOptions[$value];
1070 // If we are doing quicksearch by a field other than name, make sure that field is added to results
1071 $field_name = CRM_Utils_String
::munge($request['search_field']);
1072 // Unique name contact_id = id
1073 if ($field_name == 'contact_id') {
1076 // phone_numeric should be phone
1077 $searchField = str_replace('_numeric', '', $field_name);
1078 if (!in_array($searchField, $list)) {
1079 $list[] = $searchField;
1081 $request['description_field'] = $list;
1082 $list[] = 'contact_type';
1083 $request['params']['return'] = array_unique(array_merge($list, $request['extra']));
1084 $request['params']['options']['sort'] = 'sort_name';
1085 // Contact api doesn't support array(LIKE => 'foo') syntax
1086 if (!empty($request['input'])) {
1087 $request['params'][$request['search_field']] = $request['input'];
1092 * Get output for getlist function.
1094 * @see _civicrm_api3_generic_getlist_output
1096 * @param array $result
1097 * @param array $request
1101 function _civicrm_api3_contact_getlist_output($result, $request) {
1103 if (!empty($result['values'])) {
1104 $addressFields = array_intersect(array(
1110 $request['params']['return']);
1111 foreach ($result['values'] as $row) {
1113 'id' => $row[$request['id_field']],
1114 'label' => $row[$request['label_field']],
1115 'description' => array(),
1117 foreach ($request['description_field'] as $item) {
1118 if (!strpos($item, '_name') && !in_array($item, $addressFields) && !empty($row[$item])) {
1119 $data['description'][] = $row[$item];
1123 foreach ($addressFields as $item) {
1124 if (!empty($row[$item])) {
1125 $address[] = $row[$item];
1129 $data['description'][] = implode(' ', $address);
1131 if (!empty($request['image_field'])) {
1132 $data['image'] = isset($row[$request['image_field']]) ?
$row[$request['image_field']] : '';
1135 $data['icon_class'] = $row['contact_type'];