Merge pull request #9605 from ErichBSchulz/patch-4
[civicrm-core.git] / api / v3 / Contact.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2017 |
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 $contactID = CRM_Utils_Array::value('contact_id', $params, CRM_Utils_Array::value('id', $params));
53
54 if ($contactID && !empty($params['check_permissions']) && !CRM_Contact_BAO_Contact_Permission::allow($contactID, CRM_Core_Permission::EDIT)) {
55 throw new \Civi\API\Exception\UnauthorizedException('Permission denied to modify contact record');
56 }
57
58 $dupeCheck = CRM_Utils_Array::value('dupe_check', $params, FALSE);
59 $values = _civicrm_api3_contact_check_params($params, $dupeCheck);
60 if ($values) {
61 return $values;
62 }
63
64 if (array_key_exists('api_key', $params) && !empty($params['check_permissions'])) {
65 if (CRM_Core_Permission::check('edit api keys') || CRM_Core_Permission::check('administer CiviCRM')) {
66 // OK
67 }
68 elseif ($contactID && CRM_Core_Permission::check('edit own api keys') && CRM_Core_Session::singleton()->get('userID') == $contactID) {
69 // OK
70 }
71 else {
72 throw new \Civi\API\Exception\UnauthorizedException('Permission denied to modify api key');
73 }
74 }
75
76 if (!$contactID) {
77 // If we get here, we're ready to create a new contact
78 if (($email = CRM_Utils_Array::value('email', $params)) && !is_array($params['email'])) {
79 $defLocType = CRM_Core_BAO_LocationType::getDefault();
80 $params['email'] = array(
81 1 => array(
82 'email' => $email,
83 'is_primary' => 1,
84 'location_type_id' => ($defLocType->id) ? $defLocType->id : 1,
85 ),
86 );
87 }
88 }
89
90 if (!empty($params['home_url'])) {
91 $websiteTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Website', 'website_type_id');
92 $params['website'] = array(
93 1 => array(
94 'website_type_id' => key($websiteTypes),
95 'url' => $params['home_url'],
96 ),
97 );
98 }
99
100 _civicrm_api3_greeting_format_params($params);
101
102 $values = array();
103
104 if (empty($params['contact_type']) && $contactID) {
105 $params['contact_type'] = CRM_Contact_BAO_Contact::getContactType($contactID);
106 }
107
108 if (!isset($params['contact_sub_type']) && $contactID) {
109 $params['contact_sub_type'] = CRM_Contact_BAO_Contact::getContactSubType($contactID);
110 }
111
112 _civicrm_api3_custom_format_params($params, $values, $params['contact_type'], $contactID);
113
114 $params = array_merge($params, $values);
115 //@todo we should just call basic_create here - but need to make contact:create accept 'id' on the bao
116 $contact = _civicrm_api3_contact_update($params, $contactID);
117
118 if (is_a($contact, 'CRM_Core_Error')) {
119 throw new API_Exception($contact->_errors[0]['message']);
120 }
121 else {
122 $values = array();
123 _civicrm_api3_object_to_array_unique_fields($contact, $values[$contact->id]);
124 }
125
126 return civicrm_api3_create_success($values, $params, 'Contact', 'create');
127 }
128
129 /**
130 * Adjust Metadata for Create action.
131 *
132 * @param array $params
133 * Array of parameters determined by getfields.
134 */
135 function _civicrm_api3_contact_create_spec(&$params) {
136 $params['contact_type']['api.required'] = 1;
137 $params['id']['api.aliases'] = array('contact_id');
138 $params['current_employer'] = array(
139 'title' => 'Current Employer',
140 'description' => 'Name of Current Employer',
141 'type' => CRM_Utils_Type::T_STRING,
142 );
143 $params['dupe_check'] = array(
144 'title' => 'Check for Duplicates',
145 'description' => 'Throw error if contact create matches dedupe rule',
146 'type' => CRM_Utils_Type::T_BOOLEAN,
147 );
148 $params['prefix_id']['api.aliases'] = array('individual_prefix', 'individual_prefix_id');
149 $params['suffix_id']['api.aliases'] = array('individual_suffix', 'individual_suffix_id');
150 $params['gender_id']['api.aliases'] = array('gender');
151 }
152
153 /**
154 * Retrieve one or more contacts, given a set of search params.
155 *
156 * @param array $params
157 *
158 * @return array
159 * API Result Array
160 */
161 function civicrm_api3_contact_get($params) {
162 $options = array();
163 _civicrm_api3_contact_get_supportanomalies($params, $options);
164 $contacts = _civicrm_api3_get_using_query_object('Contact', $params, $options);
165 return civicrm_api3_create_success($contacts, $params, 'Contact');
166 }
167
168 /**
169 * Get number of contacts matching the supplied criteria.
170 *
171 * @param array $params
172 *
173 * @return int
174 */
175 function civicrm_api3_contact_getcount($params) {
176 $options = array();
177 _civicrm_api3_contact_get_supportanomalies($params, $options);
178 $count = _civicrm_api3_get_using_query_object('Contact', $params, $options, 1);
179 return (int) $count;
180 }
181
182 /**
183 * Adjust Metadata for Get action.
184 *
185 * @param array $params
186 * Array of parameters determined by getfields.
187 */
188 function _civicrm_api3_contact_get_spec(&$params) {
189 $params['contact_is_deleted']['api.default'] = 0;
190
191 // We declare all these pseudoFields as there are other undocumented fields accessible
192 // via the api - but if check permissions is set we only allow declared fields
193 $params['address_id'] = array(
194 'title' => 'Primary Address ID',
195 'type' => CRM_Utils_Type::T_INT,
196 );
197 $params['street_address'] = array(
198 'title' => 'Primary Address Street Address',
199 'type' => CRM_Utils_Type::T_STRING,
200 );
201 $params['supplemental_address_1'] = array(
202 'title' => 'Primary Address Supplemental Address 1',
203 'type' => CRM_Utils_Type::T_STRING,
204 );
205 $params['supplemental_address_2'] = array(
206 'title' => 'Primary Address Supplemental Address 2',
207 'type' => CRM_Utils_Type::T_STRING,
208 );
209 $params['current_employer'] = array(
210 'title' => 'Current Employer',
211 'type' => CRM_Utils_Type::T_STRING,
212 );
213 $params['city'] = array(
214 'title' => 'Primary Address City',
215 'type' => CRM_Utils_Type::T_STRING,
216 );
217 $params['postal_code_suffix'] = array(
218 'title' => 'Primary Address Post Code Suffix',
219 'type' => CRM_Utils_Type::T_STRING,
220 );
221 $params['postal_code'] = array(
222 'title' => 'Primary Address Post Code',
223 'type' => CRM_Utils_Type::T_STRING,
224 );
225 $params['geo_code_1'] = array(
226 'title' => 'Primary Address Latitude',
227 'type' => CRM_Utils_Type::T_STRING,
228 );
229 $params['geo_code_2'] = array(
230 'title' => 'Primary Address Longitude',
231 'type' => CRM_Utils_Type::T_STRING,
232 );
233 $params['state_province_id'] = array(
234 'title' => 'Primary Address State Province ID',
235 'type' => CRM_Utils_Type::T_INT,
236 'pseudoconstant' => array(
237 'table' => 'civicrm_state_province',
238 ),
239 );
240 $params['state_province_name'] = array(
241 'title' => 'Primary Address State Province Name',
242 'type' => CRM_Utils_Type::T_STRING,
243 'pseudoconstant' => array(
244 'table' => 'civicrm_state_province',
245 ),
246 );
247 $params['state_province'] = array(
248 'title' => 'Primary Address State Province',
249 'type' => CRM_Utils_Type::T_STRING,
250 'pseudoconstant' => array(
251 'table' => 'civicrm_state_province',
252 ),
253 );
254 $params['country_id'] = array(
255 'title' => 'Primary Address Country ID',
256 'type' => CRM_Utils_Type::T_INT,
257 'pseudoconstant' => array(
258 'table' => 'civicrm_country',
259 ),
260 );
261 $params['country'] = array(
262 'title' => 'Primary Address country',
263 'type' => CRM_Utils_Type::T_STRING,
264 'pseudoconstant' => array(
265 'table' => 'civicrm_country',
266 ),
267 );
268 $params['worldregion_id'] = array(
269 'title' => 'Primary Address World Region ID',
270 'type' => CRM_Utils_Type::T_INT,
271 'pseudoconstant' => array(
272 'table' => 'civicrm_world_region',
273 ),
274 );
275 $params['worldregion'] = array(
276 'title' => 'Primary Address World Region',
277 'type' => CRM_Utils_Type::T_STRING,
278 'pseudoconstant' => array(
279 'table' => 'civicrm_world_region',
280 ),
281 );
282 $params['phone_id'] = array(
283 'title' => 'Primary Phone ID',
284 'type' => CRM_Utils_Type::T_INT,
285 );
286 $params['phone'] = array(
287 'title' => 'Primary Phone',
288 'type' => CRM_Utils_Type::T_STRING,
289 );
290 $params['phone_type_id'] = array(
291 'title' => 'Primary Phone Type ID',
292 'type' => CRM_Utils_Type::T_INT,
293 );
294 $params['provider_id'] = array(
295 'title' => 'Primary Phone Provider ID',
296 'type' => CRM_Utils_Type::T_INT,
297 );
298 $params['email_id'] = array(
299 'title' => 'Primary Email ID',
300 'type' => CRM_Utils_Type::T_INT,
301 );
302 $params['email'] = array(
303 'title' => 'Primary Email',
304 'type' => CRM_Utils_Type::T_STRING,
305 );
306 $params['on_hold'] = array(
307 'title' => 'Primary Email On Hold',
308 'type' => CRM_Utils_Type::T_BOOLEAN,
309 );
310 $params['im'] = array(
311 'title' => 'Primary Instant Messenger',
312 'type' => CRM_Utils_Type::T_STRING,
313 );
314 $params['im_id'] = array(
315 'title' => 'Primary Instant Messenger ID',
316 'type' => CRM_Utils_Type::T_INT,
317 );
318 $params['group'] = array(
319 'title' => 'Group',
320 'pseudoconstant' => array(
321 'table' => 'civicrm_group',
322 ),
323 );
324 $params['tag'] = array(
325 'title' => 'Tags',
326 'pseudoconstant' => array(
327 'table' => 'civicrm_tag',
328 ),
329 );
330 $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'));
331 $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'));
332 $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'));
333 $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'));
334 }
335
336 /**
337 * Support for historical oddities.
338 *
339 * We are supporting 'showAll' = 'all', 'trash' or 'active' for Contact get
340 * and for getcount
341 * - hopefully some day we'll come up with a std syntax for the 3-way-boolean of
342 * 0, 1 or not set
343 *
344 * We also support 'filter_group_id' & 'filter.group_id'
345 *
346 * @param array $params
347 * As passed into api get or getcount function.
348 * @param array $options
349 * Array of options (so we can modify the filter).
350 */
351 function _civicrm_api3_contact_get_supportanomalies(&$params, &$options) {
352 if (isset($params['showAll'])) {
353 if (strtolower($params['showAll']) == "active") {
354 $params['contact_is_deleted'] = 0;
355 }
356 if (strtolower($params['showAll']) == "trash") {
357 $params['contact_is_deleted'] = 1;
358 }
359 if (strtolower($params['showAll']) == "all" && isset($params['contact_is_deleted'])) {
360 unset($params['contact_is_deleted']);
361 }
362 }
363 // support for group filters
364 if (array_key_exists('filter_group_id', $params)) {
365 $params['filter.group_id'] = $params['filter_group_id'];
366 unset($params['filter_group_id']);
367 }
368 // filter.group_id works both for 1,2,3 and array (1,2,3)
369 if (array_key_exists('filter.group_id', $params)) {
370 if (is_array($params['filter.group_id'])) {
371 $groups = $params['filter.group_id'];
372 }
373 else {
374 $groups = explode(',', $params['filter.group_id']);
375 }
376 unset($params['filter.group_id']);
377 $options['input_params']['group'] = $groups;
378 }
379 }
380
381 /**
382 * Delete a Contact with given contact_id.
383 *
384 * @param array $params
385 * input parameters per getfields
386 *
387 * @throws \Civi\API\Exception\UnauthorizedException
388 * @return array
389 * API Result Array
390 */
391 function civicrm_api3_contact_delete($params) {
392 $contactID = CRM_Utils_Array::value('id', $params);
393
394 if (!empty($params['check_permissions']) && !CRM_Contact_BAO_Contact_Permission::allow($contactID, CRM_Core_Permission::DELETE)) {
395 throw new \Civi\API\Exception\UnauthorizedException('Permission denied to modify contact record');
396 }
397
398 $session = CRM_Core_Session::singleton();
399 if ($contactID == $session->get('userID')) {
400 return civicrm_api3_create_error('This contact record is linked to the currently logged in user account - and cannot be deleted.');
401 }
402 $restore = !empty($params['restore']) ? $params['restore'] : FALSE;
403 $skipUndelete = !empty($params['skip_undelete']) ? $params['skip_undelete'] : FALSE;
404
405 // CRM-12929
406 // restrict permanent delete if a contact has financial trxn associated with it
407 $error = NULL;
408 if ($skipUndelete && CRM_Financial_BAO_FinancialItem::checkContactPresent(array($contactID), $error)) {
409 return civicrm_api3_create_error($error['_qf_default']);
410 }
411 if (CRM_Contact_BAO_Contact::deleteContact($contactID, $restore, $skipUndelete,
412 CRM_Utils_Array::value('check_permissions', $params))) {
413 return civicrm_api3_create_success();
414 }
415 else {
416 return civicrm_api3_create_error('Could not delete contact');
417 }
418 }
419
420
421 /**
422 * Check parameters passed in.
423 *
424 * This function is on it's way out.
425 *
426 * @param array $params
427 * @param bool $dupeCheck
428 *
429 * @return null
430 * @throws API_Exception
431 * @throws CiviCRM_API3_Exception
432 */
433 function _civicrm_api3_contact_check_params(&$params, $dupeCheck) {
434
435 switch (strtolower(CRM_Utils_Array::value('contact_type', $params))) {
436 case 'household':
437 civicrm_api3_verify_mandatory($params, NULL, array('household_name'));
438 break;
439
440 case 'organization':
441 civicrm_api3_verify_mandatory($params, NULL, array('organization_name'));
442 break;
443
444 case 'individual':
445 civicrm_api3_verify_one_mandatory($params, NULL, array(
446 'first_name',
447 'last_name',
448 'email',
449 'display_name',
450 )
451 );
452 break;
453 }
454
455 // Fixme: This really needs to be handled at a lower level. @See CRM-13123
456 if (isset($params['preferred_communication_method'])) {
457 $params['preferred_communication_method'] = CRM_Utils_Array::implodePadded($params['preferred_communication_method']);
458 }
459
460 if (!empty($params['contact_sub_type']) && !empty($params['contact_type'])) {
461 if (!(CRM_Contact_BAO_ContactType::isExtendsContactType($params['contact_sub_type'], $params['contact_type']))) {
462 throw new API_Exception("Invalid or Mismatched Contact Subtype: " . implode(', ', (array) $params['contact_sub_type']));
463 }
464 }
465
466 if ($dupeCheck) {
467 // check for record already existing
468 $dedupeParams = CRM_Dedupe_Finder::formatParams($params, $params['contact_type']);
469
470 // CRM-6431
471 // setting 'check_permission' here means that the dedupe checking will be carried out even if the
472 // person does not have permission to carry out de-dupes
473 // this is similar to the front end form
474 if (isset($params['check_permission'])) {
475 $dedupeParams['check_permission'] = $params['check_permission'];
476 }
477
478 $ids = CRM_Dedupe_Finder::dupesByParams($dedupeParams, $params['contact_type'], 'Unsupervised', array());
479
480 if (count($ids) > 0) {
481 throw new API_Exception("Found matching contacts: " . implode(',', $ids), "duplicate", array("ids" => $ids));
482 }
483 }
484
485 // The BAO no longer supports the legacy param "current_employer" so here is a shim for api backward-compatability
486 if (!empty($params['current_employer'])) {
487 $organizationParams = array(
488 'organization_name' => $params['current_employer'],
489 );
490
491 $dedupParams = CRM_Dedupe_Finder::formatParams($organizationParams, 'Organization');
492
493 $dedupParams['check_permission'] = FALSE;
494 $dupeIds = CRM_Dedupe_Finder::dupesByParams($dedupParams, 'Organization', 'Supervised');
495
496 // check for mismatch employer name and id
497 if (!empty($params['employer_id']) && !in_array($params['employer_id'], $dupeIds)) {
498 throw new API_Exception('Employer name and Employer id Mismatch');
499 }
500
501 // show error if multiple organisation with same name exist
502 if (empty($params['employer_id']) && (count($dupeIds) > 1)) {
503 throw new API_Exception('Found more than one Organisation with same Name.');
504 }
505
506 if ($dupeIds) {
507 $params['employer_id'] = $dupeIds[0];
508 }
509 else {
510 $result = civicrm_api3('Contact', 'create', array(
511 'organization_name' => $params['current_employer'],
512 'contact_type' => 'Organization',
513 ));
514 $params['employer_id'] = $result['id'];
515 }
516 }
517
518 return NULL;
519 }
520
521 /**
522 * Helper function for Contact create.
523 *
524 * @param array $params
525 * (reference ) an assoc array of name/value pairs.
526 * @param int $contactID
527 * If present the contact with that ID is updated.
528 *
529 * @return CRM_Contact_BAO_Contact|CRM_Core_Error
530 */
531 function _civicrm_api3_contact_update($params, $contactID = NULL) {
532 //@todo - doesn't contact create support 'id' which is already set- check & remove
533 if ($contactID) {
534 $params['contact_id'] = $contactID;
535 }
536
537 return CRM_Contact_BAO_Contact::create($params);
538 }
539
540 /**
541 * Validate the addressee or email or postal greetings.
542 *
543 * @param array $params
544 * Array per getfields metadata.
545 *
546 * @throws API_Exception
547 */
548 function _civicrm_api3_greeting_format_params($params) {
549 $greetingParams = array('', '_id', '_custom');
550 foreach (array('email', 'postal', 'addressee') as $key) {
551 $greeting = '_greeting';
552 if ($key == 'addressee') {
553 $greeting = '';
554 }
555
556 $formatParams = FALSE;
557 // Unset display value from params.
558 if (isset($params["{$key}{$greeting}_display"])) {
559 unset($params["{$key}{$greeting}_display"]);
560 }
561
562 // check if greetings are present in present
563 foreach ($greetingParams as $greetingValues) {
564 if (array_key_exists("{$key}{$greeting}{$greetingValues}", $params)) {
565 $formatParams = TRUE;
566 break;
567 }
568 }
569
570 if (!$formatParams) {
571 continue;
572 }
573
574 $nullValue = FALSE;
575 $filter = array(
576 'contact_type' => $params['contact_type'],
577 'greeting_type' => "{$key}{$greeting}",
578 );
579
580 $greetings = CRM_Core_PseudoConstant::greeting($filter);
581 $greetingId = CRM_Utils_Array::value("{$key}{$greeting}_id", $params);
582 $greetingVal = CRM_Utils_Array::value("{$key}{$greeting}", $params);
583 $customGreeting = CRM_Utils_Array::value("{$key}{$greeting}_custom", $params);
584
585 if (!$greetingId && $greetingVal) {
586 $params["{$key}{$greeting}_id"] = CRM_Utils_Array::key($params["{$key}{$greeting}"], $greetings);
587 }
588
589 if ($customGreeting && $greetingId &&
590 ($greetingId != array_search('Customized', $greetings))
591 ) {
592 throw new API_Exception(ts('Provide either %1 greeting id and/or %1 greeting or custom %1 greeting',
593 array(1 => $key)
594 ));
595 }
596
597 if ($greetingVal && $greetingId &&
598 ($greetingId != CRM_Utils_Array::key($greetingVal, $greetings))
599 ) {
600 throw new API_Exception(ts('Mismatch in %1 greeting id and %1 greeting',
601 array(1 => $key)
602 ));
603 }
604
605 if ($greetingId) {
606
607 if (!array_key_exists($greetingId, $greetings)) {
608 throw new API_Exception(ts('Invalid %1 greeting Id', array(1 => $key)));
609 }
610
611 if (!$customGreeting && ($greetingId == array_search('Customized', $greetings))) {
612 throw new API_Exception(ts('Please provide a custom value for %1 greeting',
613 array(1 => $key)
614 ));
615 }
616 }
617 elseif ($greetingVal) {
618
619 if (!in_array($greetingVal, $greetings)) {
620 throw new API_Exception(ts('Invalid %1 greeting', array(1 => $key)));
621 }
622
623 $greetingId = CRM_Utils_Array::key($greetingVal, $greetings);
624 }
625
626 if ($customGreeting) {
627 $greetingId = CRM_Utils_Array::key('Customized', $greetings);
628 }
629
630 $customValue = isset($params['contact_id']) ? CRM_Core_DAO::getFieldValue(
631 'CRM_Contact_DAO_Contact',
632 $params['contact_id'],
633 "{$key}{$greeting}_custom"
634 ) : FALSE;
635
636 if (array_key_exists("{$key}{$greeting}_id", $params) && empty($params["{$key}{$greeting}_id"])) {
637 $nullValue = TRUE;
638 }
639 elseif (array_key_exists("{$key}{$greeting}", $params) && empty($params["{$key}{$greeting}"])) {
640 $nullValue = TRUE;
641 }
642 elseif ($customValue && array_key_exists("{$key}{$greeting}_custom", $params)
643 && empty($params["{$key}{$greeting}_custom"])
644 ) {
645 $nullValue = TRUE;
646 }
647
648 $params["{$key}{$greeting}_id"] = $greetingId;
649
650 if (!$customValue && !$customGreeting && array_key_exists("{$key}{$greeting}_custom", $params)) {
651 unset($params["{$key}{$greeting}_custom"]);
652 }
653
654 if ($nullValue) {
655 $params["{$key}{$greeting}_id"] = '';
656 $params["{$key}{$greeting}_custom"] = '';
657 }
658
659 if (isset($params["{$key}{$greeting}"])) {
660 unset($params["{$key}{$greeting}"]);
661 }
662 }
663 }
664
665 /**
666 * Adjust Metadata for Get action.
667 *
668 * @param array $params
669 * Array of parameters determined by getfields.
670 */
671 function _civicrm_api3_contact_getquick_spec(&$params) {
672 $params['name']['api.required'] = TRUE;
673 $params['name']['title'] = ts('String to search on');
674 $params['name']['type'] = CRM_Utils_Type::T_STRING;
675 $params['field']['type'] = CRM_Utils_Type::T_STRING;
676 $params['field']['title'] = ts('Field to search on');
677 $params['field']['options'] = array(
678 '',
679 'id',
680 'contact_id',
681 'external_identifier',
682 'first_name',
683 'last_name',
684 'job_title',
685 'postal_code',
686 'street_address',
687 'email',
688 'city',
689 'phone_numeric',
690 );
691 $params['table_name']['type'] = CRM_Utils_Type::T_STRING;
692 $params['table_name']['title'] = ts('Table alias to search on');
693 $params['table_name']['api.default'] = 'cc';
694 }
695
696 /**
697 * Old Contact quick search api.
698 *
699 * @deprecated
700 *
701 * @param array $params
702 *
703 * @return array
704 * @throws \API_Exception
705 */
706 function civicrm_api3_contact_getquick($params) {
707 $name = CRM_Utils_Type::escape(CRM_Utils_Array::value('name', $params), 'String');
708 $table_name = CRM_Utils_String::munge($params['table_name']);
709 // get the autocomplete options from settings
710 $acpref = explode(CRM_Core_DAO::VALUE_SEPARATOR,
711 CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME,
712 'contact_autocomplete_options'
713 )
714 );
715
716 // get the option values for contact autocomplete
717 $acOptions = CRM_Core_OptionGroup::values('contact_autocomplete_options', FALSE, FALSE, FALSE, NULL, 'name');
718
719 $list = array();
720 foreach ($acpref as $value) {
721 if ($value && !empty($acOptions[$value])) {
722 $list[$value] = $acOptions[$value];
723 }
724 }
725 // If we are doing quicksearch by a field other than name, make sure that field is added to results
726 if (!empty($params['field_name'])) {
727 $field_name = CRM_Utils_String::munge($params['field_name']);
728 // Unique name contact_id = id
729 if ($field_name == 'contact_id') {
730 $field_name = 'id';
731 }
732 // phone_numeric should be phone
733 $searchField = str_replace('_numeric', '', $field_name);
734 if (!in_array($searchField, $list)) {
735 $list[] = $searchField;
736 }
737 }
738 else {
739 // Set field name to first name for exact match checking.
740 $field_name = 'sort_name';
741 }
742
743 $select = $actualSelectElements = array('sort_name');
744 $where = '';
745 $from = array();
746 foreach ($list as $value) {
747 $suffix = substr($value, 0, 2) . substr($value, -1);
748 switch ($value) {
749 case 'street_address':
750 case 'city':
751 case 'postal_code':
752 $selectText = $value;
753 $value = "address";
754 $suffix = 'sts';
755 case 'phone':
756 case 'email':
757 $actualSelectElements[] = $select[] = ($value == 'address') ? $selectText : $value;
758 if ($value == 'phone') {
759 $actualSelectElements[] = $select[] = 'phone_ext';
760 }
761 $from[$value] = "LEFT JOIN civicrm_{$value} {$suffix} ON ( cc.id = {$suffix}.contact_id AND {$suffix}.is_primary = 1 ) ";
762 break;
763
764 case 'country':
765 case 'state_province':
766 $select[] = "{$suffix}.name as {$value}";
767 $actualSelectElements[] = "{$suffix}.name";
768 if (!in_array('address', $from)) {
769 $from['address'] = 'LEFT JOIN civicrm_address sts ON ( cc.id = sts.contact_id AND sts.is_primary = 1) ';
770 }
771 $from[$value] = " LEFT JOIN civicrm_{$value} {$suffix} ON ( sts.{$value}_id = {$suffix}.id ) ";
772 break;
773
774 default:
775 if ($value != 'id') {
776 $suffix = 'cc';
777 if (!empty($params['field_name']) && $params['field_name'] == 'value') {
778 $suffix = CRM_Utils_String::munge(CRM_Utils_Array::value('table_name', $params, 'cc'));
779 }
780 $actualSelectElements[] = $select[] = $suffix . '.' . $value;
781 }
782 break;
783 }
784 }
785
786 $config = CRM_Core_Config::singleton();
787 $as = $select;
788 $select = implode(', ', $select);
789 if (!empty($select)) {
790 $select = ", $select";
791 }
792 $actualSelectElements = implode(', ', $actualSelectElements);
793 $selectAliases = $from;
794 unset($selectAliases['address']);
795 $selectAliases = implode(', ', array_keys($selectAliases));
796 if (!empty($selectAliases)) {
797 $selectAliases = ", $selectAliases";
798 }
799 $from = implode(' ', $from);
800 $limit = (int) CRM_Utils_Array::value('limit', $params);
801 $limit = $limit > 0 ? $limit : Civi::settings()->get('search_autocomplete_count');
802
803 // add acl clause here
804 list($aclFrom, $aclWhere) = CRM_Contact_BAO_Contact_Permission::cacheClause('cc');
805
806 if ($aclWhere) {
807 $where .= " AND $aclWhere ";
808 }
809 $isPrependWildcard = \Civi::settings()->get('includeWildCardInName');
810
811 if (!empty($params['org'])) {
812 $where .= " AND contact_type = \"Organization\"";
813
814 // CRM-7157, hack: get current employer details when
815 // employee_id is present.
816 $currEmpDetails = array();
817 if (!empty($params['employee_id'])) {
818 if ($currentEmployer = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact',
819 (int) $params['employee_id'],
820 'employer_id'
821 )) {
822 if ($isPrependWildcard) {
823 $strSearch = "%$name%";
824 }
825 else {
826 $strSearch = "$name%";
827 }
828
829 // get current employer details
830 $dao = CRM_Core_DAO::executeQuery("SELECT cc.id as id, CONCAT_WS( ' :: ', {$actualSelectElements} ) as data, sort_name
831 FROM civicrm_contact cc {$from} WHERE cc.contact_type = \"Organization\" AND cc.id = {$currentEmployer} AND cc.sort_name LIKE '$strSearch'");
832 if ($dao->fetch()) {
833 $currEmpDetails = array(
834 'id' => $dao->id,
835 'data' => $dao->data,
836 );
837 }
838 }
839 }
840 }
841
842 if (!empty($params['contact_sub_type'])) {
843 $contactSubType = CRM_Utils_Type::escape($params['contact_sub_type'], 'String');
844 $where .= " AND cc.contact_sub_type = '{$contactSubType}'";
845 }
846
847 if (!empty($params['contact_type'])) {
848 $contactType = CRM_Utils_Type::escape($params['contact_type'], 'String');
849 $where .= " AND cc.contact_type LIKE '{$contactType}'";
850 }
851
852 // Set default for current_employer or return contact with particular id
853 if (!empty($params['id'])) {
854 $where .= " AND cc.id = " . (int) $params['id'];
855 }
856
857 if (!empty($params['cid'])) {
858 $where .= " AND cc.id <> " . (int) $params['cid'];
859 }
860
861 // Contact's based of relationhip type
862 $relType = NULL;
863 if (!empty($params['rel'])) {
864 $relation = explode('_', CRM_Utils_Array::value('rel', $params));
865 $relType = CRM_Utils_Type::escape($relation[0], 'Integer');
866 $rel = CRM_Utils_Type::escape($relation[2], 'String');
867 }
868
869 if ($isPrependWildcard) {
870 $strSearch = "%$name%";
871 }
872 else {
873 $strSearch = "$name%";
874 }
875 $includeEmailFrom = $includeNickName = $exactIncludeNickName = '';
876 if ($config->includeNickNameInName) {
877 $includeNickName = " OR nick_name LIKE '$strSearch'";
878 $exactIncludeNickName = " OR nick_name LIKE '$name'";
879 }
880
881 //CRM-10687
882 if (!empty($params['field_name']) && !empty($params['table_name'])) {
883 $whereClause = " WHERE ( $table_name.$field_name LIKE '$strSearch') {$where}";
884 // Search by id should be exact
885 if ($field_name == 'id' || $field_name == 'external_identifier') {
886 $whereClause = " WHERE ( $table_name.$field_name = '$name') {$where}";
887 }
888 }
889 else {
890 $whereClause = " WHERE ( sort_name LIKE '$strSearch' $includeNickName ) {$where} ";
891 if ($config->includeEmailInName) {
892 if (!in_array('email', $list)) {
893 $includeEmailFrom = "LEFT JOIN civicrm_email eml ON ( cc.id = eml.contact_id AND eml.is_primary = 1 )";
894 }
895 $emailWhere = " WHERE email LIKE '$strSearch'";
896 }
897 }
898
899 $additionalFrom = '';
900 if ($relType) {
901 $additionalFrom = "
902 INNER JOIN civicrm_relationship_type r ON (
903 r.id = {$relType}
904 AND ( cc.contact_type = r.contact_type_{$rel} OR r.contact_type_{$rel} IS NULL )
905 AND ( cc.contact_sub_type = r.contact_sub_type_{$rel} OR r.contact_sub_type_{$rel} IS NULL )
906 )";
907 }
908
909 // check if only CMS users are requested
910 if (!empty($params['cmsuser'])) {
911 $additionalFrom = "
912 INNER JOIN civicrm_uf_match um ON (um.contact_id=cc.id)
913 ";
914 }
915 $orderBy = _civicrm_api3_quicksearch_get_order_by($name, $isPrependWildcard, $field_name);
916
917 //CRM-5954
918 $query = "
919 SELECT DISTINCT(id), data, sort_name {$selectAliases}, exactFirst
920 FROM (
921 ( SELECT IF($table_name.$field_name = '{$name}', 0, 1) as exactFirst, cc.id as id, CONCAT_WS( ' :: ',
922 {$actualSelectElements} )
923 as data
924 {$select}
925 FROM civicrm_contact cc {$from}
926 {$aclFrom}
927 {$additionalFrom}
928 {$whereClause}
929 {$orderBy}
930 LIMIT 0, {$limit} )
931 ";
932
933 if (!empty($emailWhere)) {
934 $query .= "
935 UNION (
936 SELECT IF($table_name.$field_name = '{$name}', 0, 1) as exactFirst, cc.id as id, CONCAT_WS( ' :: ',
937 {$actualSelectElements} )
938 as data
939 {$select}
940 FROM civicrm_contact cc {$from}
941 {$aclFrom}
942 {$additionalFrom} {$includeEmailFrom}
943 {$emailWhere} AND cc.is_deleted = 0 " . ($aclWhere ? " AND $aclWhere " : '') . "
944 {$orderBy}
945 LIMIT 0, {$limit}
946 )
947 ";
948 }
949 $query .= ") t
950 {$orderBy}
951 LIMIT 0, {$limit}
952 ";
953
954 // send query to hook to be modified if needed
955 CRM_Utils_Hook::contactListQuery($query,
956 $name,
957 empty($params['context']) ? NULL : CRM_Utils_Type::escape($params['context'], 'String'),
958 empty($params['id']) ? NULL : $params['id']
959 );
960
961 $dao = CRM_Core_DAO::executeQuery($query);
962
963 $contactList = array();
964 $listCurrentEmployer = TRUE;
965 while ($dao->fetch()) {
966 $t = array('id' => $dao->id);
967 foreach ($as as $k) {
968 $t[$k] = isset($dao->$k) ? $dao->$k : '';
969 }
970 $t['data'] = $dao->data;
971 $contactList[] = $t;
972 if (!empty($params['org']) &&
973 !empty($currEmpDetails) &&
974 $dao->id == $currEmpDetails['id']
975 ) {
976 $listCurrentEmployer = FALSE;
977 }
978 }
979
980 //return organization name if doesn't exist in db
981 if (empty($contactList)) {
982 if (!empty($params['org'])) {
983 if ($listCurrentEmployer && !empty($currEmpDetails)) {
984 $contactList = array(
985 array(
986 'data' => $currEmpDetails['data'],
987 'id' => $currEmpDetails['id'],
988 ),
989 );
990 }
991 else {
992 $contactList = array(
993 array(
994 'data' => $name,
995 'id' => $name,
996 ),
997 );
998 }
999 }
1000 }
1001
1002 return civicrm_api3_create_success($contactList, $params, 'Contact', 'getquick');
1003 }
1004
1005 /**
1006 * Get the order by string for the quicksearch query.
1007 *
1008 * Get the order by string. The string might be
1009 * - sort name if there is no search value provided and the site is configured
1010 * to search by sort name
1011 * - empty if there is no search value provided and the site is not configured
1012 * to search by sort name
1013 * - exactFirst and then sort name if a search value is provided and the site is configured
1014 * to search by sort name
1015 * - exactFirst if a search value is provided and the site is not configured
1016 * to search by sort name
1017 *
1018 * exactFirst means 'yes if the search value exactly matches the searched field. else no'.
1019 * It is intended to prioritise exact matches for the entered string so on a first name search
1020 * for 'kath' contacts with a first name of exactly Kath rise to the top.
1021 *
1022 * On short strings it is expensive. Per CRM-19547 there is still an open question
1023 * as to whether we should only do exactMatch on a minimum length or on certain fields.
1024 *
1025 * However, we have mitigated this somewhat by not doing an exact match search on
1026 * empty strings, non-wildcard sort-name searches and email searches where there is
1027 * no @ after the first character.
1028 *
1029 * For the user it is further mitigated by the fact they just don't know the
1030 * slower queries are firing. If they type 'smit' slowly enough 4 queries will trigger
1031 * but if the first 3 are slow the first result they see may be off the 4th query.
1032 *
1033 * @param string $name
1034 * @param bool $isPrependWildcard
1035 * @param string $field_name
1036 *
1037 * @return string
1038 */
1039 function _civicrm_api3_quicksearch_get_order_by($name, $isPrependWildcard, $field_name) {
1040 $skipExactMatch = ($name === '%');
1041 if ($field_name === 'email' && !strpos('@', $name)) {
1042 $skipExactMatch = TRUE;
1043 }
1044
1045 if (!\Civi::settings()->get('includeOrderByClause')) {
1046 return $skipExactMatch ? '' : "ORDER BY exactFirst";
1047 }
1048 if ($skipExactMatch || (!$isPrependWildcard && $field_name === 'sort_name')) {
1049 // If there is no wildcard then sorting by exactFirst would have the same
1050 // effect as just a sort_name search, but slower.
1051 return "ORDER BY sort_name";
1052 }
1053
1054 return "ORDER BY exactFirst, sort_name";
1055 }
1056
1057 /**
1058 * Declare deprecated api functions.
1059 *
1060 * @deprecated api notice
1061 * @return array
1062 * Array of deprecated actions
1063 */
1064 function _civicrm_api3_contact_deprecation() {
1065 return array('getquick' => 'The "getquick" action is deprecated in favor of "getlist".');
1066 }
1067
1068 /**
1069 * Merges given pair of duplicate contacts.
1070 *
1071 * @param array $params
1072 * Allowed array keys are:
1073 * -int main_id: main contact id with whom merge has to happen
1074 * -int other_id: duplicate contact which would be deleted after merge operation
1075 * -string mode: "safe" skips the merge if there are no conflicts. Does a force merge otherwise.
1076 * -boolean auto_flip: whether to let api decide which contact to retain and which to delete.
1077 *
1078 * @return array
1079 * API Result Array
1080 * @throws CiviCRM_API3_Exception
1081 */
1082 function civicrm_api3_contact_merge($params) {
1083 if (($result = CRM_Dedupe_Merger::merge(array(
1084 array(
1085 'srcID' => $params['to_remove_id'],
1086 'dstID' => $params['to_keep_id'],
1087 ),
1088 ), array(), $params['mode'], $params['auto_flip'])) != FALSE) {
1089 return civicrm_api3_create_success($result, $params);
1090 }
1091 throw new CiviCRM_API3_Exception('Merge failed');
1092 }
1093
1094 /**
1095 * Adjust metadata for contact_merge api function.
1096 *
1097 * @param array $params
1098 */
1099 function _civicrm_api3_contact_merge_spec(&$params) {
1100 $params['to_remove_id'] = array(
1101 'title' => 'ID of the contact to merge & remove',
1102 'description' => ts('Wow - these 2 params are the logical reverse of what I expect - but what to do?'),
1103 'api.required' => 1,
1104 'type' => CRM_Utils_Type::T_INT,
1105 'api.aliases' => array('main_id'),
1106 );
1107 $params['to_keep_id'] = array(
1108 'title' => 'ID of the contact to keep',
1109 'description' => ts('Wow - these 2 params are the logical reverse of what I expect - but what to do?'),
1110 'api.required' => 1,
1111 'type' => CRM_Utils_Type::T_INT,
1112 'api.aliases' => array('other_id'),
1113 );
1114 $params['auto_flip'] = array(
1115 'title' => 'Swap destination and source to retain lowest id?',
1116 'api.default' => TRUE,
1117 );
1118 $params['mode'] = array(
1119 // @todo need more detail on what this means.
1120 'title' => 'Dedupe mode',
1121 'api.default' => 'safe',
1122 );
1123 }
1124
1125 /**
1126 * Adjust metadata for contact_proximity api function.
1127 *
1128 * @param array $params
1129 */
1130 function _civicrm_api3_contact_proximity_spec(&$params) {
1131 $params['latitude'] = array(
1132 'title' => 'Latitude',
1133 'api.required' => 1,
1134 'type' => CRM_Utils_Type::T_STRING,
1135 );
1136 $params['longitude'] = array(
1137 'title' => 'Longitude',
1138 'api.required' => 1,
1139 'type' => CRM_Utils_Type::T_STRING,
1140 );
1141
1142 $params['unit'] = array(
1143 'title' => 'Unit of Measurement',
1144 'api.default' => 'meter',
1145 'type' => CRM_Utils_Type::T_STRING,
1146 );
1147 }
1148
1149 /**
1150 * Get contacts by proximity.
1151 *
1152 * @param array $params
1153 *
1154 * @return array
1155 * @throws Exception
1156 */
1157 function civicrm_api3_contact_proximity($params) {
1158 $latitude = CRM_Utils_Array::value('latitude', $params);
1159 $longitude = CRM_Utils_Array::value('longitude', $params);
1160 $distance = CRM_Utils_Array::value('distance', $params);
1161
1162 $unit = CRM_Utils_Array::value('unit', $params);
1163
1164 // check and ensure that lat/long and distance are floats
1165 if (
1166 !CRM_Utils_Rule::numeric($latitude) ||
1167 !CRM_Utils_Rule::numeric($longitude) ||
1168 !CRM_Utils_Rule::numeric($distance)
1169 ) {
1170 throw new Exception(ts('Latitude, Longitude and Distance should exist and be numeric'));
1171 }
1172
1173 if ($unit == "mile") {
1174 $conversionFactor = 1609.344;
1175 }
1176 else {
1177 $conversionFactor = 1000;
1178 }
1179 //Distance in meters
1180 $distance = $distance * $conversionFactor;
1181
1182 $whereClause = CRM_Contact_BAO_ProximityQuery::where($latitude, $longitude, $distance);
1183
1184 $query = "
1185 SELECT civicrm_contact.id as contact_id,
1186 civicrm_contact.display_name as display_name
1187 FROM civicrm_contact
1188 LEFT JOIN civicrm_address ON civicrm_contact.id = civicrm_address.contact_id
1189 WHERE $whereClause
1190 ";
1191
1192 $dao = CRM_Core_DAO::executeQuery($query);
1193 $contacts = array();
1194 while ($dao->fetch()) {
1195 $contacts[] = $dao->toArray();
1196 }
1197
1198 return civicrm_api3_create_success($contacts, $params, 'Contact', 'get_by_location', $dao);
1199 }
1200
1201
1202 /**
1203 * Get parameters for getlist function.
1204 *
1205 * @see _civicrm_api3_generic_getlist_params
1206 *
1207 * @param array $request
1208 */
1209 function _civicrm_api3_contact_getlist_params(&$request) {
1210 // get the autocomplete options from settings
1211 $acpref = explode(CRM_Core_DAO::VALUE_SEPARATOR,
1212 CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME,
1213 'contact_autocomplete_options'
1214 )
1215 );
1216
1217 // get the option values for contact autocomplete
1218 $acOptions = CRM_Core_OptionGroup::values('contact_autocomplete_options', FALSE, FALSE, FALSE, NULL, 'name');
1219
1220 $list = array();
1221 foreach ($acpref as $value) {
1222 if ($value && !empty($acOptions[$value])) {
1223 $list[] = $acOptions[$value];
1224 }
1225 }
1226 // If we are doing quicksearch by a field other than name, make sure that field is added to results
1227 $field_name = CRM_Utils_String::munge($request['search_field']);
1228 // Unique name contact_id = id
1229 if ($field_name == 'contact_id') {
1230 $field_name = 'id';
1231 }
1232 // phone_numeric should be phone
1233 $searchField = str_replace('_numeric', '', $field_name);
1234 if (!in_array($searchField, $list)) {
1235 $list[] = $searchField;
1236 }
1237 $request['description_field'] = $list;
1238 $list[] = 'contact_type';
1239 $request['params']['return'] = array_unique(array_merge($list, $request['extra']));
1240 $request['params']['options']['sort'] = 'sort_name';
1241 // Contact api doesn't support array(LIKE => 'foo') syntax
1242 if (!empty($request['input'])) {
1243 $request['params'][$request['search_field']] = $request['input'];
1244 }
1245 }
1246
1247 /**
1248 * Get output for getlist function.
1249 *
1250 * @see _civicrm_api3_generic_getlist_output
1251 *
1252 * @param array $result
1253 * @param array $request
1254 *
1255 * @return array
1256 */
1257 function _civicrm_api3_contact_getlist_output($result, $request) {
1258 $output = array();
1259 if (!empty($result['values'])) {
1260 $addressFields = array_intersect(array(
1261 'street_address',
1262 'city',
1263 'state_province',
1264 'country',
1265 ),
1266 $request['params']['return']);
1267 foreach ($result['values'] as $row) {
1268 $data = array(
1269 'id' => $row[$request['id_field']],
1270 'label' => $row[$request['label_field']],
1271 'description' => array(),
1272 );
1273 foreach ($request['description_field'] as $item) {
1274 if (!strpos($item, '_name') && !in_array($item, $addressFields) && !empty($row[$item])) {
1275 $data['description'][] = $row[$item];
1276 }
1277 }
1278 $address = array();
1279 foreach ($addressFields as $item) {
1280 if (!empty($row[$item])) {
1281 $address[] = $row[$item];
1282 }
1283 }
1284 if ($address) {
1285 $data['description'][] = implode(' ', $address);
1286 }
1287 if (!empty($request['image_field'])) {
1288 $data['image'] = isset($row[$request['image_field']]) ? $row[$request['image_field']] : '';
1289 }
1290 else {
1291 $data['icon_class'] = $row['contact_type'];
1292 }
1293 $output[] = $data;
1294 }
1295 }
1296 return $output;
1297 }
1298
1299 /**
1300 * Check for duplicate contacts.
1301 *
1302 * @param array $params
1303 * Params per getfields metadata.
1304 *
1305 * @return array
1306 * API formatted array
1307 */
1308 function civicrm_api3_contact_duplicatecheck($params) {
1309 $dedupeParams = CRM_Dedupe_Finder::formatParams($params['match'], $params['match']['contact_type']);
1310
1311 // CRM-6431
1312 // setting 'check_permission' here means that the dedupe checking will be carried out even if the
1313 // person does not have permission to carry out de-dupes
1314 // this is similar to the front end form
1315 if (isset($params['check_permission'])) {
1316 $dedupeParams['check_permission'] = $params['check_permission'];
1317 }
1318
1319 $dupes = CRM_Dedupe_Finder::dupesByParams($dedupeParams, $params['match']['contact_type'], 'Unsupervised', array(), CRM_Utils_Array::value('dedupe_rule_id', $params));
1320 $values = empty($dupes) ? array() : array_fill_keys($dupes, array());
1321 return civicrm_api3_create_success($values, $params, 'Contact', 'duplicatecheck');
1322 }
1323
1324 /**
1325 * Declare metadata for contact dedupe function.
1326 *
1327 * @param $params
1328 */
1329 function _civicrm_api3_contact_duplicatecheck_spec(&$params) {
1330 $params['dedupe_rule_id'] = array(
1331 'title' => 'Dedupe Rule ID (optional)',
1332 'description' => 'This will default to the built in unsupervised rule',
1333 'type' => CRM_Utils_Type::T_INT,
1334 );
1335 // @todo declare 'match' parameter. We don't have a standard for type = array yet.
1336 }