Merge pull request #1523 from kurund/CRM-13209
[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
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 $config = CRM_Core_Config::singleton();
373 $blanks = array(
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,
384 );
385 return $blanks;
386 }
387
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, ','),
397 )
398 );
399
400 $values = array(
401 'billing_first_name' => $result['first_name'],
402 'billing_middle_name' => $result['middle_name'],
403 'billing_last_name' => $result['last_name'],
404 );
405
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] : '';
409 }
410 }
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] : '';
414 }
415 }
416 else{
417 foreach ($addressFields as $fieldname) {
418 $values['billing_' . $fieldname . '-' . $locationTypeID] = isset($result[$fieldname]) ? $result[$fieldname] : '';
419 }
420 }
421
422 if(!empty($result['api.email.get.1']['count'])) {
423 $values['billing-email'. '-' . $locationTypeID] = $result['api.email.get.1']['values'][0]['email'];
424 }
425 elseif(!empty($result['api.email.get.2']['count'])) {
426 $values['billing-email'. '-' . $locationTypeID] = $result['api.email.get.2']['values'][0]['email'];
427 }
428 else{
429 $values['billing-email'. '-' . $locationTypeID] = $result['email'];
430 }
431 // return both variants of email to reflect inconsistencies in form layer
432 $values['email'. '-' . $locationTypeID] = $values['billing-email'. '-' . $locationTypeID];
433 return $values;
434 }
435
436 /**
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.
441 *
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
446 *
447 * @param integer $profileID
448 * @param integer $optionsBehaviour 0 = don't resolve, 1 = resolve non-aggressively, 2 = resolve aggressively - ie include country & state
449 */
450
451 function _civicrm_api3_buildprofile_submitfields($profileID, $optionsBehaviour = 1) {
452 static $profileFields = array();
453 if(isset($profileFields[$profileID])) {
454 return $profileFields[$profileID];
455 }
456 $fields = civicrm_api3('uf_field', 'get', array('uf_group_id' => $profileID));
457 $entities = array();
458
459 foreach ($fields['values'] as $id => $field) {
460 if(!$field['is_active']) {
461 continue;
462 }
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),
469 );
470
471 $realFieldName = $field['field_name'];
472 //see function notes
473 // as we build up a list of these we should be able to determine a generic approach
474 //
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',
483 'tag' => 'tag_id',
484 );
485
486 if(array_key_exists($realFieldName, $hardCodedEntityFields)) {
487 $realFieldName = $hardCodedEntityFields[$realFieldName];
488 }
489
490 $entities[$entity][$fieldName] = $realFieldName;
491 }
492
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'];
502 }
503 }
504 /**
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'];
509 }
510 */
511 }
512 }
513 return $profileFields[$profileID];
514 }
515
516 /**
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
519 *
520 */
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'])) {
525 $entity = 'Contact';
526 }
527 $fieldName = $field['field_name'];
528 if(!empty($field['location_type_id'])) {
529 if($fieldName == 'email') {
530 $entity = 'Email';
531 }
532 else{
533 $entity = 'Address';
534 }
535 $fieldName .= '-' . $field['location_type_id'];
536 }
537 if(!empty($field['phone_type_id'])) {
538 $fieldName .= '-' . $field['location_type_id'];
539 $entity = 'Phone';
540 }
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',
553 'city' => 'Address',
554 'email' => 'Email',
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',
570 );
571 if(array_key_exists($fieldName, $hardCodedEntityMappings)) {
572 $entity = $hardCodedEntityMappings[$fieldName];
573 }
574 return array($entity, $fieldName);
575 }
576
577 /**
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
580 */
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));
584 }
585 return $profileID;
586 }
587
588 /**
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
592 *
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)
595 */
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;
601 }
602 }
603 if(!empty($spec['uniqueName'])) {
604 $values[$spec['uniqueName']] = $spec;
605 }
606 }
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);
610 }
611 return $values;
612 }