CRM-13234 add support for profile names on submit
[civicrm-core.git] / api / v3 / Profile.php
1 <?php
2
3 /*
4 +--------------------------------------------------------------------+
5 | CiviCRM version 4.4 |
6 +--------------------------------------------------------------------+
7 | Copyright CiviCRM LLC (c) 2004-2013 |
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-2013
35 * @version $Id: ActivityProfile.php 30486 2011-05-20 16:12:09Z rajan $
36 *
37 */
38
39 /**
40 * Include common API util functions
41 */
42 require_once 'api/v3/utils.php';
43
44 /**
45 * Retrieve Profile field values.
46 *
47 * @param array $params Associative array of property name/value
48 * pairs to get profile field values
49 *
50 * @return Profile field values|CRM_Error
51 *
52 * NOTE this api is not standard & since it is tested we need to honour that
53 * but the correct behaviour is for it to return an id indexed array as this supports
54 * multiple instances - if a single profile is passed in we will not return a normal api result array
55 * in order to avoid breaking code. (This could still be confusing :-( but we have to keep the tested behaviour working
56 *
57 * Note that if contact_id is empty an array of defaults is returned
58 *
59 */
60 function civicrm_api3_profile_get($params) {
61 $nonStandardLegacyBehaviour = is_numeric($params['profile_id']) ? TRUE : FALSE;
62 if(!empty($params['check_permissions']) && !empty($params['contact_id']) && !1 === civicrm_api3('contact', 'getcount', array('contact_id' => $params['contact_id'], 'check_permissions' => 1))) {
63 throw new API_Exception('permission denied');
64 }
65 $profiles = (array) $params['profile_id'];
66 $values = array();
67 foreach ($profiles as $profileID) {
68 $profileID = _civicrm_api3_profile_getProfileID($profileID);
69 $values[$profileID] = array();
70 if (strtolower($profileID) == 'billing') {
71 $values[$profileID] = _civicrm_api3_profile_getbillingpseudoprofile($params);
72 continue;
73 }
74 if(!CRM_Core_DAO::getFieldValue('CRM_Core_DAO_UFGroup', $profileID, 'is_active')) {
75 throw new API_Exception('Invalid value for profile_id : ' . $profileID);
76 }
77
78 $isContactActivityProfile = CRM_Core_BAO_UFField::checkContactActivityProfileType($profileID);
79
80 $profileFields = CRM_Core_BAO_UFGroup::getFields($profileID,
81 FALSE,
82 NULL,
83 NULL,
84 NULL,
85 FALSE,
86 NULL,
87 empty($params['check_permissions']) ? FALSE : TRUE,
88 NULL,
89 CRM_Core_Permission::EDIT
90 );
91
92
93 if ($isContactActivityProfile) {
94 civicrm_api3_verify_mandatory($params, NULL, array('activity_id'));
95
96 $errors = CRM_Profile_Form::validateContactActivityProfile($params['activity_id'],
97 $params['contact_id'],
98 $params['profile_id']
99 );
100 if (!empty($errors)) {
101 throw new API_Exception(array_pop($errors));
102 }
103
104 $contactFields = $activityFields = array();
105 foreach ($profileFields as $fieldName => $field) {
106 if (CRM_Utils_Array::value('field_type', $field) == 'Activity') {
107 $activityFields[$fieldName] = $field;
108 }
109 else {
110 $contactFields[$fieldName] = $field;
111 }
112 }
113
114 CRM_Core_BAO_UFGroup::setProfileDefaults($params['contact_id'], $contactFields, $values[$profileID], TRUE);
115
116 if ($params['activity_id']) {
117 CRM_Core_BAO_UFGroup::setComponentDefaults($activityFields, $params['activity_id'], 'Activity', $values[$profileID], TRUE);
118 }
119 }
120 elseif(!empty($params['contact_id'])) {
121 CRM_Core_BAO_UFGroup::setProfileDefaults($params['contact_id'], $profileFields, $values[$profileID], TRUE);
122 }
123 else{
124 $values[$profileID] = array_fill_keys(array_keys($profileFields), '');
125 }
126 }
127 if($nonStandardLegacyBehaviour) {
128 $result = civicrm_api3_create_success();
129 $result['values'] = $values[$profileID];
130 return $result;
131 }
132 else {
133 return civicrm_api3_create_success($values, $params, 'Profile', 'Get');
134 }
135 }
136
137 function _civicrm_api3_profile_get_spec(&$params) {
138 $params['profile_id']['api.required'] = TRUE;
139 $params['contact_id']['description'] = 'If no contact is specified an array of defaults will be returned';
140 }
141
142 /**
143 * Submit a set of fields against a profile.
144 * Note choice of submit versus create is discussed CRM-13234 & related to the fact
145 * 'profile' is being treated as a data-entry entity
146 * @param array $params
147 * @return array API result array
148 */
149 function civicrm_api3_profile_submit($params) {
150 $profileID = _civicrm_api3_profile_getProfileID($params['profile_id']);
151 if (!CRM_Core_DAO::getFieldValue('CRM_Core_DAO_UFGroup', $params['profile_id'], 'is_active')) {
152 throw new API_Exception('Invalid value for profile_id');
153 }
154
155 $isContactActivityProfile = CRM_Core_BAO_UFField::checkContactActivityProfileType($params['profile_id']);
156
157 if (CRM_Core_BAO_UFField::checkProfileType($params['profile_id']) && !$isContactActivityProfile) {
158 throw new API_Exception('Can not retrieve values for profiles include fields for more than one record type.');
159 }
160
161 $contactParams = $activityParams = $missingParams = array();
162
163 $profileFields = CRM_Core_BAO_UFGroup::getFields($params['profile_id'],
164 FALSE,
165 NULL,
166 NULL,
167 NULL,
168 FALSE,
169 NULL,
170 TRUE,
171 NULL,
172 CRM_Core_Permission::EDIT
173 );
174
175 if ($isContactActivityProfile) {
176 civicrm_api3_verify_mandatory($params, NULL, array('activity_id'));
177
178 $errors = CRM_Profile_Form::validateContactActivityProfile($params['activity_id'],
179 $params['contact_id'],
180 $params['profile_id']
181 );
182 if (!empty($errors)) {
183 throw new API_Exception(array_pop($errors));
184 }
185 }
186
187 foreach ($profileFields as $fieldName => $field) {
188 if (CRM_Utils_Array::value('is_required', $field)) {
189 if (!CRM_Utils_Array::value($fieldName, $params) || empty($params[$fieldName])) {
190 $missingParams[] = $fieldName;
191 }
192 }
193
194 if (!isset($params[$fieldName])) {
195 continue;
196 }
197
198 $value = $params[$fieldName];
199 if ($params[$fieldName] && isset($params[$fieldName . '_id'])) {
200 $value = $params[$fieldName . '_id'];
201 }
202
203 if ($isContactActivityProfile && CRM_Utils_Array::value('field_type', $field) == 'Activity') {
204 $activityParams[$fieldName] = $value;
205 }
206 else {
207 $contactParams[$fieldName] = $value;
208 }
209 }
210
211 if (!empty($missingParams)) {
212 throw new API_Exception("Missing required parameters for profile id {$params['profile_id']}: " . implode(', ', $missingParams));
213 }
214
215 $contactParams['version'] = 3;
216 $contactParams['contact_id'] = CRM_Utils_Array::value('contact_id', $params);
217 $contactParams['profile_id'] = $params['profile_id'];
218 $contactParams['skip_custom'] = 1;
219
220 $contactProfileParams = civicrm_api3_profile_apply($contactParams);
221 if (CRM_Utils_Array::value('is_error', $contactProfileParams)) {
222 return $contactProfileParams;
223 }
224
225 // Contact profile fields
226 $profileParams = $contactProfileParams['values'];
227
228 // If profile having activity fields
229 if ($isContactActivityProfile && !empty($activityParams)) {
230 $activityParams['id'] = $params['activity_id'];
231 $profileParams['api.activity.create'] = $activityParams;
232 }
233
234 $groups = $tags = array();
235 if (isset($profileParams['group'])) {
236 $groups = $profileParams['group'];
237 unset($profileParams['group']);
238 }
239
240 if (isset($profileParams['tag'])) {
241 $tags = $profileParams['tag'];
242 unset($profileParams['tag']);
243 }
244
245 return civicrm_api3('contact', 'create', $profileParams);
246
247 $ufGroupDetails = array();
248 $ufGroupParams = array('id' => $params['profile_id']);
249 CRM_Core_BAO_UFGroup::retrieve($ufGroupParams, $ufGroupDetails);
250
251 if (isset($profileFields['group'])) {
252 CRM_Contact_BAO_GroupContact::create($groups,
253 $params['contact_id'],
254 FALSE,
255 'Admin'
256 );
257 }
258
259 if (isset($profileFields['tag'])) {
260 CRM_Core_BAO_EntityTag::create($tags,
261 'civicrm_contact',
262 $params['contact_id']
263 );
264 }
265
266 if (CRM_Utils_Array::value('add_to_group_id', $ufGroupDetails)) {
267 $contactIds = array($params['contact_id']);
268 CRM_Contact_BAO_GroupContact::addContactsToGroup($contactIds,
269 $ufGroupDetails['add_to_group_id']
270 );
271 }
272
273 return $result;
274
275 }
276 /**
277 * metadata for submit action
278 * @param array $params
279 * @param array $apirequest
280 */
281 function _civicrm_api3_profile_submit_spec(&$params, $apirequest) {
282 if(isset($apirequest['params']['profile_id'])) {
283 // we will return what is required for this profile
284 // note the problem with simply over-riding getfields & then calling generic if needbe is we don't have the
285 // api request array to pass to it.
286 //@todo - it may make more sense just to pass the apiRequest to getfields
287 //@todo get_options should take an array - @ the moment it is only takes 'all' - which is supported
288 // by other getfields fn
289 // we don't resolve state, country & county for performance reasons
290 $resolveOptions = CRM_Utils_Array::value('get_options',$apirequest['params']) == 'all' ? True : False;
291 $profileID = _civicrm_api3_profile_getProfileID($apirequest['params']['profile_id']);
292 $params = _civicrm_api3_buildprofile_submitfields($profileID, $resolveOptions);
293 }
294 $params['profile_id']['api.required'] = TRUE;
295 }
296
297 /**
298 * @deprecated - calling this function directly is deprecated as 'set' is not a clear action
299 * use submit
300 * Update Profile field values.
301 *
302 * @param array $params Associative array of property name/value
303 * pairs to update profile field values
304 *
305 * @return Updated Contact/ Activity object|CRM_Error
306 *
307 *
308 */
309 function civicrm_api3_profile_set($params) {
310 return civicrm_api3('profile', 'submit', $params);
311 }
312
313 /**
314 * @deprecated - appears to be an internal function - should not be accessible via api
315 * Provide formatted values for profile fields.
316 *
317 * @param array $params Associative array of property name/value
318 * pairs to profile field values
319 *
320 * @return formatted profile field values|CRM_Error
321 *
322 * @todo add example
323 * @todo add test cases
324 *
325 */
326 function civicrm_api3_profile_apply($params) {
327
328 civicrm_api3_verify_mandatory($params, NULL, array('profile_id'));
329
330 if (!CRM_Core_DAO::getFieldValue('CRM_Core_DAO_UFGroup', $params['profile_id'], 'is_active')) {
331 return civicrm_api3_create_error('Invalid value for profile_id');
332 }
333
334 $profileFields = CRM_Core_BAO_UFGroup::getFields($params['profile_id'],
335 FALSE,
336 NULL,
337 NULL,
338 NULL,
339 FALSE,
340 NULL,
341 TRUE,
342 NULL,
343 CRM_Core_Permission::EDIT
344 );
345
346 list($data, $contactDetails) = CRM_Contact_BAO_Contact::formatProfileContactParams($params,
347 $profileFields,
348 CRM_Utils_Array::value('contact_id', $params),
349 $params['profile_id'],
350 CRM_Utils_Array::value('contact_type', $params),
351 CRM_Utils_Array::value('skip_custom', $params, FALSE)
352 );
353
354 if (empty($data)) {
355 return civicrm_api3_create_error('Enable to format profile parameters.');
356 }
357
358 return civicrm_api3_create_success($data);
359 }
360
361
362 /**
363 * This is a function to help us 'pretend' billing is a profile & treat it like it is one.
364 * It gets standard credit card address fields etc
365 * Note this is 'better' that the inbuilt version as it will pull in fallback values
366 * billing location -> is_billing -> primary
367 *
368 * Note that that since the existing code for deriving a blank profile is not easily accessible our
369 * interim solution is just to return an empty array
370 */
371 function _civicrm_api3_profile_getbillingpseudoprofile(&$params) {
372 $addressFields = array('street_address', 'city', 'state_province_id', 'country_id', 'postal_code');
373 $locations = civicrm_api3('address', 'getoptions', array('field' => 'location_type_id'));
374 $locationTypeID = array_search('Billing', $locations['values']);
375
376 if(empty($params['contact_id'])) {
377 $blanks = array(
378 'billing_first_name' => '',
379 'billing_middle_name' => '',
380 'billing_last_name' => '',
381 );
382 foreach ($addressFields as $field) {
383 $blanks['billing_' . $field . '_' . $locationTypeID] = '';
384 }
385 return $blanks;
386 }
387 $result = civicrm_api3('contact', 'getsingle', array(
388 'id' => $params['contact_id'],
389 'api.address.get.1' => array('location_type_id' => 'Billing', 'return' => $addressFields),
390 // getting the is_billing required or not is an extra db call but probably cheap enough as this isn't an import api
391 'api.address.get.2' => array('is_billing' => True, 'return' => $addressFields),
392 'api.email.get.1' => array('location_type_id' => 'Billing',),
393 'api.email.get.2' => array('is_billing' => True,),
394 'return' => 'api.email.get, api.address.get, api.address.getoptions, state_province, email, first_name, last_name, middle_name, ' . implode($addressFields, ','),
395 )
396 );
397
398 $values = array(
399 'billing_first_name' => $result['first_name'],
400 'billing_middle_name' => $result['middle_name'],
401 'billing_last_name' => $result['last_name'],
402 );
403
404 if(!empty($result['api.address.get.1']['count'])) {
405 foreach ($addressFields as $fieldname) {
406 $values['billing_' . $fieldname . '-' . $locationTypeID] = isset($result['api.address.get.1']['values'][0][$fieldname]) ? $result['api.address.get.1']['values'][0][$fieldname] : '';
407 }
408 }
409 elseif(!empty($result['api.address.get.2']['count'])) {
410 foreach ($addressFields as $fieldname) {
411 $values['billing_' . $fieldname . '-' . $locationTypeID] = isset($result['api.address.get.2']['values'][0][$fieldname]) ? $result['api.address.get.2']['values'][0][$fieldname] : '';
412 }
413 }
414 else{
415 foreach ($addressFields as $fieldname) {
416 $values['billing_' . $fieldname . '-' . $locationTypeID] = isset($result[$fieldname]) ? $result[$fieldname] : '';
417 }
418 }
419
420 if(!empty($result['api.email.get.1']['count'])) {
421 $values['billing-email'. '-' . $locationTypeID] = $result['api.email.get.1']['values'][0]['email'];
422 }
423 elseif(!empty($result['api.email.get.2']['count'])) {
424 $values['billing-email'. '-' . $locationTypeID] = $result['api.email.get.2']['values'][0]['email'];
425 }
426 else{
427 $values['billing-email'. '-' . $locationTypeID] = $result['email'];
428 }
429 // return both variants of email to reflect inconsistencies in form layer
430 $values['email'. '-' . $locationTypeID] = $values['billing-email'. '-' . $locationTypeID];
431 return $values;
432 }
433
434 /**
435 * Here we will build up getfields type data for all the fields in the profile. Because the integration with the
436 * form layer in core is so hard-coded we are not going to attempt to re-use it
437 * However, as this function is unit-tested & hence 'locked in' we can aspire to extract sharable
438 * code out of the form-layer over time.
439 *
440 * The function deciphers which fields belongs to which entites & retrieves metadata about the entities
441 * Unfortunately we have inconsistencies such as 'contribution' uses contribution_status_id
442 * & participant has 'participant_status' so we have to standardise from the outside in here -
443 * find the oddities, 'mask them' at this layer, add tests & work to standardise over time so we can remove this handling
444 *
445 * @param integer $profileID
446 * @param integer $optionsBehaviour 0 = don't resolve, 1 = resolve non-aggressively, 2 = resolve aggressively - ie include country & state
447 */
448
449 function _civicrm_api3_buildprofile_submitfields($profileID, $optionsBehaviour = 1) {
450 static $profileFields = array();
451 if(isset($profileFields[$profileID])) {
452 return $profileFields[$profileID];
453 }
454 $fields = civicrm_api3('uf_field', 'get', array('uf_group_id' => $profileID));
455 $entities = array();
456
457 foreach ($fields['values'] as $id => $field) {
458 if(!$field['is_active']) {
459 continue;
460 }
461 list($entity, $fieldName) = _civicrm_api3_map_profile_fields_to_entity($field);
462 $profileFields[$profileID][$fieldName] = array(
463 'api.required' => $field['is_required'],
464 'title' => $field['label'],
465 'help_pre' => CRM_Utils_Array::value('help_pre', $field),
466 'help_post' => CRM_Utils_Array::value('help_post', $field),
467 );
468
469 $realFieldName = $field['field_name'];
470 //see function notes
471 // as we build up a list of these we should be able to determine a generic approach
472 //
473 $hardCodedEntityFields = array(
474 'state_province' => 'state_province_id',
475 'country' => 'country_id',
476 'participant_status' => 'status_id',
477 'gender' => 'gender_id',
478 'financial_type' => 'financial_type_id',
479 'soft_credit' => 'soft_credit_to',
480 'group' => 'group_id',
481 'tag' => 'tag_id',
482 );
483
484 if(array_key_exists($realFieldName, $hardCodedEntityFields)) {
485 $realFieldName = $hardCodedEntityFields[$realFieldName];
486 }
487
488 $entities[$entity][$fieldName] = $realFieldName;
489 }
490
491 foreach ($entities as $entity => $entityFields) {
492 $result = civicrm_api3($entity, 'getfields', array('action' => 'create'));
493 $entityGetFieldsResult = _civicrm_api3_profile_appendaliases($result['values'], $entity);
494 foreach ($entityFields as $entityfield => $realName) {
495 $profileFields[$profileID][$entityfield] = $entityGetFieldsResult[$realName];
496 if($optionsBehaviour && !empty($entityGetFieldsResult[$realName]['pseudoconstant'])) {
497 if($optionsBehaviour > 1 || !in_array($realName, array('state_province_id', 'county_id', 'country_id'))) {
498 $options = civicrm_api3($entity, 'getoptions', array('field' => $realName));
499 $profileFields[$profileID][$entityfield]['options'] = $options['values'];
500 }
501 }
502 /**
503 * putting this on hold -this would cause the api to set the default - but could have unexpected behaviour
504 if(isset($result['values'][$realName]['default_value'])) {
505 //this would be the case for a custom field with a configured default
506 $profileFields[$profileID][$entityfield]['api.default'] = $result['values'][$realName]['default_value'];
507 }
508 */
509 }
510 }
511 return $profileFields[$profileID];
512 }
513
514 /**
515 * Here we map the profile fields as stored in the uf_field table to their 'real entity'
516 * we also return the profile fieldname
517 *
518 */
519 function _civicrm_api3_map_profile_fields_to_entity(&$field) {
520 $entity = $field['field_type'];
521 $contactTypes = civicrm_api3('contact', 'getoptions', array('field' => 'contact_type'));
522 if(in_array($entity, $contactTypes['values'])) {
523 $entity = 'Contact';
524 }
525 $fieldName = $field['field_name'];
526 if(!empty($field['location_type_id'])) {
527 if($fieldName == 'email') {
528 $entity = 'Email';
529 }
530 else{
531 $entity = 'Address';
532 }
533 $fieldName .= '-' . $field['location_type_id'];
534 }
535 if(!empty($field['phone_type_id'])) {
536 $fieldName .= '-' . $field['location_type_id'];
537 $entity = 'Phone';
538 }
539 // @todo - sort this out!
540 //here we do a hard-code list of known fields that don't map to where they are mapped to
541 // not a great solution but probably if we looked in the BAO we'd find a scary switch statement
542 // in a perfect world the uf_field table would hold the correct entity for each item
543 // & only the relationships between entities would need to be coded
544 $hardCodedEntityMappings = array(
545 'street_address' => 'Address',
546 'street_number' => 'Address',
547 'supplemental_address_1' => 'Address',
548 'supplemental_address_2' => 'Address',
549 'supplemental_address_3' => 'Address',
550 'postal_code' => 'Address',
551 'city' => 'Address',
552 'email' => 'Email',
553 'state_province' => 'Address',
554 'country' => 'Address',
555 'county' => 'Address',
556 //note that in discussions about how to restructure the api we discussed making these membership
557 // fields into 'membership_payment' fields - which would entail declaring them in getfields
558 // & renaming them in existing profiles
559 'financial_type' => 'Contribution',
560 'total_amount' => 'Contribution',
561 'receive_date' => 'Contribution',
562 'payment_instrument' => 'Contribution',
563 'check_number' => 'Contribution',
564 'contribution_status_id' => 'Contribution',
565 'soft_credit' => 'Contribution',
566 'group' => 'GroupContact',
567 'tag' => 'EntityTag',
568 );
569 if(array_key_exists($fieldName, $hardCodedEntityMappings)) {
570 $entity = $hardCodedEntityMappings[$fieldName];
571 }
572 return array($entity, $fieldName);
573 }
574
575 /**
576 * @todo this should be handled by the api wrapper using getfields info - need to check
577 * how we add a a pseudoconstant to this pseudoapi to make that work
578 */
579 function _civicrm_api3_profile_getProfileID($profileID) {
580 if(!empty($profileID) && !strtolower($profileID) == 'billing' && !is_numeric($profileID)) {
581 $profileID = civicrm_api3('uf_group', 'getvalue', array('return' => 'id', 'name' => $profileID));
582 }
583 return $profileID;
584 }
585
586 /**
587 * helper function to add all aliases as keys to getfields response so we can look for keys within it
588 * since the relationship between profile fields & api / metadata based fields is a bit inconsistent
589 * @param array $values
590 *
591 * e.g getfields response incl 'membership_type_id' - with api.aliases = 'membership_type'
592 * returned array will include both as keys (with the same values)
593 */
594 function _civicrm_api3_profile_appendaliases($values, $entity) {
595 foreach ($values as $field => $spec) {
596 if(!empty($spec['api.aliases'])) {
597 foreach ($spec['api.aliases'] as $alias) {
598 $values[$alias] = $spec;
599 }
600 }
601 if(!empty($spec['uniqueName'])) {
602 $values[$spec['uniqueName']] = $spec;
603 }
604 }
605 //special case on membership & contribution - can't see how to handle in a generic way
606 if(in_array($entity, array('Membership', 'Contribution'))) {
607 $values['send_receipt'] = array('title' => 'Send Receipt', 'type' => 16);
608 }
609 return $values;
610 }