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