CRM-13072 - Fix typo in api getfields sequential
[civicrm-core.git] / api / v3 / Contact.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
9 | |
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. |
13 | |
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. |
18 | |
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 +--------------------------------------------------------------------+
26 */
27
28 /**
29 * This api exposes CiviCRM contacts.
30 *
31 * Contacts are the main entity in CiviCRM and this api is more robust than most.
32 * - Get action allows all params supported by advanced search.
33 * - Create action allows creating several related entities at once (e.g. email).
34 * - Create allows checking for duplicate contacts.
35 * Use getfields to list the full range of parameters and options supported by each action.
36 *
37 * @package CiviCRM_APIv3
38 */
39
40 /**
41 * Create or update a Contact.
42 *
43 * @param array $params
44 * Input parameters.
45 *
46 * @throws API_Exception
47 *
48 * @return array
49 * API Result Array
50 */
51 function civicrm_api3_contact_create($params) {
52
53 $contactID = CRM_Utils_Array::value('contact_id', $params, CRM_Utils_Array::value('id', $params));
54 $dupeCheck = CRM_Utils_Array::value('dupe_check', $params, FALSE);
55 $values = _civicrm_api3_contact_check_params($params, $dupeCheck);
56 if ($values) {
57 return $values;
58 }
59
60 if (!$contactID) {
61 // If we get here, we're ready to create a new contact
62 if (($email = CRM_Utils_Array::value('email', $params)) && !is_array($params['email'])) {
63 $defLocType = CRM_Core_BAO_LocationType::getDefault();
64 $params['email'] = array(
65 1 => array(
66 'email' => $email,
67 'is_primary' => 1,
68 'location_type_id' => ($defLocType->id) ? $defLocType->id : 1,
69 ),
70 );
71 }
72 }
73
74 if (!empty($params['home_url'])) {
75 $websiteTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Website', 'website_type_id');
76 $params['website'] = array(
77 1 => array(
78 'website_type_id' => key($websiteTypes),
79 'url' => $params['home_url'],
80 ),
81 );
82 }
83
84 _civicrm_api3_greeting_format_params($params);
85
86 $values = array();
87
88 if (empty($params['contact_type']) && $contactID) {
89 $params['contact_type'] = CRM_Contact_BAO_Contact::getContactType($contactID);
90 }
91
92 if (!isset($params['contact_sub_type']) && $contactID) {
93 $params['contact_sub_type'] = CRM_Contact_BAO_Contact::getContactSubType($contactID);
94 }
95
96 _civicrm_api3_custom_format_params($params, $values, $params['contact_type'], $contactID);
97
98 $params = array_merge($params, $values);
99 //@todo we should just call basic_create here - but need to make contact:create accept 'id' on the bao
100 $contact = _civicrm_api3_contact_update($params, $contactID);
101
102 if (is_a($contact, 'CRM_Core_Error')) {
103 throw new API_Exception($contact->_errors[0]['message']);
104 }
105 else {
106 $values = array();
107 _civicrm_api3_object_to_array_unique_fields($contact, $values[$contact->id]);
108 }
109
110 return civicrm_api3_create_success($values, $params, 'Contact', 'create');
111 }
112
113 /**
114 * Adjust Metadata for Create action.
115 *
116 * @param array $params
117 * Array of parameters determined by getfields.
118 */
119 function _civicrm_api3_contact_create_spec(&$params) {
120 $params['contact_type']['api.required'] = 1;
121 $params['id']['api.aliases'] = array('contact_id');
122 $params['current_employer'] = array(
123 'title' => 'Current Employer',
124 'description' => 'Name of Current Employer',
125 'type' => CRM_Utils_Type::T_STRING,
126 );
127 $params['dupe_check'] = array(
128 'title' => 'Check for Duplicates',
129 'description' => 'Throw error if contact create matches dedupe rule',
130 );
131 $params['prefix_id']['api.aliases'] = array('individual_prefix', 'individual_prefix_id');
132 $params['suffix_id']['api.aliases'] = array('individual_suffix', 'individual_suffix_id');
133 }
134
135 /**
136 * Retrieve one or more contacts, given a set of search params.
137 *
138 * @param array $params
139 *
140 * @return array
141 * API Result Array
142 */
143 function civicrm_api3_contact_get($params) {
144 $options = array();
145 _civicrm_api3_contact_get_supportanomalies($params, $options);
146 $contacts = _civicrm_api3_get_using_query_object('Contact', $params, $options);
147 return civicrm_api3_create_success($contacts, $params, 'Contact');
148 }
149
150 /**
151 * Get number of contacts matching the supplied criteria.
152 *
153 * @param array $params
154 *
155 * @return int
156 */
157 function civicrm_api3_contact_getcount($params) {
158 $options = array();
159 _civicrm_api3_contact_get_supportanomalies($params, $options);
160 $count = _civicrm_api3_get_using_query_object('Contact', $params, $options, 1);
161 return (int) $count;
162 }
163
164 /**
165 * Adjust Metadata for Get action.
166 *
167 * @param array $params
168 * Array of parameters determined by getfields.
169 */
170 function _civicrm_api3_contact_get_spec(&$params) {
171 $params['contact_is_deleted']['api.default'] = 0;
172
173 // We declare all these pseudoFields as there are other undocumented fields accessible
174 // via the api - but if check permissions is set we only allow declared fields
175 $params['address_id']['title'] = 'Primary Address ID';
176 $params['street_address']['title'] = 'Primary Address Street Address';
177 $params['supplemental_address_1']['title'] = 'Primary Address Supplemental Address 1';
178 $params['supplemental_address_2']['title'] = 'Primary Address Supplemental Address 2';
179 $params['current_employer']['title'] = 'Current Employer';
180 $params['city']['title'] = 'Primary Address City';
181 $params['postal_code_suffix']['title'] = 'Primary Address Post Code Suffix';
182 $params['postal_code']['title'] = 'Primary Address Post Code';
183 $params['geo_code_1']['title'] = 'Primary Address Latitude';
184 $params['geo_code_2']['title'] = 'Primary Address Longitude';
185 $params['state_province_id']['title'] = 'Primary Address State Province ID';
186 $params['state_province_name']['title'] = 'Primary Address State Province Name';
187 $params['state_province']['title'] = 'Primary Address State Province';
188 $params['country_id']['title'] = 'Primary Address Country ID';
189 $params['country']['title'] = 'Primary Address country';
190 $params['worldregion_id']['title'] = 'Primary Address World Region ID';
191 $params['worldregion']['title'] = 'Primary Address World Region';
192 $params['phone_id']['title'] = 'Primary Phone ID';
193 $params['phone']['title'] = 'Primary Phone';
194 $params['phone_type_id']['title'] = 'Primary Phone Type ID';
195 $params['provider_id']['title'] = 'Primary Phone Provider ID';
196 $params['email_id']['title'] = 'Primary Email ID';
197 $params['email']['title'] = 'Primary Email';
198 $params['gender_id']['title'] = 'Gender ID';
199 $params['gender']['title'] = 'Gender';
200 $params['on_hold']['title'] = 'Primary Email On Hold';
201 $params['im']['title'] = 'Primary Instant Messenger';
202 $params['im_id']['title'] = 'Primary Instant Messenger ID';
203 $params['group_id']['title'] = 'Group Memberships (filter)';
204 $params['group']['title'] = 'Group Memberships (filter, array)';
205 $params['tag']['title'] = 'Assigned tags (filter, array)';
206 $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'));
207 $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'));
208 $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'));
209 $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'));
210 }
211
212 /**
213 * Support for historical oddities.
214 *
215 * We are supporting 'showAll' = 'all', 'trash' or 'active' for Contact get
216 * and for getcount
217 * - hopefully some day we'll come up with a std syntax for the 3-way-boolean of
218 * 0, 1 or not set
219 *
220 * We also support 'filter_group_id' & 'filter.group_id'
221 *
222 * @param array $params
223 * As passed into api get or getcount function.
224 * @param array $options
225 * Array of options (so we can modify the filter).
226 */
227 function _civicrm_api3_contact_get_supportanomalies(&$params, &$options) {
228 if (isset($params['showAll'])) {
229 if (strtolower($params['showAll']) == "active") {
230 $params['contact_is_deleted'] = 0;
231 }
232 if (strtolower($params['showAll']) == "trash") {
233 $params['contact_is_deleted'] = 1;
234 }
235 if (strtolower($params['showAll']) == "all" && isset($params['contact_is_deleted'])) {
236 unset($params['contact_is_deleted']);
237 }
238 }
239 // support for group filters
240 if (array_key_exists('filter_group_id', $params)) {
241 $params['filter.group_id'] = $params['filter_group_id'];
242 unset($params['filter_group_id']);
243 }
244 // filter.group_id works both for 1,2,3 and array (1,2,3)
245 if (array_key_exists('filter.group_id', $params)) {
246 if (is_array($params['filter.group_id'])) {
247 $groups = $params['filter.group_id'];
248 }
249 else {
250 $groups = explode(',', $params['filter.group_id']);
251 }
252 unset($params['filter.group_id']);
253 $groups = array_flip($groups);
254 $groups[key($groups)] = 1;
255 $options['input_params']['group'] = $groups;
256 }
257 }
258
259 /**
260 * Delete a Contact with given contact_id.
261 *
262 * @param array $params
263 * input parameters per getfields
264 *
265 * @return array
266 * API Result Array
267 */
268 function civicrm_api3_contact_delete($params) {
269
270 $contactID = CRM_Utils_Array::value('id', $params);
271
272 $session = CRM_Core_Session::singleton();
273 if ($contactID == $session->get('userID')) {
274 return civicrm_api3_create_error('This contact record is linked to the currently logged in user account - and cannot be deleted.');
275 }
276 $restore = !empty($params['restore']) ? $params['restore'] : FALSE;
277 $skipUndelete = !empty($params['skip_undelete']) ? $params['skip_undelete'] : FALSE;
278
279 // CRM-12929
280 // restrict permanent delete if a contact has financial trxn associated with it
281 $error = NULL;
282 if ($skipUndelete && CRM_Financial_BAO_FinancialItem::checkContactPresent(array($contactID), $error)) {
283 return civicrm_api3_create_error($error['_qf_default']);
284 }
285 if (CRM_Contact_BAO_Contact::deleteContact($contactID, $restore, $skipUndelete)) {
286 return civicrm_api3_create_success();
287 }
288 else {
289 return civicrm_api3_create_error('Could not delete contact');
290 }
291 }
292
293
294 /**
295 * Check parameters passed in.
296 *
297 * This function is on it's way out.
298 *
299 * @param array $params
300 * @param bool $dupeCheck
301 *
302 * @return null
303 * @throws API_Exception
304 * @throws CiviCRM_API3_Exception
305 */
306 function _civicrm_api3_contact_check_params(&$params, $dupeCheck) {
307
308 switch (strtolower(CRM_Utils_Array::value('contact_type', $params))) {
309 case 'household':
310 civicrm_api3_verify_mandatory($params, NULL, array('household_name'));
311 break;
312
313 case 'organization':
314 civicrm_api3_verify_mandatory($params, NULL, array('organization_name'));
315 break;
316
317 case 'individual':
318 civicrm_api3_verify_one_mandatory($params, NULL, array(
319 'first_name',
320 'last_name',
321 'email',
322 'display_name',
323 )
324 );
325 break;
326 }
327
328 // Fixme: This really needs to be handled at a lower level. @See CRM-13123
329 if (isset($params['preferred_communication_method'])) {
330 $params['preferred_communication_method'] = CRM_Utils_Array::implodePadded($params['preferred_communication_method']);
331 }
332
333 if (!empty($params['contact_sub_type']) && !empty($params['contact_type'])) {
334 if (!(CRM_Contact_BAO_ContactType::isExtendsContactType($params['contact_sub_type'], $params['contact_type']))) {
335 throw new API_Exception("Invalid or Mismatched Contact Subtype: " . implode(', ', (array) $params['contact_sub_type']));
336 }
337 }
338
339 if ($dupeCheck) {
340 // check for record already existing
341 $dedupeParams = CRM_Dedupe_Finder::formatParams($params, $params['contact_type']);
342
343 // CRM-6431
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'];
349 }
350
351 $ids = CRM_Dedupe_Finder::dupesByParams($dedupeParams, $params['contact_type'], 'Unsupervised', array());
352
353 if (count($ids) > 0) {
354 throw new API_Exception("Found matching contacts: " . implode(',', $ids), "duplicate", array("ids" => $ids));
355 }
356 }
357
358 // The BAO no longer supports the legacy param "current_employer" so here is a shim for api backward-compatability
359 if (!empty($params['current_employer'])) {
360 $organizationParams = array(
361 'organization_name' => $params['current_employer'],
362 );
363
364 $dedupParams = CRM_Dedupe_Finder::formatParams($organizationParams, 'Organization');
365
366 $dedupParams['check_permission'] = FALSE;
367 $dupeIds = CRM_Dedupe_Finder::dupesByParams($dedupParams, 'Organization', 'Supervised');
368
369 // check for mismatch employer name and id
370 if (!empty($params['employer_id']) && !in_array($params['employer_id'], $dupeIds)) {
371 throw new API_Exception('Employer name and Employer id Mismatch');
372 }
373
374 // show error if multiple organisation with same name exist
375 if (empty($params['employer_id']) && (count($dupeIds) > 1)) {
376 throw new API_Exception('Found more than one Organisation with same Name.');
377 }
378
379 if ($dupeIds) {
380 $params['employer_id'] = $dupeIds[0];
381 }
382 else {
383 $result = civicrm_api3('Contact', 'create', array(
384 'organization_name' => $params['current_employer'],
385 'contact_type' => 'Organization',
386 ));
387 $params['employer_id'] = $result['id'];
388 }
389 }
390
391 return NULL;
392 }
393
394 /**
395 * Helper function for Contact create.
396 *
397 * @param array $params
398 * (reference ) an assoc array of name/value pairs.
399 * @param int $contactID
400 * If present the contact with that ID is updated.
401 *
402 * @return CRM_Contact_BAO_Contact|CRM_Core_Error
403 */
404 function _civicrm_api3_contact_update($params, $contactID = NULL) {
405 //@todo - doesn't contact create support 'id' which is already set- check & remove
406 if ($contactID) {
407 $params['contact_id'] = $contactID;
408 }
409
410 return CRM_Contact_BAO_Contact::create($params);
411 }
412
413 /**
414 * Validate the addressee or email or postal greetings.
415 *
416 * @param array $params
417 * Array per getfields metadata.
418 *
419 * @throws API_Exception
420 */
421 function _civicrm_api3_greeting_format_params($params) {
422 $greetingParams = array('', '_id', '_custom');
423 foreach (array('email', 'postal', 'addressee') as $key) {
424 $greeting = '_greeting';
425 if ($key == 'addressee') {
426 $greeting = '';
427 }
428
429 $formatParams = FALSE;
430 // Unset display value from params.
431 if (isset($params["{$key}{$greeting}_display"])) {
432 unset($params["{$key}{$greeting}_display"]);
433 }
434
435 // check if greetings are present in present
436 foreach ($greetingParams as $greetingValues) {
437 if (array_key_exists("{$key}{$greeting}{$greetingValues}", $params)) {
438 $formatParams = TRUE;
439 break;
440 }
441 }
442
443 if (!$formatParams) {
444 continue;
445 }
446
447 $nullValue = FALSE;
448 $filter = array(
449 'contact_type' => $params['contact_type'],
450 'greeting_type' => "{$key}{$greeting}",
451 );
452
453 $greetings = CRM_Core_PseudoConstant::greeting($filter);
454 $greetingId = CRM_Utils_Array::value("{$key}{$greeting}_id", $params);
455 $greetingVal = CRM_Utils_Array::value("{$key}{$greeting}", $params);
456 $customGreeting = CRM_Utils_Array::value("{$key}{$greeting}_custom", $params);
457
458 if (!$greetingId && $greetingVal) {
459 $params["{$key}{$greeting}_id"] = CRM_Utils_Array::key($params["{$key}{$greeting}"], $greetings);
460 }
461
462 if ($customGreeting && $greetingId &&
463 ($greetingId != array_search('Customized', $greetings))
464 ) {
465 throw new API_Exception(ts('Provide either %1 greeting id and/or %1 greeting or custom %1 greeting',
466 array(1 => $key)
467 ));
468 }
469
470 if ($greetingVal && $greetingId &&
471 ($greetingId != CRM_Utils_Array::key($greetingVal, $greetings))
472 ) {
473 throw new API_Exception(ts('Mismatch in %1 greeting id and %1 greeting',
474 array(1 => $key)
475 ));
476 }
477
478 if ($greetingId) {
479
480 if (!array_key_exists($greetingId, $greetings)) {
481 throw new API_Exception(ts('Invalid %1 greeting Id', array(1 => $key)));
482 }
483
484 if (!$customGreeting && ($greetingId == array_search('Customized', $greetings))) {
485 throw new API_Exception(ts('Please provide a custom value for %1 greeting',
486 array(1 => $key)
487 ));
488 }
489 }
490 elseif ($greetingVal) {
491
492 if (!in_array($greetingVal, $greetings)) {
493 throw new API_Exception(ts('Invalid %1 greeting', array(1 => $key)));
494 }
495
496 $greetingId = CRM_Utils_Array::key($greetingVal, $greetings);
497 }
498
499 if ($customGreeting) {
500 $greetingId = CRM_Utils_Array::key('Customized', $greetings);
501 }
502
503 $customValue = isset($params['contact_id']) ? CRM_Core_DAO::getFieldValue(
504 'CRM_Contact_DAO_Contact',
505 $params['contact_id'],
506 "{$key}{$greeting}_custom"
507 ) : FALSE;
508
509 if (array_key_exists("{$key}{$greeting}_id", $params) && empty($params["{$key}{$greeting}_id"])) {
510 $nullValue = TRUE;
511 }
512 elseif (array_key_exists("{$key}{$greeting}", $params) && empty($params["{$key}{$greeting}"])) {
513 $nullValue = TRUE;
514 }
515 elseif ($customValue && array_key_exists("{$key}{$greeting}_custom", $params)
516 && empty($params["{$key}{$greeting}_custom"])
517 ) {
518 $nullValue = TRUE;
519 }
520
521 $params["{$key}{$greeting}_id"] = $greetingId;
522
523 if (!$customValue && !$customGreeting && array_key_exists("{$key}{$greeting}_custom", $params)) {
524 unset($params["{$key}{$greeting}_custom"]);
525 }
526
527 if ($nullValue) {
528 $params["{$key}{$greeting}_id"] = '';
529 $params["{$key}{$greeting}_custom"] = '';
530 }
531
532 if (isset($params["{$key}{$greeting}"])) {
533 unset($params["{$key}{$greeting}"]);
534 }
535 }
536 }
537
538 /**
539 * Old Contact quick search api.
540 *
541 * @deprecated
542 *
543 * @param array $params
544 *
545 * @return array
546 * @throws \API_Exception
547 */
548 function civicrm_api3_contact_getquick($params) {
549 civicrm_api3_verify_mandatory($params, NULL, array('name'));
550 $name = CRM_Utils_Type::escape(CRM_Utils_Array::value('name', $params), 'String');
551
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'
556 )
557 );
558
559 // get the option values for contact autocomplete
560 $acOptions = CRM_Core_OptionGroup::values('contact_autocomplete_options', FALSE, FALSE, FALSE, NULL, 'name');
561
562 $list = array();
563 foreach ($acpref as $value) {
564 if ($value && !empty($acOptions[$value])) {
565 $list[$value] = $acOptions[$value];
566 }
567 }
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') {
573 $field_name = 'id';
574 }
575 // phone_numeric should be phone
576 $searchField = str_replace('_numeric', '', $field_name);
577 if (!in_array($searchField, $list)) {
578 $list[] = $searchField;
579 }
580 }
581
582 $select = $actualSelectElements = array('sort_name');
583 $where = '';
584 $from = array();
585 foreach ($list as $value) {
586 $suffix = substr($value, 0, 2) . substr($value, -1);
587 switch ($value) {
588 case 'street_address':
589 case 'city':
590 case 'postal_code':
591 $selectText = $value;
592 $value = "address";
593 $suffix = 'sts';
594 case 'phone':
595 case 'email':
596 $actualSelectElements[] = $select[] = ($value == 'address') ? $selectText : $value;
597 if ($value == 'phone') {
598 $actualSelectElements[] = $select[] = 'phone_ext';
599 }
600 $from[$value] = "LEFT JOIN civicrm_{$value} {$suffix} ON ( cc.id = {$suffix}.contact_id AND {$suffix}.is_primary = 1 ) ";
601 break;
602
603 case 'country':
604 case 'state_province':
605 $select[] = "{$suffix}.name as {$value}";
606 $actualSelectElements[] = "{$suffix}.name";
607 if (!in_array('address', $from)) {
608 $from['address'] = 'LEFT JOIN civicrm_address sts ON ( cc.id = sts.contact_id AND sts.is_primary = 1) ';
609 }
610 $from[$value] = " LEFT JOIN civicrm_{$value} {$suffix} ON ( sts.{$value}_id = {$suffix}.id ) ";
611 break;
612
613 default:
614 if ($value != 'id') {
615 $suffix = 'cc';
616 if (!empty($params['field_name']) && $params['field_name'] == 'value') {
617 $suffix = CRM_Utils_String::munge(CRM_Utils_Array::value('table_name', $params, 'cc'));
618 }
619 $actualSelectElements[] = $select[] = $suffix . '.' . $value;
620 }
621 break;
622 }
623 }
624
625 $config = CRM_Core_Config::singleton();
626 $as = $select;
627 $select = implode(', ', $select);
628 if (!empty($select)) {
629 $select = ", $select";
630 }
631 $actualSelectElements = implode(', ', $actualSelectElements);
632 $selectAliases = $from;
633 unset($selectAliases['address']);
634 $selectAliases = implode(', ', array_keys($selectAliases));
635 if (!empty($selectAliases)) {
636 $selectAliases = ", $selectAliases";
637 }
638 $from = implode(' ', $from);
639 $limit = (int) CRM_Utils_Array::value('limit', $params);
640 $limit = $limit > 0 ? $limit : 10;
641
642 // add acl clause here
643 list($aclFrom, $aclWhere) = CRM_Contact_BAO_Contact_Permission::cacheClause('cc');
644
645 if ($aclWhere) {
646 $where .= " AND $aclWhere ";
647 }
648
649 if (!empty($params['org'])) {
650 $where .= " AND contact_type = \"Organization\"";
651
652 // CRM-7157, hack: get current employer details when
653 // employee_id is present.
654 $currEmpDetails = array();
655 if (!empty($params['employee_id'])) {
656 if ($currentEmployer = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact',
657 (int) $params['employee_id'],
658 'employer_id'
659 )) {
660 if ($config->includeWildCardInName) {
661 $strSearch = "%$name%";
662 }
663 else {
664 $strSearch = "$name%";
665 }
666
667 // get current employer details
668 $dao = CRM_Core_DAO::executeQuery("SELECT cc.id as id, CONCAT_WS( ' :: ', {$actualSelectElements} ) as data, sort_name
669 FROM civicrm_contact cc {$from} WHERE cc.contact_type = \"Organization\" AND cc.id = {$currentEmployer} AND cc.sort_name LIKE '$strSearch'");
670 if ($dao->fetch()) {
671 $currEmpDetails = array(
672 'id' => $dao->id,
673 'data' => $dao->data,
674 );
675 }
676 }
677 }
678 }
679
680 if (!empty($params['contact_sub_type'])) {
681 $contactSubType = CRM_Utils_Type::escape($params['contact_sub_type'], 'String');
682 $where .= " AND cc.contact_sub_type = '{$contactSubType}'";
683 }
684
685 if (!empty($params['contact_type'])) {
686 $contactType = CRM_Utils_Type::escape($params['contact_type'], 'String');
687 $where .= " AND cc.contact_type LIKE '{$contactType}'";
688 }
689
690 // Set default for current_employer or return contact with particular id
691 if (!empty($params['id'])) {
692 $where .= " AND cc.id = " . (int) $params['id'];
693 }
694
695 if (!empty($params['cid'])) {
696 $where .= " AND cc.id <> " . (int) $params['cid'];
697 }
698
699 // Contact's based of relationhip type
700 $relType = NULL;
701 if (!empty($params['rel'])) {
702 $relation = explode('_', CRM_Utils_Array::value('rel', $params));
703 $relType = CRM_Utils_Type::escape($relation[0], 'Integer');
704 $rel = CRM_Utils_Type::escape($relation[2], 'String');
705 }
706
707 if ($config->includeWildCardInName) {
708 $strSearch = "%$name%";
709 }
710 else {
711 $strSearch = "$name%";
712 }
713 $includeEmailFrom = $includeNickName = $exactIncludeNickName = '';
714 if ($config->includeNickNameInName) {
715 $includeNickName = " OR nick_name LIKE '$strSearch'";
716 $exactIncludeNickName = " OR nick_name LIKE '$name'";
717 }
718
719 //CRM-10687
720 if (!empty($params['field_name']) && !empty($params['table_name'])) {
721 $table_name = CRM_Utils_String::munge($params['table_name']);
722 $whereClause = " WHERE ( $table_name.$field_name LIKE '$strSearch') {$where}";
723 $exactWhereClause = " WHERE ( $table_name.$field_name = '$name') {$where}";
724 // Search by id should be exact
725 if ($field_name == 'id' || $field_name == 'external_identifier') {
726 $whereClause = $exactWhereClause;
727 }
728 }
729 else {
730 if ($config->includeEmailInName) {
731 if (!in_array('email', $list)) {
732 $includeEmailFrom = "LEFT JOIN civicrm_email eml ON ( cc.id = eml.contact_id AND eml.is_primary = 1 )";
733 }
734 $whereClause = " WHERE ( email LIKE '$strSearch' OR sort_name LIKE '$strSearch' $includeNickName ) {$where} ";
735 $exactWhereClause = " WHERE ( email LIKE '$name' OR sort_name LIKE '$name' $exactIncludeNickName ) {$where} ";
736 }
737 else {
738 $whereClause = " WHERE ( sort_name LIKE '$strSearch' $includeNickName ) {$where} ";
739 $exactWhereClause = " WHERE ( sort_name LIKE '$name' $exactIncludeNickName ) {$where} ";
740 }
741 }
742
743 $additionalFrom = '';
744 if ($relType) {
745 $additionalFrom = "
746 INNER JOIN civicrm_relationship_type r ON (
747 r.id = {$relType}
748 AND ( cc.contact_type = r.contact_type_{$rel} OR r.contact_type_{$rel} IS NULL )
749 AND ( cc.contact_sub_type = r.contact_sub_type_{$rel} OR r.contact_sub_type_{$rel} IS NULL )
750 )";
751 }
752
753 // check if only CMS users are requested
754 if (!empty($params['cmsuser'])) {
755 $additionalFrom = "
756 INNER JOIN civicrm_uf_match um ON (um.contact_id=cc.id)
757 ";
758 }
759
760 $orderByInner = "";
761 $orderByOuter = "ORDER BY exactFirst";
762 if ($config->includeOrderByClause) {
763 $orderByInner = "ORDER BY sort_name";
764 $orderByOuter .= ", sort_name";
765 }
766
767 //CRM-5954
768 $query = "
769 SELECT DISTINCT(id), data, sort_name {$selectAliases}
770 FROM (
771 ( SELECT 0 as exactFirst, cc.id as id, CONCAT_WS( ' :: ', {$actualSelectElements} ) as data {$select}
772 FROM civicrm_contact cc {$from}
773 {$aclFrom}
774 {$additionalFrom} {$includeEmailFrom}
775 {$exactWhereClause}
776 LIMIT 0, {$limit} )
777 UNION
778 ( SELECT 1 as exactFirst, cc.id as id, CONCAT_WS( ' :: ', {$actualSelectElements} ) as data {$select}
779 FROM civicrm_contact cc {$from}
780 {$aclFrom}
781 {$additionalFrom} {$includeEmailFrom}
782 {$whereClause}
783 {$orderByInner}
784 LIMIT 0, {$limit} )
785 ) t
786 {$orderByOuter}
787 LIMIT 0, {$limit}
788 ";
789 // send query to hook to be modified if needed
790 CRM_Utils_Hook::contactListQuery($query,
791 $name,
792 empty($params['context']) ? NULL : CRM_Utils_Type::escape($params['context'], 'String'),
793 empty($params['id']) ? NULL : $params['id']
794 );
795
796 $dao = CRM_Core_DAO::executeQuery($query);
797
798 $contactList = array();
799 $listCurrentEmployer = TRUE;
800 while ($dao->fetch()) {
801 $t = array('id' => $dao->id);
802 foreach ($as as $k) {
803 $t[$k] = isset($dao->$k) ? $dao->$k : '';
804 }
805 $t['data'] = $dao->data;
806 $contactList[] = $t;
807 if (!empty($params['org']) &&
808 !empty($currEmpDetails) &&
809 $dao->id == $currEmpDetails['id']
810 ) {
811 $listCurrentEmployer = FALSE;
812 }
813 }
814
815 //return organization name if doesn't exist in db
816 if (empty($contactList)) {
817 if (!empty($params['org'])) {
818 if ($listCurrentEmployer && !empty($currEmpDetails)) {
819 $contactList = array(
820 array(
821 'data' => $currEmpDetails['data'],
822 'id' => $currEmpDetails['id'],
823 ),
824 );
825 }
826 else {
827 $contactList = array(
828 array(
829 'data' => $name,
830 'id' => $name,
831 ),
832 );
833 }
834 }
835 }
836
837 return civicrm_api3_create_success($contactList, $params, 'Contact', 'getquick');
838 }
839
840 /**
841 * Declare deprecated api functions.
842 *
843 * @deprecated api notice
844 * @return array
845 * Array of deprecated actions
846 */
847 function _civicrm_api3_contact_deprecation() {
848 return array('getquick' => 'The "getquick" action is deprecated in favor of "getlist".');
849 }
850
851 /**
852 * Merges given pair of duplicate contacts.
853 *
854 * @param array $params
855 * Allowed array keys are:
856 * -int main_id: main contact id with whom merge has to happen
857 * -int other_id: duplicate contact which would be deleted after merge operation
858 * -string mode: "safe" skips the merge if there are no conflicts. Does a force merge otherwise.
859 * -boolean auto_flip: whether to let api decide which contact to retain and which to delete.
860 *
861 * @return array
862 * API Result Array
863 */
864 function civicrm_api3_contact_merge($params) {
865 $mode = CRM_Utils_Array::value('mode', $params, 'safe');
866 $autoFlip = CRM_Utils_Array::value('auto_flip', $params, TRUE);
867
868 $dupePairs = array(array(
869 'srcID' => CRM_Utils_Array::value('main_id', $params),
870 'dstID' => CRM_Utils_Array::value('other_id', $params),
871 ));
872 $result = CRM_Dedupe_Merger::merge($dupePairs, array(), $mode, $autoFlip);
873
874 if ($result['is_error'] == 0) {
875 return civicrm_api3_create_success();
876 }
877 else {
878 return civicrm_api3_create_error($result['messages']);
879 }
880 }
881
882 /**
883 * Adjust metadata for contact_proximity api function.
884 *
885 * @param array $params
886 */
887 function _civicrm_api3_contact_proximity_spec(&$params) {
888 $params['latitude']['api.required'] = 1;
889 $params['latitude']['title'] = 'Latitude';
890 $params['longitude']['api.required'] = 1;
891 $params['longitude']['title'] = 'Longitude';
892 $params['unit']['api.default'] = 'meter';
893 $params['unit']['title'] = 'Unit of Measurement';
894 }
895
896 /**
897 * Get contacts by proximity.
898 *
899 * @param array $params
900 *
901 * @return array
902 * @throws Exception
903 */
904 function civicrm_api3_contact_proximity($params) {
905 $latitude = CRM_Utils_Array::value('latitude', $params);
906 $longitude = CRM_Utils_Array::value('longitude', $params);
907 $distance = CRM_Utils_Array::value('distance', $params);
908
909 $unit = CRM_Utils_Array::value('unit', $params);
910
911 // check and ensure that lat/long and distance are floats
912 if (
913 !CRM_Utils_Rule::numeric($latitude) ||
914 !CRM_Utils_Rule::numeric($longitude) ||
915 !CRM_Utils_Rule::numeric($distance)
916 ) {
917 throw new Exception(ts('Latitude, Longitude and Distance should exist and be numeric'));
918 }
919
920 if ($unit == "mile") {
921 $conversionFactor = 1609.344;
922 }
923 else {
924 $conversionFactor = 1000;
925 }
926 //Distance in meters
927 $distance = $distance * $conversionFactor;
928
929 $whereClause = CRM_Contact_BAO_ProximityQuery::where($latitude, $longitude, $distance);
930
931 $query = "
932 SELECT civicrm_contact.id as contact_id,
933 civicrm_contact.display_name as display_name
934 FROM civicrm_contact
935 LEFT JOIN civicrm_address ON civicrm_contact.id = civicrm_address.contact_id
936 WHERE $whereClause
937 ";
938
939 $dao = CRM_Core_DAO::executeQuery($query);
940 $contacts = array();
941 while ($dao->fetch()) {
942 $contacts[] = $dao->toArray();
943 }
944
945 return civicrm_api3_create_success($contacts, $params, 'Contact', 'get_by_location', $dao);
946 }
947
948
949 /**
950 * Get parameters for getlist function.
951 *
952 * @see _civicrm_api3_generic_getlist_params
953 *
954 * @param array $request
955 */
956 function _civicrm_api3_contact_getlist_params(&$request) {
957 // get the autocomplete options from settings
958 $acpref = explode(CRM_Core_DAO::VALUE_SEPARATOR,
959 CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME,
960 'contact_autocomplete_options'
961 )
962 );
963
964 // get the option values for contact autocomplete
965 $acOptions = CRM_Core_OptionGroup::values('contact_autocomplete_options', FALSE, FALSE, FALSE, NULL, 'name');
966
967 $list = array();
968 foreach ($acpref as $value) {
969 if ($value && !empty($acOptions[$value])) {
970 $list[] = $acOptions[$value];
971 }
972 }
973 // If we are doing quicksearch by a field other than name, make sure that field is added to results
974 $field_name = CRM_Utils_String::munge($request['search_field']);
975 // Unique name contact_id = id
976 if ($field_name == 'contact_id') {
977 $field_name = 'id';
978 }
979 // phone_numeric should be phone
980 $searchField = str_replace('_numeric', '', $field_name);
981 if (!in_array($searchField, $list)) {
982 $list[] = $searchField;
983 }
984 $request['description_field'] = $list;
985 $list[] = 'contact_type';
986 $request['params']['return'] = array_unique(array_merge($list, $request['extra']));
987 $request['params']['options']['sort'] = 'sort_name';
988 // Contact api doesn't support array(LIKE => 'foo') syntax
989 if (!empty($request['input'])) {
990 $request['params'][$request['search_field']] = $request['input'];
991 }
992 }
993
994 /**
995 * Get output for getlist function.
996 *
997 * @see _civicrm_api3_generic_getlist_output
998 *
999 * @param array $result
1000 * @param array $request
1001 *
1002 * @return array
1003 */
1004 function _civicrm_api3_contact_getlist_output($result, $request) {
1005 $output = array();
1006 if (!empty($result['values'])) {
1007 $addressFields = array_intersect(array(
1008 'street_address',
1009 'city',
1010 'state_province',
1011 'country',
1012 ),
1013 $request['params']['return']);
1014 foreach ($result['values'] as $row) {
1015 $data = array(
1016 'id' => $row[$request['id_field']],
1017 'label' => $row[$request['label_field']],
1018 'description' => array(),
1019 );
1020 foreach ($request['description_field'] as $item) {
1021 if (!strpos($item, '_name') && !in_array($item, $addressFields) && !empty($row[$item])) {
1022 $data['description'][] = $row[$item];
1023 }
1024 }
1025 $address = array();
1026 foreach ($addressFields as $item) {
1027 if (!empty($row[$item])) {
1028 $address[] = $row[$item];
1029 }
1030 }
1031 if ($address) {
1032 $data['description'][] = implode(' ', $address);
1033 }
1034 if (!empty($request['image_field'])) {
1035 $data['image'] = isset($row[$request['image_field']]) ? $row[$request['image_field']] : '';
1036 }
1037 else {
1038 $data['icon_class'] = $row['contact_type'];
1039 }
1040 foreach ($request['extra'] as $field) {
1041 $data['extra'][$field] = isset($row[$field]) ? $row[$field] : NULL;
1042 }
1043 $output[] = $data;
1044 }
1045 }
1046 return $output;
1047 }