a7196eeb1047a5e8cbca203e18da0e7bf935bc44
[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
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');
155 }
156
157 $isContactActivityProfile = CRM_Core_BAO_UFField::checkContactActivityProfileType($profileID);
158
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');
161 }
162
163 $contactParams = $activityParams = $missingParams = array();
164
165 $profileFields = CRM_Core_BAO_UFGroup::getFields($profileID,
166 FALSE,
167 NULL,
168 NULL,
169 NULL,
170 FALSE,
171 NULL,
172 TRUE,
173 NULL,
174 CRM_Core_Permission::EDIT
175 );
176
177 if ($isContactActivityProfile) {
178 civicrm_api3_verify_mandatory($params, NULL, array('activity_id'));
179
180 $errors = CRM_Profile_Form::validateContactActivityProfile($params['activity_id'],
181 $params['contact_id'],
182 $profileID
183 );
184 if (!empty($errors)) {
185 throw new API_Exception(array_pop($errors));
186 }
187 }
188
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;
193 }
194 }
195
196 if (!isset($params[$fieldName])) {
197 continue;
198 }
199
200 $value = $params[$fieldName];
201 if ($params[$fieldName] && isset($params[$fieldName . '_id'])) {
202 $value = $params[$fieldName . '_id'];
203 }
204
205 if ($isContactActivityProfile && CRM_Utils_Array::value('field_type', $field) == 'Activity') {
206 $activityParams[$fieldName] = $value;
207 }
208 else {
209 $contactParams[$fieldName] = $value;
210 }
211 }
212
213 if (!empty($missingParams)) {
214 throw new API_Exception("Missing required parameters for profile id {$params['profile_id']}: " . implode(', ', $missingParams));
215 }
216
217 $contactParams['contact_id'] = CRM_Utils_Array::value('contact_id', $params);
218 $contactParams['profile_id'] = $profileID;
219 $contactParams['skip_custom'] = 1;
220
221 $contactProfileParams = civicrm_api3_profile_apply($contactParams);
222 if (CRM_Utils_Array::value('is_error', $contactProfileParams)) {
223 return $contactProfileParams;
224 }
225
226 // Contact profile fields
227 $profileParams = $contactProfileParams['values'];
228
229 // If profile having activity fields
230 if ($isContactActivityProfile && !empty($activityParams)) {
231 $activityParams['id'] = $params['activity_id'];
232 $profileParams['api.activity.create'] = $activityParams;
233 }
234
235 $groups = $tags = array();
236 if (isset($profileParams['group'])) {
237 $groups = $profileParams['group'];
238 unset($profileParams['group']);
239 }
240
241 if (isset($profileParams['tag'])) {
242 $tags = $profileParams['tag'];
243 unset($profileParams['tag']);
244 }
245
246 return civicrm_api3('contact', 'create', $profileParams);
247
248 $ufGroupDetails = array();
249 $ufGroupParams = array('id' => $profileID);
250 CRM_Core_BAO_UFGroup::retrieve($ufGroupParams, $ufGroupDetails);
251
252 if (isset($profileFields['group'])) {
253 CRM_Contact_BAO_GroupContact::create($groups,
254 $params['contact_id'],
255 FALSE,
256 'Admin'
257 );
258 }
259
260 if (isset($profileFields['tag'])) {
261 CRM_Core_BAO_EntityTag::create($tags,
262 'civicrm_contact',
263 $params['contact_id']
264 );
265 }
266
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']
271 );
272 }
273
274 return $result;
275
276 }
277 /**
278 * metadata for submit action
279 * @param array $params
280 * @param array $apirequest
281 */
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);
294 }
295 $params['profile_id']['api.required'] = TRUE;
296 }
297
298 /**
299 * @deprecated - calling this function directly is deprecated as 'set' is not a clear action
300 * use submit
301 * Update Profile field values.
302 *
303 * @param array $params Associative array of property name/value
304 * pairs to update profile field values
305 *
306 * @return Updated Contact/ Activity object|CRM_Error
307 *
308 *
309 */
310 function civicrm_api3_profile_set($params) {
311 return civicrm_api3('profile', 'submit', $params);
312 }
313
314 /**
315 * @deprecated - appears to be an internal function - should not be accessible via api
316 * Provide formatted values for profile fields.
317 *
318 * @param array $params Associative array of property name/value
319 * pairs to profile field values
320 *
321 * @return formatted profile field values|CRM_Error
322 *
323 * @todo add example
324 * @todo add test cases
325 *
326 */
327 function civicrm_api3_profile_apply($params) {
328
329 $profileFields = CRM_Core_BAO_UFGroup::getFields($params['profile_id'],
330 FALSE,
331 NULL,
332 NULL,
333 NULL,
334 FALSE,
335 NULL,
336 TRUE,
337 NULL,
338 CRM_Core_Permission::EDIT
339 );
340
341 list($data, $contactDetails) = CRM_Contact_BAO_Contact::formatProfileContactParams($params,
342 $profileFields,
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)
347 );
348
349 if (empty($data)) {
350 return civicrm_api3_create_error('Enable to format profile parameters.');
351 }
352
353 return civicrm_api3_create_success($data);
354 }
355
356
357 /**
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
362 *
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
365 */
366 function _civicrm_api3_profile_getbillingpseudoprofile(&$params) {
367 $addressFields = array('street_address', 'city', 'state_province_id', 'country_id', 'postal_code');
368 $locations = civicrm_api3('address', 'getoptions', array('field' => 'location_type_id'));
369 $locationTypeID = array_search('Billing', $locations['values']);
370
371 if(empty($params['contact_id'])) {
372 $blanks = array(
373 'billing_first_name' => '',
374 'billing_middle_name' => '',
375 'billing_last_name' => '',
376 );
377 foreach ($addressFields as $field) {
378 $blanks['billing_' . $field . '_' . $locationTypeID] = '';
379 }
380 return $blanks;
381 }
382 $result = civicrm_api3('contact', 'getsingle', array(
383 'id' => $params['contact_id'],
384 'api.address.get.1' => array('location_type_id' => 'Billing', 'return' => $addressFields),
385 // getting the is_billing required or not is an extra db call but probably cheap enough as this isn't an import api
386 'api.address.get.2' => array('is_billing' => True, 'return' => $addressFields),
387 'api.email.get.1' => array('location_type_id' => 'Billing',),
388 'api.email.get.2' => array('is_billing' => True,),
389 'return' => 'api.email.get, api.address.get, api.address.getoptions, country, state_province, email, first_name, last_name, middle_name, ' . implode($addressFields, ','),
390 )
391 );
392
393 $values = array(
394 'billing_first_name' => $result['first_name'],
395 'billing_middle_name' => $result['middle_name'],
396 'billing_last_name' => $result['last_name'],
397 );
398
399 if(!empty($result['api.address.get.1']['count'])) {
400 foreach ($addressFields as $fieldname) {
401 $values['billing_' . $fieldname . '-' . $locationTypeID] = isset($result['api.address.get.1']['values'][0][$fieldname]) ? $result['api.address.get.1']['values'][0][$fieldname] : '';
402 }
403 }
404 elseif(!empty($result['api.address.get.2']['count'])) {
405 foreach ($addressFields as $fieldname) {
406 $values['billing_' . $fieldname . '-' . $locationTypeID] = isset($result['api.address.get.2']['values'][0][$fieldname]) ? $result['api.address.get.2']['values'][0][$fieldname] : '';
407 }
408 }
409 else{
410 foreach ($addressFields as $fieldname) {
411 $values['billing_' . $fieldname . '-' . $locationTypeID] = isset($result[$fieldname]) ? $result[$fieldname] : '';
412 }
413 }
414
415 if(!empty($result['api.email.get.1']['count'])) {
416 $values['billing-email'. '-' . $locationTypeID] = $result['api.email.get.1']['values'][0]['email'];
417 }
418 elseif(!empty($result['api.email.get.2']['count'])) {
419 $values['billing-email'. '-' . $locationTypeID] = $result['api.email.get.2']['values'][0]['email'];
420 }
421 else{
422 $values['billing-email'. '-' . $locationTypeID] = $result['email'];
423 }
424 // return both variants of email to reflect inconsistencies in form layer
425 $values['email'. '-' . $locationTypeID] = $values['billing-email'. '-' . $locationTypeID];
426 return $values;
427 }
428
429 /**
430 * Here we will build up getfields type data for all the fields in the profile. Because the integration with the
431 * form layer in core is so hard-coded we are not going to attempt to re-use it
432 * However, as this function is unit-tested & hence 'locked in' we can aspire to extract sharable
433 * code out of the form-layer over time.
434 *
435 * The function deciphers which fields belongs to which entites & retrieves metadata about the entities
436 * Unfortunately we have inconsistencies such as 'contribution' uses contribution_status_id
437 * & participant has 'participant_status' so we have to standardise from the outside in here -
438 * find the oddities, 'mask them' at this layer, add tests & work to standardise over time so we can remove this handling
439 *
440 * @param integer $profileID
441 * @param integer $optionsBehaviour 0 = don't resolve, 1 = resolve non-aggressively, 2 = resolve aggressively - ie include country & state
442 */
443
444 function _civicrm_api3_buildprofile_submitfields($profileID, $optionsBehaviour = 1) {
445 static $profileFields = array();
446 if(isset($profileFields[$profileID])) {
447 return $profileFields[$profileID];
448 }
449 $fields = civicrm_api3('uf_field', 'get', array('uf_group_id' => $profileID));
450 $entities = array();
451
452 foreach ($fields['values'] as $id => $field) {
453 if(!$field['is_active']) {
454 continue;
455 }
456 list($entity, $fieldName) = _civicrm_api3_map_profile_fields_to_entity($field);
457 $profileFields[$profileID][$fieldName] = array(
458 'api.required' => $field['is_required'],
459 'title' => $field['label'],
460 'help_pre' => CRM_Utils_Array::value('help_pre', $field),
461 'help_post' => CRM_Utils_Array::value('help_post', $field),
462 );
463
464 $realFieldName = $field['field_name'];
465 //see function notes
466 // as we build up a list of these we should be able to determine a generic approach
467 //
468 $hardCodedEntityFields = array(
469 'state_province' => 'state_province_id',
470 'country' => 'country_id',
471 'participant_status' => 'status_id',
472 'gender' => 'gender_id',
473 'financial_type' => 'financial_type_id',
474 'soft_credit' => 'soft_credit_to',
475 'group' => 'group_id',
476 'tag' => 'tag_id',
477 );
478
479 if(array_key_exists($realFieldName, $hardCodedEntityFields)) {
480 $realFieldName = $hardCodedEntityFields[$realFieldName];
481 }
482
483 $entities[$entity][$fieldName] = $realFieldName;
484 }
485
486 foreach ($entities as $entity => $entityFields) {
487 $result = civicrm_api3($entity, 'getfields', array('action' => 'create'));
488 $entityGetFieldsResult = _civicrm_api3_profile_appendaliases($result['values'], $entity);
489 foreach ($entityFields as $entityfield => $realName) {
490 $profileFields[$profileID][$entityfield] = $entityGetFieldsResult[$realName];
491 if($optionsBehaviour && !empty($entityGetFieldsResult[$realName]['pseudoconstant'])) {
492 if($optionsBehaviour > 1 || !in_array($realName, array('state_province_id', 'county_id', 'country_id'))) {
493 $options = civicrm_api3($entity, 'getoptions', array('field' => $realName));
494 $profileFields[$profileID][$entityfield]['options'] = $options['values'];
495 }
496 }
497 /**
498 * putting this on hold -this would cause the api to set the default - but could have unexpected behaviour
499 if(isset($result['values'][$realName]['default_value'])) {
500 //this would be the case for a custom field with a configured default
501 $profileFields[$profileID][$entityfield]['api.default'] = $result['values'][$realName]['default_value'];
502 }
503 */
504 }
505 }
506 return $profileFields[$profileID];
507 }
508
509 /**
510 * Here we map the profile fields as stored in the uf_field table to their 'real entity'
511 * we also return the profile fieldname
512 *
513 */
514 function _civicrm_api3_map_profile_fields_to_entity(&$field) {
515 $entity = $field['field_type'];
516 $contactTypes = civicrm_api3('contact', 'getoptions', array('field' => 'contact_type'));
517 if(in_array($entity, $contactTypes['values'])) {
518 $entity = 'Contact';
519 }
520 $fieldName = $field['field_name'];
521 if(!empty($field['location_type_id'])) {
522 if($fieldName == 'email') {
523 $entity = 'Email';
524 }
525 else{
526 $entity = 'Address';
527 }
528 $fieldName .= '-' . $field['location_type_id'];
529 }
530 if(!empty($field['phone_type_id'])) {
531 $fieldName .= '-' . $field['location_type_id'];
532 $entity = 'Phone';
533 }
534 // @todo - sort this out!
535 //here we do a hard-code list of known fields that don't map to where they are mapped to
536 // not a great solution but probably if we looked in the BAO we'd find a scary switch statement
537 // in a perfect world the uf_field table would hold the correct entity for each item
538 // & only the relationships between entities would need to be coded
539 $hardCodedEntityMappings = array(
540 'street_address' => 'Address',
541 'street_number' => 'Address',
542 'supplemental_address_1' => 'Address',
543 'supplemental_address_2' => 'Address',
544 'supplemental_address_3' => 'Address',
545 'postal_code' => 'Address',
546 'city' => 'Address',
547 'email' => 'Email',
548 'state_province' => 'Address',
549 'country' => 'Address',
550 'county' => 'Address',
551 //note that in discussions about how to restructure the api we discussed making these membership
552 // fields into 'membership_payment' fields - which would entail declaring them in getfields
553 // & renaming them in existing profiles
554 'financial_type' => 'Contribution',
555 'total_amount' => 'Contribution',
556 'receive_date' => 'Contribution',
557 'payment_instrument' => 'Contribution',
558 'check_number' => 'Contribution',
559 'contribution_status_id' => 'Contribution',
560 'soft_credit' => 'Contribution',
561 'group' => 'GroupContact',
562 'tag' => 'EntityTag',
563 );
564 if(array_key_exists($fieldName, $hardCodedEntityMappings)) {
565 $entity = $hardCodedEntityMappings[$fieldName];
566 }
567 return array($entity, $fieldName);
568 }
569
570 /**
571 * @todo this should be handled by the api wrapper using getfields info - need to check
572 * how we add a a pseudoconstant to this pseudoapi to make that work
573 */
574 function _civicrm_api3_profile_getProfileID($profileID) {
575 if(!empty($profileID) && strtolower($profileID) != 'billing' && !is_numeric($profileID)) {
576 $profileID = civicrm_api3('uf_group', 'getvalue', array('return' => 'id', 'name' => $profileID));
577 }
578 return $profileID;
579 }
580
581 /**
582 * helper function to add all aliases as keys to getfields response so we can look for keys within it
583 * since the relationship between profile fields & api / metadata based fields is a bit inconsistent
584 * @param array $values
585 *
586 * e.g getfields response incl 'membership_type_id' - with api.aliases = 'membership_type'
587 * returned array will include both as keys (with the same values)
588 */
589 function _civicrm_api3_profile_appendaliases($values, $entity) {
590 foreach ($values as $field => $spec) {
591 if(!empty($spec['api.aliases'])) {
592 foreach ($spec['api.aliases'] as $alias) {
593 $values[$alias] = $spec;
594 }
595 }
596 if(!empty($spec['uniqueName'])) {
597 $values[$spec['uniqueName']] = $spec;
598 }
599 }
600 //special case on membership & contribution - can't see how to handle in a generic way
601 if(in_array($entity, array('Membership', 'Contribution'))) {
602 $values['send_receipt'] = array('title' => 'Send Receipt', 'type' => (int) 16);
603 }
604 return $values;
605 }