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');
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['on_hold'] = array(
269 'title' => 'Primary Email On Hold',
270 'type' => CRM_Utils_Type
::T_BOOLEAN
,
272 $params['im'] = array(
273 'title' => 'Primary Instant Messenger',
274 'type' => CRM_Utils_Type
::T_STRING
,
276 $params['im_id'] = array(
277 'title' => 'Primary Instant Messenger ID',
278 'type' => CRM_Utils_Type
::T_INT
,
280 $params['group'] = array(
282 'pseudoconstant' => array(
283 'table' => 'civicrm_group',
286 $params['tag'] = array(
288 'pseudoconstant' => array(
289 'table' => 'civicrm_tag',
292 $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'));
293 $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'));
294 $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'));
295 $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'));
299 * Support for historical oddities.
301 * We are supporting 'showAll' = 'all', 'trash' or 'active' for Contact get
303 * - hopefully some day we'll come up with a std syntax for the 3-way-boolean of
306 * We also support 'filter_group_id' & 'filter.group_id'
308 * @param array $params
309 * As passed into api get or getcount function.
310 * @param array $options
311 * Array of options (so we can modify the filter).
313 function _civicrm_api3_contact_get_supportanomalies(&$params, &$options) {
314 if (isset($params['showAll'])) {
315 if (strtolower($params['showAll']) == "active") {
316 $params['contact_is_deleted'] = 0;
318 if (strtolower($params['showAll']) == "trash") {
319 $params['contact_is_deleted'] = 1;
321 if (strtolower($params['showAll']) == "all" && isset($params['contact_is_deleted'])) {
322 unset($params['contact_is_deleted']);
325 // support for group filters
326 if (array_key_exists('filter_group_id', $params)) {
327 $params['filter.group_id'] = $params['filter_group_id'];
328 unset($params['filter_group_id']);
330 // filter.group_id works both for 1,2,3 and array (1,2,3)
331 if (array_key_exists('filter.group_id', $params)) {
332 if (is_array($params['filter.group_id'])) {
333 $groups = $params['filter.group_id'];
336 $groups = explode(',', $params['filter.group_id']);
338 unset($params['filter.group_id']);
339 $groups = array_flip($groups);
340 $groups[key($groups)] = 1;
341 $options['input_params']['group'] = $groups;
346 * Delete a Contact with given contact_id.
348 * @param array $params
349 * input parameters per getfields
354 function civicrm_api3_contact_delete($params) {
356 $contactID = CRM_Utils_Array
::value('id', $params);
358 $session = CRM_Core_Session
::singleton();
359 if ($contactID == $session->get('userID')) {
360 return civicrm_api3_create_error('This contact record is linked to the currently logged in user account - and cannot be deleted.');
362 $restore = !empty($params['restore']) ?
$params['restore'] : FALSE;
363 $skipUndelete = !empty($params['skip_undelete']) ?
$params['skip_undelete'] : FALSE;
366 // restrict permanent delete if a contact has financial trxn associated with it
368 if ($skipUndelete && CRM_Financial_BAO_FinancialItem
::checkContactPresent(array($contactID), $error)) {
369 return civicrm_api3_create_error($error['_qf_default']);
371 if (CRM_Contact_BAO_Contact
::deleteContact($contactID, $restore, $skipUndelete)) {
372 return civicrm_api3_create_success();
375 return civicrm_api3_create_error('Could not delete contact');
381 * Check parameters passed in.
383 * This function is on it's way out.
385 * @param array $params
386 * @param bool $dupeCheck
389 * @throws API_Exception
390 * @throws CiviCRM_API3_Exception
392 function _civicrm_api3_contact_check_params(&$params, $dupeCheck) {
394 switch (strtolower(CRM_Utils_Array
::value('contact_type', $params))) {
396 civicrm_api3_verify_mandatory($params, NULL, array('household_name'));
400 civicrm_api3_verify_mandatory($params, NULL, array('organization_name'));
404 civicrm_api3_verify_one_mandatory($params, NULL, array(
414 // Fixme: This really needs to be handled at a lower level. @See CRM-13123
415 if (isset($params['preferred_communication_method'])) {
416 $params['preferred_communication_method'] = CRM_Utils_Array
::implodePadded($params['preferred_communication_method']);
419 if (!empty($params['contact_sub_type']) && !empty($params['contact_type'])) {
420 if (!(CRM_Contact_BAO_ContactType
::isExtendsContactType($params['contact_sub_type'], $params['contact_type']))) {
421 throw new API_Exception("Invalid or Mismatched Contact Subtype: " . implode(', ', (array) $params['contact_sub_type']));
426 // check for record already existing
427 $dedupeParams = CRM_Dedupe_Finder
::formatParams($params, $params['contact_type']);
430 // setting 'check_permission' here means that the dedupe checking will be carried out even if the
431 // person does not have permission to carry out de-dupes
432 // this is similar to the front end form
433 if (isset($params['check_permission'])) {
434 $dedupeParams['check_permission'] = $params['check_permission'];
437 $ids = CRM_Dedupe_Finder
::dupesByParams($dedupeParams, $params['contact_type'], 'Unsupervised', array());
439 if (count($ids) > 0) {
440 throw new API_Exception("Found matching contacts: " . implode(',', $ids), "duplicate", array("ids" => $ids));
444 // The BAO no longer supports the legacy param "current_employer" so here is a shim for api backward-compatability
445 if (!empty($params['current_employer'])) {
446 $organizationParams = array(
447 'organization_name' => $params['current_employer'],
450 $dedupParams = CRM_Dedupe_Finder
::formatParams($organizationParams, 'Organization');
452 $dedupParams['check_permission'] = FALSE;
453 $dupeIds = CRM_Dedupe_Finder
::dupesByParams($dedupParams, 'Organization', 'Supervised');
455 // check for mismatch employer name and id
456 if (!empty($params['employer_id']) && !in_array($params['employer_id'], $dupeIds)) {
457 throw new API_Exception('Employer name and Employer id Mismatch');
460 // show error if multiple organisation with same name exist
461 if (empty($params['employer_id']) && (count($dupeIds) > 1)) {
462 throw new API_Exception('Found more than one Organisation with same Name.');
466 $params['employer_id'] = $dupeIds[0];
469 $result = civicrm_api3('Contact', 'create', array(
470 'organization_name' => $params['current_employer'],
471 'contact_type' => 'Organization',
473 $params['employer_id'] = $result['id'];
481 * Helper function for Contact create.
483 * @param array $params
484 * (reference ) an assoc array of name/value pairs.
485 * @param int $contactID
486 * If present the contact with that ID is updated.
488 * @return CRM_Contact_BAO_Contact|CRM_Core_Error
490 function _civicrm_api3_contact_update($params, $contactID = NULL) {
491 //@todo - doesn't contact create support 'id' which is already set- check & remove
493 $params['contact_id'] = $contactID;
496 return CRM_Contact_BAO_Contact
::create($params);
500 * Validate the addressee or email or postal greetings.
502 * @param array $params
503 * Array per getfields metadata.
505 * @throws API_Exception
507 function _civicrm_api3_greeting_format_params($params) {
508 $greetingParams = array('', '_id', '_custom');
509 foreach (array('email', 'postal', 'addressee') as $key) {
510 $greeting = '_greeting';
511 if ($key == 'addressee') {
515 $formatParams = FALSE;
516 // Unset display value from params.
517 if (isset($params["{$key}{$greeting}_display"])) {
518 unset($params["{$key}{$greeting}_display"]);
521 // check if greetings are present in present
522 foreach ($greetingParams as $greetingValues) {
523 if (array_key_exists("{$key}{$greeting}{$greetingValues}", $params)) {
524 $formatParams = TRUE;
529 if (!$formatParams) {
535 'contact_type' => $params['contact_type'],
536 'greeting_type' => "{$key}{$greeting}",
539 $greetings = CRM_Core_PseudoConstant
::greeting($filter);
540 $greetingId = CRM_Utils_Array
::value("{$key}{$greeting}_id", $params);
541 $greetingVal = CRM_Utils_Array
::value("{$key}{$greeting}", $params);
542 $customGreeting = CRM_Utils_Array
::value("{$key}{$greeting}_custom", $params);
544 if (!$greetingId && $greetingVal) {
545 $params["{$key}{$greeting}_id"] = CRM_Utils_Array
::key($params["{$key}{$greeting}"], $greetings);
548 if ($customGreeting && $greetingId &&
549 ($greetingId != array_search('Customized', $greetings))
551 throw new API_Exception(ts('Provide either %1 greeting id and/or %1 greeting or custom %1 greeting',
556 if ($greetingVal && $greetingId &&
557 ($greetingId != CRM_Utils_Array
::key($greetingVal, $greetings))
559 throw new API_Exception(ts('Mismatch in %1 greeting id and %1 greeting',
566 if (!array_key_exists($greetingId, $greetings)) {
567 throw new API_Exception(ts('Invalid %1 greeting Id', array(1 => $key)));
570 if (!$customGreeting && ($greetingId == array_search('Customized', $greetings))) {
571 throw new API_Exception(ts('Please provide a custom value for %1 greeting',
576 elseif ($greetingVal) {
578 if (!in_array($greetingVal, $greetings)) {
579 throw new API_Exception(ts('Invalid %1 greeting', array(1 => $key)));
582 $greetingId = CRM_Utils_Array
::key($greetingVal, $greetings);
585 if ($customGreeting) {
586 $greetingId = CRM_Utils_Array
::key('Customized', $greetings);
589 $customValue = isset($params['contact_id']) ? CRM_Core_DAO
::getFieldValue(
590 'CRM_Contact_DAO_Contact',
591 $params['contact_id'],
592 "{$key}{$greeting}_custom"
595 if (array_key_exists("{$key}{$greeting}_id", $params) && empty($params["{$key}{$greeting}_id"])) {
598 elseif (array_key_exists("{$key}{$greeting}", $params) && empty($params["{$key}{$greeting}"])) {
601 elseif ($customValue && array_key_exists("{$key}{$greeting}_custom", $params)
602 && empty($params["{$key}{$greeting}_custom"])
607 $params["{$key}{$greeting}_id"] = $greetingId;
609 if (!$customValue && !$customGreeting && array_key_exists("{$key}{$greeting}_custom", $params)) {
610 unset($params["{$key}{$greeting}_custom"]);
614 $params["{$key}{$greeting}_id"] = '';
615 $params["{$key}{$greeting}_custom"] = '';
618 if (isset($params["{$key}{$greeting}"])) {
619 unset($params["{$key}{$greeting}"]);
625 * Old Contact quick search api.
629 * @param array $params
632 * @throws \API_Exception
634 function civicrm_api3_contact_getquick($params) {
635 civicrm_api3_verify_mandatory($params, NULL, array('name'));
636 $name = CRM_Utils_Type
::escape(CRM_Utils_Array
::value('name', $params), 'String');
638 // get the autocomplete options from settings
639 $acpref = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
640 CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
,
641 'contact_autocomplete_options'
645 // get the option values for contact autocomplete
646 $acOptions = CRM_Core_OptionGroup
::values('contact_autocomplete_options', FALSE, FALSE, FALSE, NULL, 'name');
649 foreach ($acpref as $value) {
650 if ($value && !empty($acOptions[$value])) {
651 $list[$value] = $acOptions[$value];
654 // If we are doing quicksearch by a field other than name, make sure that field is added to results
655 if (!empty($params['field_name'])) {
656 $field_name = CRM_Utils_String
::munge($params['field_name']);
657 // Unique name contact_id = id
658 if ($field_name == 'contact_id') {
661 // phone_numeric should be phone
662 $searchField = str_replace('_numeric', '', $field_name);
663 if (!in_array($searchField, $list)) {
664 $list[] = $searchField;
668 $select = $actualSelectElements = array('sort_name');
671 foreach ($list as $value) {
672 $suffix = substr($value, 0, 2) . substr($value, -1);
674 case 'street_address':
677 $selectText = $value;
682 $actualSelectElements[] = $select[] = ($value == 'address') ?
$selectText : $value;
683 if ($value == 'phone') {
684 $actualSelectElements[] = $select[] = 'phone_ext';
686 $from[$value] = "LEFT JOIN civicrm_{$value} {$suffix} ON ( cc.id = {$suffix}.contact_id AND {$suffix}.is_primary = 1 ) ";
690 case 'state_province':
691 $select[] = "{$suffix}.name as {$value}";
692 $actualSelectElements[] = "{$suffix}.name";
693 if (!in_array('address', $from)) {
694 $from['address'] = 'LEFT JOIN civicrm_address sts ON ( cc.id = sts.contact_id AND sts.is_primary = 1) ';
696 $from[$value] = " LEFT JOIN civicrm_{$value} {$suffix} ON ( sts.{$value}_id = {$suffix}.id ) ";
700 if ($value != 'id') {
702 if (!empty($params['field_name']) && $params['field_name'] == 'value') {
703 $suffix = CRM_Utils_String
::munge(CRM_Utils_Array
::value('table_name', $params, 'cc'));
705 $actualSelectElements[] = $select[] = $suffix . '.' . $value;
711 $config = CRM_Core_Config
::singleton();
713 $select = implode(', ', $select);
714 if (!empty($select)) {
715 $select = ", $select";
717 $actualSelectElements = implode(', ', $actualSelectElements);
718 $selectAliases = $from;
719 unset($selectAliases['address']);
720 $selectAliases = implode(', ', array_keys($selectAliases));
721 if (!empty($selectAliases)) {
722 $selectAliases = ", $selectAliases";
724 $from = implode(' ', $from);
725 $limit = (int) CRM_Utils_Array
::value('limit', $params);
726 $limit = $limit > 0 ?
$limit : CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::SEARCH_PREFERENCES_NAME
, 'search_autocomplete_count', NULL, 10);
728 // add acl clause here
729 list($aclFrom, $aclWhere) = CRM_Contact_BAO_Contact_Permission
::cacheClause('cc');
732 $where .= " AND $aclWhere ";
735 if (!empty($params['org'])) {
736 $where .= " AND contact_type = \"Organization\"";
738 // CRM-7157, hack: get current employer details when
739 // employee_id is present.
740 $currEmpDetails = array();
741 if (!empty($params['employee_id'])) {
742 if ($currentEmployer = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact',
743 (int) $params['employee_id'],
746 if ($config->includeWildCardInName
) {
747 $strSearch = "%$name%";
750 $strSearch = "$name%";
753 // get current employer details
754 $dao = CRM_Core_DAO
::executeQuery("SELECT cc.id as id, CONCAT_WS( ' :: ', {$actualSelectElements} ) as data, sort_name
755 FROM civicrm_contact cc {$from} WHERE cc.contact_type = \"Organization\" AND cc.id = {$currentEmployer} AND cc.sort_name LIKE '$strSearch'");
757 $currEmpDetails = array(
759 'data' => $dao->data
,
766 if (!empty($params['contact_sub_type'])) {
767 $contactSubType = CRM_Utils_Type
::escape($params['contact_sub_type'], 'String');
768 $where .= " AND cc.contact_sub_type = '{$contactSubType}'";
771 if (!empty($params['contact_type'])) {
772 $contactType = CRM_Utils_Type
::escape($params['contact_type'], 'String');
773 $where .= " AND cc.contact_type LIKE '{$contactType}'";
776 // Set default for current_employer or return contact with particular id
777 if (!empty($params['id'])) {
778 $where .= " AND cc.id = " . (int) $params['id'];
781 if (!empty($params['cid'])) {
782 $where .= " AND cc.id <> " . (int) $params['cid'];
785 // Contact's based of relationhip type
787 if (!empty($params['rel'])) {
788 $relation = explode('_', CRM_Utils_Array
::value('rel', $params));
789 $relType = CRM_Utils_Type
::escape($relation[0], 'Integer');
790 $rel = CRM_Utils_Type
::escape($relation[2], 'String');
793 if ($config->includeWildCardInName
) {
794 $strSearch = "%$name%";
797 $strSearch = "$name%";
799 $includeEmailFrom = $includeNickName = $exactIncludeNickName = '';
800 if ($config->includeNickNameInName
) {
801 $includeNickName = " OR nick_name LIKE '$strSearch'";
802 $exactIncludeNickName = " OR nick_name LIKE '$name'";
806 if (!empty($params['field_name']) && !empty($params['table_name'])) {
807 $table_name = CRM_Utils_String
::munge($params['table_name']);
808 $whereClause = " WHERE ( $table_name.$field_name LIKE '$strSearch') {$where}";
809 $exactWhereClause = " WHERE ( $table_name.$field_name = '$name') {$where}";
810 // Search by id should be exact
811 if ($field_name == 'id' ||
$field_name == 'external_identifier') {
812 $whereClause = $exactWhereClause;
816 if ($config->includeEmailInName
) {
817 if (!in_array('email', $list)) {
818 $includeEmailFrom = "LEFT JOIN civicrm_email eml ON ( cc.id = eml.contact_id AND eml.is_primary = 1 )";
820 $whereClause = " WHERE ( email LIKE '$strSearch' OR sort_name LIKE '$strSearch' $includeNickName ) {$where} ";
821 $exactWhereClause = " WHERE ( email LIKE '$name' OR sort_name LIKE '$name' $exactIncludeNickName ) {$where} ";
824 $whereClause = " WHERE ( sort_name LIKE '$strSearch' $includeNickName ) {$where} ";
825 $exactWhereClause = " WHERE ( sort_name LIKE '$name' $exactIncludeNickName ) {$where} ";
829 $additionalFrom = '';
832 INNER JOIN civicrm_relationship_type r ON (
834 AND ( cc.contact_type = r.contact_type_{$rel} OR r.contact_type_{$rel} IS NULL )
835 AND ( cc.contact_sub_type = r.contact_sub_type_{$rel} OR r.contact_sub_type_{$rel} IS NULL )
839 // check if only CMS users are requested
840 if (!empty($params['cmsuser'])) {
842 INNER JOIN civicrm_uf_match um ON (um.contact_id=cc.id)
847 $orderByOuter = "ORDER BY exactFirst";
848 if ($config->includeOrderByClause
) {
849 $orderByInner = "ORDER BY sort_name";
850 $orderByOuter .= ", sort_name";
855 SELECT DISTINCT(id), data, sort_name {$selectAliases}
857 ( SELECT 0 as exactFirst, cc.id as id, CONCAT_WS( ' :: ', {$actualSelectElements} ) as data {$select}
858 FROM civicrm_contact cc {$from}
860 {$additionalFrom} {$includeEmailFrom}
864 ( SELECT 1 as exactFirst, cc.id as id, CONCAT_WS( ' :: ', {$actualSelectElements} ) as data {$select}
865 FROM civicrm_contact cc {$from}
867 {$additionalFrom} {$includeEmailFrom}
875 // send query to hook to be modified if needed
876 CRM_Utils_Hook
::contactListQuery($query,
878 empty($params['context']) ?
NULL : CRM_Utils_Type
::escape($params['context'], 'String'),
879 empty($params['id']) ?
NULL : $params['id']
882 $dao = CRM_Core_DAO
::executeQuery($query);
884 $contactList = array();
885 $listCurrentEmployer = TRUE;
886 while ($dao->fetch()) {
887 $t = array('id' => $dao->id
);
888 foreach ($as as $k) {
889 $t[$k] = isset($dao->$k) ?
$dao->$k : '';
891 $t['data'] = $dao->data
;
893 if (!empty($params['org']) &&
894 !empty($currEmpDetails) &&
895 $dao->id
== $currEmpDetails['id']
897 $listCurrentEmployer = FALSE;
901 //return organization name if doesn't exist in db
902 if (empty($contactList)) {
903 if (!empty($params['org'])) {
904 if ($listCurrentEmployer && !empty($currEmpDetails)) {
905 $contactList = array(
907 'data' => $currEmpDetails['data'],
908 'id' => $currEmpDetails['id'],
913 $contactList = array(
923 return civicrm_api3_create_success($contactList, $params, 'Contact', 'getquick');
927 * Declare deprecated api functions.
929 * @deprecated api notice
931 * Array of deprecated actions
933 function _civicrm_api3_contact_deprecation() {
934 return array('getquick' => 'The "getquick" action is deprecated in favor of "getlist".');
938 * Merges given pair of duplicate contacts.
940 * @param array $params
941 * Allowed array keys are:
942 * -int main_id: main contact id with whom merge has to happen
943 * -int other_id: duplicate contact which would be deleted after merge operation
944 * -string mode: "safe" skips the merge if there are no conflicts. Does a force merge otherwise.
945 * -boolean auto_flip: whether to let api decide which contact to retain and which to delete.
950 function civicrm_api3_contact_merge($params) {
951 $mode = CRM_Utils_Array
::value('mode', $params, 'safe');
952 $autoFlip = CRM_Utils_Array
::value('auto_flip', $params, TRUE);
954 $dupePairs = array(array(
955 'srcID' => CRM_Utils_Array
::value('main_id', $params),
956 'dstID' => CRM_Utils_Array
::value('other_id', $params),
958 $result = CRM_Dedupe_Merger
::merge($dupePairs, array(), $mode, $autoFlip);
960 if ($result['is_error'] == 0) {
961 return civicrm_api3_create_success();
964 return civicrm_api3_create_error($result['messages']);
969 * Adjust metadata for contact_proximity api function.
971 * @param array $params
973 function _civicrm_api3_contact_proximity_spec(&$params) {
974 $params['latitude'] = array(
975 'title' => 'Latitude',
977 'type' => CRM_Utils_Type
::T_STRING
,
979 $params['longitude'] = array(
980 'title' => 'Longitude',
982 'type' => CRM_Utils_Type
::T_STRING
,
985 $params['unit'] = array(
986 'title' => 'Unit of Measurement',
987 'api.default' => 'meter',
988 'type' => CRM_Utils_Type
::T_STRING
,
993 * Get contacts by proximity.
995 * @param array $params
1000 function civicrm_api3_contact_proximity($params) {
1001 $latitude = CRM_Utils_Array
::value('latitude', $params);
1002 $longitude = CRM_Utils_Array
::value('longitude', $params);
1003 $distance = CRM_Utils_Array
::value('distance', $params);
1005 $unit = CRM_Utils_Array
::value('unit', $params);
1007 // check and ensure that lat/long and distance are floats
1009 !CRM_Utils_Rule
::numeric($latitude) ||
1010 !CRM_Utils_Rule
::numeric($longitude) ||
1011 !CRM_Utils_Rule
::numeric($distance)
1013 throw new Exception(ts('Latitude, Longitude and Distance should exist and be numeric'));
1016 if ($unit == "mile") {
1017 $conversionFactor = 1609.344;
1020 $conversionFactor = 1000;
1022 //Distance in meters
1023 $distance = $distance * $conversionFactor;
1025 $whereClause = CRM_Contact_BAO_ProximityQuery
::where($latitude, $longitude, $distance);
1028 SELECT civicrm_contact.id as contact_id,
1029 civicrm_contact.display_name as display_name
1030 FROM civicrm_contact
1031 LEFT JOIN civicrm_address ON civicrm_contact.id = civicrm_address.contact_id
1035 $dao = CRM_Core_DAO
::executeQuery($query);
1036 $contacts = array();
1037 while ($dao->fetch()) {
1038 $contacts[] = $dao->toArray();
1041 return civicrm_api3_create_success($contacts, $params, 'Contact', 'get_by_location', $dao);
1046 * Get parameters for getlist function.
1048 * @see _civicrm_api3_generic_getlist_params
1050 * @param array $request
1052 function _civicrm_api3_contact_getlist_params(&$request) {
1053 // get the autocomplete options from settings
1054 $acpref = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1055 CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
,
1056 'contact_autocomplete_options'
1060 // get the option values for contact autocomplete
1061 $acOptions = CRM_Core_OptionGroup
::values('contact_autocomplete_options', FALSE, FALSE, FALSE, NULL, 'name');
1064 foreach ($acpref as $value) {
1065 if ($value && !empty($acOptions[$value])) {
1066 $list[] = $acOptions[$value];
1069 // If we are doing quicksearch by a field other than name, make sure that field is added to results
1070 $field_name = CRM_Utils_String
::munge($request['search_field']);
1071 // Unique name contact_id = id
1072 if ($field_name == 'contact_id') {
1075 // phone_numeric should be phone
1076 $searchField = str_replace('_numeric', '', $field_name);
1077 if (!in_array($searchField, $list)) {
1078 $list[] = $searchField;
1080 $request['description_field'] = $list;
1081 $list[] = 'contact_type';
1082 $request['params']['return'] = array_unique(array_merge($list, $request['extra']));
1083 $request['params']['options']['sort'] = 'sort_name';
1084 // Contact api doesn't support array(LIKE => 'foo') syntax
1085 if (!empty($request['input'])) {
1086 $request['params'][$request['search_field']] = $request['input'];
1091 * Get output for getlist function.
1093 * @see _civicrm_api3_generic_getlist_output
1095 * @param array $result
1096 * @param array $request
1100 function _civicrm_api3_contact_getlist_output($result, $request) {
1102 if (!empty($result['values'])) {
1103 $addressFields = array_intersect(array(
1109 $request['params']['return']);
1110 foreach ($result['values'] as $row) {
1112 'id' => $row[$request['id_field']],
1113 'label' => $row[$request['label_field']],
1114 'description' => array(),
1116 foreach ($request['description_field'] as $item) {
1117 if (!strpos($item, '_name') && !in_array($item, $addressFields) && !empty($row[$item])) {
1118 $data['description'][] = $row[$item];
1122 foreach ($addressFields as $item) {
1123 if (!empty($row[$item])) {
1124 $address[] = $row[$item];
1128 $data['description'][] = implode(' ', $address);
1130 if (!empty($request['image_field'])) {
1131 $data['image'] = isset($row[$request['image_field']]) ?
$row[$request['image_field']] : '';
1134 $data['icon_class'] = $row['contact_type'];