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 * Note choice of submit versus create is discussed CRM-13234 & related to the fact
154 * 'profile' is being treated as a data-entry entity
155 *
156 * @param array $params
157 *
158 * @throws API_Exception
159 * @return array
160 * API result array
161 */
162 function civicrm_api3_profile_submit($params) {
163 $profileID = _civicrm_api3_profile_getProfileID($params['profile_id']);
164 if (!CRM_Core_DAO::getFieldValue('CRM_Core_DAO_UFGroup', $profileID, 'is_active')) {
165 //@todo declare pseudoconstant & let api do this
166 throw new API_Exception('Invalid value for profile_id');
167 }
168
169 $isContactActivityProfile = CRM_Core_BAO_UFField::checkContactActivityProfileType($profileID);
170
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');
173 }
174
175 $contactParams = $activityParams = $missingParams = array();
176
177 $profileFields = civicrm_api3('profile', 'getfields', array('action' => 'submit', 'profile_id' => $profileID));
178 $profileFields = $profileFields['values'];
179 if ($isContactActivityProfile) {
180 civicrm_api3_verify_mandatory($params, NULL, array('activity_id'));
181
182 $errors = CRM_Profile_Form::validateContactActivityProfile($params['activity_id'],
183 $params['contact_id'],
184 $profileID
185 );
186 if (!empty($errors)) {
187 throw new API_Exception(array_pop($errors));
188 }
189 }
190
191 foreach ($profileFields as $fieldName => $field) {
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 }
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));
204 if ($entity && !in_array($entity, array_merge($contactEntities, $locationEntities))) {
205 $contactParams['api.' . $entity . '.create'][$fieldName] = $value;
206 //@todo we are not currently declaring this option
207 if (isset($params['batch_id']) && strtolower($entity) == 'contribution') {
208 $contactParams['api.' . $entity . '.create']['batch_id'] = $params['batch_id'];
209 }
210 if (isset($params[$entity . '_id'])) {
211 //todo possibly declare $entity_id in getfields ?
212 $contactParams['api.' . $entity . '.create']['id'] = $params[$entity . '_id'];
213 }
214 }
215 else {
216 $contactParams[_civicrm_api3_profile_translate_fieldnames_for_bao($fieldName)] = $value;
217 }
218 }
219 if (isset($contactParams['api.contribution.create']) && isset($contactParams['api.membership.create'])) {
220 $contactParams['api.membership_payment.create'] = array(
221 'contribution_id' => '$value.api.contribution.create.id',
222 'membership_id' => '$value.api.membership.create.id',
223 );
224 }
225
226 if (isset($contactParams['api.contribution.create']) && isset($contactParams['api.participant.create'])) {
227 $contactParams['api.participant_payment.create'] = array(
228 'contribution_id' => '$value.api.contribution.create.id',
229 'participant_id' => '$value.api.participant.create.id',
230 );
231 }
232
233 $contactParams['contact_id'] = CRM_Utils_Array::value('contact_id', $params);
234 $contactParams['profile_id'] = $profileID;
235 $contactParams['skip_custom'] = 1;
236
237 $contactProfileParams = civicrm_api3_profile_apply($contactParams);
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 }
258
259 return civicrm_api3('contact', 'create', $profileParams);
260
261 $ufGroupDetails = array();
262 $ufGroupParams = array('id' => $profileID);
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'])) {
274 CRM_Core_BAO_EntityTag::create($tags,
275 'civicrm_contact',
276 $params['contact_id']
277 );
278 }
279
280 if (!empty($ufGroupDetails['add_to_group_id'])) {
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;
288
289 }
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
296 * @param string $fieldName
297 * API field name.
298 *
299 * @return string
300 * BAO Field Name
301 */
302 function _civicrm_api3_profile_translate_fieldnames_for_bao($fieldName) {
303 $fieldName = str_replace('url', 'URL', $fieldName);
304 return str_replace('primary', 'Primary', $fieldName);
305 }
306 /**
307 * metadata for submit action
308 * @param array $params
309 * @param array $apirequest
310 */
311 function _civicrm_api3_profile_submit_spec(&$params, $apirequest) {
312 if (isset($apirequest['params']['profile_id'])) {
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
320 $resolveOptions = CRM_Utils_Array::value('get_options', $apirequest['params']) == 'all' ? TRUE : FALSE;
321 $profileID = _civicrm_api3_profile_getProfileID($apirequest['params']['profile_id']);
322 $params = _civicrm_api3_buildprofile_submitfields($profileID, $resolveOptions, CRM_Utils_Array::value('cache_clear', $params));
323 }
324 elseif (isset($apirequest['params']['cache_clear'])) {
325 _civicrm_api3_buildprofile_submitfields(FALSE, FALSE, TRUE);
326 }
327 $params['profile_id']['api.required'] = TRUE;
328 $params['profile_id']['title'] = 'Profile ID';
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 *
336 * @param array $params
337 * Associative array of property name/value.
338 * pairs to update profile field values
339 *
340 * @return array
341 * Updated Contact/ Activity object|CRM_Error
342 *
343 *
344 */
345 function civicrm_api3_profile_set($params) {
346 return civicrm_api3('profile', 'submit', $params);
347 }
348
349 /**
350 * @deprecated - appears to be an internal function - should not be accessible via api
351 * Provide formatted values for profile fields.
352 *
353 * @param array $params
354 * Associative array of property name/value.
355 * pairs to profile field values
356 *
357 * @throws API_Exception
358 * @return array
359 *
360 * @todo add example
361 * @todo add test cases
362 */
363 function civicrm_api3_profile_apply($params) {
364
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)) {
386 throw new API_Exception('Enable to format profile parameters.');
387 }
388
389 return civicrm_api3_create_success($data);
390 }
391
392
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
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
401 *
402 * @param array $params
403 *
404 * @return array
405 */
406 function _civicrm_api3_profile_getbillingpseudoprofile(&$params) {
407
408 $locations = civicrm_api3('address', 'getoptions', array('field' => 'location_type_id', 'context' => 'validate'));
409 $locationTypeID = array_search('Billing', $locations['values']);
410
411 if (empty($params['contact_id'])) {
412 $config = CRM_Core_Config::singleton();
413 $blanks = array(
414 'billing_first_name' => '',
415 'billing_middle_name' => '',
416 'billing_last_name' => '',
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,
424 );
425 return $blanks;
426 }
427
428 $addressFields = array('street_address', 'city', 'state_province_id', 'country_id', 'postal_code');
429 $result = civicrm_api3('contact', 'getsingle', array(
430 'id' => $params['contact_id'],
431 'api.address.get.1' => array('location_type_id' => 'Billing', 'return' => $addressFields),
432 // getting the is_billing required or not is an extra db call but probably cheap enough as this isn't an import api
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),
436 'return' => 'api.email.get, api.address.get, api.address.getoptions, country, state_province, email, first_name, last_name, middle_name, ' . implode($addressFields, ','),
437 )
438 );
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
446 if (!empty($result['api.address.get.1']['count'])) {
447 foreach ($addressFields as $fieldname) {
448 $values['billing_' . $fieldname . '-' . $locationTypeID] = isset($result['api.address.get.1']['values'][0][$fieldname]) ? $result['api.address.get.1']['values'][0][$fieldname] : '';
449 }
450 }
451 elseif (!empty($result['api.address.get.2']['count'])) {
452 foreach ($addressFields as $fieldname) {
453 $values['billing_' . $fieldname . '-' . $locationTypeID] = isset($result['api.address.get.2']['values'][0][$fieldname]) ? $result['api.address.get.2']['values'][0][$fieldname] : '';
454 }
455 }
456 else {
457 foreach ($addressFields as $fieldname) {
458 $values['billing_' . $fieldname . '-' . $locationTypeID] = isset($result[$fieldname]) ? $result[$fieldname] : '';
459 }
460 }
461
462 if (!empty($result['api.email.get.1']['count'])) {
463 $values['billing-email' . '-' . $locationTypeID] = $result['api.email.get.1']['values'][0]['email'];
464 }
465 elseif (!empty($result['api.email.get.2']['count'])) {
466 $values['billing-email' . '-' . $locationTypeID] = $result['api.email.get.2']['values'][0]['email'];
467 }
468 else {
469 $values['billing-email' . '-' . $locationTypeID] = $result['email'];
470 }
471 // return both variants of email to reflect inconsistencies in form layer
472 $values['email' . '-' . $locationTypeID] = $values['billing-email' . '-' . $locationTypeID];
473 return $values;
474 }
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 *
487 * @param int $profileID
488 * @param int $optionsBehaviour
489 * 0 = don't resolve, 1 = resolve non-aggressively, 2 = resolve aggressively - ie include country & state.
490 * @param $is_flush
491 *
492 * @return array|void
493 */
494 function _civicrm_api3_buildprofile_submitfields($profileID, $optionsBehaviour = 1, $is_flush) {
495 static $profileFields = array();
496 if ($is_flush) {
497 $profileFields = array();
498 if (empty($profileID)) {
499 return NULL;
500 }
501 }
502 if (isset($profileFields[$profileID])) {
503 return $profileFields[$profileID];
504 }
505 $fields = civicrm_api3('uf_field', 'get', array('uf_group_id' => $profileID));
506 $entities = array();
507 foreach ($fields['values'] as $field) {
508 if (!$field['is_active']) {
509 continue;
510 }
511 list($entity, $fieldName) = _civicrm_api3_map_profile_fields_to_entity($field);
512 $aliasArray = array();
513 if (strtolower($fieldName) != $fieldName) {
514 $aliasArray['api.aliases'] = array($fieldName);
515 $fieldName = strtolower($fieldName);
516 }
517 $profileFields[$profileID][$fieldName] = array_merge(array(
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),
522 'entity' => $entity,
523 'weight' => CRM_Utils_Array::value('weight', $field),
524 ), $aliasArray);
525
526 $ufFieldTaleFieldName = $field['field_name'];
527 if (isset($entity[$ufFieldTaleFieldName]['name'])) {
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 }
532 //see function notes
533 // as we build up a list of these we should be able to determine a generic approach
534 //
535 $hardCodedEntityFields = array(
536 'state_province' => 'state_province_id',
537 'country' => 'country_id',
538 'participant_status' => 'status_id',
539 'gender' => 'gender_id',
540 'financial_type' => 'financial_type_id',
541 'soft_credit' => 'soft_credit_to',
542 'group' => 'group_id',
543 'tag' => 'tag_id',
544 'soft_credit_type' => 'soft_credit_type_id',
545 );
546
547 if (array_key_exists($ufFieldTaleFieldName, $hardCodedEntityFields)) {
548 $ufFieldTaleFieldName = $hardCodedEntityFields[$ufFieldTaleFieldName];
549 }
550
551 $entities[$entity][$fieldName] = $ufFieldTaleFieldName;
552 }
553
554 foreach ($entities as $entity => $entityFields) {
555 $result = civicrm_api3($entity, 'getfields', array('action' => 'create'));
556 $entityGetFieldsResult = _civicrm_api3_profile_appendaliases($result['values'], $entity);
557 foreach ($entityFields as $entityfield => $realName) {
558 $fieldName = strtolower($entityfield);
559 if (!strstr($fieldName, '-')) {
560 if (strtolower($realName) != $fieldName) {
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);
566 }
567 if (isset($entityGetFieldsResult[$realName]['uniqueName'])) {
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
570 $fieldName = $entityGetFieldsResult[$realName]['uniqueName'];
571 }
572 else {
573 if (isset($entityGetFieldsResult[$realName]['name'])) {
574 // this will sort out membership_type_id vs membership_type
575 $fieldName = $entityGetFieldsResult[$realName]['name'];
576 }
577 }
578 }
579 $profileFields[$profileID][$fieldName] = array_merge($entityGetFieldsResult[$realName], $profileFields[$profileID][$entityfield]);
580 if (!isset($profileFields[$profileID][$fieldName]['api.aliases'])) {
581 $profileFields[$profileID][$fieldName]['api.aliases'] = array();
582 }
583 if ($optionsBehaviour && !empty($entityGetFieldsResult[$realName]['pseudoconstant'])) {
584 if ($optionsBehaviour > 1 || !in_array($realName, array('state_province_id', 'county_id', 'country_id'))) {
585 $options = civicrm_api3($entity, 'getoptions', array('field' => $realName));
586 $profileFields[$profileID][$fieldName]['options'] = $options['values'];
587 }
588 }
589
590 if ($entityfield != $fieldName) {
591 if (isset($profileFields[$profileID][$entityfield])) {
592 unset($profileFields[$profileID][$entityfield]);
593 }
594 if (!in_array($entityfield, $profileFields[$profileID][$fieldName]['api.aliases'])) {
595 // we will make the mixed case version (e.g. of 'Primary') an alias
596 $profileFields[$profileID][$fieldName]['api.aliases'][] = $entityfield;
597 }
598 }
599 /**
600 * putting this on hold -this would cause the api to set the default - but could have unexpected behaviour
601 if (isset($result['values'][$realName]['default_value'])) {
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'];
604 }
605 */
606 }
607 }
608 uasort($profileFields[$profileID], "_civicrm_api3_order_by_weight");
609 return $profileFields[$profileID];
610 }
611
612 /**
613 * @param $a
614 * @param $b
615 *
616 * @return bool
617 */
618 function _civicrm_api3_order_by_weight($a, $b) {
619 return CRM_Utils_Array::value('weight', $b) < CRM_Utils_Array::value('weight', $a) ? TRUE : FALSE;
620 }
621
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 *
626 * @param $field
627 *
628 * @return array
629 */
630 function _civicrm_api3_map_profile_fields_to_entity(&$field) {
631 $entity = $field['field_type'];
632 $contactTypes = civicrm_api3('contact', 'getoptions', array('field' => 'contact_type'));
633 if (in_array($entity, $contactTypes['values'])) {
634 $entity = 'contact';
635 }
636 $entity = _civicrm_api_get_entity_name_from_camel($entity);
637 $locationFields = array('email' => 'email');
638 $fieldName = $field['field_name'];
639 if (!empty($field['location_type_id'])) {
640 if ($fieldName == 'email') {
641 $entity = 'email';
642 }
643 else {
644 $entity = 'address';
645 }
646 $fieldName .= '-' . $field['location_type_id'];
647 }
648 elseif (array_key_exists($fieldName, $locationFields)) {
649 $fieldName .= '-Primary';
650 $entity = 'email';
651 }
652 if (!empty($field['phone_type_id'])) {
653 $fieldName .= '-' . $field['location_type_id'];
654 $entity = 'phone';
655 }
656
657 // @todo - sort this out!
658 //here we do a hard-code list of known fields that don't map to where they are mapped to
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
662 $hardCodedEntityMappings = array(
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',
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
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',
684 'soft_credit_type' => 'contribution_soft',
685 'group' => 'group_contact',
686 'tag' => 'entity_tag',
687 );
688 if (array_key_exists($fieldName, $hardCodedEntityMappings)) {
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
696 * how we add a a pseudoconstant to this pseudo api to make that work
697 *
698 * @param int $profileID
699 *
700 * @return int|string
701 * @throws CiviCRM_API3_Exception
702 */
703 function _civicrm_api3_profile_getProfileID($profileID) {
704 if (!empty($profileID) && strtolower($profileID) != 'billing' && !is_numeric($profileID)) {
705 $profileID = civicrm_api3('uf_group', 'getvalue', array('return' => 'id', 'name' => $profileID));
706 }
707 return $profileID;
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
713 *
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)
718 * @param $entity
719 *
720 * @return array
721 */
722 function _civicrm_api3_profile_appendaliases($values, $entity) {
723 foreach ($values as $field => $spec) {
724 if (!empty($spec['api.aliases'])) {
725 foreach ($spec['api.aliases'] as $alias) {
726 $values[$alias] = $spec;
727 }
728 }
729 if (!empty($spec['uniqueName'])) {
730 $values[$spec['uniqueName']] = $spec;
731 }
732 }
733 //special case on membership & contribution - can't see how to handle in a generic way
734 if (in_array($entity, array('membership', 'contribution'))) {
735 $values['send_receipt'] = array('title' => 'Send Receipt', 'type' => (int) 16);
736 }
737 return $values;
738 }
739
740 /**
741 * @deprecated api notice
742 * @return array
743 * Array of deprecated actions
744 */
745 function _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 }