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