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