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