3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2015 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
29 * This api exposes CiviCRM contacts.
31 * Contacts are the main entity in CiviCRM and this api is more robust than most.
32 * - Get action allows all params supported by advanced search.
33 * - Create action allows creating several related entities at once (e.g. email).
34 * - Create allows checking for duplicate contacts.
35 * Use getfields to list the full range of parameters and options supported by each action.
37 * @package CiviCRM_APIv3
41 * Create or update a Contact.
43 * @param array $params
46 * @throws API_Exception
51 function civicrm_api3_contact_create($params) {
53 $contactID = CRM_Utils_Array
::value('contact_id', $params, CRM_Utils_Array
::value('id', $params));
54 $dupeCheck = CRM_Utils_Array
::value('dupe_check', $params, FALSE);
55 $values = _civicrm_api3_contact_check_params($params, $dupeCheck);
61 // If we get here, we're ready to create a new contact
62 if (($email = CRM_Utils_Array
::value('email', $params)) && !is_array($params['email'])) {
63 $defLocType = CRM_Core_BAO_LocationType
::getDefault();
64 $params['email'] = array(
68 'location_type_id' => ($defLocType->id
) ?
$defLocType->id
: 1,
74 if (!empty($params['home_url'])) {
75 $websiteTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Website', 'website_type_id');
76 $params['website'] = array(
78 'website_type_id' => key($websiteTypes),
79 'url' => $params['home_url'],
84 _civicrm_api3_greeting_format_params($params);
88 if (empty($params['contact_type']) && $contactID) {
89 $params['contact_type'] = CRM_Contact_BAO_Contact
::getContactType($contactID);
92 if (!isset($params['contact_sub_type']) && $contactID) {
93 $params['contact_sub_type'] = CRM_Contact_BAO_Contact
::getContactSubType($contactID);
96 _civicrm_api3_custom_format_params($params, $values, $params['contact_type'], $contactID);
98 $params = array_merge($params, $values);
99 //@todo we should just call basic_create here - but need to make contact:create accept 'id' on the bao
100 $contact = _civicrm_api3_contact_update($params, $contactID);
102 if (is_a($contact, 'CRM_Core_Error')) {
103 throw new API_Exception($contact->_errors
[0]['message']);
107 _civicrm_api3_object_to_array_unique_fields($contact, $values[$contact->id
]);
110 return civicrm_api3_create_success($values, $params, 'Contact', 'create');
114 * Adjust Metadata for Create action.
116 * @param array $params
117 * Array of parameters determined by getfields.
119 function _civicrm_api3_contact_create_spec(&$params) {
120 $params['contact_type']['api.required'] = 1;
121 $params['id']['api.aliases'] = array('contact_id');
122 $params['current_employer'] = array(
123 'title' => 'Current Employer',
124 'description' => 'Name of Current Employer',
125 'type' => CRM_Utils_Type
::T_STRING
,
127 $params['dupe_check'] = array(
128 'title' => 'Check for Duplicates',
129 'description' => 'Throw error if contact create matches dedupe rule',
130 'type' => CRM_Utils_Type
::T_BOOLEAN
,
132 $params['prefix_id']['api.aliases'] = array('individual_prefix', 'individual_prefix_id');
133 $params['suffix_id']['api.aliases'] = array('individual_suffix', 'individual_suffix_id');
134 $params['gender_id']['api.aliases'] = array('gender');
138 * Retrieve one or more contacts, given a set of search params.
140 * @param array $params
145 function civicrm_api3_contact_get($params) {
147 _civicrm_api3_contact_get_supportanomalies($params, $options);
148 $contacts = _civicrm_api3_get_using_query_object('Contact', $params, $options);
149 return civicrm_api3_create_success($contacts, $params, 'Contact');
153 * Get number of contacts matching the supplied criteria.
155 * @param array $params
159 function civicrm_api3_contact_getcount($params) {
161 _civicrm_api3_contact_get_supportanomalies($params, $options);
162 $count = _civicrm_api3_get_using_query_object('Contact', $params, $options, 1);
167 * Adjust Metadata for Get action.
169 * @param array $params
170 * Array of parameters determined by getfields.
172 function _civicrm_api3_contact_get_spec(&$params) {
173 $params['contact_is_deleted']['api.default'] = 0;
175 // We declare all these pseudoFields as there are other undocumented fields accessible
176 // via the api - but if check permissions is set we only allow declared fields
177 $params['address_id'] = array(
178 'title' => 'Primary Address ID',
179 'type' => CRM_Utils_Type
::T_INT
,
181 $params['street_address'] = array(
182 'title' => 'Primary Address Street Address',
183 'type' => CRM_Utils_Type
::T_STRING
,
185 $params['supplemental_address_1'] = array(
186 'title' => 'Primary Address Supplemental Address 1',
187 'type' => CRM_Utils_Type
::T_STRING
,
189 $params['supplemental_address_2'] = array(
190 'title' => 'Primary Address Supplemental Address 2',
191 'type' => CRM_Utils_Type
::T_STRING
,
193 $params['current_employer'] = array(
194 'title' => 'Current Employer',
195 'type' => CRM_Utils_Type
::T_STRING
,
197 $params['city'] = array(
198 'title' => 'Primary Address City',
199 'type' => CRM_Utils_Type
::T_STRING
,
201 $params['postal_code_suffix'] = array(
202 'title' => 'Primary Address Post Code Suffix',
203 'type' => CRM_Utils_Type
::T_STRING
,
205 $params['postal_code'] = array(
206 'title' => 'Primary Address Post Code',
207 'type' => CRM_Utils_Type
::T_STRING
,
209 $params['geo_code_1'] = array(
210 'title' => 'Primary Address Latitude',
211 'type' => CRM_Utils_Type
::T_STRING
,
213 $params['geo_code_2'] = array(
214 'title' => 'Primary Address Longitude',
215 'type' => CRM_Utils_Type
::T_STRING
,
217 $params['state_province_id'] = array(
218 'title' => 'Primary Address State Province ID',
219 'type' => CRM_Utils_Type
::T_INT
,
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 $options['input_params']['group'] = $groups;
345 * Delete a Contact with given contact_id.
347 * @param array $params
348 * input parameters per getfields
353 function civicrm_api3_contact_delete($params) {
355 $contactID = CRM_Utils_Array
::value('id', $params);
357 $session = CRM_Core_Session
::singleton();
358 if ($contactID == $session->get('userID')) {
359 return civicrm_api3_create_error('This contact record is linked to the currently logged in user account - and cannot be deleted.');
361 $restore = !empty($params['restore']) ?
$params['restore'] : FALSE;
362 $skipUndelete = !empty($params['skip_undelete']) ?
$params['skip_undelete'] : FALSE;
365 // restrict permanent delete if a contact has financial trxn associated with it
367 if ($skipUndelete && CRM_Financial_BAO_FinancialItem
::checkContactPresent(array($contactID), $error)) {
368 return civicrm_api3_create_error($error['_qf_default']);
370 if (CRM_Contact_BAO_Contact
::deleteContact($contactID, $restore, $skipUndelete)) {
371 return civicrm_api3_create_success();
374 return civicrm_api3_create_error('Could not delete contact');
380 * Check parameters passed in.
382 * This function is on it's way out.
384 * @param array $params
385 * @param bool $dupeCheck
388 * @throws API_Exception
389 * @throws CiviCRM_API3_Exception
391 function _civicrm_api3_contact_check_params(&$params, $dupeCheck) {
393 switch (strtolower(CRM_Utils_Array
::value('contact_type', $params))) {
395 civicrm_api3_verify_mandatory($params, NULL, array('household_name'));
399 civicrm_api3_verify_mandatory($params, NULL, array('organization_name'));
403 civicrm_api3_verify_one_mandatory($params, NULL, array(
413 // Fixme: This really needs to be handled at a lower level. @See CRM-13123
414 if (isset($params['preferred_communication_method'])) {
415 $params['preferred_communication_method'] = CRM_Utils_Array
::implodePadded($params['preferred_communication_method']);
418 if (!empty($params['contact_sub_type']) && !empty($params['contact_type'])) {
419 if (!(CRM_Contact_BAO_ContactType
::isExtendsContactType($params['contact_sub_type'], $params['contact_type']))) {
420 throw new API_Exception("Invalid or Mismatched Contact Subtype: " . implode(', ', (array) $params['contact_sub_type']));
425 // check for record already existing
426 $dedupeParams = CRM_Dedupe_Finder
::formatParams($params, $params['contact_type']);
429 // setting 'check_permission' here means that the dedupe checking will be carried out even if the
430 // person does not have permission to carry out de-dupes
431 // this is similar to the front end form
432 if (isset($params['check_permission'])) {
433 $dedupeParams['check_permission'] = $params['check_permission'];
436 $ids = CRM_Dedupe_Finder
::dupesByParams($dedupeParams, $params['contact_type'], 'Unsupervised', array());
438 if (count($ids) > 0) {
439 throw new API_Exception("Found matching contacts: " . implode(',', $ids), "duplicate", array("ids" => $ids));
443 // The BAO no longer supports the legacy param "current_employer" so here is a shim for api backward-compatability
444 if (!empty($params['current_employer'])) {
445 $organizationParams = array(
446 'organization_name' => $params['current_employer'],
449 $dedupParams = CRM_Dedupe_Finder
::formatParams($organizationParams, 'Organization');
451 $dedupParams['check_permission'] = FALSE;
452 $dupeIds = CRM_Dedupe_Finder
::dupesByParams($dedupParams, 'Organization', 'Supervised');
454 // check for mismatch employer name and id
455 if (!empty($params['employer_id']) && !in_array($params['employer_id'], $dupeIds)) {
456 throw new API_Exception('Employer name and Employer id Mismatch');
459 // show error if multiple organisation with same name exist
460 if (empty($params['employer_id']) && (count($dupeIds) > 1)) {
461 throw new API_Exception('Found more than one Organisation with same Name.');
465 $params['employer_id'] = $dupeIds[0];
468 $result = civicrm_api3('Contact', 'create', array(
469 'organization_name' => $params['current_employer'],
470 'contact_type' => 'Organization',
472 $params['employer_id'] = $result['id'];
480 * Helper function for Contact create.
482 * @param array $params
483 * (reference ) an assoc array of name/value pairs.
484 * @param int $contactID
485 * If present the contact with that ID is updated.
487 * @return CRM_Contact_BAO_Contact|CRM_Core_Error
489 function _civicrm_api3_contact_update($params, $contactID = NULL) {
490 //@todo - doesn't contact create support 'id' which is already set- check & remove
492 $params['contact_id'] = $contactID;
495 return CRM_Contact_BAO_Contact
::create($params);
499 * Validate the addressee or email or postal greetings.
501 * @param array $params
502 * Array per getfields metadata.
504 * @throws API_Exception
506 function _civicrm_api3_greeting_format_params($params) {
507 $greetingParams = array('', '_id', '_custom');
508 foreach (array('email', 'postal', 'addressee') as $key) {
509 $greeting = '_greeting';
510 if ($key == 'addressee') {
514 $formatParams = FALSE;
515 // Unset display value from params.
516 if (isset($params["{$key}{$greeting}_display"])) {
517 unset($params["{$key}{$greeting}_display"]);
520 // check if greetings are present in present
521 foreach ($greetingParams as $greetingValues) {
522 if (array_key_exists("{$key}{$greeting}{$greetingValues}", $params)) {
523 $formatParams = TRUE;
528 if (!$formatParams) {
534 'contact_type' => $params['contact_type'],
535 'greeting_type' => "{$key}{$greeting}",
538 $greetings = CRM_Core_PseudoConstant
::greeting($filter);
539 $greetingId = CRM_Utils_Array
::value("{$key}{$greeting}_id", $params);
540 $greetingVal = CRM_Utils_Array
::value("{$key}{$greeting}", $params);
541 $customGreeting = CRM_Utils_Array
::value("{$key}{$greeting}_custom", $params);
543 if (!$greetingId && $greetingVal) {
544 $params["{$key}{$greeting}_id"] = CRM_Utils_Array
::key($params["{$key}{$greeting}"], $greetings);
547 if ($customGreeting && $greetingId &&
548 ($greetingId != array_search('Customized', $greetings))
550 throw new API_Exception(ts('Provide either %1 greeting id and/or %1 greeting or custom %1 greeting',
555 if ($greetingVal && $greetingId &&
556 ($greetingId != CRM_Utils_Array
::key($greetingVal, $greetings))
558 throw new API_Exception(ts('Mismatch in %1 greeting id and %1 greeting',
565 if (!array_key_exists($greetingId, $greetings)) {
566 throw new API_Exception(ts('Invalid %1 greeting Id', array(1 => $key)));
569 if (!$customGreeting && ($greetingId == array_search('Customized', $greetings))) {
570 throw new API_Exception(ts('Please provide a custom value for %1 greeting',
575 elseif ($greetingVal) {
577 if (!in_array($greetingVal, $greetings)) {
578 throw new API_Exception(ts('Invalid %1 greeting', array(1 => $key)));
581 $greetingId = CRM_Utils_Array
::key($greetingVal, $greetings);
584 if ($customGreeting) {
585 $greetingId = CRM_Utils_Array
::key('Customized', $greetings);
588 $customValue = isset($params['contact_id']) ? CRM_Core_DAO
::getFieldValue(
589 'CRM_Contact_DAO_Contact',
590 $params['contact_id'],
591 "{$key}{$greeting}_custom"
594 if (array_key_exists("{$key}{$greeting}_id", $params) && empty($params["{$key}{$greeting}_id"])) {
597 elseif (array_key_exists("{$key}{$greeting}", $params) && empty($params["{$key}{$greeting}"])) {
600 elseif ($customValue && array_key_exists("{$key}{$greeting}_custom", $params)
601 && empty($params["{$key}{$greeting}_custom"])
606 $params["{$key}{$greeting}_id"] = $greetingId;
608 if (!$customValue && !$customGreeting && array_key_exists("{$key}{$greeting}_custom", $params)) {
609 unset($params["{$key}{$greeting}_custom"]);
613 $params["{$key}{$greeting}_id"] = '';
614 $params["{$key}{$greeting}_custom"] = '';
617 if (isset($params["{$key}{$greeting}"])) {
618 unset($params["{$key}{$greeting}"]);
624 * Adjust Metadata for Get action.
626 * @param array $params
627 * Array of parameters determined by getfields.
629 function _civicrm_api3_contact_getquick_spec(&$params) {
630 $params['name']['api.required'] = TRUE;
631 $params['name']['title'] = ts('String to search on');
632 $params['name']['type'] = CRM_Utils_Type
::T_STRING
;
633 $params['field']['type'] = CRM_Utils_Type
::T_STRING
;
634 $params['field']['title'] = ts('Field to search on');
635 $params['field']['options'] = array(
639 'external_identifier',
649 $params['table_name']['type'] = CRM_Utils_Type
::T_STRING
;
650 $params['table_name']['title'] = ts('Table alias to search on');
651 $params['table_name']['api.default'] = 'cc';
655 * Old Contact quick search api.
659 * @param array $params
662 * @throws \API_Exception
664 function civicrm_api3_contact_getquick($params) {
665 $name = CRM_Utils_Type
::escape(CRM_Utils_Array
::value('name', $params), 'String');
666 $table_name = CRM_Utils_String
::munge($params['table_name']);
667 // get the autocomplete options from settings
668 $acpref = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
669 CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
,
670 'contact_autocomplete_options'
674 // get the option values for contact autocomplete
675 $acOptions = CRM_Core_OptionGroup
::values('contact_autocomplete_options', FALSE, FALSE, FALSE, NULL, 'name');
678 foreach ($acpref as $value) {
679 if ($value && !empty($acOptions[$value])) {
680 $list[$value] = $acOptions[$value];
683 // If we are doing quicksearch by a field other than name, make sure that field is added to results
684 if (!empty($params['field_name'])) {
685 $field_name = CRM_Utils_String
::munge($params['field_name']);
686 // Unique name contact_id = id
687 if ($field_name == 'contact_id') {
690 // phone_numeric should be phone
691 $searchField = str_replace('_numeric', '', $field_name);
692 if (!in_array($searchField, $list)) {
693 $list[] = $searchField;
697 // Set field name to first name for exact match checking.
698 $field_name = 'sort_name';
701 $select = $actualSelectElements = array('sort_name');
704 foreach ($list as $value) {
705 $suffix = substr($value, 0, 2) . substr($value, -1);
707 case 'street_address':
710 $selectText = $value;
715 $actualSelectElements[] = $select[] = ($value == 'address') ?
$selectText : $value;
716 if ($value == 'phone') {
717 $actualSelectElements[] = $select[] = 'phone_ext';
719 $from[$value] = "LEFT JOIN civicrm_{$value} {$suffix} ON ( cc.id = {$suffix}.contact_id AND {$suffix}.is_primary = 1 ) ";
723 case 'state_province':
724 $select[] = "{$suffix}.name as {$value}";
725 $actualSelectElements[] = "{$suffix}.name";
726 if (!in_array('address', $from)) {
727 $from['address'] = 'LEFT JOIN civicrm_address sts ON ( cc.id = sts.contact_id AND sts.is_primary = 1) ';
729 $from[$value] = " LEFT JOIN civicrm_{$value} {$suffix} ON ( sts.{$value}_id = {$suffix}.id ) ";
733 if ($value != 'id') {
735 if (!empty($params['field_name']) && $params['field_name'] == 'value') {
736 $suffix = CRM_Utils_String
::munge(CRM_Utils_Array
::value('table_name', $params, 'cc'));
738 $actualSelectElements[] = $select[] = $suffix . '.' . $value;
744 $config = CRM_Core_Config
::singleton();
746 $select = implode(', ', $select);
747 if (!empty($select)) {
748 $select = ", $select";
750 $actualSelectElements = implode(', ', $actualSelectElements);
751 $selectAliases = $from;
752 unset($selectAliases['address']);
753 $selectAliases = implode(', ', array_keys($selectAliases));
754 if (!empty($selectAliases)) {
755 $selectAliases = ", $selectAliases";
757 $from = implode(' ', $from);
758 $limit = (int) CRM_Utils_Array
::value('limit', $params);
759 $limit = $limit > 0 ?
$limit : Civi
::settings()->get('search_autocomplete_count');
761 // add acl clause here
762 list($aclFrom, $aclWhere) = CRM_Contact_BAO_Contact_Permission
::cacheClause('cc');
765 $where .= " AND $aclWhere ";
768 if (!empty($params['org'])) {
769 $where .= " AND contact_type = \"Organization\"";
771 // CRM-7157, hack: get current employer details when
772 // employee_id is present.
773 $currEmpDetails = array();
774 if (!empty($params['employee_id'])) {
775 if ($currentEmployer = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact',
776 (int) $params['employee_id'],
779 if ($config->includeWildCardInName
) {
780 $strSearch = "%$name%";
783 $strSearch = "$name%";
786 // get current employer details
787 $dao = CRM_Core_DAO
::executeQuery("SELECT cc.id as id, CONCAT_WS( ' :: ', {$actualSelectElements} ) as data, sort_name
788 FROM civicrm_contact cc {$from} WHERE cc.contact_type = \"Organization\" AND cc.id = {$currentEmployer} AND cc.sort_name LIKE '$strSearch'");
790 $currEmpDetails = array(
792 'data' => $dao->data
,
799 if (!empty($params['contact_sub_type'])) {
800 $contactSubType = CRM_Utils_Type
::escape($params['contact_sub_type'], 'String');
801 $where .= " AND cc.contact_sub_type = '{$contactSubType}'";
804 if (!empty($params['contact_type'])) {
805 $contactType = CRM_Utils_Type
::escape($params['contact_type'], 'String');
806 $where .= " AND cc.contact_type LIKE '{$contactType}'";
809 // Set default for current_employer or return contact with particular id
810 if (!empty($params['id'])) {
811 $where .= " AND cc.id = " . (int) $params['id'];
814 if (!empty($params['cid'])) {
815 $where .= " AND cc.id <> " . (int) $params['cid'];
818 // Contact's based of relationhip type
820 if (!empty($params['rel'])) {
821 $relation = explode('_', CRM_Utils_Array
::value('rel', $params));
822 $relType = CRM_Utils_Type
::escape($relation[0], 'Integer');
823 $rel = CRM_Utils_Type
::escape($relation[2], 'String');
826 if ($config->includeWildCardInName
) {
827 $strSearch = "%$name%";
830 $strSearch = "$name%";
832 $includeEmailFrom = $includeNickName = $exactIncludeNickName = '';
833 if ($config->includeNickNameInName
) {
834 $includeNickName = " OR nick_name LIKE '$strSearch'";
835 $exactIncludeNickName = " OR nick_name LIKE '$name'";
839 if (!empty($params['field_name']) && !empty($params['table_name'])) {
840 $whereClause = " WHERE ( $table_name.$field_name LIKE '$strSearch') {$where}";
841 $exactWhereClause = " WHERE ( $table_name.$field_name = '$name') {$where}";
842 // Search by id should be exact
843 if ($field_name == 'id' ||
$field_name == 'external_identifier') {
844 $whereClause = $exactWhereClause;
848 $whereClause = " WHERE ( sort_name LIKE '$strSearch' $includeNickName ) {$where} ";
849 $exactWhereClause = " WHERE ( sort_name LIKE '$name' $exactIncludeNickName ) {$where} ";
850 if ($config->includeEmailInName
) {
851 if (!in_array('email', $list)) {
852 $includeEmailFrom = "LEFT JOIN civicrm_email eml ON ( cc.id = eml.contact_id AND eml.is_primary = 1 )";
854 $emailWhere = " WHERE email LIKE '$strSearch'";
858 $additionalFrom = '';
861 INNER JOIN civicrm_relationship_type r ON (
863 AND ( cc.contact_type = r.contact_type_{$rel} OR r.contact_type_{$rel} IS NULL )
864 AND ( cc.contact_sub_type = r.contact_sub_type_{$rel} OR r.contact_sub_type_{$rel} IS NULL )
868 // check if only CMS users are requested
869 if (!empty($params['cmsuser'])) {
871 INNER JOIN civicrm_uf_match um ON (um.contact_id=cc.id)
875 $orderByInner = $orderByOuter = "ORDER BY exactFirst";
876 if ($config->includeOrderByClause
) {
877 $orderByInner = "ORDER BY exactFirst, sort_name";
878 $orderByOuter .= ", sort_name";
883 SELECT DISTINCT(id), data, sort_name {$selectAliases}, exactFirst
885 ( SELECT IF($table_name.$field_name = '{$name}', 0, 1) as exactFirst, cc.id as id, CONCAT_WS( ' :: ',
886 {$actualSelectElements} )
889 FROM civicrm_contact cc {$from}
897 if (!empty($emailWhere)) {
900 SELECT IF($table_name.$field_name = '{$name}', 0, 1) as exactFirst, cc.id as id, CONCAT_WS( ' :: ',
901 {$actualSelectElements} )
904 FROM civicrm_contact cc {$from}
906 {$additionalFrom} {$includeEmailFrom}
907 {$emailWhere} AND cc.is_deleted = 0 " . ($aclWhere ?
" AND $aclWhere " : '') . "
918 // send query to hook to be modified if needed
919 CRM_Utils_Hook
::contactListQuery($query,
921 empty($params['context']) ?
NULL : CRM_Utils_Type
::escape($params['context'], 'String'),
922 empty($params['id']) ?
NULL : $params['id']
925 $dao = CRM_Core_DAO
::executeQuery($query);
927 $contactList = array();
928 $listCurrentEmployer = TRUE;
929 while ($dao->fetch()) {
930 $t = array('id' => $dao->id
);
931 foreach ($as as $k) {
932 $t[$k] = isset($dao->$k) ?
$dao->$k : '';
934 $t['data'] = $dao->data
;
936 if (!empty($params['org']) &&
937 !empty($currEmpDetails) &&
938 $dao->id
== $currEmpDetails['id']
940 $listCurrentEmployer = FALSE;
944 //return organization name if doesn't exist in db
945 if (empty($contactList)) {
946 if (!empty($params['org'])) {
947 if ($listCurrentEmployer && !empty($currEmpDetails)) {
948 $contactList = array(
950 'data' => $currEmpDetails['data'],
951 'id' => $currEmpDetails['id'],
956 $contactList = array(
966 return civicrm_api3_create_success($contactList, $params, 'Contact', 'getquick');
970 * Declare deprecated api functions.
972 * @deprecated api notice
974 * Array of deprecated actions
976 function _civicrm_api3_contact_deprecation() {
977 return array('getquick' => 'The "getquick" action is deprecated in favor of "getlist".');
981 * Merges given pair of duplicate contacts.
983 * @param array $params
984 * Allowed array keys are:
985 * -int main_id: main contact id with whom merge has to happen
986 * -int other_id: duplicate contact which would be deleted after merge operation
987 * -string mode: "safe" skips the merge if there are no conflicts. Does a force merge otherwise.
988 * -boolean auto_flip: whether to let api decide which contact to retain and which to delete.
993 function civicrm_api3_contact_merge($params) {
994 $mode = CRM_Utils_Array
::value('mode', $params, 'safe');
995 $autoFlip = CRM_Utils_Array
::value('auto_flip', $params, TRUE);
997 $dupePairs = array(array(
998 'srcID' => CRM_Utils_Array
::value('main_id', $params),
999 'dstID' => CRM_Utils_Array
::value('other_id', $params),
1001 $result = CRM_Dedupe_Merger
::merge($dupePairs, array(), $mode, $autoFlip);
1003 if ($result['is_error'] == 0) {
1004 return civicrm_api3_create_success();
1007 return civicrm_api3_create_error($result['messages']);
1012 * Adjust metadata for contact_proximity api function.
1014 * @param array $params
1016 function _civicrm_api3_contact_proximity_spec(&$params) {
1017 $params['latitude'] = array(
1018 'title' => 'Latitude',
1019 'api.required' => 1,
1020 'type' => CRM_Utils_Type
::T_STRING
,
1022 $params['longitude'] = array(
1023 'title' => 'Longitude',
1024 'api.required' => 1,
1025 'type' => CRM_Utils_Type
::T_STRING
,
1028 $params['unit'] = array(
1029 'title' => 'Unit of Measurement',
1030 'api.default' => 'meter',
1031 'type' => CRM_Utils_Type
::T_STRING
,
1036 * Get contacts by proximity.
1038 * @param array $params
1043 function civicrm_api3_contact_proximity($params) {
1044 $latitude = CRM_Utils_Array
::value('latitude', $params);
1045 $longitude = CRM_Utils_Array
::value('longitude', $params);
1046 $distance = CRM_Utils_Array
::value('distance', $params);
1048 $unit = CRM_Utils_Array
::value('unit', $params);
1050 // check and ensure that lat/long and distance are floats
1052 !CRM_Utils_Rule
::numeric($latitude) ||
1053 !CRM_Utils_Rule
::numeric($longitude) ||
1054 !CRM_Utils_Rule
::numeric($distance)
1056 throw new Exception(ts('Latitude, Longitude and Distance should exist and be numeric'));
1059 if ($unit == "mile") {
1060 $conversionFactor = 1609.344;
1063 $conversionFactor = 1000;
1065 //Distance in meters
1066 $distance = $distance * $conversionFactor;
1068 $whereClause = CRM_Contact_BAO_ProximityQuery
::where($latitude, $longitude, $distance);
1071 SELECT civicrm_contact.id as contact_id,
1072 civicrm_contact.display_name as display_name
1073 FROM civicrm_contact
1074 LEFT JOIN civicrm_address ON civicrm_contact.id = civicrm_address.contact_id
1078 $dao = CRM_Core_DAO
::executeQuery($query);
1079 $contacts = array();
1080 while ($dao->fetch()) {
1081 $contacts[] = $dao->toArray();
1084 return civicrm_api3_create_success($contacts, $params, 'Contact', 'get_by_location', $dao);
1089 * Get parameters for getlist function.
1091 * @see _civicrm_api3_generic_getlist_params
1093 * @param array $request
1095 function _civicrm_api3_contact_getlist_params(&$request) {
1096 // get the autocomplete options from settings
1097 $acpref = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1098 CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
,
1099 'contact_autocomplete_options'
1103 // get the option values for contact autocomplete
1104 $acOptions = CRM_Core_OptionGroup
::values('contact_autocomplete_options', FALSE, FALSE, FALSE, NULL, 'name');
1107 foreach ($acpref as $value) {
1108 if ($value && !empty($acOptions[$value])) {
1109 $list[] = $acOptions[$value];
1112 // If we are doing quicksearch by a field other than name, make sure that field is added to results
1113 $field_name = CRM_Utils_String
::munge($request['search_field']);
1114 // Unique name contact_id = id
1115 if ($field_name == 'contact_id') {
1118 // phone_numeric should be phone
1119 $searchField = str_replace('_numeric', '', $field_name);
1120 if (!in_array($searchField, $list)) {
1121 $list[] = $searchField;
1123 $request['description_field'] = $list;
1124 $list[] = 'contact_type';
1125 $request['params']['return'] = array_unique(array_merge($list, $request['extra']));
1126 $request['params']['options']['sort'] = 'sort_name';
1127 // Contact api doesn't support array(LIKE => 'foo') syntax
1128 if (!empty($request['input'])) {
1129 $request['params'][$request['search_field']] = $request['input'];
1134 * Get output for getlist function.
1136 * @see _civicrm_api3_generic_getlist_output
1138 * @param array $result
1139 * @param array $request
1143 function _civicrm_api3_contact_getlist_output($result, $request) {
1145 if (!empty($result['values'])) {
1146 $addressFields = array_intersect(array(
1152 $request['params']['return']);
1153 foreach ($result['values'] as $row) {
1155 'id' => $row[$request['id_field']],
1156 'label' => $row[$request['label_field']],
1157 'description' => array(),
1159 foreach ($request['description_field'] as $item) {
1160 if (!strpos($item, '_name') && !in_array($item, $addressFields) && !empty($row[$item])) {
1161 $data['description'][] = $row[$item];
1165 foreach ($addressFields as $item) {
1166 if (!empty($row[$item])) {
1167 $address[] = $row[$item];
1171 $data['description'][] = implode(' ', $address);
1173 if (!empty($request['image_field'])) {
1174 $data['image'] = isset($row[$request['image_field']]) ?
$row[$request['image_field']] : '';
1177 $data['icon_class'] = $row['contact_type'];
1186 * Check for duplicate contacts.
1188 * @param array $params
1189 * Params per getfields metadata.
1192 * API formatted array
1194 function civicrm_api3_contact_duplicatecheck($params) {
1195 $dedupeParams = CRM_Dedupe_Finder
::formatParams($params['match'], $params['match']['contact_type']);
1198 // setting 'check_permission' here means that the dedupe checking will be carried out even if the
1199 // person does not have permission to carry out de-dupes
1200 // this is similar to the front end form
1201 if (isset($params['check_permission'])) {
1202 $dedupeParams['check_permission'] = $params['check_permission'];
1205 $dupes = CRM_Dedupe_Finder
::dupesByParams($dedupeParams, $params['match']['contact_type'], 'Unsupervised', array(), CRM_Utils_Array
::value('dedupe_rule_id', $params));
1206 $values = empty($dupes) ?
array() : array_fill_keys($dupes, array());
1207 return civicrm_api3_create_success($values, $params, 'Contact', 'duplicatecheck');
1211 * Declare metadata for contact dedupe function.
1215 function _civicrm_api3_contact_duplicatecheck_spec(&$params) {
1216 $params['dedupe_rule_id'] = array(
1217 'title' => 'Dedupe Rule ID (optional)',
1218 'description' => 'This will default to the built in unsupervised rule',
1219 'type' => CRM_Utils_Type
::T_INT
,
1221 // @todo declare 'match' parameter. We don't have a standard for type = array yet.