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