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.
30 * Contacts are the main entity in CiviCRM and this api is more robust than most.
31 * - Get action allows all params supported by advanced search.
32 * - Create action allows creating several related entities at once (e.g. email).
33 * - Create allows checking for duplicate contacts.
34 * Use getfields to list the full range of parameters and options supported by each action.
36 * @package CiviCRM_APIv3
40 * Create or update a contact.
42 * @param array $params
45 * @throws API_Exception
50 function civicrm_api3_contact_create($params) {
52 $contactID = CRM_Utils_Array
::value('contact_id', $params, CRM_Utils_Array
::value('id', $params));
53 $dupeCheck = CRM_Utils_Array
::value('dupe_check', $params, FALSE);
54 $values = _civicrm_api3_contact_check_params($params, $dupeCheck);
60 // If we get here, we're ready to create a new contact
61 if (($email = CRM_Utils_Array
::value('email', $params)) && !is_array($params['email'])) {
62 $defLocType = CRM_Core_BAO_LocationType
::getDefault();
63 $params['email'] = array(
67 'location_type_id' => ($defLocType->id
) ?
$defLocType->id
: 1,
73 if (!empty($params['home_url'])) {
74 $websiteTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Website', 'website_type_id');
75 $params['website'] = array(
77 'website_type_id' => key($websiteTypes),
78 'url' => $params['home_url'],
83 _civicrm_api3_greeting_format_params($params);
87 if (empty($params['contact_type']) && $contactID) {
88 $params['contact_type'] = CRM_Contact_BAO_Contact
::getContactType($contactID);
91 if (!isset($params['contact_sub_type']) && $contactID) {
92 $params['contact_sub_type'] = CRM_Contact_BAO_Contact
::getContactSubType($contactID);
95 _civicrm_api3_custom_format_params($params, $values, $params['contact_type'], $contactID);
97 $params = array_merge($params, $values);
98 //@todo we should just call basic_create here - but need to make contact:create accept 'id' on the bao
99 $contact = _civicrm_api3_contact_update($params, $contactID);
101 if (is_a($contact, 'CRM_Core_Error')) {
102 throw new API_Exception($contact->_errors
[0]['message']);
106 _civicrm_api3_object_to_array_unique_fields($contact, $values[$contact->id
]);
109 return civicrm_api3_create_success($values, $params, 'Contact', 'create');
113 * Adjust Metadata for Create action.
115 * @param array $params
116 * Array of parameters determined by getfields.
118 function _civicrm_api3_contact_create_spec(&$params) {
119 $params['contact_type']['api.required'] = 1;
120 $params['id']['api.aliases'] = array('contact_id');
121 $params['current_employer'] = array(
122 'title' => 'Current Employer',
123 'description' => 'Name of Current Employer',
124 'type' => CRM_Utils_Type
::T_STRING
,
126 $params['dupe_check'] = array(
127 'title' => 'Check for Duplicates',
128 'description' => 'Throw error if contact create matches dedupe rule',
130 $params['prefix_id']['api.aliases'] = array('individual_prefix', 'individual_prefix_id');
131 $params['suffix_id']['api.aliases'] = array('individual_suffix', 'individual_suffix_id');
135 * Retrieve one or more contacts, given a set of search params.
137 * @param array $params
142 function civicrm_api3_contact_get($params) {
144 _civicrm_api3_contact_get_supportanomalies($params, $options);
145 $contacts = _civicrm_api3_get_using_query_object('contact', $params, $options);
146 return civicrm_api3_create_success($contacts, $params, 'contact');
150 * Get count of contact.
152 * @param array $params
156 function civicrm_api3_contact_getcount($params) {
158 _civicrm_api3_contact_get_supportanomalies($params, $options);
159 $count = _civicrm_api3_get_using_query_object('contact', $params, $options, 1);
164 * Adjust Metadata for Get action.
166 * @param array $params
167 * Array of parameters determined by getfields.
169 function _civicrm_api3_contact_get_spec(&$params) {
170 $params['contact_is_deleted']['api.default'] = 0;
172 // We declare all these pseudoFields as there are other undocumented fields accessible
173 // via the api - but if check permissions is set we only allow declared fields
174 $params['address_id']['title'] = 'Primary Address ID';
175 $params['street_address']['title'] = 'Primary Address Street Address';
176 $params['supplemental_address_1']['title'] = 'Primary Address Supplemental Address 1';
177 $params['supplemental_address_2']['title'] = 'Primary Address Supplemental Address 2';
178 $params['current_employer']['title'] = 'Current Employer';
179 $params['city']['title'] = 'Primary Address City';
180 $params['postal_code_suffix']['title'] = 'Primary Address Post Code Suffix';
181 $params['postal_code']['title'] = 'Primary Address Post Code';
182 $params['geo_code_1']['title'] = 'Primary Address Latitude';
183 $params['geo_code_2']['title'] = 'Primary Address Longitude';
184 $params['state_province_id']['title'] = 'Primary Address State Province ID';
185 $params['state_province_name']['title'] = 'Primary Address State Province Name';
186 $params['state_province']['title'] = 'Primary Address State Province';
187 $params['country_id']['title'] = 'Primary Address Country ID';
188 $params['country']['title'] = 'Primary Address country';
189 $params['worldregion_id']['title'] = 'Primary Address World Region ID';
190 $params['worldregion']['title'] = 'Primary Address World Region';
191 $params['phone_id']['title'] = 'Primary Phone ID';
192 $params['phone']['title'] = 'Primary Phone';
193 $params['phone_type_id']['title'] = 'Primary Phone Type ID';
194 $params['provider_id']['title'] = 'Primary Phone Provider ID';
195 $params['email_id']['title'] = 'Primary Email ID';
196 $params['email']['title'] = 'Primary Email';
197 $params['gender_id']['title'] = 'Gender ID';
198 $params['gender']['title'] = 'Gender';
199 $params['on_hold']['title'] = 'Primary Email On Hold';
200 $params['im']['title'] = 'Primary Instant Messenger';
201 $params['im_id']['title'] = 'Primary Instant Messenger ID';
202 $params['group_id']['title'] = 'Group Memberships (filter)';
203 $params['group']['title'] = 'Group Memberships (filter, array)';
204 $params['tag']['title'] = 'Assigned tags (filter, array)';
205 $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'));
206 $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'));
207 $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'));
208 $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'));
212 * Support for historical oddities.
214 * We are supporting 'showAll' = 'all', 'trash' or 'active' for contact get
216 * - hopefully some day we'll come up with a std syntax for the 3-way-boolean of
219 * We also support 'filter_group_id' & 'filter.group_id'
221 * @param array $params
222 * As passed into api get or getcount function.
223 * @param array $options
224 * Array of options (so we can modify the filter).
226 function _civicrm_api3_contact_get_supportanomalies(&$params, &$options) {
227 if (isset($params['showAll'])) {
228 if (strtolower($params['showAll']) == "active") {
229 $params['contact_is_deleted'] = 0;
231 if (strtolower($params['showAll']) == "trash") {
232 $params['contact_is_deleted'] = 1;
234 if (strtolower($params['showAll']) == "all" && isset($params['contact_is_deleted'])) {
235 unset($params['contact_is_deleted']);
238 // support for group filters
239 if (array_key_exists('filter_group_id', $params)) {
240 $params['filter.group_id'] = $params['filter_group_id'];
241 unset($params['filter_group_id']);
243 // filter.group_id works both for 1,2,3 and array (1,2,3)
244 if (array_key_exists('filter.group_id', $params)) {
245 if (is_array($params['filter.group_id'])) {
246 $groups = $params['filter.group_id'];
249 $groups = explode(',', $params['filter.group_id']);
251 unset($params['filter.group_id']);
252 $groups = array_flip($groups);
253 $groups[key($groups)] = 1;
254 $options['input_params']['group'] = $groups;
259 * Delete a contact with given contact id.
261 * @param array $params
262 * input parameters per getfields
267 function civicrm_api3_contact_delete($params) {
269 $contactID = CRM_Utils_Array
::value('id', $params);
271 $session = CRM_Core_Session
::singleton();
272 if ($contactID == $session->get('userID')) {
273 return civicrm_api3_create_error('This contact record is linked to the currently logged in user account - and cannot be deleted.');
275 $restore = !empty($params['restore']) ?
$params['restore'] : FALSE;
276 $skipUndelete = !empty($params['skip_undelete']) ?
$params['skip_undelete'] : FALSE;
279 // restrict permanent delete if a contact has financial trxn associated with it
281 if ($skipUndelete && CRM_Financial_BAO_FinancialItem
::checkContactPresent(array($contactID), $error)) {
282 return civicrm_api3_create_error($error['_qf_default']);
284 if (CRM_Contact_BAO_Contact
::deleteContact($contactID, $restore, $skipUndelete)) {
285 return civicrm_api3_create_success();
288 return civicrm_api3_create_error('Could not delete contact');
294 * Check parameters passed in.
296 * This function is on it's way out.
298 * @param array $params
299 * @param bool $dupeCheck
302 * @throws API_Exception
303 * @throws CiviCRM_API3_Exception
305 function _civicrm_api3_contact_check_params(&$params, $dupeCheck) {
307 switch (strtolower(CRM_Utils_Array
::value('contact_type', $params))) {
309 civicrm_api3_verify_mandatory($params, NULL, array('household_name'));
313 civicrm_api3_verify_mandatory($params, NULL, array('organization_name'));
317 civicrm_api3_verify_one_mandatory($params, NULL, array(
327 // Fixme: This really needs to be handled at a lower level. @See CRM-13123
328 if (isset($params['preferred_communication_method'])) {
329 $params['preferred_communication_method'] = CRM_Utils_Array
::implodePadded($params['preferred_communication_method']);
332 if (!empty($params['contact_sub_type']) && !empty($params['contact_type'])) {
333 if (!(CRM_Contact_BAO_ContactType
::isExtendsContactType($params['contact_sub_type'], $params['contact_type']))) {
334 throw new API_Exception("Invalid or Mismatched Contact Subtype: " . implode(', ', (array) $params['contact_sub_type']));
339 // check for record already existing
340 $dedupeParams = CRM_Dedupe_Finder
::formatParams($params, $params['contact_type']);
343 // setting 'check_permission' here means that the dedupe checking will be carried out even if the
344 // person does not have permission to carry out de-dupes
345 // this is similar to the front end form
346 if (isset($params['check_permission'])) {
347 $dedupeParams['check_permission'] = $params['check_permission'];
350 $ids = CRM_Dedupe_Finder
::dupesByParams($dedupeParams, $params['contact_type'], 'Unsupervised', array());
352 if (count($ids) > 0) {
353 throw new API_Exception("Found matching contacts: " . implode(',', $ids), "duplicate", array("ids" => $ids));
357 // The BAO no longer supports the legacy param "current_employer" so here is a shim for api backward-compatability
358 if (!empty($params['current_employer'])) {
359 $organizationParams = array(
360 'organization_name' => $params['current_employer'],
363 $dedupParams = CRM_Dedupe_Finder
::formatParams($organizationParams, 'Organization');
365 $dedupParams['check_permission'] = FALSE;
366 $dupeIds = CRM_Dedupe_Finder
::dupesByParams($dedupParams, 'Organization', 'Supervised');
368 // check for mismatch employer name and id
369 if (!empty($params['employer_id']) && !in_array($params['employer_id'], $dupeIds)) {
370 throw new API_Exception('Employer name and Employer id Mismatch');
373 // show error if multiple organisation with same name exist
374 if (empty($params['employer_id']) && (count($dupeIds) > 1)) {
375 throw new API_Exception('Found more than one Organisation with same Name.');
379 $params['employer_id'] = $dupeIds[0];
382 $result = civicrm_api3('contact', 'create', array(
383 'organization_name' => $params['current_employer'],
384 'contact_type' => 'Organization',
386 $params['employer_id'] = $result['id'];
394 * Helper function for contact create.
396 * @param array $params
397 * (reference ) an assoc array of name/value pairs.
398 * @param int $contactID
399 * If present the contact with that ID is updated.
401 * @return CRM_Contact_BAO_Contact|CRM_Core_Error
403 function _civicrm_api3_contact_update($params, $contactID = NULL) {
404 //@todo - doesn't contact create support 'id' which is already set- check & remove
406 $params['contact_id'] = $contactID;
409 return CRM_Contact_BAO_Contact
::create($params);
413 * Validate the addressee or email or postal greetings.
415 * @param array $params
416 * Array per getfields metadata.
418 * @throws API_Exception
420 function _civicrm_api3_greeting_format_params($params) {
421 $greetingParams = array('', '_id', '_custom');
422 foreach (array('email', 'postal', 'addressee') as $key) {
423 $greeting = '_greeting';
424 if ($key == 'addressee') {
428 $formatParams = FALSE;
429 // Unset display value from params.
430 if (isset($params["{$key}{$greeting}_display"])) {
431 unset($params["{$key}{$greeting}_display"]);
434 // check if greetings are present in present
435 foreach ($greetingParams as $greetingValues) {
436 if (array_key_exists("{$key}{$greeting}{$greetingValues}", $params)) {
437 $formatParams = TRUE;
442 if (!$formatParams) {
448 'contact_type' => $params['contact_type'],
449 'greeting_type' => "{$key}{$greeting}",
452 $greetings = CRM_Core_PseudoConstant
::greeting($filter);
453 $greetingId = CRM_Utils_Array
::value("{$key}{$greeting}_id", $params);
454 $greetingVal = CRM_Utils_Array
::value("{$key}{$greeting}", $params);
455 $customGreeting = CRM_Utils_Array
::value("{$key}{$greeting}_custom", $params);
457 if (!$greetingId && $greetingVal) {
458 $params["{$key}{$greeting}_id"] = CRM_Utils_Array
::key($params["{$key}{$greeting}"], $greetings);
461 if ($customGreeting && $greetingId &&
462 ($greetingId != array_search('Customized', $greetings))
464 throw new API_Exception(ts('Provide either %1 greeting id and/or %1 greeting or custom %1 greeting',
469 if ($greetingVal && $greetingId &&
470 ($greetingId != CRM_Utils_Array
::key($greetingVal, $greetings))
472 throw new API_Exception(ts('Mismatch in %1 greeting id and %1 greeting',
479 if (!array_key_exists($greetingId, $greetings)) {
480 throw new API_Exception(ts('Invalid %1 greeting Id', array(1 => $key)));
483 if (!$customGreeting && ($greetingId == array_search('Customized', $greetings))) {
484 throw new API_Exception(ts('Please provide a custom value for %1 greeting',
489 elseif ($greetingVal) {
491 if (!in_array($greetingVal, $greetings)) {
492 throw new API_Exception(ts('Invalid %1 greeting', array(1 => $key)));
495 $greetingId = CRM_Utils_Array
::key($greetingVal, $greetings);
498 if ($customGreeting) {
499 $greetingId = CRM_Utils_Array
::key('Customized', $greetings);
502 $customValue = isset($params['contact_id']) ? CRM_Core_DAO
::getFieldValue(
503 'CRM_Contact_DAO_Contact',
504 $params['contact_id'],
505 "{$key}{$greeting}_custom"
508 if (array_key_exists("{$key}{$greeting}_id", $params) && empty($params["{$key}{$greeting}_id"])) {
511 elseif (array_key_exists("{$key}{$greeting}", $params) && empty($params["{$key}{$greeting}"])) {
514 elseif ($customValue && array_key_exists("{$key}{$greeting}_custom", $params)
515 && empty($params["{$key}{$greeting}_custom"])
520 $params["{$key}{$greeting}_id"] = $greetingId;
522 if (!$customValue && !$customGreeting && array_key_exists("{$key}{$greeting}_custom", $params)) {
523 unset($params["{$key}{$greeting}_custom"]);
527 $params["{$key}{$greeting}_id"] = '';
528 $params["{$key}{$greeting}_custom"] = '';
531 if (isset($params["{$key}{$greeting}"])) {
532 unset($params["{$key}{$greeting}"]);
538 * Old contact quick search api.
542 * @param array $params
545 * @throws \API_Exception
547 function civicrm_api3_contact_getquick($params) {
548 civicrm_api3_verify_mandatory($params, NULL, array('name'));
549 $name = CRM_Utils_Type
::escape(CRM_Utils_Array
::value('name', $params), 'String');
551 // get the autocomplete options from settings
552 $acpref = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
553 CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
,
554 'contact_autocomplete_options'
558 // get the option values for contact autocomplete
559 $acOptions = CRM_Core_OptionGroup
::values('contact_autocomplete_options', FALSE, FALSE, FALSE, NULL, 'name');
562 foreach ($acpref as $value) {
563 if ($value && !empty($acOptions[$value])) {
564 $list[$value] = $acOptions[$value];
567 // If we are doing quicksearch by a field other than name, make sure that field is added to results
568 if (!empty($params['field_name'])) {
569 $field_name = CRM_Utils_String
::munge($params['field_name']);
570 // Unique name contact_id = id
571 if ($field_name == 'contact_id') {
574 // phone_numeric should be phone
575 $searchField = str_replace('_numeric', '', $field_name);
576 if (!in_array($searchField, $list)) {
577 $list[] = $searchField;
581 $select = $actualSelectElements = array('sort_name');
584 foreach ($list as $value) {
585 $suffix = substr($value, 0, 2) . substr($value, -1);
587 case 'street_address':
590 $selectText = $value;
595 $actualSelectElements[] = $select[] = ($value == 'address') ?
$selectText : $value;
596 if ($value == 'phone') {
597 $actualSelectElements[] = $select[] = 'phone_ext';
599 $from[$value] = "LEFT JOIN civicrm_{$value} {$suffix} ON ( cc.id = {$suffix}.contact_id AND {$suffix}.is_primary = 1 ) ";
603 case 'state_province':
604 $select[] = "{$suffix}.name as {$value}";
605 $actualSelectElements[] = "{$suffix}.name";
606 if (!in_array('address', $from)) {
607 $from['address'] = 'LEFT JOIN civicrm_address sts ON ( cc.id = sts.contact_id AND sts.is_primary = 1) ';
609 $from[$value] = " LEFT JOIN civicrm_{$value} {$suffix} ON ( sts.{$value}_id = {$suffix}.id ) ";
613 if ($value != 'id') {
615 if (!empty($params['field_name']) && $params['field_name'] == 'value') {
616 $suffix = CRM_Utils_String
::munge(CRM_Utils_Array
::value('table_name', $params, 'cc'));
618 $actualSelectElements[] = $select[] = $suffix . '.' . $value;
624 $config = CRM_Core_Config
::singleton();
626 $select = implode(', ', $select);
627 if (!empty($select)) {
628 $select = ", $select";
630 $actualSelectElements = implode(', ', $actualSelectElements);
631 $selectAliases = $from;
632 unset($selectAliases['address']);
633 $selectAliases = implode(', ', array_keys($selectAliases));
634 if (!empty($selectAliases)) {
635 $selectAliases = ", $selectAliases";
637 $from = implode(' ', $from);
638 $limit = (int) CRM_Utils_Array
::value('limit', $params);
639 $limit = $limit > 0 ?
$limit : 10;
641 // add acl clause here
642 list($aclFrom, $aclWhere) = CRM_Contact_BAO_Contact_Permission
::cacheClause('cc');
645 $where .= " AND $aclWhere ";
648 if (!empty($params['org'])) {
649 $where .= " AND contact_type = \"Organization\"";
651 // CRM-7157, hack: get current employer details when
652 // employee_id is present.
653 $currEmpDetails = array();
654 if (!empty($params['employee_id'])) {
655 if ($currentEmployer = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact',
656 (int) $params['employee_id'],
659 if ($config->includeWildCardInName
) {
660 $strSearch = "%$name%";
663 $strSearch = "$name%";
666 // get current employer details
667 $dao = CRM_Core_DAO
::executeQuery("SELECT cc.id as id, CONCAT_WS( ' :: ', {$actualSelectElements} ) as data, sort_name
668 FROM civicrm_contact cc {$from} WHERE cc.contact_type = \"Organization\" AND cc.id = {$currentEmployer} AND cc.sort_name LIKE '$strSearch'");
670 $currEmpDetails = array(
672 'data' => $dao->data
,
679 if (!empty($params['contact_sub_type'])) {
680 $contactSubType = CRM_Utils_Type
::escape($params['contact_sub_type'], 'String');
681 $where .= " AND cc.contact_sub_type = '{$contactSubType}'";
684 if (!empty($params['contact_type'])) {
685 $contactType = CRM_Utils_Type
::escape($params['contact_type'], 'String');
686 $where .= " AND cc.contact_type LIKE '{$contactType}'";
689 //set default for current_employer or return contact with particular id
690 if (!empty($params['id'])) {
691 $where .= " AND cc.id = " . (int) $params['id'];
694 if (!empty($params['cid'])) {
695 $where .= " AND cc.id <> " . (int) $params['cid'];
698 //contact's based of relationhip type
700 if (!empty($params['rel'])) {
701 $relation = explode('_', CRM_Utils_Array
::value('rel', $params));
702 $relType = CRM_Utils_Type
::escape($relation[0], 'Integer');
703 $rel = CRM_Utils_Type
::escape($relation[2], 'String');
706 if ($config->includeWildCardInName
) {
707 $strSearch = "%$name%";
710 $strSearch = "$name%";
712 $includeEmailFrom = $includeNickName = $exactIncludeNickName = '';
713 if ($config->includeNickNameInName
) {
714 $includeNickName = " OR nick_name LIKE '$strSearch'";
715 $exactIncludeNickName = " OR nick_name LIKE '$name'";
719 if (!empty($params['field_name']) && !empty($params['table_name'])) {
720 $table_name = CRM_Utils_String
::munge($params['table_name']);
721 $whereClause = " WHERE ( $table_name.$field_name LIKE '$strSearch') {$where}";
722 $exactWhereClause = " WHERE ( $table_name.$field_name = '$name') {$where}";
723 // Search by id should be exact
724 if ($field_name == 'id' ||
$field_name == 'external_identifier') {
725 $whereClause = $exactWhereClause;
729 if ($config->includeEmailInName
) {
730 if (!in_array('email', $list)) {
731 $includeEmailFrom = "LEFT JOIN civicrm_email eml ON ( cc.id = eml.contact_id AND eml.is_primary = 1 )";
733 $whereClause = " WHERE ( email LIKE '$strSearch' OR sort_name LIKE '$strSearch' $includeNickName ) {$where} ";
734 $exactWhereClause = " WHERE ( email LIKE '$name' OR sort_name LIKE '$name' $exactIncludeNickName ) {$where} ";
737 $whereClause = " WHERE ( sort_name LIKE '$strSearch' $includeNickName ) {$where} ";
738 $exactWhereClause = " WHERE ( sort_name LIKE '$name' $exactIncludeNickName ) {$where} ";
742 $additionalFrom = '';
745 INNER JOIN civicrm_relationship_type r ON (
747 AND ( cc.contact_type = r.contact_type_{$rel} OR r.contact_type_{$rel} IS NULL )
748 AND ( cc.contact_sub_type = r.contact_sub_type_{$rel} OR r.contact_sub_type_{$rel} IS NULL )
752 // check if only CMS users are requested
753 if (!empty($params['cmsuser'])) {
755 INNER JOIN civicrm_uf_match um ON (um.contact_id=cc.id)
760 $orderByOuter = "ORDER BY exactFirst";
761 if ($config->includeOrderByClause
) {
762 $orderByInner = "ORDER BY sort_name";
763 $orderByOuter .= ", sort_name";
768 SELECT DISTINCT(id), data, sort_name {$selectAliases}
770 ( SELECT 0 as exactFirst, cc.id as id, CONCAT_WS( ' :: ', {$actualSelectElements} ) as data {$select}
771 FROM civicrm_contact cc {$from}
773 {$additionalFrom} {$includeEmailFrom}
777 ( SELECT 1 as exactFirst, cc.id as id, CONCAT_WS( ' :: ', {$actualSelectElements} ) as data {$select}
778 FROM civicrm_contact cc {$from}
780 {$additionalFrom} {$includeEmailFrom}
788 // send query to hook to be modified if needed
789 CRM_Utils_Hook
::contactListQuery($query,
791 empty($params['context']) ?
NULL : CRM_Utils_Type
::escape($params['context'], 'String'),
792 empty($params['id']) ?
NULL : $params['id']
795 $dao = CRM_Core_DAO
::executeQuery($query);
797 $contactList = array();
798 $listCurrentEmployer = TRUE;
799 while ($dao->fetch()) {
800 $t = array('id' => $dao->id
);
801 foreach ($as as $k) {
802 $t[$k] = isset($dao->$k) ?
$dao->$k : '';
804 $t['data'] = $dao->data
;
806 if (!empty($params['org']) &&
807 !empty($currEmpDetails) &&
808 $dao->id
== $currEmpDetails['id']
810 $listCurrentEmployer = FALSE;
814 //return organization name if doesn't exist in db
815 if (empty($contactList)) {
816 if (!empty($params['org'])) {
817 if ($listCurrentEmployer && !empty($currEmpDetails)) {
818 $contactList = array(
820 'data' => $currEmpDetails['data'],
821 'id' => $currEmpDetails['id'],
826 $contactList = array(
836 return civicrm_api3_create_success($contactList, $params, 'contact', 'getquick');
840 * Declare deprecated api functions.
842 * @deprecated api notice
844 * Array of deprecated actions
846 function _civicrm_api3_contact_deprecation() {
847 return array('getquick' => 'The "getquick" action is deprecated in favor of "getlist".');
851 * Merges given pair of duplicate contacts.
853 * @param array $params
854 * Allowed array keys are:
855 * -int main_id: main contact id with whom merge has to happen
856 * -int other_id: duplicate contact which would be deleted after merge operation
857 * -string mode: "safe" skips the merge if there are no conflicts. Does a force merge otherwise.
858 * -boolean auto_flip: whether to let api decide which contact to retain and which to delete.
863 function civicrm_api3_contact_merge($params) {
864 $mode = CRM_Utils_Array
::value('mode', $params, 'safe');
865 $autoFlip = CRM_Utils_Array
::value('auto_flip', $params, TRUE);
867 $dupePairs = array(array(
868 'srcID' => CRM_Utils_Array
::value('main_id', $params),
869 'dstID' => CRM_Utils_Array
::value('other_id', $params),
871 $result = CRM_Dedupe_Merger
::merge($dupePairs, array(), $mode, $autoFlip);
873 if ($result['is_error'] == 0) {
874 return civicrm_api3_create_success();
877 return civicrm_api3_create_error($result['messages']);
882 * Adjust metadata for contact_proximity api function.
884 * @param array $params
886 function _civicrm_api3_contact_proximity_spec(&$params) {
887 $params['latitude']['api.required'] = 1;
888 $params['latitude']['title'] = 'Latitude';
889 $params['longitude']['api.required'] = 1;
890 $params['longitude']['title'] = 'Longitude';
891 $params['unit']['api.default'] = 'meter';
892 $params['unit']['title'] = 'Unit of Measurement';
896 * Get contacts by proximity.
898 * @param array $params
903 function civicrm_api3_contact_proximity($params) {
904 $latitude = CRM_Utils_Array
::value('latitude', $params);
905 $longitude = CRM_Utils_Array
::value('longitude', $params);
906 $distance = CRM_Utils_Array
::value('distance', $params);
908 $unit = CRM_Utils_Array
::value('unit', $params);
910 // check and ensure that lat/long and distance are floats
912 !CRM_Utils_Rule
::numeric($latitude) ||
913 !CRM_Utils_Rule
::numeric($longitude) ||
914 !CRM_Utils_Rule
::numeric($distance)
916 throw new Exception(ts('Latitude, Longitude and Distance should exist and be numeric'));
919 if ($unit == "mile") {
920 $conversionFactor = 1609.344;
923 $conversionFactor = 1000;
926 $distance = $distance * $conversionFactor;
928 $whereClause = CRM_Contact_BAO_ProximityQuery
::where($latitude, $longitude, $distance);
931 SELECT civicrm_contact.id as contact_id,
932 civicrm_contact.display_name as display_name
934 LEFT JOIN civicrm_address ON civicrm_contact.id = civicrm_address.contact_id
938 $dao = CRM_Core_DAO
::executeQuery($query);
940 while ($dao->fetch()) {
941 $contacts[] = $dao->toArray();
944 return civicrm_api3_create_success($contacts, $params, 'contact', 'get_by_location', $dao);
949 * Get parameters for getlist function.
951 * @see _civicrm_api3_generic_getlist_params
953 * @param array $request
955 function _civicrm_api3_contact_getlist_params(&$request) {
956 // get the autocomplete options from settings
957 $acpref = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
958 CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
,
959 'contact_autocomplete_options'
963 // get the option values for contact autocomplete
964 $acOptions = CRM_Core_OptionGroup
::values('contact_autocomplete_options', FALSE, FALSE, FALSE, NULL, 'name');
967 foreach ($acpref as $value) {
968 if ($value && !empty($acOptions[$value])) {
969 $list[] = $acOptions[$value];
972 // If we are doing quicksearch by a field other than name, make sure that field is added to results
973 $field_name = CRM_Utils_String
::munge($request['search_field']);
974 // Unique name contact_id = id
975 if ($field_name == 'contact_id') {
978 // phone_numeric should be phone
979 $searchField = str_replace('_numeric', '', $field_name);
980 if (!in_array($searchField, $list)) {
981 $list[] = $searchField;
983 $request['description_field'] = $list;
984 $list[] = 'contact_type';
985 $request['params']['return'] = array_unique(array_merge($list, $request['extra']));
986 $request['params']['options']['sort'] = 'sort_name';
987 // Contact api doesn't support array(LIKE => 'foo') syntax
988 if (!empty($request['input'])) {
989 $request['params'][$request['search_field']] = $request['input'];
994 * Get output for getlist function.
996 * @see _civicrm_api3_generic_getlist_output
998 * @param array $result
999 * @param array $request
1003 function _civicrm_api3_contact_getlist_output($result, $request) {
1005 if (!empty($result['values'])) {
1006 $addressFields = array_intersect(array(
1012 $request['params']['return']);
1013 foreach ($result['values'] as $row) {
1015 'id' => $row[$request['id_field']],
1016 'label' => $row[$request['label_field']],
1017 'description' => array(),
1019 foreach ($request['description_field'] as $item) {
1020 if (!strpos($item, '_name') && !in_array($item, $addressFields) && !empty($row[$item])) {
1021 $data['description'][] = $row[$item];
1025 foreach ($addressFields as $item) {
1026 if (!empty($row[$item])) {
1027 $address[] = $row[$item];
1031 $data['description'][] = implode(' ', $address);
1033 if (!empty($request['image_field'])) {
1034 $data['image'] = isset($row[$request['image_field']]) ?
$row[$request['image_field']] : '';
1037 $data['icon_class'] = $row['contact_type'];
1039 foreach ($request['extra'] as $field) {
1040 $data['extra'][$field] = isset($row[$field]) ?
$row[$field] : NULL;