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',
131 $params['prefix_id']['api.aliases'] = array('individual_prefix', 'individual_prefix_id');
132 $params['suffix_id']['api.aliases'] = array('individual_suffix', 'individual_suffix_id');
136 * Retrieve one or more contacts, given a set of search params.
138 * @param array $params
143 function civicrm_api3_contact_get($params) {
145 _civicrm_api3_contact_get_supportanomalies($params, $options);
146 $contacts = _civicrm_api3_get_using_query_object('Contact', $params, $options);
147 return civicrm_api3_create_success($contacts, $params, 'Contact');
151 * Get number of contacts matching the supplied criteria.
153 * @param array $params
157 function civicrm_api3_contact_getcount($params) {
159 _civicrm_api3_contact_get_supportanomalies($params, $options);
160 $count = _civicrm_api3_get_using_query_object('Contact', $params, $options, 1);
165 * Adjust Metadata for Get action.
167 * @param array $params
168 * Array of parameters determined by getfields.
170 function _civicrm_api3_contact_get_spec(&$params) {
171 $params['contact_is_deleted']['api.default'] = 0;
173 // We declare all these pseudoFields as there are other undocumented fields accessible
174 // via the api - but if check permissions is set we only allow declared fields
175 $params['address_id']['title'] = 'Primary Address ID';
176 $params['street_address']['title'] = 'Primary Address Street Address';
177 $params['supplemental_address_1']['title'] = 'Primary Address Supplemental Address 1';
178 $params['supplemental_address_2']['title'] = 'Primary Address Supplemental Address 2';
179 $params['current_employer']['title'] = 'Current Employer';
180 $params['city']['title'] = 'Primary Address City';
181 $params['postal_code_suffix']['title'] = 'Primary Address Post Code Suffix';
182 $params['postal_code']['title'] = 'Primary Address Post Code';
183 $params['geo_code_1']['title'] = 'Primary Address Latitude';
184 $params['geo_code_2']['title'] = 'Primary Address Longitude';
185 $params['state_province_id']['title'] = 'Primary Address State Province ID';
186 $params['state_province_name']['title'] = 'Primary Address State Province Name';
187 $params['state_province']['title'] = 'Primary Address State Province';
188 $params['country_id']['title'] = 'Primary Address Country ID';
189 $params['country']['title'] = 'Primary Address country';
190 $params['worldregion_id']['title'] = 'Primary Address World Region ID';
191 $params['worldregion']['title'] = 'Primary Address World Region';
192 $params['phone_id']['title'] = 'Primary Phone ID';
193 $params['phone']['title'] = 'Primary Phone';
194 $params['phone_type_id']['title'] = 'Primary Phone Type ID';
195 $params['provider_id']['title'] = 'Primary Phone Provider ID';
196 $params['email_id']['title'] = 'Primary Email ID';
197 $params['email']['title'] = 'Primary Email';
198 $params['gender_id']['title'] = 'Gender ID';
199 $params['gender']['title'] = 'Gender';
200 $params['on_hold']['title'] = 'Primary Email On Hold';
201 $params['im']['title'] = 'Primary Instant Messenger';
202 $params['im_id']['title'] = 'Primary Instant Messenger ID';
203 $params['group_id']['title'] = 'Group Memberships (filter)';
204 $params['group']['title'] = 'Group Memberships (filter, array)';
205 $params['tag']['title'] = 'Assigned tags (filter, array)';
206 $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'));
207 $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'));
208 $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'));
209 $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'));
213 * Support for historical oddities.
215 * We are supporting 'showAll' = 'all', 'trash' or 'active' for Contact get
217 * - hopefully some day we'll come up with a std syntax for the 3-way-boolean of
220 * We also support 'filter_group_id' & 'filter.group_id'
222 * @param array $params
223 * As passed into api get or getcount function.
224 * @param array $options
225 * Array of options (so we can modify the filter).
227 function _civicrm_api3_contact_get_supportanomalies(&$params, &$options) {
228 if (isset($params['showAll'])) {
229 if (strtolower($params['showAll']) == "active") {
230 $params['contact_is_deleted'] = 0;
232 if (strtolower($params['showAll']) == "trash") {
233 $params['contact_is_deleted'] = 1;
235 if (strtolower($params['showAll']) == "all" && isset($params['contact_is_deleted'])) {
236 unset($params['contact_is_deleted']);
239 // support for group filters
240 if (array_key_exists('filter_group_id', $params)) {
241 $params['filter.group_id'] = $params['filter_group_id'];
242 unset($params['filter_group_id']);
244 // filter.group_id works both for 1,2,3 and array (1,2,3)
245 if (array_key_exists('filter.group_id', $params)) {
246 if (is_array($params['filter.group_id'])) {
247 $groups = $params['filter.group_id'];
250 $groups = explode(',', $params['filter.group_id']);
252 unset($params['filter.group_id']);
253 $groups = array_flip($groups);
254 $groups[key($groups)] = 1;
255 $options['input_params']['group'] = $groups;
260 * Delete a Contact with given contact_id.
262 * @param array $params
263 * input parameters per getfields
268 function civicrm_api3_contact_delete($params) {
270 $contactID = CRM_Utils_Array
::value('id', $params);
272 $session = CRM_Core_Session
::singleton();
273 if ($contactID == $session->get('userID')) {
274 return civicrm_api3_create_error('This contact record is linked to the currently logged in user account - and cannot be deleted.');
276 $restore = !empty($params['restore']) ?
$params['restore'] : FALSE;
277 $skipUndelete = !empty($params['skip_undelete']) ?
$params['skip_undelete'] : FALSE;
280 // restrict permanent delete if a contact has financial trxn associated with it
282 if ($skipUndelete && CRM_Financial_BAO_FinancialItem
::checkContactPresent(array($contactID), $error)) {
283 return civicrm_api3_create_error($error['_qf_default']);
285 if (CRM_Contact_BAO_Contact
::deleteContact($contactID, $restore, $skipUndelete)) {
286 return civicrm_api3_create_success();
289 return civicrm_api3_create_error('Could not delete contact');
295 * Check parameters passed in.
297 * This function is on it's way out.
299 * @param array $params
300 * @param bool $dupeCheck
303 * @throws API_Exception
304 * @throws CiviCRM_API3_Exception
306 function _civicrm_api3_contact_check_params(&$params, $dupeCheck) {
308 switch (strtolower(CRM_Utils_Array
::value('contact_type', $params))) {
310 civicrm_api3_verify_mandatory($params, NULL, array('household_name'));
314 civicrm_api3_verify_mandatory($params, NULL, array('organization_name'));
318 civicrm_api3_verify_one_mandatory($params, NULL, array(
328 // Fixme: This really needs to be handled at a lower level. @See CRM-13123
329 if (isset($params['preferred_communication_method'])) {
330 $params['preferred_communication_method'] = CRM_Utils_Array
::implodePadded($params['preferred_communication_method']);
333 if (!empty($params['contact_sub_type']) && !empty($params['contact_type'])) {
334 if (!(CRM_Contact_BAO_ContactType
::isExtendsContactType($params['contact_sub_type'], $params['contact_type']))) {
335 throw new API_Exception("Invalid or Mismatched Contact Subtype: " . implode(', ', (array) $params['contact_sub_type']));
340 // check for record already existing
341 $dedupeParams = CRM_Dedupe_Finder
::formatParams($params, $params['contact_type']);
344 // setting 'check_permission' here means that the dedupe checking will be carried out even if the
345 // person does not have permission to carry out de-dupes
346 // this is similar to the front end form
347 if (isset($params['check_permission'])) {
348 $dedupeParams['check_permission'] = $params['check_permission'];
351 $ids = CRM_Dedupe_Finder
::dupesByParams($dedupeParams, $params['contact_type'], 'Unsupervised', array());
353 if (count($ids) > 0) {
354 throw new API_Exception("Found matching contacts: " . implode(',', $ids), "duplicate", array("ids" => $ids));
358 // The BAO no longer supports the legacy param "current_employer" so here is a shim for api backward-compatability
359 if (!empty($params['current_employer'])) {
360 $organizationParams = array(
361 'organization_name' => $params['current_employer'],
364 $dedupParams = CRM_Dedupe_Finder
::formatParams($organizationParams, 'Organization');
366 $dedupParams['check_permission'] = FALSE;
367 $dupeIds = CRM_Dedupe_Finder
::dupesByParams($dedupParams, 'Organization', 'Supervised');
369 // check for mismatch employer name and id
370 if (!empty($params['employer_id']) && !in_array($params['employer_id'], $dupeIds)) {
371 throw new API_Exception('Employer name and Employer id Mismatch');
374 // show error if multiple organisation with same name exist
375 if (empty($params['employer_id']) && (count($dupeIds) > 1)) {
376 throw new API_Exception('Found more than one Organisation with same Name.');
380 $params['employer_id'] = $dupeIds[0];
383 $result = civicrm_api3('Contact', 'create', array(
384 'organization_name' => $params['current_employer'],
385 'contact_type' => 'Organization',
387 $params['employer_id'] = $result['id'];
395 * Helper function for Contact create.
397 * @param array $params
398 * (reference ) an assoc array of name/value pairs.
399 * @param int $contactID
400 * If present the contact with that ID is updated.
402 * @return CRM_Contact_BAO_Contact|CRM_Core_Error
404 function _civicrm_api3_contact_update($params, $contactID = NULL) {
405 //@todo - doesn't contact create support 'id' which is already set- check & remove
407 $params['contact_id'] = $contactID;
410 return CRM_Contact_BAO_Contact
::create($params);
414 * Validate the addressee or email or postal greetings.
416 * @param array $params
417 * Array per getfields metadata.
419 * @throws API_Exception
421 function _civicrm_api3_greeting_format_params($params) {
422 $greetingParams = array('', '_id', '_custom');
423 foreach (array('email', 'postal', 'addressee') as $key) {
424 $greeting = '_greeting';
425 if ($key == 'addressee') {
429 $formatParams = FALSE;
430 // Unset display value from params.
431 if (isset($params["{$key}{$greeting}_display"])) {
432 unset($params["{$key}{$greeting}_display"]);
435 // check if greetings are present in present
436 foreach ($greetingParams as $greetingValues) {
437 if (array_key_exists("{$key}{$greeting}{$greetingValues}", $params)) {
438 $formatParams = TRUE;
443 if (!$formatParams) {
449 'contact_type' => $params['contact_type'],
450 'greeting_type' => "{$key}{$greeting}",
453 $greetings = CRM_Core_PseudoConstant
::greeting($filter);
454 $greetingId = CRM_Utils_Array
::value("{$key}{$greeting}_id", $params);
455 $greetingVal = CRM_Utils_Array
::value("{$key}{$greeting}", $params);
456 $customGreeting = CRM_Utils_Array
::value("{$key}{$greeting}_custom", $params);
458 if (!$greetingId && $greetingVal) {
459 $params["{$key}{$greeting}_id"] = CRM_Utils_Array
::key($params["{$key}{$greeting}"], $greetings);
462 if ($customGreeting && $greetingId &&
463 ($greetingId != array_search('Customized', $greetings))
465 throw new API_Exception(ts('Provide either %1 greeting id and/or %1 greeting or custom %1 greeting',
470 if ($greetingVal && $greetingId &&
471 ($greetingId != CRM_Utils_Array
::key($greetingVal, $greetings))
473 throw new API_Exception(ts('Mismatch in %1 greeting id and %1 greeting',
480 if (!array_key_exists($greetingId, $greetings)) {
481 throw new API_Exception(ts('Invalid %1 greeting Id', array(1 => $key)));
484 if (!$customGreeting && ($greetingId == array_search('Customized', $greetings))) {
485 throw new API_Exception(ts('Please provide a custom value for %1 greeting',
490 elseif ($greetingVal) {
492 if (!in_array($greetingVal, $greetings)) {
493 throw new API_Exception(ts('Invalid %1 greeting', array(1 => $key)));
496 $greetingId = CRM_Utils_Array
::key($greetingVal, $greetings);
499 if ($customGreeting) {
500 $greetingId = CRM_Utils_Array
::key('Customized', $greetings);
503 $customValue = isset($params['contact_id']) ? CRM_Core_DAO
::getFieldValue(
504 'CRM_Contact_DAO_Contact',
505 $params['contact_id'],
506 "{$key}{$greeting}_custom"
509 if (array_key_exists("{$key}{$greeting}_id", $params) && empty($params["{$key}{$greeting}_id"])) {
512 elseif (array_key_exists("{$key}{$greeting}", $params) && empty($params["{$key}{$greeting}"])) {
515 elseif ($customValue && array_key_exists("{$key}{$greeting}_custom", $params)
516 && empty($params["{$key}{$greeting}_custom"])
521 $params["{$key}{$greeting}_id"] = $greetingId;
523 if (!$customValue && !$customGreeting && array_key_exists("{$key}{$greeting}_custom", $params)) {
524 unset($params["{$key}{$greeting}_custom"]);
528 $params["{$key}{$greeting}_id"] = '';
529 $params["{$key}{$greeting}_custom"] = '';
532 if (isset($params["{$key}{$greeting}"])) {
533 unset($params["{$key}{$greeting}"]);
539 * Old Contact quick search api.
543 * @param array $params
546 * @throws \API_Exception
548 function civicrm_api3_contact_getquick($params) {
549 civicrm_api3_verify_mandatory($params, NULL, array('name'));
550 $name = CRM_Utils_Type
::escape(CRM_Utils_Array
::value('name', $params), 'String');
552 // get the autocomplete options from settings
553 $acpref = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
554 CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
,
555 'contact_autocomplete_options'
559 // get the option values for contact autocomplete
560 $acOptions = CRM_Core_OptionGroup
::values('contact_autocomplete_options', FALSE, FALSE, FALSE, NULL, 'name');
563 foreach ($acpref as $value) {
564 if ($value && !empty($acOptions[$value])) {
565 $list[$value] = $acOptions[$value];
568 // If we are doing quicksearch by a field other than name, make sure that field is added to results
569 if (!empty($params['field_name'])) {
570 $field_name = CRM_Utils_String
::munge($params['field_name']);
571 // Unique name contact_id = id
572 if ($field_name == 'contact_id') {
575 // phone_numeric should be phone
576 $searchField = str_replace('_numeric', '', $field_name);
577 if (!in_array($searchField, $list)) {
578 $list[] = $searchField;
582 $select = $actualSelectElements = array('sort_name');
585 foreach ($list as $value) {
586 $suffix = substr($value, 0, 2) . substr($value, -1);
588 case 'street_address':
591 $selectText = $value;
596 $actualSelectElements[] = $select[] = ($value == 'address') ?
$selectText : $value;
597 if ($value == 'phone') {
598 $actualSelectElements[] = $select[] = 'phone_ext';
600 $from[$value] = "LEFT JOIN civicrm_{$value} {$suffix} ON ( cc.id = {$suffix}.contact_id AND {$suffix}.is_primary = 1 ) ";
604 case 'state_province':
605 $select[] = "{$suffix}.name as {$value}";
606 $actualSelectElements[] = "{$suffix}.name";
607 if (!in_array('address', $from)) {
608 $from['address'] = 'LEFT JOIN civicrm_address sts ON ( cc.id = sts.contact_id AND sts.is_primary = 1) ';
610 $from[$value] = " LEFT JOIN civicrm_{$value} {$suffix} ON ( sts.{$value}_id = {$suffix}.id ) ";
614 if ($value != 'id') {
616 if (!empty($params['field_name']) && $params['field_name'] == 'value') {
617 $suffix = CRM_Utils_String
::munge(CRM_Utils_Array
::value('table_name', $params, 'cc'));
619 $actualSelectElements[] = $select[] = $suffix . '.' . $value;
625 $config = CRM_Core_Config
::singleton();
627 $select = implode(', ', $select);
628 if (!empty($select)) {
629 $select = ", $select";
631 $actualSelectElements = implode(', ', $actualSelectElements);
632 $selectAliases = $from;
633 unset($selectAliases['address']);
634 $selectAliases = implode(', ', array_keys($selectAliases));
635 if (!empty($selectAliases)) {
636 $selectAliases = ", $selectAliases";
638 $from = implode(' ', $from);
639 $limit = (int) CRM_Utils_Array
::value('limit', $params);
640 $limit = $limit > 0 ?
$limit : 10;
642 // add acl clause here
643 list($aclFrom, $aclWhere) = CRM_Contact_BAO_Contact_Permission
::cacheClause('cc');
646 $where .= " AND $aclWhere ";
649 if (!empty($params['org'])) {
650 $where .= " AND contact_type = \"Organization\"";
652 // CRM-7157, hack: get current employer details when
653 // employee_id is present.
654 $currEmpDetails = array();
655 if (!empty($params['employee_id'])) {
656 if ($currentEmployer = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact',
657 (int) $params['employee_id'],
660 if ($config->includeWildCardInName
) {
661 $strSearch = "%$name%";
664 $strSearch = "$name%";
667 // get current employer details
668 $dao = CRM_Core_DAO
::executeQuery("SELECT cc.id as id, CONCAT_WS( ' :: ', {$actualSelectElements} ) as data, sort_name
669 FROM civicrm_contact cc {$from} WHERE cc.contact_type = \"Organization\" AND cc.id = {$currentEmployer} AND cc.sort_name LIKE '$strSearch'");
671 $currEmpDetails = array(
673 'data' => $dao->data
,
680 if (!empty($params['contact_sub_type'])) {
681 $contactSubType = CRM_Utils_Type
::escape($params['contact_sub_type'], 'String');
682 $where .= " AND cc.contact_sub_type = '{$contactSubType}'";
685 if (!empty($params['contact_type'])) {
686 $contactType = CRM_Utils_Type
::escape($params['contact_type'], 'String');
687 $where .= " AND cc.contact_type LIKE '{$contactType}'";
690 // Set default for current_employer or return contact with particular id
691 if (!empty($params['id'])) {
692 $where .= " AND cc.id = " . (int) $params['id'];
695 if (!empty($params['cid'])) {
696 $where .= " AND cc.id <> " . (int) $params['cid'];
699 // Contact's based of relationhip type
701 if (!empty($params['rel'])) {
702 $relation = explode('_', CRM_Utils_Array
::value('rel', $params));
703 $relType = CRM_Utils_Type
::escape($relation[0], 'Integer');
704 $rel = CRM_Utils_Type
::escape($relation[2], 'String');
707 if ($config->includeWildCardInName
) {
708 $strSearch = "%$name%";
711 $strSearch = "$name%";
713 $includeEmailFrom = $includeNickName = $exactIncludeNickName = '';
714 if ($config->includeNickNameInName
) {
715 $includeNickName = " OR nick_name LIKE '$strSearch'";
716 $exactIncludeNickName = " OR nick_name LIKE '$name'";
720 if (!empty($params['field_name']) && !empty($params['table_name'])) {
721 $table_name = CRM_Utils_String
::munge($params['table_name']);
722 $whereClause = " WHERE ( $table_name.$field_name LIKE '$strSearch') {$where}";
723 $exactWhereClause = " WHERE ( $table_name.$field_name = '$name') {$where}";
724 // Search by id should be exact
725 if ($field_name == 'id' ||
$field_name == 'external_identifier') {
726 $whereClause = $exactWhereClause;
730 if ($config->includeEmailInName
) {
731 if (!in_array('email', $list)) {
732 $includeEmailFrom = "LEFT JOIN civicrm_email eml ON ( cc.id = eml.contact_id AND eml.is_primary = 1 )";
734 $whereClause = " WHERE ( email LIKE '$strSearch' OR sort_name LIKE '$strSearch' $includeNickName ) {$where} ";
735 $exactWhereClause = " WHERE ( email LIKE '$name' OR sort_name LIKE '$name' $exactIncludeNickName ) {$where} ";
738 $whereClause = " WHERE ( sort_name LIKE '$strSearch' $includeNickName ) {$where} ";
739 $exactWhereClause = " WHERE ( sort_name LIKE '$name' $exactIncludeNickName ) {$where} ";
743 $additionalFrom = '';
746 INNER JOIN civicrm_relationship_type r ON (
748 AND ( cc.contact_type = r.contact_type_{$rel} OR r.contact_type_{$rel} IS NULL )
749 AND ( cc.contact_sub_type = r.contact_sub_type_{$rel} OR r.contact_sub_type_{$rel} IS NULL )
753 // check if only CMS users are requested
754 if (!empty($params['cmsuser'])) {
756 INNER JOIN civicrm_uf_match um ON (um.contact_id=cc.id)
761 $orderByOuter = "ORDER BY exactFirst";
762 if ($config->includeOrderByClause
) {
763 $orderByInner = "ORDER BY sort_name";
764 $orderByOuter .= ", sort_name";
769 SELECT DISTINCT(id), data, sort_name {$selectAliases}
771 ( SELECT 0 as exactFirst, cc.id as id, CONCAT_WS( ' :: ', {$actualSelectElements} ) as data {$select}
772 FROM civicrm_contact cc {$from}
774 {$additionalFrom} {$includeEmailFrom}
778 ( SELECT 1 as exactFirst, cc.id as id, CONCAT_WS( ' :: ', {$actualSelectElements} ) as data {$select}
779 FROM civicrm_contact cc {$from}
781 {$additionalFrom} {$includeEmailFrom}
789 // send query to hook to be modified if needed
790 CRM_Utils_Hook
::contactListQuery($query,
792 empty($params['context']) ?
NULL : CRM_Utils_Type
::escape($params['context'], 'String'),
793 empty($params['id']) ?
NULL : $params['id']
796 $dao = CRM_Core_DAO
::executeQuery($query);
798 $contactList = array();
799 $listCurrentEmployer = TRUE;
800 while ($dao->fetch()) {
801 $t = array('id' => $dao->id
);
802 foreach ($as as $k) {
803 $t[$k] = isset($dao->$k) ?
$dao->$k : '';
805 $t['data'] = $dao->data
;
807 if (!empty($params['org']) &&
808 !empty($currEmpDetails) &&
809 $dao->id
== $currEmpDetails['id']
811 $listCurrentEmployer = FALSE;
815 //return organization name if doesn't exist in db
816 if (empty($contactList)) {
817 if (!empty($params['org'])) {
818 if ($listCurrentEmployer && !empty($currEmpDetails)) {
819 $contactList = array(
821 'data' => $currEmpDetails['data'],
822 'id' => $currEmpDetails['id'],
827 $contactList = array(
837 return civicrm_api3_create_success($contactList, $params, 'Contact', 'getquick');
841 * Declare deprecated api functions.
843 * @deprecated api notice
845 * Array of deprecated actions
847 function _civicrm_api3_contact_deprecation() {
848 return array('getquick' => 'The "getquick" action is deprecated in favor of "getlist".');
852 * Merges given pair of duplicate contacts.
854 * @param array $params
855 * Allowed array keys are:
856 * -int main_id: main contact id with whom merge has to happen
857 * -int other_id: duplicate contact which would be deleted after merge operation
858 * -string mode: "safe" skips the merge if there are no conflicts. Does a force merge otherwise.
859 * -boolean auto_flip: whether to let api decide which contact to retain and which to delete.
864 function civicrm_api3_contact_merge($params) {
865 $mode = CRM_Utils_Array
::value('mode', $params, 'safe');
866 $autoFlip = CRM_Utils_Array
::value('auto_flip', $params, TRUE);
868 $dupePairs = array(array(
869 'srcID' => CRM_Utils_Array
::value('main_id', $params),
870 'dstID' => CRM_Utils_Array
::value('other_id', $params),
872 $result = CRM_Dedupe_Merger
::merge($dupePairs, array(), $mode, $autoFlip);
874 if ($result['is_error'] == 0) {
875 return civicrm_api3_create_success();
878 return civicrm_api3_create_error($result['messages']);
883 * Adjust metadata for contact_proximity api function.
885 * @param array $params
887 function _civicrm_api3_contact_proximity_spec(&$params) {
888 $params['latitude']['api.required'] = 1;
889 $params['latitude']['title'] = 'Latitude';
890 $params['longitude']['api.required'] = 1;
891 $params['longitude']['title'] = 'Longitude';
892 $params['unit']['api.default'] = 'meter';
893 $params['unit']['title'] = 'Unit of Measurement';
897 * Get contacts by proximity.
899 * @param array $params
904 function civicrm_api3_contact_proximity($params) {
905 $latitude = CRM_Utils_Array
::value('latitude', $params);
906 $longitude = CRM_Utils_Array
::value('longitude', $params);
907 $distance = CRM_Utils_Array
::value('distance', $params);
909 $unit = CRM_Utils_Array
::value('unit', $params);
911 // check and ensure that lat/long and distance are floats
913 !CRM_Utils_Rule
::numeric($latitude) ||
914 !CRM_Utils_Rule
::numeric($longitude) ||
915 !CRM_Utils_Rule
::numeric($distance)
917 throw new Exception(ts('Latitude, Longitude and Distance should exist and be numeric'));
920 if ($unit == "mile") {
921 $conversionFactor = 1609.344;
924 $conversionFactor = 1000;
927 $distance = $distance * $conversionFactor;
929 $whereClause = CRM_Contact_BAO_ProximityQuery
::where($latitude, $longitude, $distance);
932 SELECT civicrm_contact.id as contact_id,
933 civicrm_contact.display_name as display_name
935 LEFT JOIN civicrm_address ON civicrm_contact.id = civicrm_address.contact_id
939 $dao = CRM_Core_DAO
::executeQuery($query);
941 while ($dao->fetch()) {
942 $contacts[] = $dao->toArray();
945 return civicrm_api3_create_success($contacts, $params, 'Contact', 'get_by_location', $dao);
950 * Get parameters for getlist function.
952 * @see _civicrm_api3_generic_getlist_params
954 * @param array $request
956 function _civicrm_api3_contact_getlist_params(&$request) {
957 // get the autocomplete options from settings
958 $acpref = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
959 CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
,
960 'contact_autocomplete_options'
964 // get the option values for contact autocomplete
965 $acOptions = CRM_Core_OptionGroup
::values('contact_autocomplete_options', FALSE, FALSE, FALSE, NULL, 'name');
968 foreach ($acpref as $value) {
969 if ($value && !empty($acOptions[$value])) {
970 $list[] = $acOptions[$value];
973 // If we are doing quicksearch by a field other than name, make sure that field is added to results
974 $field_name = CRM_Utils_String
::munge($request['search_field']);
975 // Unique name contact_id = id
976 if ($field_name == 'contact_id') {
979 // phone_numeric should be phone
980 $searchField = str_replace('_numeric', '', $field_name);
981 if (!in_array($searchField, $list)) {
982 $list[] = $searchField;
984 $request['description_field'] = $list;
985 $list[] = 'contact_type';
986 $request['params']['return'] = array_unique(array_merge($list, $request['extra']));
987 $request['params']['options']['sort'] = 'sort_name';
988 // Contact api doesn't support array(LIKE => 'foo') syntax
989 if (!empty($request['input'])) {
990 $request['params'][$request['search_field']] = $request['input'];
995 * Get output for getlist function.
997 * @see _civicrm_api3_generic_getlist_output
999 * @param array $result
1000 * @param array $request
1004 function _civicrm_api3_contact_getlist_output($result, $request) {
1006 if (!empty($result['values'])) {
1007 $addressFields = array_intersect(array(
1013 $request['params']['return']);
1014 foreach ($result['values'] as $row) {
1016 'id' => $row[$request['id_field']],
1017 'label' => $row[$request['label_field']],
1018 'description' => array(),
1020 foreach ($request['description_field'] as $item) {
1021 if (!strpos($item, '_name') && !in_array($item, $addressFields) && !empty($row[$item])) {
1022 $data['description'][] = $row[$item];
1026 foreach ($addressFields as $item) {
1027 if (!empty($row[$item])) {
1028 $address[] = $row[$item];
1032 $data['description'][] = implode(' ', $address);
1034 if (!empty($request['image_field'])) {
1035 $data['image'] = isset($row[$request['image_field']]) ?
$row[$request['image_field']] : '';
1038 $data['icon_class'] = $row['contact_type'];
1040 foreach ($request['extra'] as $field) {
1041 $data['extra'][$field] = isset($row[$field]) ?
$row[$field] : NULL;