3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
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');
137 * Retrieve one or more contacts, given a set of search params.
139 * @param array $params
144 function civicrm_api3_contact_get($params) {
146 _civicrm_api3_contact_get_supportanomalies($params, $options);
147 $contacts = _civicrm_api3_get_using_query_object('Contact', $params, $options);
148 return civicrm_api3_create_success($contacts, $params, 'Contact');
152 * Get number of contacts matching the supplied criteria.
154 * @param array $params
158 function civicrm_api3_contact_getcount($params) {
160 _civicrm_api3_contact_get_supportanomalies($params, $options);
161 $count = _civicrm_api3_get_using_query_object('Contact', $params, $options, 1);
166 * Adjust Metadata for Get action.
168 * @param array $params
169 * Array of parameters determined by getfields.
171 function _civicrm_api3_contact_get_spec(&$params) {
172 $params['contact_is_deleted']['api.default'] = 0;
174 // We declare all these pseudoFields as there are other undocumented fields accessible
175 // via the api - but if check permissions is set we only allow declared fields
176 $params['address_id'] = array(
177 'title' => 'Primary Address ID',
178 'type' => CRM_Utils_Type
::T_INT
,
180 $params['street_address'] = array(
181 'title' => 'Primary Address Street Address',
182 'type' => CRM_Utils_Type
::T_STRING
,
184 $params['supplemental_address_1'] = array(
185 'title' => 'Primary Address Supplemental Address 1',
186 'type' => CRM_Utils_Type
::T_STRING
,
188 $params['supplemental_address_2'] = array(
189 'title' => 'Primary Address Supplemental Address 2',
190 'type' => CRM_Utils_Type
::T_STRING
,
192 $params['current_employer'] = array(
193 'title' => 'Current Employer',
194 'type' => CRM_Utils_Type
::T_STRING
,
196 $params['city'] = array(
197 'title' => 'Primary Address City',
198 'type' => CRM_Utils_Type
::T_STRING
,
200 $params['postal_code_suffix'] = array(
201 'title' => 'Primary Address Post Code Suffix',
202 'type' => CRM_Utils_Type
::T_STRING
,
204 $params['postal_code'] = array(
205 'title' => 'Primary Address Post Code',
206 'type' => CRM_Utils_Type
::T_STRING
,
208 $params['geo_code_1'] = array(
209 'title' => 'Primary Address Latitude',
210 'type' => CRM_Utils_Type
::T_STRING
,
212 $params['geo_code_2'] = array(
213 'title' => 'Primary Address Longitude',
214 'type' => CRM_Utils_Type
::T_STRING
,
216 $params['state_province_id'] = array(
217 'title' => 'Primary Address State Province ID',
218 'type' => CRM_Utils_Type
::T_INT
,
220 $params['state_province_name'] = array(
221 'title' => 'Primary Address State Province Name',
222 'type' => CRM_Utils_Type
::T_STRING
,
224 $params['state_province'] = array(
225 'title' => 'Primary Address State Province',
226 'type' => CRM_Utils_Type
::T_STRING
,
228 $params['country_id'] = array(
229 'title' => 'Primary Address Country ID',
230 'type' => CRM_Utils_Type
::T_INT
,
232 $params['country'] = array(
233 'title' => 'Primary Address country',
234 'type' => CRM_Utils_Type
::T_STRING
,
236 $params['worldregion_id'] = array(
237 'title' => 'Primary Address World Region ID',
238 'type' => CRM_Utils_Type
::T_INT
,
240 $params['worldregion'] = array(
241 'title' => 'Primary Address World Region',
242 'type' => CRM_Utils_Type
::T_STRING
,
244 $params['phone_id'] = array(
245 'title' => 'Primary Phone ID',
246 'type' => CRM_Utils_Type
::T_INT
,
248 $params['phone'] = array(
249 'title' => 'Primary Phone',
250 'type' => CRM_Utils_Type
::T_STRING
,
252 $params['phone_type_id'] = array(
253 'title' => 'Primary Phone Type ID',
254 'type' => CRM_Utils_Type
::T_INT
,
256 $params['provider_id'] = array(
257 'title' => 'Primary Phone Provider ID',
258 'type' => CRM_Utils_Type
::T_INT
,
260 $params['email_id'] = array(
261 'title' => 'Primary Email ID',
262 'type' => CRM_Utils_Type
::T_INT
,
264 $params['email'] = array(
265 'title' => 'Primary Email',
266 'type' => CRM_Utils_Type
::T_STRING
,
268 $params['gender_id'] = array(
269 'title' => 'Gender ID',
270 'type' => CRM_Utils_Type
::T_INT
,
272 $params['gender'] = array(
274 'type' => CRM_Utils_Type
::T_STRING
,
276 $params['on_hold'] = array(
277 'title' => 'Primary Email On Hold',
278 'type' => CRM_Utils_Type
::T_BOOLEAN
,
280 $params['im'] = array(
281 'title' => 'Primary Instant Messenger',
282 'type' => CRM_Utils_Type
::T_STRING
,
284 $params['im_id'] = array(
285 'title' => 'Primary Instant Messenger ID',
286 'type' => CRM_Utils_Type
::T_INT
,
288 $params['group_id'] = array(
289 'title' => 'Group Memberships (filter)',
291 $params['group'] = array(
292 'title' => 'Group Memberships (filter, array)',
294 $params['tag'] = array(
295 'title' => 'Assigned tags (filter, array)',
297 $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'));
298 $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'));
299 $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'));
300 $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'));
304 * Support for historical oddities.
306 * We are supporting 'showAll' = 'all', 'trash' or 'active' for Contact get
308 * - hopefully some day we'll come up with a std syntax for the 3-way-boolean of
311 * We also support 'filter_group_id' & 'filter.group_id'
313 * @param array $params
314 * As passed into api get or getcount function.
315 * @param array $options
316 * Array of options (so we can modify the filter).
318 function _civicrm_api3_contact_get_supportanomalies(&$params, &$options) {
319 if (isset($params['showAll'])) {
320 if (strtolower($params['showAll']) == "active") {
321 $params['contact_is_deleted'] = 0;
323 if (strtolower($params['showAll']) == "trash") {
324 $params['contact_is_deleted'] = 1;
326 if (strtolower($params['showAll']) == "all" && isset($params['contact_is_deleted'])) {
327 unset($params['contact_is_deleted']);
330 // support for group filters
331 if (array_key_exists('filter_group_id', $params)) {
332 $params['filter.group_id'] = $params['filter_group_id'];
333 unset($params['filter_group_id']);
335 // filter.group_id works both for 1,2,3 and array (1,2,3)
336 if (array_key_exists('filter.group_id', $params)) {
337 if (is_array($params['filter.group_id'])) {
338 $groups = $params['filter.group_id'];
341 $groups = explode(',', $params['filter.group_id']);
343 unset($params['filter.group_id']);
344 $groups = array_flip($groups);
345 $groups[key($groups)] = 1;
346 $options['input_params']['group'] = $groups;
351 * Delete a Contact with given contact_id.
353 * @param array $params
354 * input parameters per getfields
359 function civicrm_api3_contact_delete($params) {
361 $contactID = CRM_Utils_Array
::value('id', $params);
363 $session = CRM_Core_Session
::singleton();
364 if ($contactID == $session->get('userID')) {
365 return civicrm_api3_create_error('This contact record is linked to the currently logged in user account - and cannot be deleted.');
367 $restore = !empty($params['restore']) ?
$params['restore'] : FALSE;
368 $skipUndelete = !empty($params['skip_undelete']) ?
$params['skip_undelete'] : FALSE;
371 // restrict permanent delete if a contact has financial trxn associated with it
373 if ($skipUndelete && CRM_Financial_BAO_FinancialItem
::checkContactPresent(array($contactID), $error)) {
374 return civicrm_api3_create_error($error['_qf_default']);
376 if (CRM_Contact_BAO_Contact
::deleteContact($contactID, $restore, $skipUndelete)) {
377 return civicrm_api3_create_success();
380 return civicrm_api3_create_error('Could not delete contact');
386 * Check parameters passed in.
388 * This function is on it's way out.
390 * @param array $params
391 * @param bool $dupeCheck
394 * @throws API_Exception
395 * @throws CiviCRM_API3_Exception
397 function _civicrm_api3_contact_check_params(&$params, $dupeCheck) {
399 switch (strtolower(CRM_Utils_Array
::value('contact_type', $params))) {
401 civicrm_api3_verify_mandatory($params, NULL, array('household_name'));
405 civicrm_api3_verify_mandatory($params, NULL, array('organization_name'));
409 civicrm_api3_verify_one_mandatory($params, NULL, array(
419 // Fixme: This really needs to be handled at a lower level. @See CRM-13123
420 if (isset($params['preferred_communication_method'])) {
421 $params['preferred_communication_method'] = CRM_Utils_Array
::implodePadded($params['preferred_communication_method']);
424 if (!empty($params['contact_sub_type']) && !empty($params['contact_type'])) {
425 if (!(CRM_Contact_BAO_ContactType
::isExtendsContactType($params['contact_sub_type'], $params['contact_type']))) {
426 throw new API_Exception("Invalid or Mismatched Contact Subtype: " . implode(', ', (array) $params['contact_sub_type']));
431 // check for record already existing
432 $dedupeParams = CRM_Dedupe_Finder
::formatParams($params, $params['contact_type']);
435 // setting 'check_permission' here means that the dedupe checking will be carried out even if the
436 // person does not have permission to carry out de-dupes
437 // this is similar to the front end form
438 if (isset($params['check_permission'])) {
439 $dedupeParams['check_permission'] = $params['check_permission'];
442 $ids = CRM_Dedupe_Finder
::dupesByParams($dedupeParams, $params['contact_type'], 'Unsupervised', array());
444 if (count($ids) > 0) {
445 throw new API_Exception("Found matching contacts: " . implode(',', $ids), "duplicate", array("ids" => $ids));
449 // The BAO no longer supports the legacy param "current_employer" so here is a shim for api backward-compatability
450 if (!empty($params['current_employer'])) {
451 $organizationParams = array(
452 'organization_name' => $params['current_employer'],
455 $dedupParams = CRM_Dedupe_Finder
::formatParams($organizationParams, 'Organization');
457 $dedupParams['check_permission'] = FALSE;
458 $dupeIds = CRM_Dedupe_Finder
::dupesByParams($dedupParams, 'Organization', 'Supervised');
460 // check for mismatch employer name and id
461 if (!empty($params['employer_id']) && !in_array($params['employer_id'], $dupeIds)) {
462 throw new API_Exception('Employer name and Employer id Mismatch');
465 // show error if multiple organisation with same name exist
466 if (empty($params['employer_id']) && (count($dupeIds) > 1)) {
467 throw new API_Exception('Found more than one Organisation with same Name.');
471 $params['employer_id'] = $dupeIds[0];
474 $result = civicrm_api3('Contact', 'create', array(
475 'organization_name' => $params['current_employer'],
476 'contact_type' => 'Organization',
478 $params['employer_id'] = $result['id'];
486 * Helper function for Contact create.
488 * @param array $params
489 * (reference ) an assoc array of name/value pairs.
490 * @param int $contactID
491 * If present the contact with that ID is updated.
493 * @return CRM_Contact_BAO_Contact|CRM_Core_Error
495 function _civicrm_api3_contact_update($params, $contactID = NULL) {
496 //@todo - doesn't contact create support 'id' which is already set- check & remove
498 $params['contact_id'] = $contactID;
501 return CRM_Contact_BAO_Contact
::create($params);
505 * Validate the addressee or email or postal greetings.
507 * @param array $params
508 * Array per getfields metadata.
510 * @throws API_Exception
512 function _civicrm_api3_greeting_format_params($params) {
513 $greetingParams = array('', '_id', '_custom');
514 foreach (array('email', 'postal', 'addressee') as $key) {
515 $greeting = '_greeting';
516 if ($key == 'addressee') {
520 $formatParams = FALSE;
521 // Unset display value from params.
522 if (isset($params["{$key}{$greeting}_display"])) {
523 unset($params["{$key}{$greeting}_display"]);
526 // check if greetings are present in present
527 foreach ($greetingParams as $greetingValues) {
528 if (array_key_exists("{$key}{$greeting}{$greetingValues}", $params)) {
529 $formatParams = TRUE;
534 if (!$formatParams) {
540 'contact_type' => $params['contact_type'],
541 'greeting_type' => "{$key}{$greeting}",
544 $greetings = CRM_Core_PseudoConstant
::greeting($filter);
545 $greetingId = CRM_Utils_Array
::value("{$key}{$greeting}_id", $params);
546 $greetingVal = CRM_Utils_Array
::value("{$key}{$greeting}", $params);
547 $customGreeting = CRM_Utils_Array
::value("{$key}{$greeting}_custom", $params);
549 if (!$greetingId && $greetingVal) {
550 $params["{$key}{$greeting}_id"] = CRM_Utils_Array
::key($params["{$key}{$greeting}"], $greetings);
553 if ($customGreeting && $greetingId &&
554 ($greetingId != array_search('Customized', $greetings))
556 throw new API_Exception(ts('Provide either %1 greeting id and/or %1 greeting or custom %1 greeting',
561 if ($greetingVal && $greetingId &&
562 ($greetingId != CRM_Utils_Array
::key($greetingVal, $greetings))
564 throw new API_Exception(ts('Mismatch in %1 greeting id and %1 greeting',
571 if (!array_key_exists($greetingId, $greetings)) {
572 throw new API_Exception(ts('Invalid %1 greeting Id', array(1 => $key)));
575 if (!$customGreeting && ($greetingId == array_search('Customized', $greetings))) {
576 throw new API_Exception(ts('Please provide a custom value for %1 greeting',
581 elseif ($greetingVal) {
583 if (!in_array($greetingVal, $greetings)) {
584 throw new API_Exception(ts('Invalid %1 greeting', array(1 => $key)));
587 $greetingId = CRM_Utils_Array
::key($greetingVal, $greetings);
590 if ($customGreeting) {
591 $greetingId = CRM_Utils_Array
::key('Customized', $greetings);
594 $customValue = isset($params['contact_id']) ? CRM_Core_DAO
::getFieldValue(
595 'CRM_Contact_DAO_Contact',
596 $params['contact_id'],
597 "{$key}{$greeting}_custom"
600 if (array_key_exists("{$key}{$greeting}_id", $params) && empty($params["{$key}{$greeting}_id"])) {
603 elseif (array_key_exists("{$key}{$greeting}", $params) && empty($params["{$key}{$greeting}"])) {
606 elseif ($customValue && array_key_exists("{$key}{$greeting}_custom", $params)
607 && empty($params["{$key}{$greeting}_custom"])
612 $params["{$key}{$greeting}_id"] = $greetingId;
614 if (!$customValue && !$customGreeting && array_key_exists("{$key}{$greeting}_custom", $params)) {
615 unset($params["{$key}{$greeting}_custom"]);
619 $params["{$key}{$greeting}_id"] = '';
620 $params["{$key}{$greeting}_custom"] = '';
623 if (isset($params["{$key}{$greeting}"])) {
624 unset($params["{$key}{$greeting}"]);
630 * Old Contact quick search api.
634 * @param array $params
637 * @throws \API_Exception
639 function civicrm_api3_contact_getquick($params) {
640 civicrm_api3_verify_mandatory($params, NULL, array('name'));
641 $name = CRM_Utils_Type
::escape(CRM_Utils_Array
::value('name', $params), 'String');
643 // get the autocomplete options from settings
644 $acpref = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
645 CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
,
646 'contact_autocomplete_options'
650 // get the option values for contact autocomplete
651 $acOptions = CRM_Core_OptionGroup
::values('contact_autocomplete_options', FALSE, FALSE, FALSE, NULL, 'name');
654 foreach ($acpref as $value) {
655 if ($value && !empty($acOptions[$value])) {
656 $list[$value] = $acOptions[$value];
659 // If we are doing quicksearch by a field other than name, make sure that field is added to results
660 if (!empty($params['field_name'])) {
661 $field_name = CRM_Utils_String
::munge($params['field_name']);
662 // Unique name contact_id = id
663 if ($field_name == 'contact_id') {
666 // phone_numeric should be phone
667 $searchField = str_replace('_numeric', '', $field_name);
668 if (!in_array($searchField, $list)) {
669 $list[] = $searchField;
673 $select = $actualSelectElements = array('sort_name');
676 foreach ($list as $value) {
677 $suffix = substr($value, 0, 2) . substr($value, -1);
679 case 'street_address':
682 $selectText = $value;
687 $actualSelectElements[] = $select[] = ($value == 'address') ?
$selectText : $value;
688 if ($value == 'phone') {
689 $actualSelectElements[] = $select[] = 'phone_ext';
691 $from[$value] = "LEFT JOIN civicrm_{$value} {$suffix} ON ( cc.id = {$suffix}.contact_id AND {$suffix}.is_primary = 1 ) ";
695 case 'state_province':
696 $select[] = "{$suffix}.name as {$value}";
697 $actualSelectElements[] = "{$suffix}.name";
698 if (!in_array('address', $from)) {
699 $from['address'] = 'LEFT JOIN civicrm_address sts ON ( cc.id = sts.contact_id AND sts.is_primary = 1) ';
701 $from[$value] = " LEFT JOIN civicrm_{$value} {$suffix} ON ( sts.{$value}_id = {$suffix}.id ) ";
705 if ($value != 'id') {
707 if (!empty($params['field_name']) && $params['field_name'] == 'value') {
708 $suffix = CRM_Utils_String
::munge(CRM_Utils_Array
::value('table_name', $params, 'cc'));
710 $actualSelectElements[] = $select[] = $suffix . '.' . $value;
716 $config = CRM_Core_Config
::singleton();
718 $select = implode(', ', $select);
719 if (!empty($select)) {
720 $select = ", $select";
722 $actualSelectElements = implode(', ', $actualSelectElements);
723 $selectAliases = $from;
724 unset($selectAliases['address']);
725 $selectAliases = implode(', ', array_keys($selectAliases));
726 if (!empty($selectAliases)) {
727 $selectAliases = ", $selectAliases";
729 $from = implode(' ', $from);
730 $limit = (int) CRM_Utils_Array
::value('limit', $params);
731 $limit = $limit > 0 ?
$limit : 10;
733 // add acl clause here
734 list($aclFrom, $aclWhere) = CRM_Contact_BAO_Contact_Permission
::cacheClause('cc');
737 $where .= " AND $aclWhere ";
740 if (!empty($params['org'])) {
741 $where .= " AND contact_type = \"Organization\"";
743 // CRM-7157, hack: get current employer details when
744 // employee_id is present.
745 $currEmpDetails = array();
746 if (!empty($params['employee_id'])) {
747 if ($currentEmployer = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact',
748 (int) $params['employee_id'],
751 if ($config->includeWildCardInName
) {
752 $strSearch = "%$name%";
755 $strSearch = "$name%";
758 // get current employer details
759 $dao = CRM_Core_DAO
::executeQuery("SELECT cc.id as id, CONCAT_WS( ' :: ', {$actualSelectElements} ) as data, sort_name
760 FROM civicrm_contact cc {$from} WHERE cc.contact_type = \"Organization\" AND cc.id = {$currentEmployer} AND cc.sort_name LIKE '$strSearch'");
762 $currEmpDetails = array(
764 'data' => $dao->data
,
771 if (!empty($params['contact_sub_type'])) {
772 $contactSubType = CRM_Utils_Type
::escape($params['contact_sub_type'], 'String');
773 $where .= " AND cc.contact_sub_type = '{$contactSubType}'";
776 if (!empty($params['contact_type'])) {
777 $contactType = CRM_Utils_Type
::escape($params['contact_type'], 'String');
778 $where .= " AND cc.contact_type LIKE '{$contactType}'";
781 // Set default for current_employer or return contact with particular id
782 if (!empty($params['id'])) {
783 $where .= " AND cc.id = " . (int) $params['id'];
786 if (!empty($params['cid'])) {
787 $where .= " AND cc.id <> " . (int) $params['cid'];
790 // Contact's based of relationhip type
792 if (!empty($params['rel'])) {
793 $relation = explode('_', CRM_Utils_Array
::value('rel', $params));
794 $relType = CRM_Utils_Type
::escape($relation[0], 'Integer');
795 $rel = CRM_Utils_Type
::escape($relation[2], 'String');
798 if ($config->includeWildCardInName
) {
799 $strSearch = "%$name%";
802 $strSearch = "$name%";
804 $includeEmailFrom = $includeNickName = $exactIncludeNickName = '';
805 if ($config->includeNickNameInName
) {
806 $includeNickName = " OR nick_name LIKE '$strSearch'";
807 $exactIncludeNickName = " OR nick_name LIKE '$name'";
811 if (!empty($params['field_name']) && !empty($params['table_name'])) {
812 $table_name = CRM_Utils_String
::munge($params['table_name']);
813 $whereClause = " WHERE ( $table_name.$field_name LIKE '$strSearch') {$where}";
814 $exactWhereClause = " WHERE ( $table_name.$field_name = '$name') {$where}";
815 // Search by id should be exact
816 if ($field_name == 'id' ||
$field_name == 'external_identifier') {
817 $whereClause = $exactWhereClause;
821 if ($config->includeEmailInName
) {
822 if (!in_array('email', $list)) {
823 $includeEmailFrom = "LEFT JOIN civicrm_email eml ON ( cc.id = eml.contact_id AND eml.is_primary = 1 )";
825 $whereClause = " WHERE ( email LIKE '$strSearch' OR sort_name LIKE '$strSearch' $includeNickName ) {$where} ";
826 $exactWhereClause = " WHERE ( email LIKE '$name' OR sort_name LIKE '$name' $exactIncludeNickName ) {$where} ";
829 $whereClause = " WHERE ( sort_name LIKE '$strSearch' $includeNickName ) {$where} ";
830 $exactWhereClause = " WHERE ( sort_name LIKE '$name' $exactIncludeNickName ) {$where} ";
834 $additionalFrom = '';
837 INNER JOIN civicrm_relationship_type r ON (
839 AND ( cc.contact_type = r.contact_type_{$rel} OR r.contact_type_{$rel} IS NULL )
840 AND ( cc.contact_sub_type = r.contact_sub_type_{$rel} OR r.contact_sub_type_{$rel} IS NULL )
844 // check if only CMS users are requested
845 if (!empty($params['cmsuser'])) {
847 INNER JOIN civicrm_uf_match um ON (um.contact_id=cc.id)
852 $orderByOuter = "ORDER BY exactFirst";
853 if ($config->includeOrderByClause
) {
854 $orderByInner = "ORDER BY sort_name";
855 $orderByOuter .= ", sort_name";
860 SELECT DISTINCT(id), data, sort_name {$selectAliases}
862 ( SELECT 0 as exactFirst, cc.id as id, CONCAT_WS( ' :: ', {$actualSelectElements} ) as data {$select}
863 FROM civicrm_contact cc {$from}
865 {$additionalFrom} {$includeEmailFrom}
869 ( SELECT 1 as exactFirst, cc.id as id, CONCAT_WS( ' :: ', {$actualSelectElements} ) as data {$select}
870 FROM civicrm_contact cc {$from}
872 {$additionalFrom} {$includeEmailFrom}
880 // send query to hook to be modified if needed
881 CRM_Utils_Hook
::contactListQuery($query,
883 empty($params['context']) ?
NULL : CRM_Utils_Type
::escape($params['context'], 'String'),
884 empty($params['id']) ?
NULL : $params['id']
887 $dao = CRM_Core_DAO
::executeQuery($query);
889 $contactList = array();
890 $listCurrentEmployer = TRUE;
891 while ($dao->fetch()) {
892 $t = array('id' => $dao->id
);
893 foreach ($as as $k) {
894 $t[$k] = isset($dao->$k) ?
$dao->$k : '';
896 $t['data'] = $dao->data
;
898 if (!empty($params['org']) &&
899 !empty($currEmpDetails) &&
900 $dao->id
== $currEmpDetails['id']
902 $listCurrentEmployer = FALSE;
906 //return organization name if doesn't exist in db
907 if (empty($contactList)) {
908 if (!empty($params['org'])) {
909 if ($listCurrentEmployer && !empty($currEmpDetails)) {
910 $contactList = array(
912 'data' => $currEmpDetails['data'],
913 'id' => $currEmpDetails['id'],
918 $contactList = array(
928 return civicrm_api3_create_success($contactList, $params, 'Contact', 'getquick');
932 * Declare deprecated api functions.
934 * @deprecated api notice
936 * Array of deprecated actions
938 function _civicrm_api3_contact_deprecation() {
939 return array('getquick' => 'The "getquick" action is deprecated in favor of "getlist".');
943 * Merges given pair of duplicate contacts.
945 * @param array $params
946 * Allowed array keys are:
947 * -int main_id: main contact id with whom merge has to happen
948 * -int other_id: duplicate contact which would be deleted after merge operation
949 * -string mode: "safe" skips the merge if there are no conflicts. Does a force merge otherwise.
950 * -boolean auto_flip: whether to let api decide which contact to retain and which to delete.
955 function civicrm_api3_contact_merge($params) {
956 $mode = CRM_Utils_Array
::value('mode', $params, 'safe');
957 $autoFlip = CRM_Utils_Array
::value('auto_flip', $params, TRUE);
959 $dupePairs = array(array(
960 'srcID' => CRM_Utils_Array
::value('main_id', $params),
961 'dstID' => CRM_Utils_Array
::value('other_id', $params),
963 $result = CRM_Dedupe_Merger
::merge($dupePairs, array(), $mode, $autoFlip);
965 if ($result['is_error'] == 0) {
966 return civicrm_api3_create_success();
969 return civicrm_api3_create_error($result['messages']);
974 * Adjust metadata for contact_proximity api function.
976 * @param array $params
978 function _civicrm_api3_contact_proximity_spec(&$params) {
979 $params['latitude'] = array(
980 'title' => 'Latitude',
982 'type' => CRM_Utils_Type
::T_STRING
,
984 $params['longitude'] = array(
985 'title' => 'Longitude',
987 'type' => CRM_Utils_Type
::T_STRING
,
990 $params['unit'] = array(
991 'title' => 'Unit of Measurement',
992 'api.default' => 'meter',
993 'type' => CRM_Utils_Type
::T_STRING
,
998 * Get contacts by proximity.
1000 * @param array $params
1005 function civicrm_api3_contact_proximity($params) {
1006 $latitude = CRM_Utils_Array
::value('latitude', $params);
1007 $longitude = CRM_Utils_Array
::value('longitude', $params);
1008 $distance = CRM_Utils_Array
::value('distance', $params);
1010 $unit = CRM_Utils_Array
::value('unit', $params);
1012 // check and ensure that lat/long and distance are floats
1014 !CRM_Utils_Rule
::numeric($latitude) ||
1015 !CRM_Utils_Rule
::numeric($longitude) ||
1016 !CRM_Utils_Rule
::numeric($distance)
1018 throw new Exception(ts('Latitude, Longitude and Distance should exist and be numeric'));
1021 if ($unit == "mile") {
1022 $conversionFactor = 1609.344;
1025 $conversionFactor = 1000;
1027 //Distance in meters
1028 $distance = $distance * $conversionFactor;
1030 $whereClause = CRM_Contact_BAO_ProximityQuery
::where($latitude, $longitude, $distance);
1033 SELECT civicrm_contact.id as contact_id,
1034 civicrm_contact.display_name as display_name
1035 FROM civicrm_contact
1036 LEFT JOIN civicrm_address ON civicrm_contact.id = civicrm_address.contact_id
1040 $dao = CRM_Core_DAO
::executeQuery($query);
1041 $contacts = array();
1042 while ($dao->fetch()) {
1043 $contacts[] = $dao->toArray();
1046 return civicrm_api3_create_success($contacts, $params, 'Contact', 'get_by_location', $dao);
1051 * Get parameters for getlist function.
1053 * @see _civicrm_api3_generic_getlist_params
1055 * @param array $request
1057 function _civicrm_api3_contact_getlist_params(&$request) {
1058 // get the autocomplete options from settings
1059 $acpref = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1060 CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
,
1061 'contact_autocomplete_options'
1065 // get the option values for contact autocomplete
1066 $acOptions = CRM_Core_OptionGroup
::values('contact_autocomplete_options', FALSE, FALSE, FALSE, NULL, 'name');
1069 foreach ($acpref as $value) {
1070 if ($value && !empty($acOptions[$value])) {
1071 $list[] = $acOptions[$value];
1074 // If we are doing quicksearch by a field other than name, make sure that field is added to results
1075 $field_name = CRM_Utils_String
::munge($request['search_field']);
1076 // Unique name contact_id = id
1077 if ($field_name == 'contact_id') {
1080 // phone_numeric should be phone
1081 $searchField = str_replace('_numeric', '', $field_name);
1082 if (!in_array($searchField, $list)) {
1083 $list[] = $searchField;
1085 $request['description_field'] = $list;
1086 $list[] = 'contact_type';
1087 $request['params']['return'] = array_unique(array_merge($list, $request['extra']));
1088 $request['params']['options']['sort'] = 'sort_name';
1089 // Contact api doesn't support array(LIKE => 'foo') syntax
1090 if (!empty($request['input'])) {
1091 $request['params'][$request['search_field']] = $request['input'];
1096 * Get output for getlist function.
1098 * @see _civicrm_api3_generic_getlist_output
1100 * @param array $result
1101 * @param array $request
1105 function _civicrm_api3_contact_getlist_output($result, $request) {
1107 if (!empty($result['values'])) {
1108 $addressFields = array_intersect(array(
1114 $request['params']['return']);
1115 foreach ($result['values'] as $row) {
1117 'id' => $row[$request['id_field']],
1118 'label' => $row[$request['label_field']],
1119 'description' => array(),
1121 foreach ($request['description_field'] as $item) {
1122 if (!strpos($item, '_name') && !in_array($item, $addressFields) && !empty($row[$item])) {
1123 $data['description'][] = $row[$item];
1127 foreach ($addressFields as $item) {
1128 if (!empty($row[$item])) {
1129 $address[] = $row[$item];
1133 $data['description'][] = implode(' ', $address);
1135 if (!empty($request['image_field'])) {
1136 $data['image'] = isset($row[$request['image_field']]) ?
$row[$request['image_field']] : '';
1139 $data['icon_class'] = $row['contact_type'];
1141 foreach ($request['extra'] as $field) {
1142 $data['extra'][$field] = isset($row[$field]) ?
$row[$field] : NULL;