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