backwards arguments are deprecated
[civicrm-core.git] / api / v3 / Profile.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
5 | |
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
9 +--------------------------------------------------------------------+
10 */
11
12 /**
13 * This api exposes CiviCRM profiles.
14 *
15 * Profiles are collections of fields used as forms, listings, search columns, etc.
16 *
17 * @package CiviCRM_APIv3
18 */
19
20 /**
21 * Retrieve Profile field values.
22 *
23 * NOTE this api is not standard & since it is tested we need to honour that
24 * but the correct behaviour is for it to return an id indexed array as this supports
25 * multiple instances - if a single profile is passed in we will not return a normal api result array
26 * in order to avoid breaking code. (This could still be confusing :-( but we have to keep the tested behaviour working
27 *
28 * Note that if contact_id is empty an array of defaults is returned
29 *
30 * @param array $params
31 * Associative array of property name/value.
32 * pairs to get profile field values
33 *
34 * @return array
35 * @throws \CRM_Core_Exception
36 * @throws API_Exception
37 */
38 function civicrm_api3_profile_get($params) {
39 $nonStandardLegacyBehaviour = is_numeric($params['profile_id']);
40 if (!empty($params['check_permissions']) && !empty($params['contact_id']) && !1 === civicrm_api3('contact', 'getcount', ['contact_id' => $params['contact_id'], 'check_permissions' => 1])) {
41 throw new API_Exception('permission denied');
42 }
43 $profiles = (array) $params['profile_id'];
44 $values = [];
45 $ufGroupBAO = new CRM_Core_BAO_UFGroup();
46 foreach ($profiles as $profileID) {
47 $profileID = _civicrm_api3_profile_getProfileID($profileID);
48 $values[$profileID] = [];
49 if (strtolower($profileID) == 'billing') {
50 $values[$profileID] = _civicrm_api3_profile_getbillingpseudoprofile($params);
51 continue;
52 }
53 if (!CRM_Core_DAO::getFieldValue('CRM_Core_DAO_UFGroup', $profileID, 'is_active')) {
54 throw new API_Exception('Invalid value for profile_id : ' . $profileID);
55 }
56
57 $isContactActivityProfile = CRM_Core_BAO_UFField::checkContactActivityProfileType($profileID);
58
59 $profileFields = CRM_Core_BAO_UFGroup::getFields($profileID,
60 FALSE,
61 NULL,
62 NULL,
63 NULL,
64 FALSE,
65 NULL,
66 empty($params['check_permissions']),
67 NULL,
68 CRM_Core_Permission::EDIT
69 );
70
71 if ($isContactActivityProfile) {
72 civicrm_api3_verify_mandatory($params, NULL, ['activity_id']);
73
74 $errors = CRM_Profile_Form::validateContactActivityProfile($params['activity_id'],
75 $params['contact_id'],
76 $params['profile_id']
77 );
78 if (!empty($errors)) {
79 throw new API_Exception(array_pop($errors));
80 }
81
82 $contactFields = $activityFields = [];
83 foreach ($profileFields as $fieldName => $field) {
84 if (CRM_Utils_Array::value('field_type', $field) == 'Activity') {
85 $activityFields[$fieldName] = $field;
86 }
87 else {
88 $contactFields[$fieldName] = $field;
89 // we should return 'Primary' with & without capitalisation. it is more consistent with api to not
90 // capitalise, but for form support we need it for now. Hopefully we can move away from it
91 $contactFields[strtolower($fieldName)] = $field;
92 }
93 }
94
95 $ufGroupBAO->setProfileDefaults($params['contact_id'], $contactFields, $values[$profileID], TRUE);
96
97 if ($params['activity_id']) {
98 $ufGroupBAO->setComponentDefaults($activityFields, $params['activity_id'], 'Activity', $values[$profileID], TRUE);
99 }
100 }
101 elseif (!empty($params['contact_id'])) {
102 $ufGroupBAO->setProfileDefaults($params['contact_id'], $profileFields, $values[$profileID], TRUE);
103 foreach ($values[$profileID] as $fieldName => $field) {
104 // we should return 'Primary' with & without capitalisation. it is more consistent with api to not
105 // capitalise, but for form support we need it for now. Hopefully we can move away from it
106 $values[$profileID][strtolower($fieldName)] = $field;
107 }
108 }
109 else {
110 $values[$profileID] = array_fill_keys(array_keys($profileFields), '');
111 }
112 }
113 if ($nonStandardLegacyBehaviour) {
114 $result = civicrm_api3_create_success();
115 $result['values'] = $values[$profileID];
116 return $result;
117 }
118 else {
119 return civicrm_api3_create_success($values, $params, 'Profile', 'Get');
120 }
121 }
122
123 /**
124 * Adjust profile get function metadata.
125 *
126 * @param array $params
127 */
128 function _civicrm_api3_profile_get_spec(&$params) {
129 $params['profile_id']['api.required'] = TRUE;
130 $params['profile_id']['title'] = 'Profile ID';
131 $params['contact_id']['description'] = 'If no contact is specified an array of defaults will be returned';
132 $params['contact_id']['title'] = 'Contact ID';
133 }
134
135 /**
136 * Submit a set of fields against a profile.
137 *
138 * Note choice of submit versus create is discussed CRM-13234 & related to the fact
139 * 'profile' is being treated as a data-entry entity
140 *
141 * @param array $params
142 *
143 * @throws API_Exception
144 * @return array
145 * API result array
146 */
147 function civicrm_api3_profile_submit($params) {
148 $profileID = _civicrm_api3_profile_getProfileID($params['profile_id']);
149 if (!CRM_Core_DAO::getFieldValue('CRM_Core_DAO_UFGroup', $profileID, 'is_active')) {
150 //@todo declare pseudoconstant & let api do this
151 throw new API_Exception('Invalid value for profile_id');
152 }
153
154 $isContactActivityProfile = CRM_Core_BAO_UFField::checkContactActivityProfileType($profileID);
155
156 if (!empty($params['id']) && CRM_Core_BAO_UFField::checkProfileType($profileID) && !$isContactActivityProfile) {
157 throw new API_Exception('Update profiles including more than one entity not currently supported');
158 }
159
160 $contactParams = $activityParams = $missingParams = [];
161
162 $profileFields = civicrm_api3('Profile', 'getfields', ['action' => 'submit', 'profile_id' => $profileID]);
163 $profileFields = $profileFields['values'];
164 if ($isContactActivityProfile) {
165 civicrm_api3_verify_mandatory($params, NULL, ['activity_id']);
166
167 $errors = CRM_Profile_Form::validateContactActivityProfile($params['activity_id'],
168 $params['contact_id'],
169 $profileID
170 );
171 if (!empty($errors)) {
172 throw new API_Exception(array_pop($errors));
173 }
174 }
175
176 // Add custom greeting fields
177 $greetingFields = ['email_greeting', 'postal_greeting', 'addressee'];
178 foreach ($greetingFields as $greetingField) {
179 if (isset($profileFields[$greetingField]) && !isset($profileFields["{$greetingField}_custom"])) {
180 $profileFields["{$greetingField}_custom"] = ['name' => "{$greetingField}_custom"];
181 }
182 }
183
184 foreach ($profileFields as $fieldName => $field) {
185 if (!isset($params[$fieldName])) {
186 continue;
187 }
188
189 $value = $params[$fieldName];
190 if ($params[$fieldName] && isset($params[$fieldName . '_id'])) {
191 $value = $params[$fieldName . '_id'];
192 }
193 $contactEntities = ['contact', 'individual', 'organization', 'household'];
194 $locationEntities = ['email', 'address', 'phone', 'website', 'im'];
195
196 $entity = strtolower(CRM_Utils_Array::value('entity', $field));
197 if ($entity && !in_array($entity, array_merge($contactEntities, $locationEntities))) {
198 switch ($entity) {
199 case 'note':
200 if ($value) {
201 $contactParams['api.Note.create'] = [
202 'note' => $value,
203 'contact_id' => 'user_contact_id',
204 ];
205 }
206 break;
207
208 case 'entity_tag':
209 if (!is_array($value)) {
210 $value = $value ? explode(',', $value) : [];
211 }
212 $contactParams['api.entity_tag.replace'] = [
213 'tag_id' => $value,
214 ];
215 break;
216
217 default:
218 $contactParams['api.' . $entity . '.create'][$fieldName] = $value;
219 //@todo we are not currently declaring this option
220 if (isset($params['batch_id']) && strtolower($entity) == 'contribution') {
221 $contactParams['api.' . $entity . '.create']['batch_id'] = $params['batch_id'];
222 }
223 if (isset($params[$entity . '_id'])) {
224 //todo possibly declare $entity_id in getfields ?
225 $contactParams['api.' . $entity . '.create']['id'] = $params[$entity . '_id'];
226 }
227 }
228 }
229 else {
230 $contactParams[_civicrm_api3_profile_translate_fieldnames_for_bao($fieldName)] = $value;
231 }
232 }
233 if (isset($contactParams['api.contribution.create']) && isset($contactParams['api.membership.create'])) {
234 $contactParams['api.membership_payment.create'] = [
235 'contribution_id' => '$value.api.contribution.create.id',
236 'membership_id' => '$value.api.membership.create.id',
237 ];
238 }
239
240 if (isset($contactParams['api.contribution.create']) && isset($contactParams['api.participant.create'])) {
241 $contactParams['api.participant_payment.create'] = [
242 'contribution_id' => '$value.api.contribution.create.id',
243 'participant_id' => '$value.api.participant.create.id',
244 ];
245 }
246
247 $contactParams['contact_id'] = empty($params['contact_id']) ? CRM_Utils_Array::value('id', $params) : $params['contact_id'];
248 $contactParams['profile_id'] = $profileID;
249 $contactParams['skip_custom'] = 1;
250
251 $contactProfileParams = civicrm_api3_profile_apply($contactParams);
252
253 // Contact profile fields
254 $profileParams = $contactProfileParams['values'];
255
256 // If profile having activity fields
257 if ($isContactActivityProfile && !empty($activityParams)) {
258 $activityParams['id'] = $params['activity_id'];
259 $profileParams['api.activity.create'] = $activityParams;
260 }
261
262 return civicrm_api3('contact', 'create', $profileParams);
263 }
264
265 /**
266 * Translate field names for BAO.
267 *
268 * The api standards expect field names to be lower case but the BAO uses mixed case
269 * so we accept 'email-primary' but pass 'email-Primary' to the BAO
270 * we could make the BAO handle email-primary but this would alter the fieldname seen by hooks
271 * & we would need to consider that change
272 *
273 * @param string $fieldName
274 * API field name.
275 *
276 * @return string
277 * BAO Field Name
278 */
279 function _civicrm_api3_profile_translate_fieldnames_for_bao($fieldName) {
280 $fieldName = str_replace('url', 'URL', $fieldName);
281 return str_replace('primary', 'Primary', $fieldName);
282 }
283
284 /**
285 * Metadata for submit action.
286 *
287 * @param array $params
288 * @param array $apirequest
289 */
290 function _civicrm_api3_profile_submit_spec(&$params, $apirequest) {
291 if (isset($apirequest['params']['profile_id'])) {
292 // we will return what is required for this profile
293 // note the problem with simply over-riding getfields & then calling generic if needbe is we don't have the
294 // api request array to pass to it.
295 //@todo - it may make more sense just to pass the apiRequest to getfields
296 //@todo get_options should take an array - @ the moment it is only takes 'all' - which is supported
297 // by other getfields fn
298 // we don't resolve state, country & county for performance reasons
299 $resolveOptions = ($apirequest['params']['get_options'] ?? NULL) == 'all';
300 $profileID = _civicrm_api3_profile_getProfileID($apirequest['params']['profile_id']);
301 $params = _civicrm_api3_buildprofile_submitfields($profileID, $resolveOptions, CRM_Utils_Array::value('cache_clear', $params));
302 }
303 elseif (isset($apirequest['params']['cache_clear'])) {
304 _civicrm_api3_buildprofile_submitfields(FALSE, FALSE, TRUE);
305 }
306 $params['profile_id']['api.required'] = TRUE;
307 $params['profile_id']['title'] = 'Profile ID';
308 // Profile forms submit tag values as a string; hack to get past api wrapper validation
309 if (!empty($params['tag_id'])) {
310 unset($params['tag_id']['pseudoconstant']);
311 $params['tag_id']['type'] = CRM_Utils_Type::T_STRING;
312 }
313 }
314
315 /**
316 * Update Profile field values.
317 *
318 * @deprecated - calling this function directly is deprecated as 'set' is not a clear action
319 * use submit
320 *
321 * @param array $params
322 * Array of property name/value.
323 * pairs to update profile field values
324 *
325 * @return array
326 * Updated Contact/ Activity object|CRM_Error
327 */
328 function civicrm_api3_profile_set($params) {
329 return civicrm_api3('profile', 'submit', $params);
330 }
331
332 /**
333 * Apply profile.
334 *
335 * @deprecated - appears to be an internal function - should not be accessible via api
336 * Provide formatted values for profile fields.
337 *
338 * @param array $params
339 * Array of property name/value.
340 * pairs to profile field values
341 *
342 * @throws API_Exception
343 * @return array
344 *
345 * @todo add example
346 * @todo add test cases
347 */
348 function civicrm_api3_profile_apply($params) {
349 $profileFields = CRM_Core_BAO_UFGroup::getFields($params['profile_id'],
350 FALSE,
351 NULL,
352 NULL,
353 NULL,
354 FALSE,
355 NULL,
356 TRUE,
357 NULL,
358 CRM_Core_Permission::EDIT
359 );
360
361 list($data, $contactDetails) = CRM_Contact_BAO_Contact::formatProfileContactParams($params,
362 $profileFields,
363 CRM_Utils_Array::value('contact_id', $params),
364 $params['profile_id'],
365 CRM_Utils_Array::value('contact_type', $params),
366 CRM_Utils_Array::value('skip_custom', $params, FALSE)
367 );
368
369 if (empty($data)) {
370 throw new API_Exception('Unable to format profile parameters.');
371 }
372
373 return civicrm_api3_create_success($data);
374 }
375
376 /**
377 * Adjust Metadata for Apply action.
378 *
379 * The metadata is used for setting defaults, documentation & validation.
380 *
381 * @param array $params
382 * Array of parameters determined by getfields.
383 */
384 function _civicrm_api3_profile_apply_spec(&$params) {
385 $params['profile_id']['api.required'] = 1;
386 $params['profile_id']['title'] = 'Profile ID';
387 }
388
389 /**
390 * Get pseudo profile 'billing'.
391 *
392 * This is a function to help us 'pretend' billing is a profile & treat it like it is one.
393 * It gets standard credit card address fields etc
394 * Note this is 'better' that the inbuilt version as it will pull in fallback values
395 * billing location -> is_billing -> primary
396 *
397 * Note that that since the existing code for deriving a blank profile is not easily accessible our
398 * interim solution is just to return an empty array
399 *
400 * @param array $params
401 *
402 * @return array
403 */
404 function _civicrm_api3_profile_getbillingpseudoprofile(&$params) {
405
406 $locationTypeID = CRM_Core_BAO_LocationType::getBilling();
407
408 if (empty($params['contact_id'])) {
409 $config = CRM_Core_Config::singleton();
410 $blanks = [
411 'billing_first_name' => '',
412 'billing_middle_name' => '',
413 'billing_last_name' => '',
414 'email-' . $locationTypeID => '',
415 'billing_email-' . $locationTypeID => '',
416 'billing_city-' . $locationTypeID => '',
417 'billing_postal_code-' . $locationTypeID => '',
418 'billing_street_address-' . $locationTypeID => '',
419 'billing_country_id-' . $locationTypeID => $config->defaultContactCountry,
420 'billing_state_province_id-' . $locationTypeID => $config->defaultContactStateProvince,
421 ];
422 return $blanks;
423 }
424
425 $addressFields = ['street_address', 'city', 'state_province_id', 'country_id', 'postal_code'];
426 $result = civicrm_api3('contact', 'getsingle', [
427 'id' => $params['contact_id'],
428 'api.address.get.1' => ['location_type_id' => 'Billing', 'return' => $addressFields],
429 // getting the is_billing required or not is an extra db call but probably cheap enough as this isn't an import api
430 'api.address.get.2' => ['is_billing' => TRUE, 'return' => $addressFields],
431 'api.email.get.1' => ['location_type_id' => 'Billing'],
432 'api.email.get.2' => ['is_billing' => TRUE],
433 'return' => 'api.email.get, api.address.get, api.address.getoptions, country, state_province, email, first_name, last_name, middle_name, ' . implode(',', $addressFields),
434 ]
435 );
436
437 $values = [
438 'billing_first_name' => $result['first_name'],
439 'billing_middle_name' => $result['middle_name'],
440 'billing_last_name' => $result['last_name'],
441 ];
442
443 if (!empty($result['api.address.get.1']['count'])) {
444 foreach ($addressFields as $fieldname) {
445 $values['billing_' . $fieldname . '-' . $locationTypeID] = $result['api.address.get.1']['values'][0][$fieldname] ?? '';
446 }
447 }
448 elseif (!empty($result['api.address.get.2']['count'])) {
449 foreach ($addressFields as $fieldname) {
450 $values['billing_' . $fieldname . '-' . $locationTypeID] = $result['api.address.get.2']['values'][0][$fieldname] ?? '';
451 }
452 }
453 else {
454 foreach ($addressFields as $fieldname) {
455 $values['billing_' . $fieldname . '-' . $locationTypeID] = $result[$fieldname] ?? '';
456 }
457 }
458
459 if (!empty($result['api.email.get.1']['count'])) {
460 $values['billing-email' . '-' . $locationTypeID] = $result['api.email.get.1']['values'][0]['email'];
461 }
462 elseif (!empty($result['api.email.get.2']['count'])) {
463 $values['billing-email' . '-' . $locationTypeID] = $result['api.email.get.2']['values'][0]['email'];
464 }
465 else {
466 $values['billing-email' . '-' . $locationTypeID] = $result['email'];
467 }
468 // return both variants of email to reflect inconsistencies in form layer
469 $values['email' . '-' . $locationTypeID] = $values['billing-email' . '-' . $locationTypeID];
470 return $values;
471 }
472
473 /**
474 * Here we will build up getfields type data for all the fields in the profile.
475 *
476 * Because the integration with the form layer in core is so hard-coded we are not going to attempt to re-use it
477 * However, as this function is unit-tested & hence 'locked in' we can aspire to extract sharable
478 * code out of the form-layer over time.
479 *
480 * The function deciphers which fields belongs to which entites & retrieves metadata about the entities
481 * Unfortunately we have inconsistencies such as 'contribution' uses contribution_status_id
482 * & participant has 'participant_status' so we have to standardise from the outside in here -
483 * find the oddities, 'mask them' at this layer, add tests & work to standardise over time so we can remove this handling
484 *
485 * @param int $profileID
486 * @param int $optionsBehaviour
487 * 0 = don't resolve, 1 = resolve non-aggressively, 2 = resolve aggressively - ie include country & state.
488 * @param $is_flush
489 *
490 * @return array|void
491 */
492 function _civicrm_api3_buildprofile_submitfields($profileID, $optionsBehaviour = 1, $is_flush) {
493 static $profileFields = [];
494 if ($is_flush) {
495 $profileFields = [];
496 if (empty($profileID)) {
497 return NULL;
498 }
499 }
500 if (isset($profileFields[$profileID])) {
501 return $profileFields[$profileID];
502 }
503 $fields = civicrm_api3('uf_field', 'get', ['uf_group_id' => $profileID]);
504 $entities = [];
505 foreach ($fields['values'] as $field) {
506 if (!$field['is_active']) {
507 continue;
508 }
509 list($entity, $fieldName) = _civicrm_api3_map_profile_fields_to_entity($field);
510 $aliasArray = [];
511 if (strtolower($fieldName) != $fieldName) {
512 $aliasArray['api.aliases'] = [$fieldName];
513 $fieldName = strtolower($fieldName);
514 }
515 $profileFields[$profileID][$fieldName] = array_merge([
516 'api.required' => $field['is_required'],
517 'title' => $field['label'],
518 'help_pre' => $field['help_pre'] ?? NULL,
519 'help_post' => $field['help_post'] ?? NULL,
520 'entity' => $entity,
521 'weight' => $field['weight'] ?? NULL,
522 ], $aliasArray);
523
524 $ufFieldTaleFieldName = $field['field_name'];
525 if (isset($entity[$ufFieldTaleFieldName]['name'])) {
526 // in the case where we are dealing with an alias we map back to a name
527 // this will be tested by 'membership_type_id' field
528 $ufFieldTaleFieldName = $entity[$ufFieldTaleFieldName]['name'];
529 }
530 //see function notes
531 // as we build up a list of these we should be able to determine a generic approach
532 //
533 $hardCodedEntityFields = [
534 'state_province' => 'state_province_id',
535 'country' => 'country_id',
536 'participant_status' => 'status_id',
537 'gender' => 'gender_id',
538 'financial_type' => 'financial_type_id',
539 'soft_credit' => 'soft_credit_to',
540 'group' => 'group_id',
541 'tag' => 'tag_id',
542 'soft_credit_type' => 'soft_credit_type_id',
543 ];
544
545 if (array_key_exists($ufFieldTaleFieldName, $hardCodedEntityFields)) {
546 $ufFieldTaleFieldName = $hardCodedEntityFields[$ufFieldTaleFieldName];
547 }
548
549 $entities[$entity][$fieldName] = $ufFieldTaleFieldName;
550 }
551
552 foreach ($entities as $entity => $entityFields) {
553 $result = civicrm_api3($entity, 'getfields', ['action' => 'create']);
554 $entityGetFieldsResult = _civicrm_api3_profile_appendaliases($result['values'], $entity);
555 foreach ($entityFields as $entityfield => $realName) {
556 $fieldName = strtolower($entityfield);
557 if (!strstr($fieldName, '-')) {
558 if (strtolower($realName) != $fieldName) {
559 // we want to keep the '-' pattern for locations but otherwise
560 // we are going to make the api-standard field the main / preferred name but support the db name
561 // in future naming the fields in the DB to reflect the way the rest of the api / BAO / metadata works would
562 // reduce code
563 $fieldName = strtolower($realName);
564 }
565 if (isset($entityGetFieldsResult[$realName]['uniqueName'])) {
566 // we won't alias the field name on here are we are using uniqueNames for the possibility of needing to differentiate
567 // which entity 'status_id' belongs to
568 $fieldName = $entityGetFieldsResult[$realName]['uniqueName'];
569 }
570 else {
571 if (isset($entityGetFieldsResult[$realName]['name'])) {
572 // this will sort out membership_type_id vs membership_type
573 $fieldName = $entityGetFieldsResult[$realName]['name'];
574 }
575 }
576 }
577 $profileFields[$profileID][$fieldName] = array_merge($entityGetFieldsResult[$realName], $profileFields[$profileID][$entityfield]);
578 if (!isset($profileFields[$profileID][$fieldName]['api.aliases'])) {
579 $profileFields[$profileID][$fieldName]['api.aliases'] = [];
580 }
581 if ($optionsBehaviour && !empty($entityGetFieldsResult[$realName]['pseudoconstant'])) {
582 if ($optionsBehaviour > 1 || !in_array($realName, ['state_province_id', 'county_id', 'country_id'])) {
583 $options = civicrm_api3($entity, 'getoptions', ['field' => $realName]);
584 $profileFields[$profileID][$fieldName]['options'] = $options['values'];
585 }
586 }
587
588 if ($entityfield != $fieldName) {
589 if (isset($profileFields[$profileID][$entityfield])) {
590 unset($profileFields[$profileID][$entityfield]);
591 }
592 if (!in_array($entityfield, $profileFields[$profileID][$fieldName]['api.aliases'])) {
593 // we will make the mixed case version (e.g. of 'Primary') an alias
594 $profileFields[$profileID][$fieldName]['api.aliases'][] = $entityfield;
595 }
596 }
597 /**
598 * putting this on hold -this would cause the api to set the default - but could have unexpected behaviour
599 * if (isset($result['values'][$realName]['default_value'])) {
600 * //this would be the case for a custom field with a configured default
601 * $profileFields[$profileID][$entityfield]['api.default'] = $result['values'][$realName]['default_value'];
602 * }
603 */
604 }
605 }
606 uasort($profileFields[$profileID], "_civicrm_api3_order_by_weight");
607 return $profileFields[$profileID];
608 }
609
610 /**
611 * @param array $a
612 * @param array $b
613 *
614 * @return bool
615 */
616 function _civicrm_api3_order_by_weight($a, $b) {
617 return ($b['weight'] ?? 0) < ($a['weight'] ?? 0);
618 }
619
620 /**
621 * Here we map the profile fields as stored in the uf_field table to their 'real entity'
622 * we also return the profile fieldname
623 *
624 * @param $field
625 *
626 * @return array
627 */
628 function _civicrm_api3_map_profile_fields_to_entity(&$field) {
629 $entity = $field['field_type'];
630 $contactTypes = civicrm_api3('contact', 'getoptions', ['field' => 'contact_type']);
631 if (in_array($entity, $contactTypes['values'])) {
632 $entity = 'contact';
633 }
634 $entity = _civicrm_api_get_entity_name_from_camel($entity);
635 $locationFields = ['email', 'phone'];
636 $fieldName = $field['field_name'];
637 if (!empty($field['location_type_id'])) {
638 if (in_array($fieldName, $locationFields)) {
639 $entity = $fieldName;
640 }
641 else {
642 $entity = 'address';
643 }
644 $fieldName .= '-' . $field['location_type_id'];
645 }
646 elseif (in_array($fieldName, $locationFields)) {
647 $entity = $fieldName;
648 $fieldName .= '-Primary';
649 }
650 if (!empty($field['phone_type_id'])) {
651 $fieldName .= '-' . $field['phone_type_id'];
652 $entity = 'phone';
653 }
654
655 // @todo - sort this out!
656 //here we do a hard-code list of known fields that don't map to where they are mapped to
657 // not a great solution but probably if we looked in the BAO we'd find a scary switch statement
658 // in a perfect world the uf_field table would hold the correct entity for each item
659 // & only the relationships between entities would need to be coded
660 $hardCodedEntityMappings = [
661 'street_address' => 'address',
662 'street_number' => 'address',
663 'supplemental_address_1' => 'address',
664 'supplemental_address_2' => 'address',
665 'supplemental_address_3' => 'address',
666 'postal_code' => 'address',
667 'city' => 'address',
668 'email' => 'email',
669 'state_province' => 'address',
670 'country' => 'address',
671 'county' => 'address',
672 //note that in discussions about how to restructure the api we discussed making these membership
673 // fields into 'membership_payment' fields - which would entail declaring them in getfields
674 // & renaming them in existing profiles
675 'financial_type' => 'contribution',
676 'total_amount' => 'contribution',
677 'receive_date' => 'contribution',
678 'payment_instrument' => 'contribution',
679 'contribution_check_number' => 'contribution',
680 'contribution_status_id' => 'contribution',
681 'soft_credit' => 'contribution',
682 'soft_credit_type' => 'contribution_soft',
683 'group' => 'group_contact',
684 'tag' => 'entity_tag',
685 'note' => 'note',
686 ];
687 if (array_key_exists($fieldName, $hardCodedEntityMappings)) {
688 $entity = $hardCodedEntityMappings[$fieldName];
689 }
690 return [$entity, $fieldName];
691 }
692
693 /**
694 * @todo this should be handled by the api wrapper using getfields info - need to check
695 * how we add a a pseudoconstant to this pseudo api to make that work
696 *
697 * @param int $profileID
698 *
699 * @return int|string
700 * @throws CiviCRM_API3_Exception
701 */
702 function _civicrm_api3_profile_getProfileID($profileID) {
703 if (!empty($profileID) && strtolower($profileID) != 'billing' && !is_numeric($profileID)) {
704 $profileID = civicrm_api3('uf_group', 'getvalue', ['return' => 'id', 'name' => $profileID]);
705 }
706 return $profileID;
707 }
708
709 /**
710 * helper function to add all aliases as keys to getfields response so we can look for keys within it
711 * since the relationship between profile fields & api / metadata based fields is a bit inconsistent
712 *
713 * @param array $values
714 *
715 * e.g getfields response incl 'membership_type_id' - with api.aliases = 'membership_type'
716 * returned array will include both as keys (with the same values)
717 * @param $entity
718 *
719 * @return array
720 */
721 function _civicrm_api3_profile_appendaliases($values, $entity) {
722 foreach ($values as $field => $spec) {
723 if (!empty($spec['api.aliases'])) {
724 foreach ($spec['api.aliases'] as $alias) {
725 $values[$alias] = $spec;
726 }
727 }
728 if (!empty($spec['uniqueName'])) {
729 $values[$spec['uniqueName']] = $spec;
730 }
731 }
732 //special case on membership & contribution - can't see how to handle in a generic way
733 if (in_array($entity, ['membership', 'contribution'])) {
734 $values['send_receipt'] = ['title' => 'Send Receipt', 'type' => 16];
735 }
736 return $values;
737 }
738
739 /**
740 * @deprecated api notice
741 * @return array
742 * Array of deprecated actions
743 */
744 function _civicrm_api3_profile_deprecation() {
745 return [
746 'set' => 'Profile api "set" action is deprecated in favor of "submit".',
747 'apply' => 'Profile api "apply" action is deprecated in favor of "submit".',
748 ];
749 }