3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.3 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2013 |
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-2013
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 input parameters
45 * Allowed @params array keys are:
46 * {@getfields contact_create}
49 * @example ContactCreate.php Example of Create Call
51 * @return array API Result Array
56 function civicrm_api3_contact_create($params) {
58 $contactID = CRM_Utils_Array
::value('contact_id', $params, CRM_Utils_Array
::value('id', $params));
59 $dupeCheck = CRM_Utils_Array
::value('dupe_check', $params, FALSE);
60 $values = _civicrm_api3_contact_check_params($params, $dupeCheck);
66 // If we get here, we're ready to create a new contact
67 if (($email = CRM_Utils_Array
::value('email', $params)) && !is_array($params['email'])) {
68 $defLocType = CRM_Core_BAO_LocationType
::getDefault();
69 $params['email'] = array(
70 1 => array('email' => $email,
72 'location_type_id' => ($defLocType->id
) ?
$defLocType->id
: 1,
78 if (!empty($params['home_url'])) {
79 $websiteTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Website', 'website_type_id');
80 $params['website'] = array(1 => array('website_type_id' => key($websiteTypes),
81 'url' => $params['home_url'],
86 if (isset($params['suffix_id']) && !(is_numeric($params['suffix_id']))) {
87 $params['suffix_id'] = array_search($params['suffix_id'], CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'suffix_id'));
90 if (isset($params['prefix_id']) && !(is_numeric($params['prefix_id']))) {
91 $params['prefix_id'] = array_search($params['prefix_id'], CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'prefix_id'));
94 if (isset($params['gender_id']) && !(is_numeric($params['gender_id']))) {
95 $params['gender_id'] = array_search($params['gender_id'], CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'gender_id'));
98 $error = _civicrm_api3_greeting_format_params($params);
99 if (civicrm_error($error)) {
104 $entityId = $contactID;
106 if (empty($params['contact_type']) && $entityId) {
107 $params['contact_type'] = CRM_Contact_BAO_Contact
::getContactType($entityId);
110 if (!isset($params['contact_sub_type']) && $entityId) {
111 $params['contact_sub_type'] = CRM_Contact_BAO_Contact
::getContactSubType($entityId);
114 _civicrm_api3_custom_format_params($params, $values, $params['contact_type'], $entityId);
116 $params = array_merge($params, $values);
118 $contact = _civicrm_api3_contact_update($params, $contactID);
120 if (is_a($contact, 'CRM_Core_Error')) {
121 return civicrm_api3_create_error($contact->_errors
[0]['message']);
125 _civicrm_api3_object_to_array_unique_fields($contact, $values[$contact->id
]);
128 return civicrm_api3_create_success($values, $params, 'Contact', 'create');
132 * Adjust Metadata for Create action
134 * @param array $params array or parameters determined by getfields
136 function _civicrm_api3_contact_create_spec(&$params) {
137 $params['contact_type']['api.required'] = 1;
138 $params['id']['api.aliases'] = array('contact_id');
139 $params['current_employer'] = array(
140 'title' => 'Current Employer',
141 'description' => 'Name of Current Employer',
143 $params['dupe_check'] = array(
144 'title' => 'Check for Duplicates',
145 'description' => 'Throw error if contact create matches dedupe rule',
150 * Retrieve one or more contacts, given a set of search params
152 * @param array input parameters
154 * @return array API Result Array
155 * (@getfields contact_get}
159 * @example ContactGet.php Standard GET example
162 function civicrm_api3_contact_get($params) {
164 _civicrm_api3_contact_get_supportanomalies($params, $options);
165 $contacts = _civicrm_api3_get_using_query_object('contact', $params, $options);
167 // CRM-7929 Quick fix by colemanw
168 // TODO: Figure out what function is responsible for prepending 'individual_' to these keys
169 // and sort it out there rather than going to all this trouble here.
170 // Eileen's note - not sure anymore if we went the right path stripping the 'individual' here
171 // 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
172 // the individual prefix but we are stuck with it now for apiv3 series.
173 $returnContacts = array();
174 if (is_array($contacts)) {
175 foreach ($contacts as $cid => $contact) {
176 if (is_array($contact)) {
177 $returnContacts[$cid] = array();
178 foreach ($contact as $key => $value) {
179 $key = str_replace(array('individual_prefix', 'individual_suffix'), array('prefix', 'suffix'), $key);
180 $returnContacts[$cid][$key] = $value;
185 return civicrm_api3_create_success($returnContacts, $params, 'contact');
188 function civicrm_api3_contact_getcount($params) {
190 _civicrm_api3_contact_get_supportanomalies($params, $options);
191 $count = _civicrm_api3_get_using_query_object('contact', $params, $options,1);
196 * Adjust Metadata for Get action
198 * @param array $params array or parameters determined by getfields
200 function _civicrm_api3_contact_get_spec(&$params) {
201 $params['contact_is_deleted']['api.default'] = 0;
203 //we declare all these pseudofields as there are other undocumented fields accessible
204 // via the api - but if check permissions is set we only allow declared fields
205 $params['address_id']['title'] = 'Primary Address ID';
206 $params['street_address']['title'] = 'Primary Address Street Address';
207 $params['supplemental_address_1']['title'] = 'Primary Address Supplemental Address 1';
208 $params['supplemental_address_2']['title'] = 'Primary Address Supplemental Address 2';
209 $params['city']['title'] = 'Primary Address City';
210 $params['postal_code_suffix']['title'] = 'Primary Address Post Code Suffix';
211 $params['postal_code']['title'] = 'Primary Address Post Code';
212 $params['geo_code_1']['title'] = 'Primary Address Latitude';
213 $params['geo_code_2']['title'] = 'Primary Address Longitude';
214 $params['state_province_id']['title'] = 'Primary Address State Province ID';
215 $params['state_province_name']['title'] = 'Primary Address State Province Name';
216 $params['state_province']['title'] = 'Primary Address State Province';
217 $params['country_id']['title'] = 'Primary Address State Province ID';
218 $params['country']['title'] = 'Primary Address country';
219 $params['worldregion_id']['title'] = 'Primary Address World Region ID';
220 $params['worldregion']['title'] = 'Primary Address World Region';
221 $params['phone_id']['title'] = 'Primary Phone ID';
222 $params['phone_type_id']['title'] = 'Primary Phone Type ID';
223 $params['provider_id']['title'] = 'Primary Phone Provider ID';
224 $params['email_id']['title'] = 'Primary Email ID';
225 $params['email']['title'] = 'Primary Email';
226 $params['on_hold']['title'] = 'Primary Email On Hold';
227 $params['im']['title'] = 'Primary Instant Messanger';
228 $params['im_id']['title'] = 'Primary Instant Messanger ID';
229 $params['group_id']['title'] = 'Group Memberships (filter)';
230 $params['group']['title'] = 'Group Memberships (filter, array)';
231 $params['tag']['title'] = 'Assigned tags (filter, array)';
235 * We are supporting 'showAll' = 'all', 'trash' or 'active' for contact get
237 * - hopefully some day we'll come up with a std syntax for the 3-way-boolean of
240 * We also support 'filter_group_id' & 'filter.group_id'
242 * @param array $params as passed into api get or getcount function
243 * @param array $options array of options (so we can modify the filter)
245 function _civicrm_api3_contact_get_supportanomalies(&$params, &$options) {
246 if (isset($params['showAll'])) {
247 if (strtolower($params['showAll']) == "active") {
248 $params['contact_is_deleted'] = 0;
250 if (strtolower($params['showAll']) == "trash") {
251 $params['contact_is_deleted'] = 1;
253 if (strtolower($params['showAll']) == "all" && isset($params['contact_is_deleted'])) {
254 unset($params['contact_is_deleted']);
257 // support for group filters
258 if (array_key_exists('filter_group_id', $params)) {
259 $params['filter.group_id'] = $params['filter_group_id'];
260 unset($params['filter_group_id']);
262 // filter.group_id works both for 1,2,3 and array (1,2,3)
263 if (array_key_exists('filter.group_id', $params)) {
264 if (is_array($params['filter.group_id'])) {
265 $groups = $params['filter.group_id'];
267 else $groups = explode(',', $params['filter.group_id']);
268 unset($params['filter.group_id']);
269 $groups = array_flip($groups);
270 $groups[key($groups)] = 1;
271 $options['input_params']['group'] = $groups;
276 * Delete a contact with given contact id
278 * @param array $params (reference ) input parameters, contact_id element required
280 * @return array API Result Array
283 * @example ContactDelete.php
284 * {@getfields contact_delete}
286 function civicrm_api3_contact_delete($params) {
288 $contactID = CRM_Utils_Array
::value('id', $params);
290 $session = CRM_Core_Session
::singleton();
291 if ($contactID == $session->get('userID')) {
292 return civicrm_api3_create_error('This contact record is linked to the currently logged in user account - and cannot be deleted.');
294 $restore = CRM_Utils_Array
::value('restore', $params) ?
$params['restore'] : FALSE;
295 $skipUndelete = CRM_Utils_Array
::value('skip_undelete', $params) ?
$params['skip_undelete'] : FALSE;
298 // restrict permanent delete if a contact has financial trxn associated with it
300 if ($skipUndelete && CRM_Financial_BAO_FinancialItem
::checkContactPresent(array($contactID), $error)) {
301 return civicrm_api3_create_error($error['_qf_default']);
303 if (CRM_Contact_BAO_Contact
::deleteContact($contactID, $restore, $skipUndelete)) {
304 return civicrm_api3_create_success();
307 return civicrm_api3_create_error('Could not delete contact');
312 function _civicrm_api3_contact_check_params( &$params, $dupeCheck = true, $dupeErrorArray = false, $obsoletevalue = true, $dedupeRuleGroupID = null )
315 switch (strtolower(CRM_Utils_Array
::value('contact_type', $params))) {
317 civicrm_api3_verify_mandatory($params, null, array('household_name'));
320 civicrm_api3_verify_mandatory($params, null, array('organization_name'));
323 civicrm_api3_verify_one_mandatory($params, null, array(
333 if (CRM_Utils_Array
::value('contact_sub_type', $params) && CRM_Utils_Array
::value('contact_type', $params)) {
334 if (!(CRM_Contact_BAO_ContactType
::isExtendsContactType($params['contact_sub_type'], $params['contact_type']))) {
335 return civicrm_api3_create_error("Invalid or Mismatched Contact SubType: " . implode(', ', (array)$params['contact_sub_type']));
340 // check for record already existing
341 $dedupeParams = CRM_Dedupe_Finder
::formatParams($params, $params['contact_type']);
344 // setting 'check_permission' here means that the dedupe checking will be carried out even if the
345 // person does not have permission to carry out de-dupes
346 // this is similar to the front end form
347 if (isset($params['check_permission'])) {
348 $dedupeParams['check_permission'] = $params['check_permission'];
351 $ids = CRM_Dedupe_Finder
::dupesByParams($dedupeParams, $params['contact_type'], 'Strict', array());
353 if (count($ids) >0) {
354 throw new API_Exception("Found matching contacts: ". implode(',',$ids),"duplicate",array("ids"=>$ids));
358 //check for organisations with same name
359 if (!empty($params['current_employer'])) {
360 $organizationParams = array();
361 $organizationParams['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.');
383 * Takes an associative array and creates a contact object and all the associated
384 * derived objects (i.e. individual, location, email, phone etc)
386 * @param array $params (reference ) an assoc array of name/value pairs
387 * @param int $contactID if present the contact with that ID is updated
389 * @return object CRM_Contact_BAO_Contact object
393 function _civicrm_api3_contact_update($params, $contactID = NULL) {
394 $transaction = new CRM_Core_Transaction();
397 $params['contact_id'] = $contactID;
400 $contact = CRM_Contact_BAO_Contact
::create($params);
402 $transaction->commit();
408 * Validate the addressee or email or postal greetings
410 * @param $params Associative array of property name/value
411 * pairs to insert in new contact.
413 * @return array (reference ) null on success, error message otherwise
417 function _civicrm_api3_greeting_format_params($params) {
418 $greetingParams = array('', '_id', '_custom');
419 foreach (array('email', 'postal', 'addressee') as $key) {
420 $greeting = '_greeting';
421 if ($key == 'addressee') {
425 $formatParams = FALSE;
426 // unset display value from params.
427 if (isset($params["{$key}{$greeting}_display"])) {
428 unset($params["{$key}{$greeting}_display"]);
431 // check if greetings are present in present
432 foreach ($greetingParams as $greetingValues) {
433 if (array_key_exists("{$key}{$greeting}{$greetingValues}", $params)) {
434 $formatParams = TRUE;
439 if (!$formatParams) {
445 'contact_type' => $params['contact_type'],
446 'greeting_type' => "{$key}{$greeting}",
449 $greetings = CRM_Core_PseudoConstant
::greeting($filter);
450 $greetingId = CRM_Utils_Array
::value("{$key}{$greeting}_id", $params);
451 $greetingVal = CRM_Utils_Array
::value("{$key}{$greeting}", $params);
452 $customGreeting = CRM_Utils_Array
::value("{$key}{$greeting}_custom", $params);
454 if (!$greetingId && $greetingVal) {
455 $params["{$key}{$greeting}_id"] = CRM_Utils_Array
::key($params["{$key}{$greeting}"], $greetings);
458 if ($customGreeting && $greetingId &&
459 ($greetingId != array_search('Customized', $greetings))
461 return civicrm_api3_create_error(ts('Provide either %1 greeting id and/or %1 greeting or custom %1 greeting',
466 if ($greetingVal && $greetingId &&
467 ($greetingId != CRM_Utils_Array
::key($greetingVal, $greetings))
469 return civicrm_api3_create_error(ts('Mismatch in %1 greeting id and %1 greeting',
476 if (!array_key_exists($greetingId, $greetings)) {
477 return civicrm_api3_create_error(ts('Invalid %1 greeting Id', array(1 => $key)));
480 if (!$customGreeting && ($greetingId == array_search('Customized', $greetings))) {
481 return civicrm_api3_create_error(ts('Please provide a custom value for %1 greeting',
486 elseif ($greetingVal) {
488 if (!in_array($greetingVal, $greetings)) {
489 return civicrm_api3_create_error(ts('Invalid %1 greeting', array(1 => $key)));
492 $greetingId = CRM_Utils_Array
::key($greetingVal, $greetings);
495 if ($customGreeting) {
496 $greetingId = CRM_Utils_Array
::key('Customized', $greetings);
499 $customValue = isset($params['contact_id']) ?
500 CRM_Core_DAO
::getFieldValue(
501 'CRM_Contact_DAO_Contact',
502 $params['contact_id'],
503 "{$key}{$greeting}_custom"
507 if (array_key_exists("{$key}{$greeting}_id", $params) && empty($params["{$key}{$greeting}_id"])) {
510 elseif (array_key_exists("{$key}{$greeting}", $params) && empty($params["{$key}{$greeting}"])) {
513 elseif ($customValue && array_key_exists("{$key}{$greeting}_custom", $params)
514 && empty($params["{$key}{$greeting}_custom"])
519 $params["{$key}{$greeting}_id"] = $greetingId;
521 if (!$customValue && !$customGreeting && array_key_exists("{$key}{$greeting}_custom", $params)) {
522 unset($params["{$key}{$greeting}_custom"]);
526 $params["{$key}{$greeting}_id"] = '';
527 $params["{$key}{$greeting}_custom"] = '';
530 if (isset($params["{$key}{$greeting}"])) {
531 unset($params["{$key}{$greeting}"]);
537 * Contact quick search api
541 * {@example ContactGetquick.php 0}
544 function civicrm_api3_contact_quicksearch($params) {
545 // kept as an alias for compatibility reasons. CRM-11136
546 return civicrm_api3_contact_getquick($params);
549 function civicrm_api3_contact_getquick($params) {
550 civicrm_api3_verify_mandatory($params, NULL, array('name'));
551 $name = CRM_Utils_Type
::escape($params['name'], 'String');
553 // get the autocomplete options from settings
554 $acpref = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
555 CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
,
556 'contact_autocomplete_options'
560 // get the option values for contact autocomplete
561 $acOptions = CRM_Core_OptionGroup
::values('contact_autocomplete_options', FALSE, FALSE, FALSE, NULL, 'name');
564 foreach ($acpref as $value) {
565 if ($value && CRM_Utils_Array
::value($value, $acOptions)) {
566 $list[$value] = $acOptions[$value];
569 // If we are doing quicksearch by a field other than name, make sure that field is added to results
570 if (!empty($params['field_name'])) {
571 $field_name = CRM_Utils_String
::munge($params['field_name']);
572 // Unique name contact_id = id
573 if ($field_name == 'contact_id') {
576 // phone_numeric should be phone
577 $searchField = str_replace('_numeric', '', $field_name);
578 if(!in_array($searchField, $list)) {
579 $list[] = $searchField;
583 $select = $actualSelectElements = array('sort_name');
586 foreach ($list as $value) {
587 $suffix = substr($value, 0, 2) . substr($value, -1);
589 case 'street_address':
592 $selectText = $value;
597 $actualSelectElements[] = $select[] = ($value == 'address') ?
$selectText : $value;
598 $from[$value] = "LEFT JOIN civicrm_{$value} {$suffix} ON ( cc.id = {$suffix}.contact_id AND {$suffix}.is_primary = 1 ) ";
602 case 'state_province':
603 $select[] = "{$suffix}.name as {$value}";
604 $actualSelectElements[] = "{$suffix}.name";
605 if (!in_array('address', $from)) {
606 $from['address'] = 'LEFT JOIN civicrm_address sts ON ( cc.id = sts.contact_id AND sts.is_primary = 1) ';
608 $from[$value] = " LEFT JOIN civicrm_{$value} {$suffix} ON ( sts.{$value}_id = {$suffix}.id ) ";
612 if ($value != 'id') {
614 if (!empty($params['field_name']) && $params['field_name'] == 'value') {
615 $suffix = CRM_Utils_String
::munge(CRM_Utils_Array
::value('table_name', $params, 'cc'));
617 $actualSelectElements[] = $select[] = $suffix . '.' . $value;
623 $config = CRM_Core_Config
::singleton();
625 $select = implode(', ', $select);
626 if (!empty($select)) {
627 $select = ", $select";
629 $actualSelectElements = implode(', ', $actualSelectElements);
630 $selectAliases = $from;
631 unset($selectAliases['address']);
632 $selectAliases = implode(', ', array_keys($selectAliases));
633 if (!empty($selectAliases)) {
634 $selectAliases = ", $selectAliases";
636 $from = implode(' ', $from);
637 $limit = (int) CRM_Utils_Array
::value('limit', $params);
638 $limit = $limit > 0 ?
$limit : 10;
640 // add acl clause here
641 list($aclFrom, $aclWhere) = CRM_Contact_BAO_Contact_Permission
::cacheClause('cc');
644 $where .= " AND $aclWhere ";
647 if (CRM_Utils_Array
::value('org', $params)) {
648 $where .= " AND contact_type = \"Organization\"";
650 // CRM-7157, hack: get current employer details when
651 // employee_id is present.
652 $currEmpDetails = array();
653 if (CRM_Utils_Array
::value('employee_id', $params)) {
654 if ($currentEmployer = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact',
655 (int) $params['employee_id'],
658 if ($config->includeWildCardInName
) {
659 $strSearch = "%$name%";
662 $strSearch = "$name%";
665 // get current employer details
666 $dao = CRM_Core_DAO
::executeQuery("SELECT cc.id as id, CONCAT_WS( ' :: ', {$actualSelectElements} ) as data, sort_name
667 FROM civicrm_contact cc {$from} WHERE cc.contact_type = \"Organization\" AND cc.id = {$currentEmployer} AND cc.sort_name LIKE '$strSearch'");
669 $currEmpDetails = array(
671 'data' => $dao->data
,
678 //set default for current_employer or return contact with particular id
679 if (CRM_Utils_Array
::value('id', $params)) {
680 $where .= " AND cc.id = " . (int) $params['id'];
683 if (CRM_Utils_Array
::value('cid', $params)) {
684 $where .= " AND cc.id <> " . (int) $params['cid'];
687 //contact's based of relationhip type
689 if (CRM_Utils_Array
::value('rel', $params)) {
690 $relation = explode('_', CRM_Utils_Array
::value('rel', $params));
691 $relType = CRM_Utils_Type
::escape($relation[0], 'Integer');
692 $rel = CRM_Utils_Type
::escape($relation[2], 'String');
695 if ($config->includeWildCardInName
) {
696 $strSearch = "%$name%";
699 $strSearch = "$name%";
701 $includeEmailFrom = $includeNickName = $exactIncludeNickName = '';
702 if ($config->includeNickNameInName
) {
703 $includeNickName = " OR nick_name LIKE '$strSearch'";
704 $exactIncludeNickName = " OR nick_name LIKE '$name'";
708 if (!empty($params['field_name']) && !empty($params['table_name'])) {
709 $table_name = CRM_Utils_String
::munge($params['table_name']);
710 $whereClause = " WHERE ( $table_name.$field_name LIKE '$strSearch')";
711 $exactWhereClause = " WHERE ( $table_name.$field_name = '$name')";
712 // Search by id should be exact
713 if ($field_name == 'id' ||
$field_name == 'external_identifier') {
714 $whereClause = $exactWhereClause;
718 if ($config->includeEmailInName
) {
719 if (!in_array('email', $list)) {
720 $includeEmailFrom = "LEFT JOIN civicrm_email eml ON ( cc.id = eml.contact_id AND eml.is_primary = 1 )";
722 $whereClause = " WHERE ( email LIKE '$strSearch' OR sort_name LIKE '$strSearch' $includeNickName ) {$where} ";
723 $exactWhereClause = " WHERE ( email LIKE '$name' OR sort_name LIKE '$name' $exactIncludeNickName ) {$where} ";
726 $whereClause = " WHERE ( sort_name LIKE '$strSearch' $includeNickName ) {$where} ";
727 $exactWhereClause = " WHERE ( sort_name LIKE '$name' $exactIncludeNickName ) {$where} ";
731 $additionalFrom = '';
734 INNER JOIN civicrm_relationship_type r ON (
736 AND ( cc.contact_type = r.contact_type_{$rel} OR r.contact_type_{$rel} IS NULL )
737 AND ( cc.contact_sub_type = r.contact_sub_type_{$rel} OR r.contact_sub_type_{$rel} IS NULL )
741 // check if only CMS users are requested
742 if (CRM_Utils_Array
::value('cmsuser', $params)) {
744 INNER JOIN civicrm_uf_match um ON (um.contact_id=cc.id)
749 $orderByOuter = "ORDER BY exactFirst";
750 if ($config->includeOrderByClause
) {
751 $orderByInner = "ORDER BY sort_name";
752 $orderByOuter .= ", sort_name";
757 SELECT DISTINCT(id), data, sort_name {$selectAliases}
759 ( SELECT 0 as exactFirst, cc.id as id, CONCAT_WS( ' :: ', {$actualSelectElements} ) as data {$select}
760 FROM civicrm_contact cc {$from}
762 {$additionalFrom} {$includeEmailFrom}
766 ( SELECT 1 as exactFirst, cc.id as id, CONCAT_WS( ' :: ', {$actualSelectElements} ) as data {$select}
767 FROM civicrm_contact cc {$from}
769 {$additionalFrom} {$includeEmailFrom}
777 // send query to hook to be modified if needed
778 CRM_Utils_Hook
::contactListQuery($query,
780 empty($params['context']) ?
NULL : CRM_Utils_Type
::escape($params['context'], 'String'),
781 empty($params['id']) ?
NULL : $params['id']
784 $dao = CRM_Core_DAO
::executeQuery($query);
786 $contactList = array();
787 $listCurrentEmployer = TRUE;
788 while ($dao->fetch()) {
789 $t = array('id' => $dao->id
);
790 foreach ($as as $k) {
791 $t[$k] = isset($dao->$k)?
$dao->$k: '';
793 $t['data'] = $dao->data
;
795 if (CRM_Utils_Array
::value('org', $params) &&
796 !empty($currEmpDetails) &&
797 $dao->id
== $currEmpDetails['id']
799 $listCurrentEmployer = FALSE;
803 //return organization name if doesn't exist in db
804 if (empty($contactList)) {
805 if (CRM_Utils_Array
::value('org', $params)) {
806 if ($listCurrentEmployer && !empty($currEmpDetails)) {
807 $contactList = array(
809 'data' => $currEmpDetails['data'],
810 'id' => $currEmpDetails['id']
815 $contactList = array(
825 return civicrm_api3_create_success($contactList, $params);
829 * Merges given pair of duplicate contacts.
831 * @param array $params input parameters
833 * Allowed @params array keys are:
834 * {int main_id main contact id with whom merge has to happen}
835 * {int other_id duplicate contact which would be deleted after merge operation}
836 * {string mode helps decide how to behave when there are conflicts.
837 * A 'safe' value skips the merge if there are no conflicts. Does a force merge otherwise.}
838 * {boolean auto_flip wether to let api decide which contact to retain and which to delete.}
840 * @return array API Result Array
845 function civicrm_api3_contact_merge($params) {
846 $mode = CRM_Utils_Array
::value('mode', $params, 'safe');
847 $autoFlip = CRM_Utils_Array
::value('auto_flip', $params, TRUE);
849 $dupePairs = array(array('srcID' => CRM_Utils_Array
::value('main_id', $params),
850 'dstID' => CRM_Utils_Array
::value('other_id', $params),
852 $result = CRM_Dedupe_Merger
::merge($dupePairs, array(), $mode, $autoFlip);
854 if ($result['is_error'] == 0) {
855 return civicrm_api3_create_success();
858 return civicrm_api3_create_error($result['messages']);
862 function _civicrm_api3_contact_proximity_spec(&$params) {
863 $params['latitude']['api.required'] = 1;
864 $params['longitude']['api.required'] = 1;
865 $params['unit']['api.default'] = 'meter';
868 function civicrm_api3_contact_proximity($params) {
869 $latitude = CRM_Utils_Array
::value('latitude', $params);
870 $longitude = CRM_Utils_Array
::value('longitude', $params);
871 $distance = CRM_Utils_Array
::value('distance', $params);
873 $unit = CRM_Utils_Array
::value('unit', $params);
875 // check and ensure that lat/long and distance are floats
877 !CRM_Utils_Rule
::numeric($latitude) ||
878 !CRM_Utils_Rule
::numeric($longitude) ||
879 !CRM_Utils_Rule
::numeric($distance)
881 throw new Exception(ts('Latitude, Longitude and Distance should exist and be numeric'));
884 if ($unit == "mile") {
885 $conversionFactor = 1609.344;
888 $conversionFactor = 1000;
891 $distance = $distance * $conversionFactor;
893 $whereClause = CRM_Contact_BAO_ProximityQuery
::where($latitude, $longitude, $distance);
896 SELECT civicrm_contact.id as contact_id,
897 civicrm_contact.display_name as display_name
899 LEFT JOIN civicrm_address ON civicrm_contact.id = civicrm_address.contact_id
903 $dao = CRM_Core_DAO
::executeQuery($query);
905 while ($dao->fetch()) {
906 $contacts[] = $dao->toArray();
909 return civicrm_api3_create_success($contacts, $params, 'contact', 'get_by_location', $dao);