5 +--------------------------------------------------------------------+
6 | CiviCRM version 4.3 |
7 +--------------------------------------------------------------------+
8 | Copyright CiviCRM LLC (c) 2004-2013 |
9 +--------------------------------------------------------------------+
10 | This file is a part of CiviCRM. |
12 | CiviCRM is free software; you can copy, modify, and distribute it |
13 | under the terms of the GNU Affero General Public License |
14 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
16 | CiviCRM is distributed in the hope that it will be useful, but |
17 | WITHOUT ANY WARRANTY; without even the implied warranty of |
18 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
19 | See the GNU Affero General Public License for more details. |
21 | You should have received a copy of the GNU Affero General Public |
22 | License and the CiviCRM Licensing Exception along |
23 | with this program; if not, contact CiviCRM LLC |
24 | at info[AT]civicrm[DOT]org. If you have questions about the |
25 | GNU Affero General Public License or the licensing of CiviCRM, |
26 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
27 +--------------------------------------------------------------------+
31 * new version of civicrm apis. See blog post at
32 * http://civicrm.org/node/131
35 * @package CiviCRM_APIv3
36 * @subpackage API_Contact
37 * @copyright CiviCRM LLC (c) 2004-2013
38 * $Id: Contact.php 30879 2010-11-22 15:45:55Z shot $
43 * Create or update a contact (note you should always call this via civicrm_api() & never directly)
45 * @param array $params input parameters
47 * Allowed @params array keys are:
48 * {@getfields contact_create}
51 * @example ContactCreate.php Example of Create Call
53 * @return array API Result Array
58 function civicrm_api3_contact_create($params) {
60 $contactID = CRM_Utils_Array
::value('contact_id', $params, CRM_Utils_Array
::value('id', $params));
61 $dupeCheck = CRM_Utils_Array
::value('dupe_check', $params, FALSE);
62 $values = _civicrm_api3_contact_check_params($params, $dupeCheck);
68 // If we get here, we're ready to create a new contact
69 if (($email = CRM_Utils_Array
::value('email', $params)) && !is_array($params['email'])) {
70 $defLocType = CRM_Core_BAO_LocationType
::getDefault();
71 $params['email'] = array(
72 1 => array('email' => $email,
74 'location_type_id' => ($defLocType->id
) ?
$defLocType->id
: 1,
80 if (!empty($params['home_url'])) {
81 $websiteTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Website', 'website_type_id');
82 $params['website'] = array(1 => array('website_type_id' => key($websiteTypes),
83 'url' => $params['home_url'],
88 if (isset($params['suffix_id']) && !(is_numeric($params['suffix_id']))) {
89 $params['suffix_id'] = array_search($params['suffix_id'], CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'suffix_id'));
92 if (isset($params['prefix_id']) && !(is_numeric($params['prefix_id']))) {
93 $params['prefix_id'] = array_search($params['prefix_id'], CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'prefix_id'));
96 if (isset($params['gender_id']) && !(is_numeric($params['gender_id']))) {
97 $params['gender_id'] = array_search($params['gender_id'], CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'gender_id'));
100 $error = _civicrm_api3_greeting_format_params($params);
101 if (civicrm_error($error)) {
106 $entityId = $contactID;
108 if (empty($params['contact_type']) && $entityId) {
109 $params['contact_type'] = CRM_Contact_BAO_Contact
::getContactType($entityId);
112 if (!isset($params['contact_sub_type']) && $entityId) {
113 $params['contact_sub_type'] = CRM_Contact_BAO_Contact
::getContactSubType($entityId);
116 _civicrm_api3_custom_format_params($params, $values, $params['contact_type'], $entityId);
118 $params = array_merge($params, $values);
120 $contact = _civicrm_api3_contact_update($params, $contactID);
122 if (is_a($contact, 'CRM_Core_Error')) {
123 return civicrm_api3_create_error($contact->_errors
[0]['message']);
127 _civicrm_api3_object_to_array_unique_fields($contact, $values[$contact->id
]);
130 return civicrm_api3_create_success($values, $params, 'Contact', 'create');
134 * Adjust Metadata for Create action
136 * @param array $params array or parameters determined by getfields
138 function _civicrm_api3_contact_create_spec(&$params) {
139 $params['contact_type']['api.required'] = 1;
140 $params['id']['api.aliases'] = array('contact_id');
141 $params['current_employer'] = array(
142 'title' => 'Current Employer',
143 'description' => 'Name of Current Employer',
145 $params['dupe_check'] = array(
146 'title' => 'Check for Duplicates',
147 'description' => 'Throw error if contact create matches dedupe rule',
152 * Retrieve one or more contacts, given a set of search params
154 * @param array input parameters
156 * @return array API Result Array
157 * (@getfields contact_get}
161 * @example ContactGet.php Standard GET example
164 function civicrm_api3_contact_get($params) {
166 _civicrm_api3_contact_get_supportanomalies($params, $options);
167 $contacts = _civicrm_api3_get_using_query_object('contact', $params, $options);
169 // CRM-7929 Quick fix by colemanw
170 // TODO: Figure out what function is responsible for prepending 'individual_' to these keys
171 // and sort it out there rather than going to all this trouble here.
172 // Eileen's note - not sure anymore if we went the right path stripping the 'individual' here
173 // as is arguable whether it makes more sense now I think it would make more sense to rename the table field or uniquefield to have
174 // the individual prefix but we are stuck with it now for apiv3 series.
175 $returnContacts = array();
176 if (is_array($contacts)) {
177 foreach ($contacts as $cid => $contact) {
178 if (is_array($contact)) {
179 $returnContacts[$cid] = array();
180 foreach ($contact as $key => $value) {
181 $key = str_replace(array('individual_prefix', 'individual_suffix'), array('prefix', 'suffix'), $key);
182 $returnContacts[$cid][$key] = $value;
187 return civicrm_api3_create_success($returnContacts, $params, 'contact');
190 function civicrm_api3_contact_getcount($params) {
192 _civicrm_api3_contact_get_supportanomalies($params, $options);
193 $count = _civicrm_api3_get_using_query_object('contact', $params, $options,1);
198 * Adjust Metadata for Get action
200 * @param array $params array or parameters determined by getfields
202 function _civicrm_api3_contact_get_spec(&$params) {
203 $params['contact_is_deleted']['api.default'] = 0;
205 //we declare all these pseudofields as there are other undocumented fields accessible
206 // via the api - but if check permissions is set we only allow declared fields
207 $params['address_id']['title'] = 'Primary Address ID';
208 $params['street_address']['title'] = 'Primary Address Street Address';
209 $params['supplemental_address_1']['title'] = 'Primary Address Supplemental Address 1';
210 $params['supplemental_address_2']['title'] = 'Primary Address Supplemental Address 2';
211 $params['city']['title'] = 'Primary Address City';
212 $params['postal_code_suffix']['title'] = 'Primary Address Post Code Suffix';
213 $params['postal_code']['title'] = 'Primary Address Post Code';
214 $params['geo_code_1']['title'] = 'Primary Address Latitude';
215 $params['geo_code_2']['title'] = 'Primary Address Longitude';
216 $params['state_province_id']['title'] = 'Primary Address State Province ID';
217 $params['state_province_name']['title'] = 'Primary Address State Province Name';
218 $params['state_province']['title'] = 'Primary Address State Province';
219 $params['country_id']['title'] = 'Primary Address State Province ID';
220 $params['country']['title'] = 'Primary Address country';
221 $params['worldregion_id']['title'] = 'Primary Address World Region ID';
222 $params['worldregion']['title'] = 'Primary Address World Region';
223 $params['phone_id']['title'] = 'Primary Phone ID';
224 $params['phone_type_id']['title'] = 'Primary Phone Type ID';
225 $params['provider_id']['title'] = 'Primary Phone Provider ID';
226 $params['email_id']['title'] = 'Primary Email ID';
227 $params['email']['title'] = 'Primary Email';
228 $params['on_hold']['title'] = 'Primary Email On Hold';
229 $params['im']['title'] = 'Primary Instant Messanger';
230 $params['im_id']['title'] = 'Primary Instant Messanger ID';
231 $params['group_id']['title'] = 'Group Memberships (filter)';
232 $params['group']['title'] = 'Group Memberships (filter, array)';
233 $params['tag']['title'] = 'Assigned tags (filter, array)';
237 * We are supporting 'showAll' = 'all', 'trash' or 'active' for contact get
239 * - hopefully some day we'll come up with a std syntax for the 3-way-boolean of
242 * We also support 'filter_group_id' & 'filter.group_id'
244 * @param array $params as passed into api get or getcount function
245 * @param array $options array of options (so we can modify the filter)
247 function _civicrm_api3_contact_get_supportanomalies(&$params, &$options) {
248 if (isset($params['showAll'])) {
249 if (strtolower($params['showAll']) == "active") {
250 $params['contact_is_deleted'] = 0;
252 if (strtolower($params['showAll']) == "trash") {
253 $params['contact_is_deleted'] = 1;
255 if (strtolower($params['showAll']) == "all" && isset($params['contact_is_deleted'])) {
256 unset($params['contact_is_deleted']);
259 // support for group filters
260 if (array_key_exists('filter_group_id', $params)) {
261 $params['filter.group_id'] = $params['filter_group_id'];
262 unset($params['filter_group_id']);
264 // filter.group_id works both for 1,2,3 and array (1,2,3)
265 if (array_key_exists('filter.group_id', $params)) {
266 if (is_array($params['filter.group_id'])) {
267 $groups = $params['filter.group_id'];
269 else $groups = explode(',', $params['filter.group_id']);
270 unset($params['filter.group_id']);
271 $groups = array_flip($groups);
272 $groups[key($groups)] = 1;
273 $options['input_params']['group'] = $groups;
278 * Delete a contact with given contact id
280 * @param array $params (reference ) input parameters, contact_id element required
282 * @return array API Result Array
285 * @example ContactDelete.php
286 * {@getfields contact_delete}
288 function civicrm_api3_contact_delete($params) {
290 $contactID = CRM_Utils_Array
::value('id', $params);
292 $session = CRM_Core_Session
::singleton();
293 if ($contactID == $session->get('userID')) {
294 return civicrm_api3_create_error('This contact record is linked to the currently logged in user account - and cannot be deleted.');
296 $restore = CRM_Utils_Array
::value('restore', $params) ?
$params['restore'] : FALSE;
297 $skipUndelete = CRM_Utils_Array
::value('skip_undelete', $params) ?
$params['skip_undelete'] : FALSE;
300 // restrict permanent delete if a contact has financial trxn associated with it
302 if ($skipUndelete && CRM_Financial_BAO_FinancialItem
::checkContactPresent(array($contactID), $error)) {
303 return civicrm_api3_create_error($error['_qf_default']);
305 if (CRM_Contact_BAO_Contact
::deleteContact($contactID, $restore, $skipUndelete)) {
306 return civicrm_api3_create_success();
309 return civicrm_api3_create_error('Could not delete contact');
314 function _civicrm_api3_contact_check_params( &$params, $dupeCheck = true, $dupeErrorArray = false, $obsoletevalue = true, $dedupeRuleGroupID = null )
317 switch (strtolower(CRM_Utils_Array
::value('contact_type', $params))) {
319 civicrm_api3_verify_mandatory($params, null, array('household_name'));
322 civicrm_api3_verify_mandatory($params, null, array('organization_name'));
325 civicrm_api3_verify_one_mandatory($params, null, array(
335 if (CRM_Utils_Array
::value('contact_sub_type', $params) && CRM_Utils_Array
::value('contact_type', $params)) {
336 if (!(CRM_Contact_BAO_ContactType
::isExtendsContactType($params['contact_sub_type'], $params['contact_type']))) {
337 return civicrm_api3_create_error("Invalid or Mismatched Contact SubType: " . implode(', ', (array)$params['contact_sub_type']));
342 // check for record already existing
343 $dedupeParams = CRM_Dedupe_Finder
::formatParams($params, $params['contact_type']);
346 // setting 'check_permission' here means that the dedupe checking will be carried out even if the
347 // person does not have permission to carry out de-dupes
348 // this is similar to the front end form
349 if (isset($params['check_permission'])) {
350 $dedupeParams['check_permission'] = $params['check_permission'];
353 $ids = CRM_Dedupe_Finder
::dupesByParams($dedupeParams, $params['contact_type'], 'Strict', array());
355 if (count($ids) >0) {
356 throw new API_Exception("Found matching contacts: ". implode(',',$ids),"duplicate",array("ids"=>$ids));
360 //check for organisations with same name
361 if (!empty($params['current_employer'])) {
362 $organizationParams = array();
363 $organizationParams['organization_name'] = $params['current_employer'];
365 $dedupParams = CRM_Dedupe_Finder
::formatParams($organizationParams, 'Organization');
367 $dedupParams['check_permission'] = FALSE;
368 $dupeIds = CRM_Dedupe_Finder
::dupesByParams($dedupParams, 'Organization', 'Supervised');
370 // check for mismatch employer name and id
371 if (!empty($params['employer_id']) && !in_array($params['employer_id'], $dupeIds)) {
372 throw new API_Exception('Employer name and Employer id Mismatch');
375 // show error if multiple organisation with same name exist
376 if (empty($params['employer_id']) && (count($dupeIds) > 1)) {
377 throw new API_Exception('Found more than one Organisation with same Name.');
385 * Takes an associative array and creates a contact object and all the associated
386 * derived objects (i.e. individual, location, email, phone etc)
388 * @param array $params (reference ) an assoc array of name/value pairs
389 * @param int $contactID if present the contact with that ID is updated
391 * @return object CRM_Contact_BAO_Contact object
395 function _civicrm_api3_contact_update($params, $contactID = NULL) {
396 $transaction = new CRM_Core_Transaction();
399 $params['contact_id'] = $contactID;
402 $contact = CRM_Contact_BAO_Contact
::create($params);
404 $transaction->commit();
410 * Validate the addressee or email or postal greetings
412 * @param $params Associative array of property name/value
413 * pairs to insert in new contact.
415 * @return array (reference ) null on success, error message otherwise
419 function _civicrm_api3_greeting_format_params($params) {
420 $greetingParams = array('', '_id', '_custom');
421 foreach (array('email', 'postal', 'addressee') as $key) {
422 $greeting = '_greeting';
423 if ($key == 'addressee') {
427 $formatParams = FALSE;
428 // unset display value from params.
429 if (isset($params["{$key}{$greeting}_display"])) {
430 unset($params["{$key}{$greeting}_display"]);
433 // check if greetings are present in present
434 foreach ($greetingParams as $greetingValues) {
435 if (array_key_exists("{$key}{$greeting}{$greetingValues}", $params)) {
436 $formatParams = TRUE;
441 if (!$formatParams) {
447 'contact_type' => $params['contact_type'],
448 'greeting_type' => "{$key}{$greeting}",
451 $greetings = CRM_Core_PseudoConstant
::greeting($filter);
452 $greetingId = CRM_Utils_Array
::value("{$key}{$greeting}_id", $params);
453 $greetingVal = CRM_Utils_Array
::value("{$key}{$greeting}", $params);
454 $customGreeting = CRM_Utils_Array
::value("{$key}{$greeting}_custom", $params);
456 if (!$greetingId && $greetingVal) {
457 $params["{$key}{$greeting}_id"] = CRM_Utils_Array
::key($params["{$key}{$greeting}"], $greetings);
460 if ($customGreeting && $greetingId &&
461 ($greetingId != array_search('Customized', $greetings))
463 return civicrm_api3_create_error(ts('Provide either %1 greeting id and/or %1 greeting or custom %1 greeting',
468 if ($greetingVal && $greetingId &&
469 ($greetingId != CRM_Utils_Array
::key($greetingVal, $greetings))
471 return civicrm_api3_create_error(ts('Mismatch in %1 greeting id and %1 greeting',
478 if (!array_key_exists($greetingId, $greetings)) {
479 return civicrm_api3_create_error(ts('Invalid %1 greeting Id', array(1 => $key)));
482 if (!$customGreeting && ($greetingId == array_search('Customized', $greetings))) {
483 return civicrm_api3_create_error(ts('Please provide a custom value for %1 greeting',
488 elseif ($greetingVal) {
490 if (!in_array($greetingVal, $greetings)) {
491 return civicrm_api3_create_error(ts('Invalid %1 greeting', array(1 => $key)));
494 $greetingId = CRM_Utils_Array
::key($greetingVal, $greetings);
497 if ($customGreeting) {
498 $greetingId = CRM_Utils_Array
::key('Customized', $greetings);
501 $customValue = $params['contact_id'] ? CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact',
502 $params['contact_id'],
503 "{$key}{$greeting}_custom"
506 if (array_key_exists("{$key}{$greeting}_id", $params) && empty($params["{$key}{$greeting}_id"])) {
509 elseif (array_key_exists("{$key}{$greeting}", $params) && empty($params["{$key}{$greeting}"])) {
512 elseif ($customValue && array_key_exists("{$key}{$greeting}_custom", $params)
513 && empty($params["{$key}{$greeting}_custom"])
518 $params["{$key}{$greeting}_id"] = $greetingId;
520 if (!$customValue && !$customGreeting && array_key_exists("{$key}{$greeting}_custom", $params)) {
521 unset($params["{$key}{$greeting}_custom"]);
525 $params["{$key}{$greeting}_id"] = '';
526 $params["{$key}{$greeting}_custom"] = '';
529 if (isset($params["{$key}{$greeting}"])) {
530 unset($params["{$key}{$greeting}"]);
536 * Contact quick search api
540 * {@example ContactGetquick.php 0}
543 function civicrm_api3_contact_quicksearch($params) {
544 // kept as an alias for compatibility reasons. CRM-11136
545 return civicrm_api3_contact_getquick($params);
548 function civicrm_api3_contact_getquick($params) {
549 civicrm_api3_verify_mandatory($params, NULL, array('name'));
550 $name = CRM_Utils_Type
::escape($params['name'], 'String');
552 // get the autocomplete options from settings
553 $acpref = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
554 CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
,
555 'contact_autocomplete_options'
559 // get the option values for contact autocomplete
560 $acOptions = CRM_Core_OptionGroup
::values('contact_autocomplete_options', FALSE, FALSE, FALSE, NULL, 'name');
563 foreach ($acpref as $value) {
564 if ($value && CRM_Utils_Array
::value($value, $acOptions)) {
565 $list[$value] = $acOptions[$value];
568 // If we are doing quicksearch by a field other than name, make sure that field is added to results
569 if (!empty($params['field_name'])) {
570 $field_name = CRM_Utils_String
::munge($params['field_name']);
571 // Unique name contact_id = id
572 if ($field_name == 'contact_id') {
575 // phone_numeric should be phone
576 $searchField = str_replace('_numeric', '', $field_name);
577 if(!in_array($searchField, $list)) {
578 $list[] = $searchField;
582 $select = $actualSelectElements = array('sort_name');
585 foreach ($list as $value) {
586 $suffix = substr($value, 0, 2) . substr($value, -1);
588 case 'street_address':
591 $selectText = $value;
596 $actualSelectElements[] = $select[] = ($value == 'address') ?
$selectText : $value;
597 $from[$value] = "LEFT JOIN civicrm_{$value} {$suffix} ON ( cc.id = {$suffix}.contact_id AND {$suffix}.is_primary = 1 ) ";
601 case 'state_province':
602 $select[] = "{$suffix}.name as {$value}";
603 $actualSelectElements[] = "{$suffix}.name";
604 if (!in_array('address', $from)) {
605 $from['address'] = 'LEFT JOIN civicrm_address sts ON ( cc.id = sts.contact_id AND sts.is_primary = 1) ';
607 $from[$value] = " LEFT JOIN civicrm_{$value} {$suffix} ON ( sts.{$value}_id = {$suffix}.id ) ";
611 if ($value != 'id') {
613 if (!empty($params['field_name']) && $params['field_name'] == 'value') {
614 $suffix = CRM_Utils_String
::munge(CRM_Utils_Array
::value('table_name', $params, 'cc'));
616 $actualSelectElements[] = $select[] = $suffix . '.' . $value;
622 $config = CRM_Core_Config
::singleton();
624 $select = implode(', ', $select);
625 if (!empty($select)) {
626 $select = ", $select";
628 $actualSelectElements = implode(', ', $actualSelectElements);
629 $selectAliases = $from;
630 unset($selectAliases['address']);
631 $selectAliases = implode(', ', array_keys($selectAliases));
632 if (!empty($selectAliases)) {
633 $selectAliases = ", $selectAliases";
635 $from = implode(' ', $from);
636 $limit = (int) CRM_Utils_Array
::value('limit', $params);
637 $limit = $limit > 0 ?
$limit : 10;
639 // add acl clause here
640 list($aclFrom, $aclWhere) = CRM_Contact_BAO_Contact_Permission
::cacheClause('cc');
643 $where .= " AND $aclWhere ";
646 if (CRM_Utils_Array
::value('org', $params)) {
647 $where .= " AND contact_type = \"Organization\"";
649 // CRM-7157, hack: get current employer details when
650 // employee_id is present.
651 $currEmpDetails = array();
652 if (CRM_Utils_Array
::value('employee_id', $params)) {
653 if ($currentEmployer = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact',
654 (int) $params['employee_id'],
657 if ($config->includeWildCardInName
) {
658 $strSearch = "%$name%";
661 $strSearch = "$name%";
664 // get current employer details
665 $dao = CRM_Core_DAO
::executeQuery("SELECT cc.id as id, CONCAT_WS( ' :: ', {$actualSelectElements} ) as data, sort_name
666 FROM civicrm_contact cc {$from} WHERE cc.contact_type = \"Organization\" AND cc.id = {$currentEmployer} AND cc.sort_name LIKE '$strSearch'");
668 $currEmpDetails = array(
670 'data' => $dao->data
,
677 //set default for current_employer or return contact with particular id
678 if (CRM_Utils_Array
::value('id', $params)) {
679 $where .= " AND cc.id = " . (int) $params['id'];
682 if (CRM_Utils_Array
::value('cid', $params)) {
683 $where .= " AND cc.id <> " . (int) $params['cid'];
686 //contact's based of relationhip type
688 if (CRM_Utils_Array
::value('rel', $params)) {
689 $relation = explode('_', CRM_Utils_Array
::value('rel', $params));
690 $relType = CRM_Utils_Type
::escape($relation[0], 'Integer');
691 $rel = CRM_Utils_Type
::escape($relation[2], 'String');
694 if ($config->includeWildCardInName
) {
695 $strSearch = "%$name%";
698 $strSearch = "$name%";
700 $includeEmailFrom = $includeNickName = $exactIncludeNickName = '';
701 if ($config->includeNickNameInName
) {
702 $includeNickName = " OR nick_name LIKE '$strSearch'";
703 $exactIncludeNickName = " OR nick_name LIKE '$name'";
707 if (!empty($params['field_name']) && !empty($params['table_name'])) {
708 $table_name = CRM_Utils_String
::munge($params['table_name']);
709 $whereClause = " WHERE ( $table_name.$field_name LIKE '$strSearch')";
710 $exactWhereClause = " WHERE ( $table_name.$field_name = '$name')";
711 // Search by id should be exact
712 if ($field_name == 'id' ||
$field_name == 'external_identifier') {
713 $whereClause = $exactWhereClause;
717 if ($config->includeEmailInName
) {
718 if (!in_array('email', $list)) {
719 $includeEmailFrom = "LEFT JOIN civicrm_email eml ON ( cc.id = eml.contact_id AND eml.is_primary = 1 )";
721 $whereClause = " WHERE ( email LIKE '$strSearch' OR sort_name LIKE '$strSearch' $includeNickName ) {$where} ";
722 $exactWhereClause = " WHERE ( email LIKE '$name' OR sort_name LIKE '$name' $exactIncludeNickName ) {$where} ";
725 $whereClause = " WHERE ( sort_name LIKE '$strSearch' $includeNickName ) {$where} ";
726 $exactWhereClause = " WHERE ( sort_name LIKE '$name' $exactIncludeNickName ) {$where} ";
730 $additionalFrom = '';
733 INNER JOIN civicrm_relationship_type r ON (
735 AND ( cc.contact_type = r.contact_type_{$rel} OR r.contact_type_{$rel} IS NULL )
736 AND ( cc.contact_sub_type = r.contact_sub_type_{$rel} OR r.contact_sub_type_{$rel} IS NULL )
740 // check if only CMS users are requested
741 if (CRM_Utils_Array
::value('cmsuser', $params)) {
743 INNER JOIN civicrm_uf_match um ON (um.contact_id=cc.id)
748 $orderByOuter = "ORDER BY exactFirst";
749 if ($config->includeOrderByClause
) {
750 $orderByInner = "ORDER BY sort_name";
751 $orderByOuter .= ", sort_name";
756 SELECT DISTINCT(id), data, sort_name {$selectAliases}
758 ( SELECT 0 as exactFirst, cc.id as id, CONCAT_WS( ' :: ', {$actualSelectElements} ) as data {$select}
759 FROM civicrm_contact cc {$from}
761 {$additionalFrom} {$includeEmailFrom}
765 ( SELECT 1 as exactFirst, cc.id as id, CONCAT_WS( ' :: ', {$actualSelectElements} ) as data {$select}
766 FROM civicrm_contact cc {$from}
768 {$additionalFrom} {$includeEmailFrom}
776 // send query to hook to be modified if needed
777 CRM_Utils_Hook
::contactListQuery($query,
779 empty($params['context']) ?
NULL : CRM_Utils_Type
::escape($params['context'], 'String'),
780 empty($params['id']) ?
NULL : $params['id']
783 $dao = CRM_Core_DAO
::executeQuery($query);
785 $contactList = array();
786 $listCurrentEmployer = TRUE;
787 while ($dao->fetch()) {
788 $t = array('id' => $dao->id
);
789 foreach ($as as $k) {
790 $t[$k] = isset($dao->$k)?
$dao->$k: '';
792 $t['data'] = $dao->data
;
794 if (CRM_Utils_Array
::value('org', $params) &&
795 !empty($currEmpDetails) &&
796 $dao->id
== $currEmpDetails['id']
798 $listCurrentEmployer = FALSE;
802 //return organization name if doesn't exist in db
803 if (empty($contactList)) {
804 if (CRM_Utils_Array
::value('org', $params)) {
805 if ($listCurrentEmployer && !empty($currEmpDetails)) {
806 $contactList = array(
808 'data' => $currEmpDetails['data'],
809 'id' => $currEmpDetails['id']
814 $contactList = array(
824 return civicrm_api3_create_success($contactList, $params);
828 * Merges given pair of duplicate contacts.
830 * @param array $params input parameters
832 * Allowed @params array keys are:
833 * {int main_id main contact id with whom merge has to happen}
834 * {int other_id duplicate contact which would be deleted after merge operation}
835 * {string mode helps decide how to behave when there are conflicts.
836 * A 'safe' value skips the merge if there are no conflicts. Does a force merge otherwise.}
837 * {boolean auto_flip wether to let api decide which contact to retain and which to delete.}
839 * @return array API Result Array
844 function civicrm_api3_contact_merge($params) {
845 $mode = CRM_Utils_Array
::value('mode', $params, 'safe');
846 $autoFlip = CRM_Utils_Array
::value('auto_flip', $params, TRUE);
848 $dupePairs = array(array('srcID' => CRM_Utils_Array
::value('main_id', $params),
849 'dstID' => CRM_Utils_Array
::value('other_id', $params),
851 $result = CRM_Dedupe_Merger
::merge($dupePairs, array(), $mode, $autoFlip);
853 if ($result['is_error'] == 0) {
854 return civicrm_api3_create_success();
857 return civicrm_api3_create_error($result['messages']);
861 function _civicrm_api3_contact_proximity_spec(&$params) {
862 $params['latitude']['api.required'] = 1;
863 $params['longitude']['api.required'] = 1;
864 $params['unit']['api.default'] = 'meter';
867 function civicrm_api3_contact_proximity($params) {
868 $latitude = CRM_Utils_Array
::value('latitude', $params);
869 $longitude = CRM_Utils_Array
::value('longitude', $params);
870 $distance = CRM_Utils_Array
::value('distance', $params);
872 $unit = CRM_Utils_Array
::value('unit', $params);
874 // check and ensure that lat/long and distance are floats
876 !CRM_Utils_Rule
::numeric($latitude) ||
877 !CRM_Utils_Rule
::numeric($longitude) ||
878 !CRM_Utils_Rule
::numeric($distance)
880 throw new Exception(ts('Latitude, Longitude and Distance should exist and be numeric'));
883 if ($unit == "mile") {
884 $conversionFactor = 1609.344;
887 $conversionFactor = 1000;
890 $distance = $distance * $conversionFactor;
892 $whereClause = CRM_Contact_BAO_ProximityQuery
::where($latitude, $longitude, $distance);
895 SELECT civicrm_contact.id as contact_id,
896 civicrm_contact.display_name as display_name
898 LEFT JOIN civicrm_address ON civicrm_contact.id = civicrm_address.contact_id
902 $dao = CRM_Core_DAO
::executeQuery($query);
904 while ($dao->fetch()) {
905 $contacts[] = $dao->toArray();
908 return civicrm_api3_create_success($contacts, $params, 'contact', 'get_by_location', $dao);