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
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(
75 'location_type_id' => ($defLocType->id
) ?
$defLocType->id
: 1,
81 if (!empty($params['home_url'])) {
82 $websiteTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Website', 'website_type_id');
83 $params['website'] = array(
85 'website_type_id' => key($websiteTypes),
86 'url' => $params['home_url'],
91 _civicrm_api3_greeting_format_params($params);
95 if (empty($params['contact_type']) && $contactID) {
96 $params['contact_type'] = CRM_Contact_BAO_Contact
::getContactType($contactID);
99 if (!isset($params['contact_sub_type']) && $contactID) {
100 $params['contact_sub_type'] = CRM_Contact_BAO_Contact
::getContactSubType($contactID);
103 _civicrm_api3_custom_format_params($params, $values, $params['contact_type'], $contactID);
105 $params = array_merge($params, $values);
106 //@todo we should just call basic_create here - but need to make contact:create accept 'id' on the bao
107 $contact = _civicrm_api3_contact_update($params, $contactID);
109 if (is_a($contact, 'CRM_Core_Error')) {
110 throw new API_Exception($contact->_errors
[0]['message']);
114 _civicrm_api3_object_to_array_unique_fields($contact, $values[$contact->id
]);
117 return civicrm_api3_create_success($values, $params, 'Contact', 'create');
121 * Adjust Metadata for Create action
123 * @param array $params
124 * Array or parameters determined by getfields.
126 function _civicrm_api3_contact_create_spec(&$params) {
127 $params['contact_type']['api.required'] = 1;
128 $params['id']['api.aliases'] = array('contact_id');
129 $params['current_employer'] = array(
130 'title' => 'Current Employer',
131 'description' => 'Name of Current Employer',
132 'type' => CRM_Utils_Type
::T_STRING
,
134 $params['dupe_check'] = array(
135 'title' => 'Check for Duplicates',
136 'description' => 'Throw error if contact create matches dedupe rule',
138 $params['prefix_id']['api.aliases'] = array('individual_prefix', 'individual_prefix_id');
139 $params['suffix_id']['api.aliases'] = array('individual_suffix', 'individual_suffix_id');
143 * Retrieve one or more contacts, given a set of search params
145 * @param array input parameters
147 * @return array API Result Array
148 * (@getfields contact_get}
152 * @example ContactGet.php Standard GET example
155 function civicrm_api3_contact_get($params) {
157 _civicrm_api3_contact_get_supportanomalies($params, $options);
158 $contacts = _civicrm_api3_get_using_query_object('contact', $params, $options);
159 return civicrm_api3_create_success($contacts, $params, 'contact');
163 * @param array $params
167 function civicrm_api3_contact_getcount($params) {
169 _civicrm_api3_contact_get_supportanomalies($params, $options);
170 $count = _civicrm_api3_get_using_query_object('contact', $params, $options, 1);
175 * Adjust Metadata for Get action
177 * @param array $params
178 * Array or parameters determined by getfields.
180 function _civicrm_api3_contact_get_spec(&$params) {
181 $params['contact_is_deleted']['api.default'] = 0;
183 //we declare all these pseudofields as there are other undocumented fields accessible
184 // via the api - but if check permissions is set we only allow declared fields
185 $params['address_id']['title'] = 'Primary Address ID';
186 $params['street_address']['title'] = 'Primary Address Street Address';
187 $params['supplemental_address_1']['title'] = 'Primary Address Supplemental Address 1';
188 $params['supplemental_address_2']['title'] = 'Primary Address Supplemental Address 2';
189 $params['current_employer']['title'] = 'Current Employer';
190 $params['city']['title'] = 'Primary Address City';
191 $params['postal_code_suffix']['title'] = 'Primary Address Post Code Suffix';
192 $params['postal_code']['title'] = 'Primary Address Post Code';
193 $params['geo_code_1']['title'] = 'Primary Address Latitude';
194 $params['geo_code_2']['title'] = 'Primary Address Longitude';
195 $params['state_province_id']['title'] = 'Primary Address State Province ID';
196 $params['state_province_name']['title'] = 'Primary Address State Province Name';
197 $params['state_province']['title'] = 'Primary Address State Province';
198 $params['country_id']['title'] = 'Primary Address Country ID';
199 $params['country']['title'] = 'Primary Address country';
200 $params['worldregion_id']['title'] = 'Primary Address World Region ID';
201 $params['worldregion']['title'] = 'Primary Address World Region';
202 $params['phone_id']['title'] = 'Primary Phone ID';
203 $params['phone']['title'] = 'Primary Phone';
204 $params['phone_type_id']['title'] = 'Primary Phone Type ID';
205 $params['provider_id']['title'] = 'Primary Phone Provider ID';
206 $params['email_id']['title'] = 'Primary Email ID';
207 $params['email']['title'] = 'Primary Email';
208 $params['gender_id']['title'] = 'Gender ID';
209 $params['gender']['title'] = 'Gender';
210 $params['on_hold']['title'] = 'Primary Email On Hold';
211 $params['im']['title'] = 'Primary Instant Messenger';
212 $params['im_id']['title'] = 'Primary Instant Messenger ID';
213 $params['group_id']['title'] = 'Group Memberships (filter)';
214 $params['group']['title'] = 'Group Memberships (filter, array)';
215 $params['tag']['title'] = 'Assigned tags (filter, array)';
216 $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'));
217 $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'));
218 $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'));
219 $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'));
223 * We are supporting 'showAll' = 'all', 'trash' or 'active' for contact get
225 * - hopefully some day we'll come up with a std syntax for the 3-way-boolean of
228 * We also support 'filter_group_id' & 'filter.group_id'
230 * @param array $params
231 * As passed into api get or getcount function.
232 * @param array $options
233 * Array of options (so we can modify the filter).
235 function _civicrm_api3_contact_get_supportanomalies(&$params, &$options) {
236 if (isset($params['showAll'])) {
237 if (strtolower($params['showAll']) == "active") {
238 $params['contact_is_deleted'] = 0;
240 if (strtolower($params['showAll']) == "trash") {
241 $params['contact_is_deleted'] = 1;
243 if (strtolower($params['showAll']) == "all" && isset($params['contact_is_deleted'])) {
244 unset($params['contact_is_deleted']);
247 // support for group filters
248 if (array_key_exists('filter_group_id', $params)) {
249 $params['filter.group_id'] = $params['filter_group_id'];
250 unset($params['filter_group_id']);
252 // filter.group_id works both for 1,2,3 and array (1,2,3)
253 if (array_key_exists('filter.group_id', $params)) {
254 if (is_array($params['filter.group_id'])) {
255 $groups = $params['filter.group_id'];
258 $groups = explode(',', $params['filter.group_id']);
260 unset($params['filter.group_id']);
261 $groups = array_flip($groups);
262 $groups[key($groups)] = 1;
263 $options['input_params']['group'] = $groups;
268 * Delete a contact with given contact id
270 * @param array $params
271 * (reference ) input parameters, contact_id element required.
273 * @return array API Result Array
276 * @example ContactDelete.php
277 * {@getfields contact_delete}
279 function civicrm_api3_contact_delete($params) {
281 $contactID = CRM_Utils_Array
::value('id', $params);
283 $session = CRM_Core_Session
::singleton();
284 if ($contactID == $session->get('userID')) {
285 return civicrm_api3_create_error('This contact record is linked to the currently logged in user account - and cannot be deleted.');
287 $restore = !empty($params['restore']) ?
$params['restore'] : FALSE;
288 $skipUndelete = !empty($params['skip_undelete']) ?
$params['skip_undelete'] : FALSE;
291 // restrict permanent delete if a contact has financial trxn associated with it
293 if ($skipUndelete && CRM_Financial_BAO_FinancialItem
::checkContactPresent(array($contactID), $error)) {
294 return civicrm_api3_create_error($error['_qf_default']);
296 if (CRM_Contact_BAO_Contact
::deleteContact($contactID, $restore, $skipUndelete)) {
297 return civicrm_api3_create_success();
300 return civicrm_api3_create_error('Could not delete contact');
306 * @param array $params
307 * @param bool $dupeCheck
308 * @param bool $dupeErrorArray
309 * @param bool $obsoletevalue
310 * @param int $dedupeRuleGroupID
313 * @throws API_Exception
314 * @throws CiviCRM_API3_Exception
316 function _civicrm_api3_contact_check_params(&$params, $dupeCheck = TRUE, $dupeErrorArray = FALSE, $obsoletevalue = TRUE, $dedupeRuleGroupID = NULL)
319 switch (strtolower(CRM_Utils_Array
::value('contact_type', $params))) {
321 civicrm_api3_verify_mandatory($params, NULL, array('household_name'));
325 civicrm_api3_verify_mandatory($params, NULL, array('organization_name'));
329 civicrm_api3_verify_one_mandatory($params, NULL, array(
339 // Fixme: This really needs to be handled at a lower level. @See CRM-13123
340 if (isset($params['preferred_communication_method'])) {
341 $params['preferred_communication_method'] = CRM_Utils_Array
::implodePadded($params['preferred_communication_method']);
344 if (!empty($params['contact_sub_type']) && !empty($params['contact_type'])) {
345 if (!(CRM_Contact_BAO_ContactType
::isExtendsContactType($params['contact_sub_type'], $params['contact_type']))) {
346 throw new API_Exception("Invalid or Mismatched Contact Subtype: " . implode(', ', (array) $params['contact_sub_type']));
351 // check for record already existing
352 $dedupeParams = CRM_Dedupe_Finder
::formatParams($params, $params['contact_type']);
355 // setting 'check_permission' here means that the dedupe checking will be carried out even if the
356 // person does not have permission to carry out de-dupes
357 // this is similar to the front end form
358 if (isset($params['check_permission'])) {
359 $dedupeParams['check_permission'] = $params['check_permission'];
362 $ids = CRM_Dedupe_Finder
::dupesByParams($dedupeParams, $params['contact_type'], 'Unsupervised', array());
364 if (count($ids) > 0) {
365 throw new API_Exception("Found matching contacts: " . implode(',', $ids), "duplicate", array("ids" => $ids));
369 // The BAO no longer supports the legacy param "current_employer" so here is a shim for api backward-compatability
370 if (!empty($params['current_employer'])) {
371 $organizationParams = array(
372 'organization_name' => $params['current_employer'],
375 $dedupParams = CRM_Dedupe_Finder
::formatParams($organizationParams, 'Organization');
377 $dedupParams['check_permission'] = FALSE;
378 $dupeIds = CRM_Dedupe_Finder
::dupesByParams($dedupParams, 'Organization', 'Supervised');
380 // check for mismatch employer name and id
381 if (!empty($params['employer_id']) && !in_array($params['employer_id'], $dupeIds)) {
382 throw new API_Exception('Employer name and Employer id Mismatch');
385 // show error if multiple organisation with same name exist
386 if (empty($params['employer_id']) && (count($dupeIds) > 1)) {
387 throw new API_Exception('Found more than one Organisation with same Name.');
391 $params['employer_id'] = $dupeIds[0];
394 $result = civicrm_api3('contact', 'create', array(
395 'organization_name' => $params['current_employer'],
396 'contact_type' => 'Organization'
398 $params['employer_id'] = $result['id'];
406 * Takes an associative array and creates a contact object and all the associated
407 * derived objects (i.e. individual, location, email, phone etc)
409 * @param array $params
410 * (reference ) an assoc array of name/value pairs.
411 * @param int $contactID
412 * If present the contact with that ID is updated.
414 * @return CRM_Contact_BAO_Contact object
418 function _civicrm_api3_contact_update($params, $contactID = NULL) {
419 //@todo - doesn't contact create support 'id' which is already set- check & remove
421 $params['contact_id'] = $contactID;
424 return CRM_Contact_BAO_Contact
::create($params);
428 * Validate the addressee or email or postal greetings
430 * @param array $params
431 * Associative array of property name/value.
432 * pairs to insert in new contact.
434 * @throws API_Exception
438 function _civicrm_api3_greeting_format_params($params) {
439 $greetingParams = array('', '_id', '_custom');
440 foreach (array('email', 'postal', 'addressee') as $key) {
441 $greeting = '_greeting';
442 if ($key == 'addressee') {
446 $formatParams = FALSE;
447 // unset display value from params.
448 if (isset($params["{$key}{$greeting}_display"])) {
449 unset($params["{$key}{$greeting}_display"]);
452 // check if greetings are present in present
453 foreach ($greetingParams as $greetingValues) {
454 if (array_key_exists("{$key}{$greeting}{$greetingValues}", $params)) {
455 $formatParams = TRUE;
460 if (!$formatParams) {
466 'contact_type' => $params['contact_type'],
467 'greeting_type' => "{$key}{$greeting}",
470 $greetings = CRM_Core_PseudoConstant
::greeting($filter);
471 $greetingId = CRM_Utils_Array
::value("{$key}{$greeting}_id", $params);
472 $greetingVal = CRM_Utils_Array
::value("{$key}{$greeting}", $params);
473 $customGreeting = CRM_Utils_Array
::value("{$key}{$greeting}_custom", $params);
475 if (!$greetingId && $greetingVal) {
476 $params["{$key}{$greeting}_id"] = CRM_Utils_Array
::key($params["{$key}{$greeting}"], $greetings);
479 if ($customGreeting && $greetingId &&
480 ($greetingId != array_search('Customized', $greetings))
482 throw new API_Exception(ts('Provide either %1 greeting id and/or %1 greeting or custom %1 greeting',
487 if ($greetingVal && $greetingId &&
488 ($greetingId != CRM_Utils_Array
::key($greetingVal, $greetings))
490 throw new API_Exception(ts('Mismatch in %1 greeting id and %1 greeting',
497 if (!array_key_exists($greetingId, $greetings)) {
498 throw new API_Exception(ts('Invalid %1 greeting Id', array(1 => $key)));
501 if (!$customGreeting && ($greetingId == array_search('Customized', $greetings))) {
502 throw new API_Exception(ts('Please provide a custom value for %1 greeting',
507 elseif ($greetingVal) {
509 if (!in_array($greetingVal, $greetings)) {
510 throw new API_Exception(ts('Invalid %1 greeting', array(1 => $key)));
513 $greetingId = CRM_Utils_Array
::key($greetingVal, $greetings);
516 if ($customGreeting) {
517 $greetingId = CRM_Utils_Array
::key('Customized', $greetings);
520 $customValue = isset($params['contact_id']) ? CRM_Core_DAO
::getFieldValue(
521 'CRM_Contact_DAO_Contact',
522 $params['contact_id'],
523 "{$key}{$greeting}_custom"
526 if (array_key_exists("{$key}{$greeting}_id", $params) && empty($params["{$key}{$greeting}_id"])) {
529 elseif (array_key_exists("{$key}{$greeting}", $params) && empty($params["{$key}{$greeting}"])) {
532 elseif ($customValue && array_key_exists("{$key}{$greeting}_custom", $params)
533 && empty($params["{$key}{$greeting}_custom"])
538 $params["{$key}{$greeting}_id"] = $greetingId;
540 if (!$customValue && !$customGreeting && array_key_exists("{$key}{$greeting}_custom", $params)) {
541 unset($params["{$key}{$greeting}_custom"]);
545 $params["{$key}{$greeting}_id"] = '';
546 $params["{$key}{$greeting}_custom"] = '';
549 if (isset($params["{$key}{$greeting}"])) {
550 unset($params["{$key}{$greeting}"]);
556 * Old contact quick search api
560 * {@example ContactGetquick.php 0}
563 function civicrm_api3_contact_getquick($params) {
564 civicrm_api3_verify_mandatory($params, NULL, array('name'));
565 $name = CRM_Utils_Type
::escape(CRM_Utils_Array
::value('name', $params), 'String');
567 // get the autocomplete options from settings
568 $acpref = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
569 CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
,
570 'contact_autocomplete_options'
574 // get the option values for contact autocomplete
575 $acOptions = CRM_Core_OptionGroup
::values('contact_autocomplete_options', FALSE, FALSE, FALSE, NULL, 'name');
578 foreach ($acpref as $value) {
579 if ($value && !empty($acOptions[$value])) {
580 $list[$value] = $acOptions[$value];
583 // If we are doing quicksearch by a field other than name, make sure that field is added to results
584 if (!empty($params['field_name'])) {
585 $field_name = CRM_Utils_String
::munge($params['field_name']);
586 // Unique name contact_id = id
587 if ($field_name == 'contact_id') {
590 // phone_numeric should be phone
591 $searchField = str_replace('_numeric', '', $field_name);
592 if (!in_array($searchField, $list)) {
593 $list[] = $searchField;
597 $select = $actualSelectElements = array('sort_name');
600 foreach ($list as $value) {
601 $suffix = substr($value, 0, 2) . substr($value, -1);
603 case 'street_address':
606 $selectText = $value;
611 $actualSelectElements[] = $select[] = ($value == 'address') ?
$selectText : $value;
612 if ($value == 'phone') {
613 $actualSelectElements[] = $select[] = 'phone_ext';
615 $from[$value] = "LEFT JOIN civicrm_{$value} {$suffix} ON ( cc.id = {$suffix}.contact_id AND {$suffix}.is_primary = 1 ) ";
619 case 'state_province':
620 $select[] = "{$suffix}.name as {$value}";
621 $actualSelectElements[] = "{$suffix}.name";
622 if (!in_array('address', $from)) {
623 $from['address'] = 'LEFT JOIN civicrm_address sts ON ( cc.id = sts.contact_id AND sts.is_primary = 1) ';
625 $from[$value] = " LEFT JOIN civicrm_{$value} {$suffix} ON ( sts.{$value}_id = {$suffix}.id ) ";
629 if ($value != 'id') {
631 if (!empty($params['field_name']) && $params['field_name'] == 'value') {
632 $suffix = CRM_Utils_String
::munge(CRM_Utils_Array
::value('table_name', $params, 'cc'));
634 $actualSelectElements[] = $select[] = $suffix . '.' . $value;
640 $config = CRM_Core_Config
::singleton();
642 $select = implode(', ', $select);
643 if (!empty($select)) {
644 $select = ", $select";
646 $actualSelectElements = implode(', ', $actualSelectElements);
647 $selectAliases = $from;
648 unset($selectAliases['address']);
649 $selectAliases = implode(', ', array_keys($selectAliases));
650 if (!empty($selectAliases)) {
651 $selectAliases = ", $selectAliases";
653 $from = implode(' ', $from);
654 $limit = (int) CRM_Utils_Array
::value('limit', $params);
655 $limit = $limit > 0 ?
$limit : 10;
657 // add acl clause here
658 list($aclFrom, $aclWhere) = CRM_Contact_BAO_Contact_Permission
::cacheClause('cc');
661 $where .= " AND $aclWhere ";
664 if (!empty($params['org'])) {
665 $where .= " AND contact_type = \"Organization\"";
667 // CRM-7157, hack: get current employer details when
668 // employee_id is present.
669 $currEmpDetails = array();
670 if (!empty($params['employee_id'])) {
671 if ($currentEmployer = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact',
672 (int) $params['employee_id'],
675 if ($config->includeWildCardInName
) {
676 $strSearch = "%$name%";
679 $strSearch = "$name%";
682 // get current employer details
683 $dao = CRM_Core_DAO
::executeQuery("SELECT cc.id as id, CONCAT_WS( ' :: ', {$actualSelectElements} ) as data, sort_name
684 FROM civicrm_contact cc {$from} WHERE cc.contact_type = \"Organization\" AND cc.id = {$currentEmployer} AND cc.sort_name LIKE '$strSearch'");
686 $currEmpDetails = array(
688 'data' => $dao->data
,
695 if (!empty($params['contact_sub_type'])) {
696 $contactSubType = CRM_Utils_Type
::escape($params['contact_sub_type'], 'String');
697 $where .= " AND cc.contact_sub_type = '{$contactSubType}'";
700 if (!empty($params['contact_type'])) {
701 $contactType = CRM_Utils_Type
::escape($params['contact_type'], 'String');
702 $where .= " AND cc.contact_type LIKE '{$contactType}'";
705 //set default for current_employer or return contact with particular id
706 if (!empty($params['id'])) {
707 $where .= " AND cc.id = " . (int) $params['id'];
710 if (!empty($params['cid'])) {
711 $where .= " AND cc.id <> " . (int) $params['cid'];
714 //contact's based of relationhip type
716 if (!empty($params['rel'])) {
717 $relation = explode('_', CRM_Utils_Array
::value('rel', $params));
718 $relType = CRM_Utils_Type
::escape($relation[0], 'Integer');
719 $rel = CRM_Utils_Type
::escape($relation[2], 'String');
722 if ($config->includeWildCardInName
) {
723 $strSearch = "%$name%";
726 $strSearch = "$name%";
728 $includeEmailFrom = $includeNickName = $exactIncludeNickName = '';
729 if ($config->includeNickNameInName
) {
730 $includeNickName = " OR nick_name LIKE '$strSearch'";
731 $exactIncludeNickName = " OR nick_name LIKE '$name'";
735 if (!empty($params['field_name']) && !empty($params['table_name'])) {
736 $table_name = CRM_Utils_String
::munge($params['table_name']);
737 $whereClause = " WHERE ( $table_name.$field_name LIKE '$strSearch') {$where}";
738 $exactWhereClause = " WHERE ( $table_name.$field_name = '$name') {$where}";
739 // Search by id should be exact
740 if ($field_name == 'id' ||
$field_name == 'external_identifier') {
741 $whereClause = $exactWhereClause;
745 if ($config->includeEmailInName
) {
746 if (!in_array('email', $list)) {
747 $includeEmailFrom = "LEFT JOIN civicrm_email eml ON ( cc.id = eml.contact_id AND eml.is_primary = 1 )";
749 $whereClause = " WHERE ( email LIKE '$strSearch' OR sort_name LIKE '$strSearch' $includeNickName ) {$where} ";
750 $exactWhereClause = " WHERE ( email LIKE '$name' OR sort_name LIKE '$name' $exactIncludeNickName ) {$where} ";
753 $whereClause = " WHERE ( sort_name LIKE '$strSearch' $includeNickName ) {$where} ";
754 $exactWhereClause = " WHERE ( sort_name LIKE '$name' $exactIncludeNickName ) {$where} ";
758 $additionalFrom = '';
761 INNER JOIN civicrm_relationship_type r ON (
763 AND ( cc.contact_type = r.contact_type_{$rel} OR r.contact_type_{$rel} IS NULL )
764 AND ( cc.contact_sub_type = r.contact_sub_type_{$rel} OR r.contact_sub_type_{$rel} IS NULL )
768 // check if only CMS users are requested
769 if (!empty($params['cmsuser'])) {
771 INNER JOIN civicrm_uf_match um ON (um.contact_id=cc.id)
776 $orderByOuter = "ORDER BY exactFirst";
777 if ($config->includeOrderByClause
) {
778 $orderByInner = "ORDER BY sort_name";
779 $orderByOuter .= ", sort_name";
784 SELECT DISTINCT(id), data, sort_name {$selectAliases}
786 ( SELECT 0 as exactFirst, cc.id as id, CONCAT_WS( ' :: ', {$actualSelectElements} ) as data {$select}
787 FROM civicrm_contact cc {$from}
789 {$additionalFrom} {$includeEmailFrom}
793 ( SELECT 1 as exactFirst, cc.id as id, CONCAT_WS( ' :: ', {$actualSelectElements} ) as data {$select}
794 FROM civicrm_contact cc {$from}
796 {$additionalFrom} {$includeEmailFrom}
804 // send query to hook to be modified if needed
805 CRM_Utils_Hook
::contactListQuery($query,
807 empty($params['context']) ?
NULL : CRM_Utils_Type
::escape($params['context'], 'String'),
808 empty($params['id']) ?
NULL : $params['id']
811 $dao = CRM_Core_DAO
::executeQuery($query);
813 $contactList = array();
814 $listCurrentEmployer = TRUE;
815 while ($dao->fetch()) {
816 $t = array('id' => $dao->id
);
817 foreach ($as as $k) {
818 $t[$k] = isset($dao->$k) ?
$dao->$k : '';
820 $t['data'] = $dao->data
;
822 if (!empty($params['org']) &&
823 !empty($currEmpDetails) &&
824 $dao->id
== $currEmpDetails['id']
826 $listCurrentEmployer = FALSE;
830 //return organization name if doesn't exist in db
831 if (empty($contactList)) {
832 if (!empty($params['org'])) {
833 if ($listCurrentEmployer && !empty($currEmpDetails)) {
834 $contactList = array(
836 'data' => $currEmpDetails['data'],
837 'id' => $currEmpDetails['id']
842 $contactList = array(
852 return civicrm_api3_create_success($contactList, $params, 'contact', 'getquick');
856 * @deprecated api notice
857 * @return array of deprecated actions
859 function _civicrm_api3_contact_deprecation() {
860 return array('getquick' => 'The "getquick" action is deprecated in favor of "getlist".');
864 * Merges given pair of duplicate contacts.
866 * @param array $params
869 * Allowed @params array keys are:
870 * {int main_id main contact id with whom merge has to happen}
871 * {int other_id duplicate contact which would be deleted after merge operation}
872 * {string mode helps decide how to behave when there are conflicts.
873 * A 'safe' value skips the merge if there are no conflicts. Does a force merge otherwise.}
874 * {boolean auto_flip wether to let api decide which contact to retain and which to delete.}
876 * @return array API Result Array
881 function civicrm_api3_contact_merge($params) {
882 $mode = CRM_Utils_Array
::value('mode', $params, 'safe');
883 $autoFlip = CRM_Utils_Array
::value('auto_flip', $params, TRUE);
885 $dupePairs = array(array(
886 'srcID' => CRM_Utils_Array
::value('main_id', $params),
887 'dstID' => CRM_Utils_Array
::value('other_id', $params),
889 $result = CRM_Dedupe_Merger
::merge($dupePairs, array(), $mode, $autoFlip);
891 if ($result['is_error'] == 0) {
892 return civicrm_api3_create_success();
895 return civicrm_api3_create_error($result['messages']);
900 * @param array $params
902 function _civicrm_api3_contact_proximity_spec(&$params) {
903 $params['latitude']['api.required'] = 1;
904 $params['latitude']['title'] = 'Latitude';
905 $params['longitude']['api.required'] = 1;
906 $params['longitude']['title'] = 'Longitude';
907 $params['unit']['api.default'] = 'meter';
908 $params['unit']['title'] = 'Unit of Measurement';
912 * @param array $params
917 function civicrm_api3_contact_proximity($params) {
918 $latitude = CRM_Utils_Array
::value('latitude', $params);
919 $longitude = CRM_Utils_Array
::value('longitude', $params);
920 $distance = CRM_Utils_Array
::value('distance', $params);
922 $unit = CRM_Utils_Array
::value('unit', $params);
924 // check and ensure that lat/long and distance are floats
926 !CRM_Utils_Rule
::numeric($latitude) ||
927 !CRM_Utils_Rule
::numeric($longitude) ||
928 !CRM_Utils_Rule
::numeric($distance)
930 throw new Exception(ts('Latitude, Longitude and Distance should exist and be numeric'));
933 if ($unit == "mile") {
934 $conversionFactor = 1609.344;
937 $conversionFactor = 1000;
940 $distance = $distance * $conversionFactor;
942 $whereClause = CRM_Contact_BAO_ProximityQuery
::where($latitude, $longitude, $distance);
945 SELECT civicrm_contact.id as contact_id,
946 civicrm_contact.display_name as display_name
948 LEFT JOIN civicrm_address ON civicrm_contact.id = civicrm_address.contact_id
952 $dao = CRM_Core_DAO
::executeQuery($query);
954 while ($dao->fetch()) {
955 $contacts[] = $dao->toArray();
958 return civicrm_api3_create_success($contacts, $params, 'contact', 'get_by_location', $dao);
963 * @see _civicrm_api3_generic_getlist_params
968 function _civicrm_api3_contact_getlist_params(&$request) {
969 // get the autocomplete options from settings
970 $acpref = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
971 CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
,
972 'contact_autocomplete_options'
976 // get the option values for contact autocomplete
977 $acOptions = CRM_Core_OptionGroup
::values('contact_autocomplete_options', FALSE, FALSE, FALSE, NULL, 'name');
980 foreach ($acpref as $value) {
981 if ($value && !empty($acOptions[$value])) {
982 $list[] = $acOptions[$value];
985 // If we are doing quicksearch by a field other than name, make sure that field is added to results
986 $field_name = CRM_Utils_String
::munge($request['search_field']);
987 // Unique name contact_id = id
988 if ($field_name == 'contact_id') {
991 // phone_numeric should be phone
992 $searchField = str_replace('_numeric', '', $field_name);
993 if (!in_array($searchField, $list)) {
994 $list[] = $searchField;
996 $request['description_field'] = $list;
997 $list[] = 'contact_type';
998 $request['params']['return'] = array_unique(array_merge($list, $request['extra']));
999 $request['params']['options']['sort'] = 'sort_name';
1000 // Contact api doesn't support array(LIKE => 'foo') syntax
1001 if (!empty($request['input'])) {
1002 $request['params'][$request['search_field']] = $request['input'];
1007 * @see _civicrm_api3_generic_getlist_output
1016 function _civicrm_api3_contact_getlist_output($result, $request) {
1018 if (!empty($result['values'])) {
1019 $addressFields = array_intersect(array('street_address', 'city', 'state_province', 'country'), $request['params']['return']);
1020 foreach ($result['values'] as $row) {
1022 'id' => $row[$request['id_field']],
1023 'label' => $row[$request['label_field']],
1024 'description' => array(),
1026 foreach ($request['description_field'] as $item) {
1027 if (!strpos($item, '_name') && !in_array($item, $addressFields) && !empty($row[$item])) {
1028 $data['description'][] = $row[$item];
1032 foreach ($addressFields as $item) {
1033 if (!empty($row[$item])) {
1034 $address[] = $row[$item];
1038 $data['description'][] = implode(' ', $address);
1040 if (!empty($request['image_field'])) {
1041 $data['image'] = isset($row[$request['image_field']]) ?
$row[$request['image_field']] : '';
1044 $data['icon_class'] = $row['contact_type'];
1046 foreach ($request['extra'] as $field) {
1047 $data['extra'][$field] = isset($row[$field]) ?
$row[$field] : NULL;