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 * new version of civicrm apis. See blog post at
30 * http://civicrm.org/node/131
33 * @package CiviCRM_APIv3
34 * @subpackage API_Contact
35 * @copyright CiviCRM LLC (c) 2004-2014
36 * $Id: Contact.php 30879 2010-11-22 15:45:55Z shot $
41 * Create or update a contact (note you should always call this via civicrm_api() & never directly)
43 * @param array $params
46 * Allowed @params array keys are:
47 * {@getfields contact_create}
50 * @throws API_Exception
51 * @example ContactCreate.php Example of Create Call
59 function civicrm_api3_contact_create($params) {
61 $contactID = CRM_Utils_Array
::value('contact_id', $params, CRM_Utils_Array
::value('id', $params));
62 $dupeCheck = CRM_Utils_Array
::value('dupe_check', $params, FALSE);
63 $values = _civicrm_api3_contact_check_params($params, $dupeCheck);
69 // If we get here, we're ready to create a new contact
70 if (($email = CRM_Utils_Array
::value('email', $params)) && !is_array($params['email'])) {
71 $defLocType = CRM_Core_BAO_LocationType
::getDefault();
72 $params['email'] = array(
76 'location_type_id' => ($defLocType->id
) ?
$defLocType->id
: 1,
82 if (!empty($params['home_url'])) {
83 $websiteTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Website', 'website_type_id');
84 $params['website'] = array(
86 'website_type_id' => key($websiteTypes),
87 'url' => $params['home_url'],
92 _civicrm_api3_greeting_format_params($params);
96 if (empty($params['contact_type']) && $contactID) {
97 $params['contact_type'] = CRM_Contact_BAO_Contact
::getContactType($contactID);
100 if (!isset($params['contact_sub_type']) && $contactID) {
101 $params['contact_sub_type'] = CRM_Contact_BAO_Contact
::getContactSubType($contactID);
104 _civicrm_api3_custom_format_params($params, $values, $params['contact_type'], $contactID);
106 $params = array_merge($params, $values);
107 //@todo we should just call basic_create here - but need to make contact:create accept 'id' on the bao
108 $contact = _civicrm_api3_contact_update($params, $contactID);
110 if (is_a($contact, 'CRM_Core_Error')) {
111 throw new API_Exception($contact->_errors
[0]['message']);
115 _civicrm_api3_object_to_array_unique_fields($contact, $values[$contact->id
]);
118 return civicrm_api3_create_success($values, $params, 'Contact', 'create');
122 * Adjust Metadata for Create action
124 * @param array $params
125 * Array or parameters determined by getfields.
127 function _civicrm_api3_contact_create_spec(&$params) {
128 $params['contact_type']['api.required'] = 1;
129 $params['id']['api.aliases'] = array('contact_id');
130 $params['current_employer'] = array(
131 'title' => 'Current Employer',
132 'description' => 'Name of Current Employer',
133 'type' => CRM_Utils_Type
::T_STRING
,
135 $params['dupe_check'] = array(
136 'title' => 'Check for Duplicates',
137 'description' => 'Throw error if contact create matches dedupe rule',
139 $params['prefix_id']['api.aliases'] = array('individual_prefix', 'individual_prefix_id');
140 $params['suffix_id']['api.aliases'] = array('individual_suffix', 'individual_suffix_id');
144 * Retrieve one or more contacts, given a set of search params
146 * @param array input parameters
150 * (@getfields contact_get}
154 * @example ContactGet.php Standard GET example
157 function civicrm_api3_contact_get($params) {
159 _civicrm_api3_contact_get_supportanomalies($params, $options);
160 $contacts = _civicrm_api3_get_using_query_object('contact', $params, $options);
161 return civicrm_api3_create_success($contacts, $params, 'contact');
165 * @param array $params
169 function civicrm_api3_contact_getcount($params) {
171 _civicrm_api3_contact_get_supportanomalies($params, $options);
172 $count = _civicrm_api3_get_using_query_object('contact', $params, $options, 1);
177 * Adjust Metadata for Get action
179 * @param array $params
180 * Array or parameters determined by getfields.
182 function _civicrm_api3_contact_get_spec(&$params) {
183 $params['contact_is_deleted']['api.default'] = 0;
185 //we declare all these pseudofields as there are other undocumented fields accessible
186 // via the api - but if check permissions is set we only allow declared fields
187 $params['address_id']['title'] = 'Primary Address ID';
188 $params['street_address']['title'] = 'Primary Address Street Address';
189 $params['supplemental_address_1']['title'] = 'Primary Address Supplemental Address 1';
190 $params['supplemental_address_2']['title'] = 'Primary Address Supplemental Address 2';
191 $params['current_employer']['title'] = 'Current Employer';
192 $params['city']['title'] = 'Primary Address City';
193 $params['postal_code_suffix']['title'] = 'Primary Address Post Code Suffix';
194 $params['postal_code']['title'] = 'Primary Address Post Code';
195 $params['geo_code_1']['title'] = 'Primary Address Latitude';
196 $params['geo_code_2']['title'] = 'Primary Address Longitude';
197 $params['state_province_id']['title'] = 'Primary Address State Province ID';
198 $params['state_province_name']['title'] = 'Primary Address State Province Name';
199 $params['state_province']['title'] = 'Primary Address State Province';
200 $params['country_id']['title'] = 'Primary Address Country ID';
201 $params['country']['title'] = 'Primary Address country';
202 $params['worldregion_id']['title'] = 'Primary Address World Region ID';
203 $params['worldregion']['title'] = 'Primary Address World Region';
204 $params['phone_id']['title'] = 'Primary Phone ID';
205 $params['phone']['title'] = 'Primary Phone';
206 $params['phone_type_id']['title'] = 'Primary Phone Type ID';
207 $params['provider_id']['title'] = 'Primary Phone Provider ID';
208 $params['email_id']['title'] = 'Primary Email ID';
209 $params['email']['title'] = 'Primary Email';
210 $params['gender_id']['title'] = 'Gender ID';
211 $params['gender']['title'] = 'Gender';
212 $params['on_hold']['title'] = 'Primary Email On Hold';
213 $params['im']['title'] = 'Primary Instant Messenger';
214 $params['im_id']['title'] = 'Primary Instant Messenger ID';
215 $params['group_id']['title'] = 'Group Memberships (filter)';
216 $params['group']['title'] = 'Group Memberships (filter, array)';
217 $params['tag']['title'] = 'Assigned tags (filter, array)';
218 $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'));
219 $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'));
220 $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'));
221 $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'));
225 * We are supporting 'showAll' = 'all', 'trash' or 'active' for contact get
227 * - hopefully some day we'll come up with a std syntax for the 3-way-boolean of
230 * We also support 'filter_group_id' & 'filter.group_id'
232 * @param array $params
233 * As passed into api get or getcount function.
234 * @param array $options
235 * Array of options (so we can modify the filter).
237 function _civicrm_api3_contact_get_supportanomalies(&$params, &$options) {
238 if (isset($params['showAll'])) {
239 if (strtolower($params['showAll']) == "active") {
240 $params['contact_is_deleted'] = 0;
242 if (strtolower($params['showAll']) == "trash") {
243 $params['contact_is_deleted'] = 1;
245 if (strtolower($params['showAll']) == "all" && isset($params['contact_is_deleted'])) {
246 unset($params['contact_is_deleted']);
249 // support for group filters
250 if (array_key_exists('filter_group_id', $params)) {
251 $params['filter.group_id'] = $params['filter_group_id'];
252 unset($params['filter_group_id']);
254 // filter.group_id works both for 1,2,3 and array (1,2,3)
255 if (array_key_exists('filter.group_id', $params)) {
256 if (is_array($params['filter.group_id'])) {
257 $groups = $params['filter.group_id'];
260 $groups = explode(',', $params['filter.group_id']);
262 unset($params['filter.group_id']);
263 $groups = array_flip($groups);
264 $groups[key($groups)] = 1;
265 $options['input_params']['group'] = $groups;
270 * Delete a contact with given contact id
272 * @param array $params
273 * (reference ) input parameters, contact_id element required.
279 * @example ContactDelete.php
280 * {@getfields contact_delete}
282 function civicrm_api3_contact_delete($params) {
284 $contactID = CRM_Utils_Array
::value('id', $params);
286 $session = CRM_Core_Session
::singleton();
287 if ($contactID == $session->get('userID')) {
288 return civicrm_api3_create_error('This contact record is linked to the currently logged in user account - and cannot be deleted.');
290 $restore = !empty($params['restore']) ?
$params['restore'] : FALSE;
291 $skipUndelete = !empty($params['skip_undelete']) ?
$params['skip_undelete'] : FALSE;
294 // restrict permanent delete if a contact has financial trxn associated with it
296 if ($skipUndelete && CRM_Financial_BAO_FinancialItem
::checkContactPresent(array($contactID), $error)) {
297 return civicrm_api3_create_error($error['_qf_default']);
299 if (CRM_Contact_BAO_Contact
::deleteContact($contactID, $restore, $skipUndelete)) {
300 return civicrm_api3_create_success();
303 return civicrm_api3_create_error('Could not delete contact');
309 * @param array $params
310 * @param bool $dupeCheck
311 * @param bool $dupeErrorArray
312 * @param bool $obsoletevalue
313 * @param int $dedupeRuleGroupID
316 * @throws API_Exception
317 * @throws CiviCRM_API3_Exception
319 function _civicrm_api3_contact_check_params(&$params, $dupeCheck = TRUE, $dupeErrorArray = FALSE, $obsoletevalue = TRUE, $dedupeRuleGroupID = NULL) {
321 switch (strtolower(CRM_Utils_Array
::value('contact_type', $params))) {
323 civicrm_api3_verify_mandatory($params, NULL, array('household_name'));
327 civicrm_api3_verify_mandatory($params, NULL, array('organization_name'));
331 civicrm_api3_verify_one_mandatory($params, NULL, array(
341 // Fixme: This really needs to be handled at a lower level. @See CRM-13123
342 if (isset($params['preferred_communication_method'])) {
343 $params['preferred_communication_method'] = CRM_Utils_Array
::implodePadded($params['preferred_communication_method']);
346 if (!empty($params['contact_sub_type']) && !empty($params['contact_type'])) {
347 if (!(CRM_Contact_BAO_ContactType
::isExtendsContactType($params['contact_sub_type'], $params['contact_type']))) {
348 throw new API_Exception("Invalid or Mismatched Contact Subtype: " . implode(', ', (array) $params['contact_sub_type']));
353 // check for record already existing
354 $dedupeParams = CRM_Dedupe_Finder
::formatParams($params, $params['contact_type']);
357 // setting 'check_permission' here means that the dedupe checking will be carried out even if the
358 // person does not have permission to carry out de-dupes
359 // this is similar to the front end form
360 if (isset($params['check_permission'])) {
361 $dedupeParams['check_permission'] = $params['check_permission'];
364 $ids = CRM_Dedupe_Finder
::dupesByParams($dedupeParams, $params['contact_type'], 'Unsupervised', array());
366 if (count($ids) > 0) {
367 throw new API_Exception("Found matching contacts: " . implode(',', $ids), "duplicate", array("ids" => $ids));
371 // The BAO no longer supports the legacy param "current_employer" so here is a shim for api backward-compatability
372 if (!empty($params['current_employer'])) {
373 $organizationParams = array(
374 'organization_name' => $params['current_employer'],
377 $dedupParams = CRM_Dedupe_Finder
::formatParams($organizationParams, 'Organization');
379 $dedupParams['check_permission'] = FALSE;
380 $dupeIds = CRM_Dedupe_Finder
::dupesByParams($dedupParams, 'Organization', 'Supervised');
382 // check for mismatch employer name and id
383 if (!empty($params['employer_id']) && !in_array($params['employer_id'], $dupeIds)) {
384 throw new API_Exception('Employer name and Employer id Mismatch');
387 // show error if multiple organisation with same name exist
388 if (empty($params['employer_id']) && (count($dupeIds) > 1)) {
389 throw new API_Exception('Found more than one Organisation with same Name.');
393 $params['employer_id'] = $dupeIds[0];
396 $result = civicrm_api3('contact', 'create', array(
397 'organization_name' => $params['current_employer'],
398 'contact_type' => 'Organization',
400 $params['employer_id'] = $result['id'];
408 * Takes an associative array and creates a contact object and all the associated
409 * derived objects (i.e. individual, location, email, phone etc)
411 * @param array $params
412 * (reference ) an assoc array of name/value pairs.
413 * @param int $contactID
414 * If present the contact with that ID is updated.
416 * @return CRM_Contact_BAO_Contact
420 function _civicrm_api3_contact_update($params, $contactID = NULL) {
421 //@todo - doesn't contact create support 'id' which is already set- check & remove
423 $params['contact_id'] = $contactID;
426 return CRM_Contact_BAO_Contact
::create($params);
430 * Validate the addressee or email or postal greetings
432 * @param array $params
433 * Associative array of property name/value.
434 * pairs to insert in new contact.
436 * @throws API_Exception
440 function _civicrm_api3_greeting_format_params($params) {
441 $greetingParams = array('', '_id', '_custom');
442 foreach (array('email', 'postal', 'addressee') as $key) {
443 $greeting = '_greeting';
444 if ($key == 'addressee') {
448 $formatParams = FALSE;
449 // unset display value from params.
450 if (isset($params["{$key}{$greeting}_display"])) {
451 unset($params["{$key}{$greeting}_display"]);
454 // check if greetings are present in present
455 foreach ($greetingParams as $greetingValues) {
456 if (array_key_exists("{$key}{$greeting}{$greetingValues}", $params)) {
457 $formatParams = TRUE;
462 if (!$formatParams) {
468 'contact_type' => $params['contact_type'],
469 'greeting_type' => "{$key}{$greeting}",
472 $greetings = CRM_Core_PseudoConstant
::greeting($filter);
473 $greetingId = CRM_Utils_Array
::value("{$key}{$greeting}_id", $params);
474 $greetingVal = CRM_Utils_Array
::value("{$key}{$greeting}", $params);
475 $customGreeting = CRM_Utils_Array
::value("{$key}{$greeting}_custom", $params);
477 if (!$greetingId && $greetingVal) {
478 $params["{$key}{$greeting}_id"] = CRM_Utils_Array
::key($params["{$key}{$greeting}"], $greetings);
481 if ($customGreeting && $greetingId &&
482 ($greetingId != array_search('Customized', $greetings))
484 throw new API_Exception(ts('Provide either %1 greeting id and/or %1 greeting or custom %1 greeting',
489 if ($greetingVal && $greetingId &&
490 ($greetingId != CRM_Utils_Array
::key($greetingVal, $greetings))
492 throw new API_Exception(ts('Mismatch in %1 greeting id and %1 greeting',
499 if (!array_key_exists($greetingId, $greetings)) {
500 throw new API_Exception(ts('Invalid %1 greeting Id', array(1 => $key)));
503 if (!$customGreeting && ($greetingId == array_search('Customized', $greetings))) {
504 throw new API_Exception(ts('Please provide a custom value for %1 greeting',
509 elseif ($greetingVal) {
511 if (!in_array($greetingVal, $greetings)) {
512 throw new API_Exception(ts('Invalid %1 greeting', array(1 => $key)));
515 $greetingId = CRM_Utils_Array
::key($greetingVal, $greetings);
518 if ($customGreeting) {
519 $greetingId = CRM_Utils_Array
::key('Customized', $greetings);
522 $customValue = isset($params['contact_id']) ? CRM_Core_DAO
::getFieldValue(
523 'CRM_Contact_DAO_Contact',
524 $params['contact_id'],
525 "{$key}{$greeting}_custom"
528 if (array_key_exists("{$key}{$greeting}_id", $params) && empty($params["{$key}{$greeting}_id"])) {
531 elseif (array_key_exists("{$key}{$greeting}", $params) && empty($params["{$key}{$greeting}"])) {
534 elseif ($customValue && array_key_exists("{$key}{$greeting}_custom", $params)
535 && empty($params["{$key}{$greeting}_custom"])
540 $params["{$key}{$greeting}_id"] = $greetingId;
542 if (!$customValue && !$customGreeting && array_key_exists("{$key}{$greeting}_custom", $params)) {
543 unset($params["{$key}{$greeting}_custom"]);
547 $params["{$key}{$greeting}_id"] = '';
548 $params["{$key}{$greeting}_custom"] = '';
551 if (isset($params["{$key}{$greeting}"])) {
552 unset($params["{$key}{$greeting}"]);
558 * Old contact quick search api
562 * {@example ContactGetquick.php 0}
565 * @throws \API_Exception
567 function civicrm_api3_contact_getquick($params) {
568 civicrm_api3_verify_mandatory($params, NULL, array('name'));
569 $name = CRM_Utils_Type
::escape(CRM_Utils_Array
::value('name', $params), 'String');
571 // get the autocomplete options from settings
572 $acpref = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
573 CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
,
574 'contact_autocomplete_options'
578 // get the option values for contact autocomplete
579 $acOptions = CRM_Core_OptionGroup
::values('contact_autocomplete_options', FALSE, FALSE, FALSE, NULL, 'name');
582 foreach ($acpref as $value) {
583 if ($value && !empty($acOptions[$value])) {
584 $list[$value] = $acOptions[$value];
587 // If we are doing quicksearch by a field other than name, make sure that field is added to results
588 if (!empty($params['field_name'])) {
589 $field_name = CRM_Utils_String
::munge($params['field_name']);
590 // Unique name contact_id = id
591 if ($field_name == 'contact_id') {
594 // phone_numeric should be phone
595 $searchField = str_replace('_numeric', '', $field_name);
596 if (!in_array($searchField, $list)) {
597 $list[] = $searchField;
601 $select = $actualSelectElements = array('sort_name');
604 foreach ($list as $value) {
605 $suffix = substr($value, 0, 2) . substr($value, -1);
607 case 'street_address':
610 $selectText = $value;
615 $actualSelectElements[] = $select[] = ($value == 'address') ?
$selectText : $value;
616 if ($value == 'phone') {
617 $actualSelectElements[] = $select[] = 'phone_ext';
619 $from[$value] = "LEFT JOIN civicrm_{$value} {$suffix} ON ( cc.id = {$suffix}.contact_id AND {$suffix}.is_primary = 1 ) ";
623 case 'state_province':
624 $select[] = "{$suffix}.name as {$value}";
625 $actualSelectElements[] = "{$suffix}.name";
626 if (!in_array('address', $from)) {
627 $from['address'] = 'LEFT JOIN civicrm_address sts ON ( cc.id = sts.contact_id AND sts.is_primary = 1) ';
629 $from[$value] = " LEFT JOIN civicrm_{$value} {$suffix} ON ( sts.{$value}_id = {$suffix}.id ) ";
633 if ($value != 'id') {
635 if (!empty($params['field_name']) && $params['field_name'] == 'value') {
636 $suffix = CRM_Utils_String
::munge(CRM_Utils_Array
::value('table_name', $params, 'cc'));
638 $actualSelectElements[] = $select[] = $suffix . '.' . $value;
644 $config = CRM_Core_Config
::singleton();
646 $select = implode(', ', $select);
647 if (!empty($select)) {
648 $select = ", $select";
650 $actualSelectElements = implode(', ', $actualSelectElements);
651 $selectAliases = $from;
652 unset($selectAliases['address']);
653 $selectAliases = implode(', ', array_keys($selectAliases));
654 if (!empty($selectAliases)) {
655 $selectAliases = ", $selectAliases";
657 $from = implode(' ', $from);
658 $limit = (int) CRM_Utils_Array
::value('limit', $params);
659 $limit = $limit > 0 ?
$limit : 10;
661 // add acl clause here
662 list($aclFrom, $aclWhere) = CRM_Contact_BAO_Contact_Permission
::cacheClause('cc');
665 $where .= " AND $aclWhere ";
668 if (!empty($params['org'])) {
669 $where .= " AND contact_type = \"Organization\"";
671 // CRM-7157, hack: get current employer details when
672 // employee_id is present.
673 $currEmpDetails = array();
674 if (!empty($params['employee_id'])) {
675 if ($currentEmployer = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact',
676 (int) $params['employee_id'],
679 if ($config->includeWildCardInName
) {
680 $strSearch = "%$name%";
683 $strSearch = "$name%";
686 // get current employer details
687 $dao = CRM_Core_DAO
::executeQuery("SELECT cc.id as id, CONCAT_WS( ' :: ', {$actualSelectElements} ) as data, sort_name
688 FROM civicrm_contact cc {$from} WHERE cc.contact_type = \"Organization\" AND cc.id = {$currentEmployer} AND cc.sort_name LIKE '$strSearch'");
690 $currEmpDetails = array(
692 'data' => $dao->data
,
699 if (!empty($params['contact_sub_type'])) {
700 $contactSubType = CRM_Utils_Type
::escape($params['contact_sub_type'], 'String');
701 $where .= " AND cc.contact_sub_type = '{$contactSubType}'";
704 if (!empty($params['contact_type'])) {
705 $contactType = CRM_Utils_Type
::escape($params['contact_type'], 'String');
706 $where .= " AND cc.contact_type LIKE '{$contactType}'";
709 //set default for current_employer or return contact with particular id
710 if (!empty($params['id'])) {
711 $where .= " AND cc.id = " . (int) $params['id'];
714 if (!empty($params['cid'])) {
715 $where .= " AND cc.id <> " . (int) $params['cid'];
718 //contact's based of relationhip type
720 if (!empty($params['rel'])) {
721 $relation = explode('_', CRM_Utils_Array
::value('rel', $params));
722 $relType = CRM_Utils_Type
::escape($relation[0], 'Integer');
723 $rel = CRM_Utils_Type
::escape($relation[2], 'String');
726 if ($config->includeWildCardInName
) {
727 $strSearch = "%$name%";
730 $strSearch = "$name%";
732 $includeEmailFrom = $includeNickName = $exactIncludeNickName = '';
733 if ($config->includeNickNameInName
) {
734 $includeNickName = " OR nick_name LIKE '$strSearch'";
735 $exactIncludeNickName = " OR nick_name LIKE '$name'";
739 if (!empty($params['field_name']) && !empty($params['table_name'])) {
740 $table_name = CRM_Utils_String
::munge($params['table_name']);
741 $whereClause = " WHERE ( $table_name.$field_name LIKE '$strSearch') {$where}";
742 $exactWhereClause = " WHERE ( $table_name.$field_name = '$name') {$where}";
743 // Search by id should be exact
744 if ($field_name == 'id' ||
$field_name == 'external_identifier') {
745 $whereClause = $exactWhereClause;
749 if ($config->includeEmailInName
) {
750 if (!in_array('email', $list)) {
751 $includeEmailFrom = "LEFT JOIN civicrm_email eml ON ( cc.id = eml.contact_id AND eml.is_primary = 1 )";
753 $whereClause = " WHERE ( email LIKE '$strSearch' OR sort_name LIKE '$strSearch' $includeNickName ) {$where} ";
754 $exactWhereClause = " WHERE ( email LIKE '$name' OR sort_name LIKE '$name' $exactIncludeNickName ) {$where} ";
757 $whereClause = " WHERE ( sort_name LIKE '$strSearch' $includeNickName ) {$where} ";
758 $exactWhereClause = " WHERE ( sort_name LIKE '$name' $exactIncludeNickName ) {$where} ";
762 $additionalFrom = '';
765 INNER JOIN civicrm_relationship_type r ON (
767 AND ( cc.contact_type = r.contact_type_{$rel} OR r.contact_type_{$rel} IS NULL )
768 AND ( cc.contact_sub_type = r.contact_sub_type_{$rel} OR r.contact_sub_type_{$rel} IS NULL )
772 // check if only CMS users are requested
773 if (!empty($params['cmsuser'])) {
775 INNER JOIN civicrm_uf_match um ON (um.contact_id=cc.id)
780 $orderByOuter = "ORDER BY exactFirst";
781 if ($config->includeOrderByClause
) {
782 $orderByInner = "ORDER BY sort_name";
783 $orderByOuter .= ", sort_name";
788 SELECT DISTINCT(id), data, sort_name {$selectAliases}
790 ( SELECT 0 as exactFirst, cc.id as id, CONCAT_WS( ' :: ', {$actualSelectElements} ) as data {$select}
791 FROM civicrm_contact cc {$from}
793 {$additionalFrom} {$includeEmailFrom}
797 ( SELECT 1 as exactFirst, cc.id as id, CONCAT_WS( ' :: ', {$actualSelectElements} ) as data {$select}
798 FROM civicrm_contact cc {$from}
800 {$additionalFrom} {$includeEmailFrom}
808 // send query to hook to be modified if needed
809 CRM_Utils_Hook
::contactListQuery($query,
811 empty($params['context']) ?
NULL : CRM_Utils_Type
::escape($params['context'], 'String'),
812 empty($params['id']) ?
NULL : $params['id']
815 $dao = CRM_Core_DAO
::executeQuery($query);
817 $contactList = array();
818 $listCurrentEmployer = TRUE;
819 while ($dao->fetch()) {
820 $t = array('id' => $dao->id
);
821 foreach ($as as $k) {
822 $t[$k] = isset($dao->$k) ?
$dao->$k : '';
824 $t['data'] = $dao->data
;
826 if (!empty($params['org']) &&
827 !empty($currEmpDetails) &&
828 $dao->id
== $currEmpDetails['id']
830 $listCurrentEmployer = FALSE;
834 //return organization name if doesn't exist in db
835 if (empty($contactList)) {
836 if (!empty($params['org'])) {
837 if ($listCurrentEmployer && !empty($currEmpDetails)) {
838 $contactList = array(
840 'data' => $currEmpDetails['data'],
841 'id' => $currEmpDetails['id'],
846 $contactList = array(
856 return civicrm_api3_create_success($contactList, $params, 'contact', 'getquick');
860 * @deprecated api notice
862 * Array of deprecated actions
864 function _civicrm_api3_contact_deprecation() {
865 return array('getquick' => 'The "getquick" action is deprecated in favor of "getlist".');
869 * Merges given pair of duplicate contacts.
871 * @param array $params
874 * Allowed @params array keys are:
875 * {int main_id main contact id with whom merge has to happen}
876 * {int other_id duplicate contact which would be deleted after merge operation}
877 * {string mode helps decide how to behave when there are conflicts.
878 * A 'safe' value skips the merge if there are no conflicts. Does a force merge otherwise.}
879 * {boolean auto_flip wether to let api decide which contact to retain and which to delete.}
887 function civicrm_api3_contact_merge($params) {
888 $mode = CRM_Utils_Array
::value('mode', $params, 'safe');
889 $autoFlip = CRM_Utils_Array
::value('auto_flip', $params, TRUE);
891 $dupePairs = array(array(
892 'srcID' => CRM_Utils_Array
::value('main_id', $params),
893 'dstID' => CRM_Utils_Array
::value('other_id', $params),
895 $result = CRM_Dedupe_Merger
::merge($dupePairs, array(), $mode, $autoFlip);
897 if ($result['is_error'] == 0) {
898 return civicrm_api3_create_success();
901 return civicrm_api3_create_error($result['messages']);
906 * @param array $params
908 function _civicrm_api3_contact_proximity_spec(&$params) {
909 $params['latitude']['api.required'] = 1;
910 $params['latitude']['title'] = 'Latitude';
911 $params['longitude']['api.required'] = 1;
912 $params['longitude']['title'] = 'Longitude';
913 $params['unit']['api.default'] = 'meter';
914 $params['unit']['title'] = 'Unit of Measurement';
918 * @param array $params
923 function civicrm_api3_contact_proximity($params) {
924 $latitude = CRM_Utils_Array
::value('latitude', $params);
925 $longitude = CRM_Utils_Array
::value('longitude', $params);
926 $distance = CRM_Utils_Array
::value('distance', $params);
928 $unit = CRM_Utils_Array
::value('unit', $params);
930 // check and ensure that lat/long and distance are floats
932 !CRM_Utils_Rule
::numeric($latitude) ||
933 !CRM_Utils_Rule
::numeric($longitude) ||
934 !CRM_Utils_Rule
::numeric($distance)
936 throw new Exception(ts('Latitude, Longitude and Distance should exist and be numeric'));
939 if ($unit == "mile") {
940 $conversionFactor = 1609.344;
943 $conversionFactor = 1000;
946 $distance = $distance * $conversionFactor;
948 $whereClause = CRM_Contact_BAO_ProximityQuery
::where($latitude, $longitude, $distance);
951 SELECT civicrm_contact.id as contact_id,
952 civicrm_contact.display_name as display_name
954 LEFT JOIN civicrm_address ON civicrm_contact.id = civicrm_address.contact_id
958 $dao = CRM_Core_DAO
::executeQuery($query);
960 while ($dao->fetch()) {
961 $contacts[] = $dao->toArray();
964 return civicrm_api3_create_success($contacts, $params, 'contact', 'get_by_location', $dao);
969 * @see _civicrm_api3_generic_getlist_params
974 function _civicrm_api3_contact_getlist_params(&$request) {
975 // get the autocomplete options from settings
976 $acpref = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
977 CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
,
978 'contact_autocomplete_options'
982 // get the option values for contact autocomplete
983 $acOptions = CRM_Core_OptionGroup
::values('contact_autocomplete_options', FALSE, FALSE, FALSE, NULL, 'name');
986 foreach ($acpref as $value) {
987 if ($value && !empty($acOptions[$value])) {
988 $list[] = $acOptions[$value];
991 // If we are doing quicksearch by a field other than name, make sure that field is added to results
992 $field_name = CRM_Utils_String
::munge($request['search_field']);
993 // Unique name contact_id = id
994 if ($field_name == 'contact_id') {
997 // phone_numeric should be phone
998 $searchField = str_replace('_numeric', '', $field_name);
999 if (!in_array($searchField, $list)) {
1000 $list[] = $searchField;
1002 $request['description_field'] = $list;
1003 $list[] = 'contact_type';
1004 $request['params']['return'] = array_unique(array_merge($list, $request['extra']));
1005 $request['params']['options']['sort'] = 'sort_name';
1006 // Contact api doesn't support array(LIKE => 'foo') syntax
1007 if (!empty($request['input'])) {
1008 $request['params'][$request['search_field']] = $request['input'];
1013 * @see _civicrm_api3_generic_getlist_output
1022 function _civicrm_api3_contact_getlist_output($result, $request) {
1024 if (!empty($result['values'])) {
1025 $addressFields = array_intersect(array('street_address', 'city', 'state_province', 'country'), $request['params']['return']);
1026 foreach ($result['values'] as $row) {
1028 'id' => $row[$request['id_field']],
1029 'label' => $row[$request['label_field']],
1030 'description' => array(),
1032 foreach ($request['description_field'] as $item) {
1033 if (!strpos($item, '_name') && !in_array($item, $addressFields) && !empty($row[$item])) {
1034 $data['description'][] = $row[$item];
1038 foreach ($addressFields as $item) {
1039 if (!empty($row[$item])) {
1040 $address[] = $row[$item];
1044 $data['description'][] = implode(' ', $address);
1046 if (!empty($request['image_field'])) {
1047 $data['image'] = isset($row[$request['image_field']]) ?
$row[$request['image_field']] : '';
1050 $data['icon_class'] = $row['contact_type'];
1052 foreach ($request['extra'] as $field) {
1053 $data['extra'][$field] = isset($row[$field]) ?
$row[$field] : NULL;