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