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