4 +--------------------------------------------------------------------+
5 | CiviCRM version 4.4 |
6 +--------------------------------------------------------------------+
7 | Copyright CiviCRM LLC (c) 2004-2013 |
8 +--------------------------------------------------------------------+
9 | This file is a part of CiviCRM. |
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. |
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. |
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 +--------------------------------------------------------------------+
30 * File for the CiviCRM APIv3 activity profile functions
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 $
40 * Include common API util functions
42 require_once 'api/v3/utils.php';
45 * Retrieve Profile field values.
47 * @param array $params Associative array of property name/value
48 * pairs to get profile field values
50 * @return Profile field values|CRM_Error
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
57 * Note that if contact_id is empty an array of defaults is returned
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');
65 $profiles = (array) $params['profile_id'];
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);
74 if(!CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_UFGroup', $profileID, 'is_active')) {
75 throw new API_Exception('Invalid value for profile_id : ' . $profileID);
78 $isContactActivityProfile = CRM_Core_BAO_UFField
::checkContactActivityProfileType($profileID);
80 $profileFields = CRM_Core_BAO_UFGroup
::getFields($profileID,
87 empty($params['check_permissions']) ?
FALSE : TRUE,
89 CRM_Core_Permission
::EDIT
93 if ($isContactActivityProfile) {
94 civicrm_api3_verify_mandatory($params, NULL, array('activity_id'));
96 $errors = CRM_Profile_Form
::validateContactActivityProfile($params['activity_id'],
97 $params['contact_id'],
100 if (!empty($errors)) {
101 throw new API_Exception(array_pop($errors));
104 $contactFields = $activityFields = array();
105 foreach ($profileFields as $fieldName => $field) {
106 if (CRM_Utils_Array
::value('field_type', $field) == 'Activity') {
107 $activityFields[$fieldName] = $field;
110 $contactFields[$fieldName] = $field;
114 CRM_Core_BAO_UFGroup
::setProfileDefaults($params['contact_id'], $contactFields, $values[$profileID], TRUE);
116 if ($params['activity_id']) {
117 CRM_Core_BAO_UFGroup
::setComponentDefaults($activityFields, $params['activity_id'], 'Activity', $values[$profileID], TRUE);
120 elseif(!empty($params['contact_id'])) {
121 CRM_Core_BAO_UFGroup
::setProfileDefaults($params['contact_id'], $profileFields, $values[$profileID], TRUE);
124 $values[$profileID] = array_fill_keys(array_keys($profileFields), '');
127 if($nonStandardLegacyBehaviour) {
128 $result = civicrm_api3_create_success();
129 $result['values'] = $values[$profileID];
133 return civicrm_api3_create_success($values, $params, 'Profile', 'Get');
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';
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
149 function civicrm_api3_profile_submit($params) {
150 $profileID = _civicrm_api3_profile_getProfileID($params['profile_id']);
152 if (!CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_UFGroup', $profileID, 'is_active')) {
153 //@todo declare pseudoconstant & let api do this
154 throw new API_Exception('Invalid value for profile_id');
157 $isContactActivityProfile = CRM_Core_BAO_UFField
::checkContactActivityProfileType($profileID);
159 if (!empty($params['id']) && CRM_Core_BAO_UFField
::checkProfileType($profileID) && !$isContactActivityProfile) {
160 throw new API_Exception('Update profiles including more than one entity not currently supported');
163 $contactParams = $activityParams = $missingParams = array();
165 $profileFields = CRM_Core_BAO_UFGroup
::getFields($profileID,
174 CRM_Core_Permission
::EDIT
177 if ($isContactActivityProfile) {
178 civicrm_api3_verify_mandatory($params, NULL, array('activity_id'));
180 $errors = CRM_Profile_Form
::validateContactActivityProfile($params['activity_id'],
181 $params['contact_id'],
184 if (!empty($errors)) {
185 throw new API_Exception(array_pop($errors));
189 foreach ($profileFields as $fieldName => $field) {
190 if (CRM_Utils_Array
::value('is_required', $field)) {
191 if (!CRM_Utils_Array
::value($fieldName, $params) ||
empty($params[$fieldName])) {
192 $missingParams[] = $fieldName;
196 if (!isset($params[$fieldName])) {
200 $value = $params[$fieldName];
201 if ($params[$fieldName] && isset($params[$fieldName . '_id'])) {
202 $value = $params[$fieldName . '_id'];
205 if ($isContactActivityProfile && CRM_Utils_Array
::value('field_type', $field) == 'Activity') {
206 $activityParams[$fieldName] = $value;
209 $contactParams[$fieldName] = $value;
213 if (!empty($missingParams)) {
214 throw new API_Exception("Missing required parameters for profile id {$params['profile_id']}: " . implode(', ', $missingParams));
217 $contactParams['contact_id'] = CRM_Utils_Array
::value('contact_id', $params);
218 $contactParams['profile_id'] = $profileID;
219 $contactParams['skip_custom'] = 1;
221 $contactProfileParams = civicrm_api3_profile_apply($contactParams);
222 if (CRM_Utils_Array
::value('is_error', $contactProfileParams)) {
223 return $contactProfileParams;
226 // Contact profile fields
227 $profileParams = $contactProfileParams['values'];
229 // If profile having activity fields
230 if ($isContactActivityProfile && !empty($activityParams)) {
231 $activityParams['id'] = $params['activity_id'];
232 $profileParams['api.activity.create'] = $activityParams;
235 $groups = $tags = array();
236 if (isset($profileParams['group'])) {
237 $groups = $profileParams['group'];
238 unset($profileParams['group']);
241 if (isset($profileParams['tag'])) {
242 $tags = $profileParams['tag'];
243 unset($profileParams['tag']);
246 return civicrm_api3('contact', 'create', $profileParams);
248 $ufGroupDetails = array();
249 $ufGroupParams = array('id' => $profileID);
250 CRM_Core_BAO_UFGroup
::retrieve($ufGroupParams, $ufGroupDetails);
252 if (isset($profileFields['group'])) {
253 CRM_Contact_BAO_GroupContact
::create($groups,
254 $params['contact_id'],
260 if (isset($profileFields['tag'])) {
261 CRM_Core_BAO_EntityTag
::create($tags,
263 $params['contact_id']
267 if (CRM_Utils_Array
::value('add_to_group_id', $ufGroupDetails)) {
268 $contactIds = array($params['contact_id']);
269 CRM_Contact_BAO_GroupContact
::addContactsToGroup($contactIds,
270 $ufGroupDetails['add_to_group_id']
278 * metadata for submit action
279 * @param array $params
280 * @param array $apirequest
282 function _civicrm_api3_profile_submit_spec(&$params, $apirequest) {
283 if(isset($apirequest['params']['profile_id'])) {
284 // we will return what is required for this profile
285 // note the problem with simply over-riding getfields & then calling generic if needbe is we don't have the
286 // api request array to pass to it.
287 //@todo - it may make more sense just to pass the apiRequest to getfields
288 //@todo get_options should take an array - @ the moment it is only takes 'all' - which is supported
289 // by other getfields fn
290 // we don't resolve state, country & county for performance reasons
291 $resolveOptions = CRM_Utils_Array
::value('get_options',$apirequest['params']) == 'all' ?
True : False;
292 $profileID = _civicrm_api3_profile_getProfileID($apirequest['params']['profile_id']);
293 $params = _civicrm_api3_buildprofile_submitfields($profileID, $resolveOptions);
295 $params['profile_id']['api.required'] = TRUE;
299 * @deprecated - calling this function directly is deprecated as 'set' is not a clear action
301 * Update Profile field values.
303 * @param array $params Associative array of property name/value
304 * pairs to update profile field values
306 * @return Updated Contact/ Activity object|CRM_Error
310 function civicrm_api3_profile_set($params) {
311 return civicrm_api3('profile', 'submit', $params);
315 * @deprecated - appears to be an internal function - should not be accessible via api
316 * Provide formatted values for profile fields.
318 * @param array $params Associative array of property name/value
319 * pairs to profile field values
321 * @return formatted profile field values|CRM_Error
324 * @todo add test cases
327 function civicrm_api3_profile_apply($params) {
329 $profileFields = CRM_Core_BAO_UFGroup
::getFields($params['profile_id'],
338 CRM_Core_Permission
::EDIT
341 list($data, $contactDetails) = CRM_Contact_BAO_Contact
::formatProfileContactParams($params,
343 CRM_Utils_Array
::value('contact_id', $params),
344 $params['profile_id'],
345 CRM_Utils_Array
::value('contact_type', $params),
346 CRM_Utils_Array
::value('skip_custom', $params, FALSE)
350 return civicrm_api3_create_error('Enable to format profile parameters.');
353 return civicrm_api3_create_success($data);
358 * This is a function to help us 'pretend' billing is a profile & treat it like it is one.
359 * It gets standard credit card address fields etc
360 * Note this is 'better' that the inbuilt version as it will pull in fallback values
361 * billing location -> is_billing -> primary
363 * Note that that since the existing code for deriving a blank profile is not easily accessible our
364 * interim solution is just to return an empty array
366 function _civicrm_api3_profile_getbillingpseudoprofile(&$params) {
368 $locations = civicrm_api3('address', 'getoptions', array('field' => 'location_type_id'));
369 $locationTypeID = array_search('Billing', $locations['values']);
371 if(empty($params['contact_id'])) {
372 $config = CRM_Core_Config
::singleton();
374 'billing_first_name' => '',
375 'billing_middle_name' => '',
376 'billing_last_name' => '',
377 'email-' . $locationTypeID => '',
378 'billing_email-' . $locationTypeID => '',
379 'billing_city-' . $locationTypeID => '',
380 'billing_postal_code-' . $locationTypeID => '',
381 'billing_street_address-' . $locationTypeID => '',
382 'billing_country_id-' . $locationTypeID => $config->defaultContactCountry
,
383 'billing_state_province_id-' . $locationTypeID => $config->defaultContactStateProvince
,
388 $addressFields = array('street_address', 'city', 'state_province_id', 'country_id', 'postal_code');
389 $result = civicrm_api3('contact', 'getsingle', array(
390 'id' => $params['contact_id'],
391 'api.address.get.1' => array('location_type_id' => 'Billing', 'return' => $addressFields),
392 // getting the is_billing required or not is an extra db call but probably cheap enough as this isn't an import api
393 'api.address.get.2' => array('is_billing' => True, 'return' => $addressFields),
394 'api.email.get.1' => array('location_type_id' => 'Billing',),
395 'api.email.get.2' => array('is_billing' => True,),
396 'return' => 'api.email.get, api.address.get, api.address.getoptions, country, state_province, email, first_name, last_name, middle_name, ' . implode($addressFields, ','),
401 'billing_first_name' => $result['first_name'],
402 'billing_middle_name' => $result['middle_name'],
403 'billing_last_name' => $result['last_name'],
406 if(!empty($result['api.address.get.1']['count'])) {
407 foreach ($addressFields as $fieldname) {
408 $values['billing_' . $fieldname . '-' . $locationTypeID] = isset($result['api.address.get.1']['values'][0][$fieldname]) ?
$result['api.address.get.1']['values'][0][$fieldname] : '';
411 elseif(!empty($result['api.address.get.2']['count'])) {
412 foreach ($addressFields as $fieldname) {
413 $values['billing_' . $fieldname . '-' . $locationTypeID] = isset($result['api.address.get.2']['values'][0][$fieldname]) ?
$result['api.address.get.2']['values'][0][$fieldname] : '';
417 foreach ($addressFields as $fieldname) {
418 $values['billing_' . $fieldname . '-' . $locationTypeID] = isset($result[$fieldname]) ?
$result[$fieldname] : '';
422 if(!empty($result['api.email.get.1']['count'])) {
423 $values['billing-email'. '-' . $locationTypeID] = $result['api.email.get.1']['values'][0]['email'];
425 elseif(!empty($result['api.email.get.2']['count'])) {
426 $values['billing-email'. '-' . $locationTypeID] = $result['api.email.get.2']['values'][0]['email'];
429 $values['billing-email'. '-' . $locationTypeID] = $result['email'];
431 // return both variants of email to reflect inconsistencies in form layer
432 $values['email'. '-' . $locationTypeID] = $values['billing-email'. '-' . $locationTypeID];
437 * Here we will build up getfields type data for all the fields in the profile. Because the integration with the
438 * form layer in core is so hard-coded we are not going to attempt to re-use it
439 * However, as this function is unit-tested & hence 'locked in' we can aspire to extract sharable
440 * code out of the form-layer over time.
442 * The function deciphers which fields belongs to which entites & retrieves metadata about the entities
443 * Unfortunately we have inconsistencies such as 'contribution' uses contribution_status_id
444 * & participant has 'participant_status' so we have to standardise from the outside in here -
445 * find the oddities, 'mask them' at this layer, add tests & work to standardise over time so we can remove this handling
447 * @param integer $profileID
448 * @param integer $optionsBehaviour 0 = don't resolve, 1 = resolve non-aggressively, 2 = resolve aggressively - ie include country & state
451 function _civicrm_api3_buildprofile_submitfields($profileID, $optionsBehaviour = 1) {
452 static $profileFields = array();
453 if(isset($profileFields[$profileID])) {
454 return $profileFields[$profileID];
456 $fields = civicrm_api3('uf_field', 'get', array('uf_group_id' => $profileID));
459 foreach ($fields['values'] as $id => $field) {
460 if(!$field['is_active']) {
463 list($entity, $fieldName) = _civicrm_api3_map_profile_fields_to_entity($field);
464 $profileFields[$profileID][$fieldName] = array(
465 'api.required' => $field['is_required'],
466 'title' => $field['label'],
467 'help_pre' => CRM_Utils_Array
::value('help_pre', $field),
468 'help_post' => CRM_Utils_Array
::value('help_post', $field),
471 $realFieldName = $field['field_name'];
473 // as we build up a list of these we should be able to determine a generic approach
475 $hardCodedEntityFields = array(
476 'state_province' => 'state_province_id',
477 'country' => 'country_id',
478 'participant_status' => 'status_id',
479 'gender' => 'gender_id',
480 'financial_type' => 'financial_type_id',
481 'soft_credit' => 'soft_credit_to',
482 'group' => 'group_id',
486 if(array_key_exists($realFieldName, $hardCodedEntityFields)) {
487 $realFieldName = $hardCodedEntityFields[$realFieldName];
490 $entities[$entity][$fieldName] = $realFieldName;
493 foreach ($entities as $entity => $entityFields) {
494 $result = civicrm_api3($entity, 'getfields', array('action' => 'create'));
495 $entityGetFieldsResult = _civicrm_api3_profile_appendaliases($result['values'], $entity);
496 foreach ($entityFields as $entityfield => $realName) {
497 $profileFields[$profileID][$entityfield] = $entityGetFieldsResult[$realName];
498 if($optionsBehaviour && !empty($entityGetFieldsResult[$realName]['pseudoconstant'])) {
499 if($optionsBehaviour > 1 ||
!in_array($realName, array('state_province_id', 'county_id', 'country_id'))) {
500 $options = civicrm_api3($entity, 'getoptions', array('field' => $realName));
501 $profileFields[$profileID][$entityfield]['options'] = $options['values'];
505 * putting this on hold -this would cause the api to set the default - but could have unexpected behaviour
506 if(isset($result['values'][$realName]['default_value'])) {
507 //this would be the case for a custom field with a configured default
508 $profileFields[$profileID][$entityfield]['api.default'] = $result['values'][$realName]['default_value'];
513 return $profileFields[$profileID];
517 * Here we map the profile fields as stored in the uf_field table to their 'real entity'
518 * we also return the profile fieldname
521 function _civicrm_api3_map_profile_fields_to_entity(&$field) {
522 $entity = $field['field_type'];
523 $contactTypes = civicrm_api3('contact', 'getoptions', array('field' => 'contact_type'));
524 if(in_array($entity, $contactTypes['values'])) {
527 $fieldName = $field['field_name'];
528 if(!empty($field['location_type_id'])) {
529 if($fieldName == 'email') {
535 $fieldName .= '-' . $field['location_type_id'];
537 if(!empty($field['phone_type_id'])) {
538 $fieldName .= '-' . $field['location_type_id'];
541 // @todo - sort this out!
542 //here we do a hard-code list of known fields that don't map to where they are mapped to
543 // not a great solution but probably if we looked in the BAO we'd find a scary switch statement
544 // in a perfect world the uf_field table would hold the correct entity for each item
545 // & only the relationships between entities would need to be coded
546 $hardCodedEntityMappings = array(
547 'street_address' => 'Address',
548 'street_number' => 'Address',
549 'supplemental_address_1' => 'Address',
550 'supplemental_address_2' => 'Address',
551 'supplemental_address_3' => 'Address',
552 'postal_code' => 'Address',
555 'state_province' => 'Address',
556 'country' => 'Address',
557 'county' => 'Address',
558 //note that in discussions about how to restructure the api we discussed making these membership
559 // fields into 'membership_payment' fields - which would entail declaring them in getfields
560 // & renaming them in existing profiles
561 'financial_type' => 'Contribution',
562 'total_amount' => 'Contribution',
563 'receive_date' => 'Contribution',
564 'payment_instrument' => 'Contribution',
565 'check_number' => 'Contribution',
566 'contribution_status_id' => 'Contribution',
567 'soft_credit' => 'Contribution',
568 'group' => 'GroupContact',
569 'tag' => 'EntityTag',
571 if(array_key_exists($fieldName, $hardCodedEntityMappings)) {
572 $entity = $hardCodedEntityMappings[$fieldName];
574 return array($entity, $fieldName);
578 * @todo this should be handled by the api wrapper using getfields info - need to check
579 * how we add a a pseudoconstant to this pseudoapi to make that work
581 function _civicrm_api3_profile_getProfileID($profileID) {
582 if(!empty($profileID) && strtolower($profileID) != 'billing' && !is_numeric($profileID)) {
583 $profileID = civicrm_api3('uf_group', 'getvalue', array('return' => 'id', 'name' => $profileID));
589 * helper function to add all aliases as keys to getfields response so we can look for keys within it
590 * since the relationship between profile fields & api / metadata based fields is a bit inconsistent
591 * @param array $values
593 * e.g getfields response incl 'membership_type_id' - with api.aliases = 'membership_type'
594 * returned array will include both as keys (with the same values)
596 function _civicrm_api3_profile_appendaliases($values, $entity) {
597 foreach ($values as $field => $spec) {
598 if(!empty($spec['api.aliases'])) {
599 foreach ($spec['api.aliases'] as $alias) {
600 $values[$alias] = $spec;
603 if(!empty($spec['uniqueName'])) {
604 $values[$spec['uniqueName']] = $spec;
607 //special case on membership & contribution - can't see how to handle in a generic way
608 if(in_array($entity, array('Membership', 'Contribution'))) {
609 $values['send_receipt'] = array('title' => 'Send Receipt', 'type' => (int) 16);