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