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 object
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 function civicrm_api3_contact_getquick($params) {
566 civicrm_api3_verify_mandatory($params, NULL, array('name'));
567 $name = CRM_Utils_Type
::escape(CRM_Utils_Array
::value('name', $params), 'String');
569 // get the autocomplete options from settings
570 $acpref = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
571 CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
,
572 'contact_autocomplete_options'
576 // get the option values for contact autocomplete
577 $acOptions = CRM_Core_OptionGroup
::values('contact_autocomplete_options', FALSE, FALSE, FALSE, NULL, 'name');
580 foreach ($acpref as $value) {
581 if ($value && !empty($acOptions[$value])) {
582 $list[$value] = $acOptions[$value];
585 // If we are doing quicksearch by a field other than name, make sure that field is added to results
586 if (!empty($params['field_name'])) {
587 $field_name = CRM_Utils_String
::munge($params['field_name']);
588 // Unique name contact_id = id
589 if ($field_name == 'contact_id') {
592 // phone_numeric should be phone
593 $searchField = str_replace('_numeric', '', $field_name);
594 if (!in_array($searchField, $list)) {
595 $list[] = $searchField;
599 $select = $actualSelectElements = array('sort_name');
602 foreach ($list as $value) {
603 $suffix = substr($value, 0, 2) . substr($value, -1);
605 case 'street_address':
608 $selectText = $value;
613 $actualSelectElements[] = $select[] = ($value == 'address') ?
$selectText : $value;
614 if ($value == 'phone') {
615 $actualSelectElements[] = $select[] = 'phone_ext';
617 $from[$value] = "LEFT JOIN civicrm_{$value} {$suffix} ON ( cc.id = {$suffix}.contact_id AND {$suffix}.is_primary = 1 ) ";
621 case 'state_province':
622 $select[] = "{$suffix}.name as {$value}";
623 $actualSelectElements[] = "{$suffix}.name";
624 if (!in_array('address', $from)) {
625 $from['address'] = 'LEFT JOIN civicrm_address sts ON ( cc.id = sts.contact_id AND sts.is_primary = 1) ';
627 $from[$value] = " LEFT JOIN civicrm_{$value} {$suffix} ON ( sts.{$value}_id = {$suffix}.id ) ";
631 if ($value != 'id') {
633 if (!empty($params['field_name']) && $params['field_name'] == 'value') {
634 $suffix = CRM_Utils_String
::munge(CRM_Utils_Array
::value('table_name', $params, 'cc'));
636 $actualSelectElements[] = $select[] = $suffix . '.' . $value;
642 $config = CRM_Core_Config
::singleton();
644 $select = implode(', ', $select);
645 if (!empty($select)) {
646 $select = ", $select";
648 $actualSelectElements = implode(', ', $actualSelectElements);
649 $selectAliases = $from;
650 unset($selectAliases['address']);
651 $selectAliases = implode(', ', array_keys($selectAliases));
652 if (!empty($selectAliases)) {
653 $selectAliases = ", $selectAliases";
655 $from = implode(' ', $from);
656 $limit = (int) CRM_Utils_Array
::value('limit', $params);
657 $limit = $limit > 0 ?
$limit : 10;
659 // add acl clause here
660 list($aclFrom, $aclWhere) = CRM_Contact_BAO_Contact_Permission
::cacheClause('cc');
663 $where .= " AND $aclWhere ";
666 if (!empty($params['org'])) {
667 $where .= " AND contact_type = \"Organization\"";
669 // CRM-7157, hack: get current employer details when
670 // employee_id is present.
671 $currEmpDetails = array();
672 if (!empty($params['employee_id'])) {
673 if ($currentEmployer = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact',
674 (int) $params['employee_id'],
677 if ($config->includeWildCardInName
) {
678 $strSearch = "%$name%";
681 $strSearch = "$name%";
684 // get current employer details
685 $dao = CRM_Core_DAO
::executeQuery("SELECT cc.id as id, CONCAT_WS( ' :: ', {$actualSelectElements} ) as data, sort_name
686 FROM civicrm_contact cc {$from} WHERE cc.contact_type = \"Organization\" AND cc.id = {$currentEmployer} AND cc.sort_name LIKE '$strSearch'");
688 $currEmpDetails = array(
690 'data' => $dao->data
,
697 if (!empty($params['contact_sub_type'])) {
698 $contactSubType = CRM_Utils_Type
::escape($params['contact_sub_type'], 'String');
699 $where .= " AND cc.contact_sub_type = '{$contactSubType}'";
702 if (!empty($params['contact_type'])) {
703 $contactType = CRM_Utils_Type
::escape($params['contact_type'], 'String');
704 $where .= " AND cc.contact_type LIKE '{$contactType}'";
707 //set default for current_employer or return contact with particular id
708 if (!empty($params['id'])) {
709 $where .= " AND cc.id = " . (int) $params['id'];
712 if (!empty($params['cid'])) {
713 $where .= " AND cc.id <> " . (int) $params['cid'];
716 //contact's based of relationhip type
718 if (!empty($params['rel'])) {
719 $relation = explode('_', CRM_Utils_Array
::value('rel', $params));
720 $relType = CRM_Utils_Type
::escape($relation[0], 'Integer');
721 $rel = CRM_Utils_Type
::escape($relation[2], 'String');
724 if ($config->includeWildCardInName
) {
725 $strSearch = "%$name%";
728 $strSearch = "$name%";
730 $includeEmailFrom = $includeNickName = $exactIncludeNickName = '';
731 if ($config->includeNickNameInName
) {
732 $includeNickName = " OR nick_name LIKE '$strSearch'";
733 $exactIncludeNickName = " OR nick_name LIKE '$name'";
737 if (!empty($params['field_name']) && !empty($params['table_name'])) {
738 $table_name = CRM_Utils_String
::munge($params['table_name']);
739 $whereClause = " WHERE ( $table_name.$field_name LIKE '$strSearch') {$where}";
740 $exactWhereClause = " WHERE ( $table_name.$field_name = '$name') {$where}";
741 // Search by id should be exact
742 if ($field_name == 'id' ||
$field_name == 'external_identifier') {
743 $whereClause = $exactWhereClause;
747 if ($config->includeEmailInName
) {
748 if (!in_array('email', $list)) {
749 $includeEmailFrom = "LEFT JOIN civicrm_email eml ON ( cc.id = eml.contact_id AND eml.is_primary = 1 )";
751 $whereClause = " WHERE ( email LIKE '$strSearch' OR sort_name LIKE '$strSearch' $includeNickName ) {$where} ";
752 $exactWhereClause = " WHERE ( email LIKE '$name' OR sort_name LIKE '$name' $exactIncludeNickName ) {$where} ";
755 $whereClause = " WHERE ( sort_name LIKE '$strSearch' $includeNickName ) {$where} ";
756 $exactWhereClause = " WHERE ( sort_name LIKE '$name' $exactIncludeNickName ) {$where} ";
760 $additionalFrom = '';
763 INNER JOIN civicrm_relationship_type r ON (
765 AND ( cc.contact_type = r.contact_type_{$rel} OR r.contact_type_{$rel} IS NULL )
766 AND ( cc.contact_sub_type = r.contact_sub_type_{$rel} OR r.contact_sub_type_{$rel} IS NULL )
770 // check if only CMS users are requested
771 if (!empty($params['cmsuser'])) {
773 INNER JOIN civicrm_uf_match um ON (um.contact_id=cc.id)
778 $orderByOuter = "ORDER BY exactFirst";
779 if ($config->includeOrderByClause
) {
780 $orderByInner = "ORDER BY sort_name";
781 $orderByOuter .= ", sort_name";
786 SELECT DISTINCT(id), data, sort_name {$selectAliases}
788 ( SELECT 0 as exactFirst, cc.id as id, CONCAT_WS( ' :: ', {$actualSelectElements} ) as data {$select}
789 FROM civicrm_contact cc {$from}
791 {$additionalFrom} {$includeEmailFrom}
795 ( SELECT 1 as exactFirst, cc.id as id, CONCAT_WS( ' :: ', {$actualSelectElements} ) as data {$select}
796 FROM civicrm_contact cc {$from}
798 {$additionalFrom} {$includeEmailFrom}
806 // send query to hook to be modified if needed
807 CRM_Utils_Hook
::contactListQuery($query,
809 empty($params['context']) ?
NULL : CRM_Utils_Type
::escape($params['context'], 'String'),
810 empty($params['id']) ?
NULL : $params['id']
813 $dao = CRM_Core_DAO
::executeQuery($query);
815 $contactList = array();
816 $listCurrentEmployer = TRUE;
817 while ($dao->fetch()) {
818 $t = array('id' => $dao->id
);
819 foreach ($as as $k) {
820 $t[$k] = isset($dao->$k) ?
$dao->$k : '';
822 $t['data'] = $dao->data
;
824 if (!empty($params['org']) &&
825 !empty($currEmpDetails) &&
826 $dao->id
== $currEmpDetails['id']
828 $listCurrentEmployer = FALSE;
832 //return organization name if doesn't exist in db
833 if (empty($contactList)) {
834 if (!empty($params['org'])) {
835 if ($listCurrentEmployer && !empty($currEmpDetails)) {
836 $contactList = array(
838 'data' => $currEmpDetails['data'],
839 'id' => $currEmpDetails['id'],
844 $contactList = array(
854 return civicrm_api3_create_success($contactList, $params, 'contact', 'getquick');
858 * @deprecated api notice
860 * of deprecated actions
862 function _civicrm_api3_contact_deprecation() {
863 return array('getquick' => 'The "getquick" action is deprecated in favor of "getlist".');
867 * Merges given pair of duplicate contacts.
869 * @param array $params
872 * Allowed @params array keys are:
873 * {int main_id main contact id with whom merge has to happen}
874 * {int other_id duplicate contact which would be deleted after merge operation}
875 * {string mode helps decide how to behave when there are conflicts.
876 * A 'safe' value skips the merge if there are no conflicts. Does a force merge otherwise.}
877 * {boolean auto_flip wether to let api decide which contact to retain and which to delete.}
885 function civicrm_api3_contact_merge($params) {
886 $mode = CRM_Utils_Array
::value('mode', $params, 'safe');
887 $autoFlip = CRM_Utils_Array
::value('auto_flip', $params, TRUE);
889 $dupePairs = array(array(
890 'srcID' => CRM_Utils_Array
::value('main_id', $params),
891 'dstID' => CRM_Utils_Array
::value('other_id', $params),
893 $result = CRM_Dedupe_Merger
::merge($dupePairs, array(), $mode, $autoFlip);
895 if ($result['is_error'] == 0) {
896 return civicrm_api3_create_success();
899 return civicrm_api3_create_error($result['messages']);
904 * @param array $params
906 function _civicrm_api3_contact_proximity_spec(&$params) {
907 $params['latitude']['api.required'] = 1;
908 $params['latitude']['title'] = 'Latitude';
909 $params['longitude']['api.required'] = 1;
910 $params['longitude']['title'] = 'Longitude';
911 $params['unit']['api.default'] = 'meter';
912 $params['unit']['title'] = 'Unit of Measurement';
916 * @param array $params
921 function civicrm_api3_contact_proximity($params) {
922 $latitude = CRM_Utils_Array
::value('latitude', $params);
923 $longitude = CRM_Utils_Array
::value('longitude', $params);
924 $distance = CRM_Utils_Array
::value('distance', $params);
926 $unit = CRM_Utils_Array
::value('unit', $params);
928 // check and ensure that lat/long and distance are floats
930 !CRM_Utils_Rule
::numeric($latitude) ||
931 !CRM_Utils_Rule
::numeric($longitude) ||
932 !CRM_Utils_Rule
::numeric($distance)
934 throw new Exception(ts('Latitude, Longitude and Distance should exist and be numeric'));
937 if ($unit == "mile") {
938 $conversionFactor = 1609.344;
941 $conversionFactor = 1000;
944 $distance = $distance * $conversionFactor;
946 $whereClause = CRM_Contact_BAO_ProximityQuery
::where($latitude, $longitude, $distance);
949 SELECT civicrm_contact.id as contact_id,
950 civicrm_contact.display_name as display_name
952 LEFT JOIN civicrm_address ON civicrm_contact.id = civicrm_address.contact_id
956 $dao = CRM_Core_DAO
::executeQuery($query);
958 while ($dao->fetch()) {
959 $contacts[] = $dao->toArray();
962 return civicrm_api3_create_success($contacts, $params, 'contact', 'get_by_location', $dao);
967 * @see _civicrm_api3_generic_getlist_params
972 function _civicrm_api3_contact_getlist_params(&$request) {
973 // get the autocomplete options from settings
974 $acpref = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
975 CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
,
976 'contact_autocomplete_options'
980 // get the option values for contact autocomplete
981 $acOptions = CRM_Core_OptionGroup
::values('contact_autocomplete_options', FALSE, FALSE, FALSE, NULL, 'name');
984 foreach ($acpref as $value) {
985 if ($value && !empty($acOptions[$value])) {
986 $list[] = $acOptions[$value];
989 // If we are doing quicksearch by a field other than name, make sure that field is added to results
990 $field_name = CRM_Utils_String
::munge($request['search_field']);
991 // Unique name contact_id = id
992 if ($field_name == 'contact_id') {
995 // phone_numeric should be phone
996 $searchField = str_replace('_numeric', '', $field_name);
997 if (!in_array($searchField, $list)) {
998 $list[] = $searchField;
1000 $request['description_field'] = $list;
1001 $list[] = 'contact_type';
1002 $request['params']['return'] = array_unique(array_merge($list, $request['extra']));
1003 $request['params']['options']['sort'] = 'sort_name';
1004 // Contact api doesn't support array(LIKE => 'foo') syntax
1005 if (!empty($request['input'])) {
1006 $request['params'][$request['search_field']] = $request['input'];
1011 * @see _civicrm_api3_generic_getlist_output
1020 function _civicrm_api3_contact_getlist_output($result, $request) {
1022 if (!empty($result['values'])) {
1023 $addressFields = array_intersect(array('street_address', 'city', 'state_province', 'country'), $request['params']['return']);
1024 foreach ($result['values'] as $row) {
1026 'id' => $row[$request['id_field']],
1027 'label' => $row[$request['label_field']],
1028 'description' => array(),
1030 foreach ($request['description_field'] as $item) {
1031 if (!strpos($item, '_name') && !in_array($item, $addressFields) && !empty($row[$item])) {
1032 $data['description'][] = $row[$item];
1036 foreach ($addressFields as $item) {
1037 if (!empty($row[$item])) {
1038 $address[] = $row[$item];
1042 $data['description'][] = implode(' ', $address);
1044 if (!empty($request['image_field'])) {
1045 $data['image'] = isset($row[$request['image_field']]) ?
$row[$request['image_field']] : '';
1048 $data['icon_class'] = $row['contact_type'];
1050 foreach ($request['extra'] as $field) {
1051 $data['extra'][$field] = isset($row[$field]) ?
$row[$field] : NULL;