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