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