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