INFRA-132 - Spaces around "."
[civicrm-core.git] / api / v3 / Profile.php
1 <?php
2
3 /*
4 +--------------------------------------------------------------------+
5 | CiviCRM version 4.6 |
6 +--------------------------------------------------------------------+
7 | Copyright CiviCRM LLC (c) 2004-2014 |
8 +--------------------------------------------------------------------+
9 | This file is a part of CiviCRM. |
10 | |
11 | CiviCRM is free software; you can copy, modify, and distribute it |
12 | under the terms of the GNU Affero General Public License |
13 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | |
15 | CiviCRM is distributed in the hope that it will be useful, but |
16 | WITHOUT ANY WARRANTY; without even the implied warranty of |
17 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
18 | See the GNU Affero General Public License for more details. |
19 | |
20 | You should have received a copy of the GNU Affero General Public |
21 | License and the CiviCRM Licensing Exception along |
22 | with this program; if not, contact CiviCRM LLC |
23 | at info[AT]civicrm[DOT]org. If you have questions about the |
24 | GNU Affero General Public License or the licensing of CiviCRM, |
25 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
26 +--------------------------------------------------------------------+
27 */
28
29 /**
30 * File for the CiviCRM APIv3 activity profile functions
31 *
32 * @package CiviCRM_APIv3
33 * @subpackage API_ActivityProfile
34 * @copyright CiviCRM LLC (c) 2004-2014
35 * @version $Id: ActivityProfile.php 30486 2011-05-20 16:12:09Z rajan $
36 *
37 */
38
39 /**
40 * Retrieve Profile field values.
41 *
42 * @param array $params
43 * Associative array of property name/value.
44 * pairs to get profile field values
45 *
46 * @throws API_Exception
47 * @return Profile field values|CRM_Error
48 *
49 * NOTE this api is not standard & since it is tested we need to honour that
50 * but the correct behaviour is for it to return an id indexed array as this supports
51 * multiple instances - if a single profile is passed in we will not return a normal api result array
52 * in order to avoid breaking code. (This could still be confusing :-( but we have to keep the tested behaviour working
53 *
54 * Note that if contact_id is empty an array of defaults is returned
55 */
56 function civicrm_api3_profile_get($params) {
57 $nonStandardLegacyBehaviour = is_numeric($params['profile_id']) ? TRUE : FALSE;
58 if (!empty($params['check_permissions']) && !empty($params['contact_id']) && !1 === civicrm_api3('contact', 'getcount', array('contact_id' => $params['contact_id'], 'check_permissions' => 1))) {
59 throw new API_Exception('permission denied');
60 }
61 $profiles = (array) $params['profile_id'];
62 $values = array();
63 $ufGroupBAO = new CRM_Core_BAO_UFGroup();
64 foreach ($profiles as $profileID) {
65 $profileID = _civicrm_api3_profile_getProfileID($profileID);
66 $values[$profileID] = array();
67 if (strtolower($profileID) == 'billing') {
68 $values[$profileID] = _civicrm_api3_profile_getbillingpseudoprofile($params);
69 continue;
70 }
71 if (!CRM_Core_DAO::getFieldValue('CRM_Core_DAO_UFGroup', $profileID, 'is_active')) {
72 throw new API_Exception('Invalid value for profile_id : ' . $profileID);
73 }
74
75 $isContactActivityProfile = CRM_Core_BAO_UFField::checkContactActivityProfileType($profileID);
76
77 $profileFields = CRM_Core_BAO_UFGroup::getFields($profileID,
78 FALSE,
79 NULL,
80 NULL,
81 NULL,
82 FALSE,
83 NULL,
84 empty($params['check_permissions']) ? FALSE : TRUE,
85 NULL,
86 CRM_Core_Permission::EDIT
87 );
88
89 if ($isContactActivityProfile) {
90 civicrm_api3_verify_mandatory($params, NULL, array('activity_id'));
91
92 $errors = CRM_Profile_Form::validateContactActivityProfile($params['activity_id'],
93 $params['contact_id'],
94 $params['profile_id']
95 );
96 if (!empty($errors)) {
97 throw new API_Exception(array_pop($errors));
98 }
99
100 $contactFields = $activityFields = array();
101 foreach ($profileFields as $fieldName => $field) {
102 if (CRM_Utils_Array::value('field_type', $field) == 'Activity') {
103 $activityFields[$fieldName] = $field;
104 }
105 else {
106 $contactFields[$fieldName] = $field;
107 // we should return 'Primary' with & without capitalisation. it is more consistent with api to not
108 // capitalise, but for form support we need it for now. Hopefully we can move away from it
109 $contactFields[strtolower($fieldName)] = $field;
110 }
111 }
112
113 $ufGroupBAO->setProfileDefaults($params['contact_id'], $contactFields, $values[$profileID], TRUE);
114
115 if ($params['activity_id']) {
116 $ufGroupBAO->setComponentDefaults($activityFields, $params['activity_id'], 'Activity', $values[$profileID], TRUE);
117 }
118 }
119 elseif(!empty($params['contact_id'])) {
120 $ufGroupBAO->setProfileDefaults($params['contact_id'], $profileFields, $values[$profileID], TRUE);
121 foreach ($values[$profileID] as $fieldName => $field) {
122 // we should return 'Primary' with & without capitalisation. it is more consistent with api to not
123 // capitalise, but for form support we need it for now. Hopefully we can move away from it
124 $values[$profileID][strtolower($fieldName)] = $field;
125 }
126 }
127 else{
128 $values[$profileID] = array_fill_keys(array_keys($profileFields), '');
129 }
130 }
131 if ($nonStandardLegacyBehaviour) {
132 $result = civicrm_api3_create_success();
133 $result['values'] = $values[$profileID];
134 return $result;
135 }
136 else {
137 return civicrm_api3_create_success($values, $params, 'Profile', 'Get');
138 }
139 }
140
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 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 BAO Field Name
299 */
300 function _civicrm_api3_profile_translate_fieldnames_for_bao($fieldName) {
301 $fieldName = str_replace('url', 'URL', $fieldName);
302 return str_replace('primary', 'Primary', $fieldName);
303 }
304 /**
305 * metadata for submit action
306 * @param array $params
307 * @param array $apirequest
308 */
309 function _civicrm_api3_profile_submit_spec(&$params, $apirequest) {
310 if (isset($apirequest['params']['profile_id'])) {
311 // we will return what is required for this profile
312 // note the problem with simply over-riding getfields & then calling generic if needbe is we don't have the
313 // api request array to pass to it.
314 //@todo - it may make more sense just to pass the apiRequest to getfields
315 //@todo get_options should take an array - @ the moment it is only takes 'all' - which is supported
316 // by other getfields fn
317 // we don't resolve state, country & county for performance reasons
318 $resolveOptions = CRM_Utils_Array::value('get_options', $apirequest['params']) == 'all' ? TRUE : FALSE;
319 $profileID = _civicrm_api3_profile_getProfileID($apirequest['params']['profile_id']);
320 $params = _civicrm_api3_buildprofile_submitfields($profileID, $resolveOptions, CRM_Utils_Array::value('cache_clear', $params));
321 }
322 elseif (isset($apirequest['params']['cache_clear'])) {
323 _civicrm_api3_buildprofile_submitfields(FALSE, FALSE, TRUE);
324 }
325 $params['profile_id']['api.required'] = TRUE;
326 $params['profile_id']['title'] = 'Profile ID';
327 }
328
329 /**
330 * @deprecated - calling this function directly is deprecated as 'set' is not a clear action
331 * use submit
332 * Update Profile field values.
333 *
334 * @param array $params
335 * Associative array of property name/value.
336 * pairs to update profile field values
337 *
338 * @return array Updated Contact/ Activity object|CRM_Error
339 *
340 *
341 */
342 function civicrm_api3_profile_set($params) {
343 return civicrm_api3('profile', 'submit', $params);
344 }
345
346 /**
347 * @deprecated - appears to be an internal function - should not be accessible via api
348 * Provide formatted values for profile fields.
349 *
350 * @param array $params
351 * Associative array of property name/value.
352 * pairs to profile field values
353 *
354 * @throws API_Exception
355 * @return formatted profile field values|CRM_Error
356 *
357 * @todo add example
358 * @todo add test cases
359 */
360 function civicrm_api3_profile_apply($params) {
361
362 $profileFields = CRM_Core_BAO_UFGroup::getFields($params['profile_id'],
363 FALSE,
364 NULL,
365 NULL,
366 NULL,
367 FALSE,
368 NULL,
369 TRUE,
370 NULL,
371 CRM_Core_Permission::EDIT
372 );
373
374 list($data, $contactDetails) = CRM_Contact_BAO_Contact::formatProfileContactParams($params,
375 $profileFields,
376 CRM_Utils_Array::value('contact_id', $params),
377 $params['profile_id'],
378 CRM_Utils_Array::value('contact_type', $params),
379 CRM_Utils_Array::value('skip_custom', $params, FALSE)
380 );
381
382 if (empty($data)) {
383 throw new API_Exception('Enable to format profile parameters.');
384 }
385
386 return civicrm_api3_create_success($data);
387 }
388
389
390 /**
391 * This is a function to help us 'pretend' billing is a profile & treat it like it is one.
392 * It gets standard credit card address fields etc
393 * Note this is 'better' that the inbuilt version as it will pull in fallback values
394 * billing location -> is_billing -> primary
395 *
396 * Note that that since the existing code for deriving a blank profile is not easily accessible our
397 * interim solution is just to return an empty array
398 *
399 * @param array $params
400 *
401 * @return array
402 */
403 function _civicrm_api3_profile_getbillingpseudoprofile(&$params) {
404
405 $locations = civicrm_api3('address', 'getoptions', array('field' => 'location_type_id'));
406 $locationTypeID = array_search('Billing', $locations['values']);
407
408 if (empty($params['contact_id'])) {
409 $config = CRM_Core_Config::singleton();
410 $blanks = array(
411 'billing_first_name' => '',
412 'billing_middle_name' => '',
413 'billing_last_name' => '',
414 'email-' . $locationTypeID => '',
415 'billing_email-' . $locationTypeID => '',
416 'billing_city-' . $locationTypeID => '',
417 'billing_postal_code-' . $locationTypeID => '',
418 'billing_street_address-' . $locationTypeID => '',
419 'billing_country_id-' . $locationTypeID => $config->defaultContactCountry,
420 'billing_state_province_id-' . $locationTypeID => $config->defaultContactStateProvince,
421 );
422 return $blanks;
423 }
424
425 $addressFields = array('street_address', 'city', 'state_province_id', 'country_id', 'postal_code');
426 $result = civicrm_api3('contact', 'getsingle', array(
427 'id' => $params['contact_id'],
428 'api.address.get.1' => array('location_type_id' => 'Billing', 'return' => $addressFields),
429 // getting the is_billing required or not is an extra db call but probably cheap enough as this isn't an import api
430 'api.address.get.2' => array('is_billing' => TRUE, 'return' => $addressFields),
431 'api.email.get.1' => array('location_type_id' => 'Billing'),
432 'api.email.get.2' => array('is_billing' => TRUE),
433 'return' => 'api.email.get, api.address.get, api.address.getoptions, country, state_province, email, first_name, last_name, middle_name, ' . implode($addressFields, ','),
434 )
435 );
436
437 $values = array(
438 'billing_first_name' => $result['first_name'],
439 'billing_middle_name' => $result['middle_name'],
440 'billing_last_name' => $result['last_name'],
441 );
442
443 if (!empty($result['api.address.get.1']['count'])) {
444 foreach ($addressFields as $fieldname) {
445 $values['billing_' . $fieldname . '-' . $locationTypeID] = isset($result['api.address.get.1']['values'][0][$fieldname]) ? $result['api.address.get.1']['values'][0][$fieldname] : '';
446 }
447 }
448 elseif(!empty($result['api.address.get.2']['count'])) {
449 foreach ($addressFields as $fieldname) {
450 $values['billing_' . $fieldname . '-' . $locationTypeID] = isset($result['api.address.get.2']['values'][0][$fieldname]) ? $result['api.address.get.2']['values'][0][$fieldname] : '';
451 }
452 }
453 else{
454 foreach ($addressFields as $fieldname) {
455 $values['billing_' . $fieldname . '-' . $locationTypeID] = isset($result[$fieldname]) ? $result[$fieldname] : '';
456 }
457 }
458
459 if (!empty($result['api.email.get.1']['count'])) {
460 $values['billing-email' . '-' . $locationTypeID] = $result['api.email.get.1']['values'][0]['email'];
461 }
462 elseif(!empty($result['api.email.get.2']['count'])) {
463 $values['billing-email' . '-' . $locationTypeID] = $result['api.email.get.2']['values'][0]['email'];
464 }
465 else{
466 $values['billing-email' . '-' . $locationTypeID] = $result['email'];
467 }
468 // return both variants of email to reflect inconsistencies in form layer
469 $values['email' . '-' . $locationTypeID] = $values['billing-email' . '-' . $locationTypeID];
470 return $values;
471 }
472
473 /**
474 * Here we will build up getfields type data for all the fields in the profile. Because the integration with the
475 * form layer in core is so hard-coded we are not going to attempt to re-use it
476 * However, as this function is unit-tested & hence 'locked in' we can aspire to extract sharable
477 * code out of the form-layer over time.
478 *
479 * The function deciphers which fields belongs to which entites & retrieves metadata about the entities
480 * Unfortunately we have inconsistencies such as 'contribution' uses contribution_status_id
481 * & participant has 'participant_status' so we have to standardise from the outside in here -
482 * find the oddities, 'mask them' at this layer, add tests & work to standardise over time so we can remove this handling
483 *
484 * @param int $profileID
485 * @param int $optionsBehaviour
486 * 0 = don't resolve, 1 = resolve non-aggressively, 2 = resolve aggressively - ie include country & state.
487 * @param $is_flush
488 *
489 * @return
490 */
491
492 function _civicrm_api3_buildprofile_submitfields($profileID, $optionsBehaviour = 1, $is_flush) {
493 static $profileFields = array();
494 if ($is_flush) {
495 $profileFields = array();
496 if (empty($profileID)) {
497 return;
498 }
499 }
500 if (isset($profileFields[$profileID])) {
501 return $profileFields[$profileID];
502 }
503 $fields = civicrm_api3('uf_field', 'get', array('uf_group_id' => $profileID));
504 $entities = array();
505 foreach ($fields['values'] as $field) {
506 if (!$field['is_active']) {
507 continue;
508 }
509 list($entity, $fieldName) = _civicrm_api3_map_profile_fields_to_entity($field);
510 $aliasArray = array();
511 if (strtolower($fieldName) != $fieldName) {
512 $aliasArray['api.aliases'] = array($fieldName);
513 $fieldName = strtolower($fieldName);
514 }
515 $profileFields[$profileID][$fieldName] = array_merge(array(
516 'api.required' => $field['is_required'],
517 'title' => $field['label'],
518 'help_pre' => CRM_Utils_Array::value('help_pre', $field),
519 'help_post' => CRM_Utils_Array::value('help_post', $field),
520 'entity' => $entity,
521 'weight' => CRM_Utils_Array::value('weight', $field),
522 ), $aliasArray);
523
524 $ufFieldTaleFieldName = $field['field_name'];
525 if (isset($entity[$ufFieldTaleFieldName]['name'])) {
526 // in the case where we are dealing with an alias we map back to a name
527 // this will be tested by 'membership_type_id' field
528 $ufFieldTaleFieldName = $entity[$ufFieldTaleFieldName]['name'];
529 }
530 //see function notes
531 // as we build up a list of these we should be able to determine a generic approach
532 //
533 $hardCodedEntityFields = array(
534 'state_province' => 'state_province_id',
535 'country' => 'country_id',
536 'participant_status' => 'status_id',
537 'gender' => 'gender_id',
538 'financial_type' => 'financial_type_id',
539 'soft_credit' => 'soft_credit_to',
540 'group' => 'group_id',
541 'tag' => 'tag_id',
542 'soft_credit_type' => 'soft_credit_type_id',
543 );
544
545 if (array_key_exists($ufFieldTaleFieldName, $hardCodedEntityFields)) {
546 $ufFieldTaleFieldName = $hardCodedEntityFields[$ufFieldTaleFieldName];
547 }
548
549 $entities[$entity][$fieldName] = $ufFieldTaleFieldName;
550 }
551
552 foreach ($entities as $entity => $entityFields) {
553 $result = civicrm_api3($entity, 'getfields', array('action' => 'create'));
554 $entityGetFieldsResult = _civicrm_api3_profile_appendaliases($result['values'], $entity);
555 foreach ($entityFields as $entityfield => $realName) {
556 $fieldName = strtolower($entityfield);
557 if (!strstr($fieldName, '-')) {
558 if (strtolower($realName) != $fieldName) {
559 // we want to keep the '-' pattern for locations but otherwise
560 // we are going to make the api-standard field the main / preferred name but support the db name
561 // in future naming the fields in the DB to reflect the way the rest of the api / BAO / metadata works would
562 // reduce code
563 $fieldName = strtolower($realName);
564 }
565 if (isset($entityGetFieldsResult[$realName]['uniqueName'])) {
566 // we won't alias the field name on here are we are using uniqueNames for the possibility of needing to differentiate
567 // which entity 'status_id' belongs to
568 $fieldName = $entityGetFieldsResult[$realName]['uniqueName'];
569 }
570 else{
571 if (isset($entityGetFieldsResult[$realName]['name'])) {
572 // this will sort out membership_type_id vs membership_type
573 $fieldName = $entityGetFieldsResult[$realName]['name'];
574 }
575 }
576 }
577 $profileFields[$profileID][$fieldName] = array_merge($entityGetFieldsResult[$realName], $profileFields[$profileID][$entityfield]);
578 if (!isset($profileFields[$profileID][$fieldName]['api.aliases'])) {
579 $profileFields[$profileID][$fieldName]['api.aliases'] = array();
580 }
581 if ($optionsBehaviour && !empty($entityGetFieldsResult[$realName]['pseudoconstant'])) {
582 if ($optionsBehaviour > 1 || !in_array($realName, array('state_province_id', 'county_id', 'country_id'))) {
583 $options = civicrm_api3($entity, 'getoptions', array('field' => $realName));
584 $profileFields[$profileID][$fieldName]['options'] = $options['values'];
585 }
586 }
587
588 if ($entityfield != $fieldName) {
589 if (isset($profileFields[$profileID][$entityfield])) {
590 unset($profileFields[$profileID][$entityfield]);
591 }
592 if (!in_array($entityfield, $profileFields[$profileID][$fieldName]['api.aliases'])) {
593 // we will make the mixed case version (e.g. of 'Primary') an alias
594 $profileFields[$profileID][$fieldName]['api.aliases'][] = $entityfield;
595 }
596 }
597 /**
598 * putting this on hold -this would cause the api to set the default - but could have unexpected behaviour
599 if (isset($result['values'][$realName]['default_value'])) {
600 //this would be the case for a custom field with a configured default
601 $profileFields[$profileID][$entityfield]['api.default'] = $result['values'][$realName]['default_value'];
602 }
603 */
604 }
605 }
606 uasort($profileFields[$profileID], "_civicrm_api3_order_by_weight");
607 return $profileFields[$profileID];
608 }
609
610 /**
611 * @param $a
612 * @param $b
613 *
614 * @return bool
615 */
616 function _civicrm_api3_order_by_weight($a, $b) {
617 return CRM_Utils_Array::value('weight', $b) < CRM_Utils_Array::value('weight', $a) ? TRUE : FALSE;
618 }
619
620 /**
621 * Here we map the profile fields as stored in the uf_field table to their 'real entity'
622 * we also return the profile fieldname
623 *
624 * @param $field
625 *
626 * @return array
627 */
628 function _civicrm_api3_map_profile_fields_to_entity(&$field) {
629 $entity = $field['field_type'];
630 $contactTypes = civicrm_api3('contact', 'getoptions', array('field' => 'contact_type'));
631 if (in_array($entity, $contactTypes['values'])) {
632 $entity = 'contact';
633 }
634 $entity = _civicrm_api_get_entity_name_from_camel($entity);
635 $locationFields = array('email' => 'email');
636 $fieldName = $field['field_name'];
637 if (!empty($field['location_type_id'])) {
638 if ($fieldName == 'email') {
639 $entity = 'email';
640 }
641 else{
642 $entity = 'address';
643 }
644 $fieldName .= '-' . $field['location_type_id'];
645 }
646 elseif(array_key_exists($fieldName, $locationFields)) {
647 $fieldName .= '-Primary';
648 $entity = 'email';
649 }
650 if (!empty($field['phone_type_id'])) {
651 $fieldName .= '-' . $field['location_type_id'];
652 $entity = 'phone';
653 }
654
655 // @todo - sort this out!
656 //here we do a hard-code list of known fields that don't map to where they are mapped to
657 // not a great solution but probably if we looked in the BAO we'd find a scary switch statement
658 // in a perfect world the uf_field table would hold the correct entity for each item
659 // & only the relationships between entities would need to be coded
660 $hardCodedEntityMappings = array(
661 'street_address' => 'address',
662 'street_number' => 'address',
663 'supplemental_address_1' => 'address',
664 'supplemental_address_2' => 'address',
665 'supplemental_address_3' => 'address',
666 'postal_code' => 'address',
667 'city' => 'address',
668 'email' => 'email',
669 'state_province' => 'address',
670 'country' => 'address',
671 'county' => 'address',
672 //note that in discussions about how to restructure the api we discussed making these membership
673 // fields into 'membership_payment' fields - which would entail declaring them in getfields
674 // & renaming them in existing profiles
675 'financial_type' => 'contribution',
676 'total_amount' => 'contribution',
677 'receive_date' => 'contribution',
678 'payment_instrument' => 'contribution',
679 'check_number' => 'contribution',
680 'contribution_status_id' => 'contribution',
681 'soft_credit' => 'contribution',
682 'soft_credit_type' => 'contribution_soft',
683 'group' => 'group_contact',
684 'tag' => 'entity_tag',
685 );
686 if (array_key_exists($fieldName, $hardCodedEntityMappings)) {
687 $entity = $hardCodedEntityMappings[$fieldName];
688 }
689 return array($entity, $fieldName);
690 }
691
692 /**
693 * @todo this should be handled by the api wrapper using getfields info - need to check
694 * how we add a a pseudoconstant to this pseudo api to make that work
695 *
696 * @param int $profileID
697 *
698 * @return integer|string
699 * @throws CiviCRM_API3_Exception
700 */
701 function _civicrm_api3_profile_getProfileID($profileID) {
702 if (!empty($profileID) && strtolower($profileID) != 'billing' && !is_numeric($profileID)) {
703 $profileID = civicrm_api3('uf_group', 'getvalue', array('return' => 'id', 'name' => $profileID));
704 }
705 return $profileID;
706 }
707
708 /**
709 * helper function to add all aliases as keys to getfields response so we can look for keys within it
710 * since the relationship between profile fields & api / metadata based fields is a bit inconsistent
711 *
712 * @param array $values
713 *
714 * e.g getfields response incl 'membership_type_id' - with api.aliases = 'membership_type'
715 * returned array will include both as keys (with the same values)
716 * @param $entity
717 *
718 * @return array
719 */
720 function _civicrm_api3_profile_appendaliases($values, $entity) {
721 foreach ($values as $field => $spec) {
722 if (!empty($spec['api.aliases'])) {
723 foreach ($spec['api.aliases'] as $alias) {
724 $values[$alias] = $spec;
725 }
726 }
727 if (!empty($spec['uniqueName'])) {
728 $values[$spec['uniqueName']] = $spec;
729 }
730 }
731 //special case on membership & contribution - can't see how to handle in a generic way
732 if (in_array($entity, array('membership', 'contribution'))) {
733 $values['send_receipt'] = array('title' => 'Send Receipt', 'type' => (int) 16);
734 }
735 return $values;
736 }
737
738 /**
739 * @deprecated api notice
740 * @return array of deprecated actions
741 */
742 function _civicrm_api3_profile_deprecation() {
743 return array(
744 'set' => 'Profile api "set" action is deprecated in favor of "submit".',
745 'apply' => 'Profile api "apply" action is deprecated in favor of "submit".',
746 );
747 }