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