fix error to throw Exception
[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 * Retrieve Profile field values.
41 *
42 * @param array $params Associative array of property name/value
43 * pairs to get profile field values
44 *
45 * @throws API_Exception
46 * @return Profile field values|CRM_Error
47 *
48 * NOTE this api is not standard & since it is tested we need to honour that
49 * but the correct behaviour is for it to return an id indexed array as this supports
50 * multiple instances - if a single profile is passed in we will not return a normal api result array
51 * in order to avoid breaking code. (This could still be confusing :-( but we have to keep the tested behaviour working
52 *
53 * Note that if contact_id is empty an array of defaults is returned
54 */
55 function civicrm_api3_profile_get($params) {
56 $nonStandardLegacyBehaviour = is_numeric($params['profile_id']) ? TRUE : FALSE;
57 if(!empty($params['check_permissions']) && !empty($params['contact_id']) && !1 === civicrm_api3('contact', 'getcount', array('contact_id' => $params['contact_id'], 'check_permissions' => 1))) {
58 throw new API_Exception('permission denied');
59 }
60 $profiles = (array) $params['profile_id'];
61 $values = array();
62 $ufGroupBAO = new CRM_Core_BAO_UFGroup();
63 foreach ($profiles as $profileID) {
64 $profileID = _civicrm_api3_profile_getProfileID($profileID);
65 $values[$profileID] = array();
66 if (strtolower($profileID) == 'billing') {
67 $values[$profileID] = _civicrm_api3_profile_getbillingpseudoprofile($params);
68 continue;
69 }
70 if(!CRM_Core_DAO::getFieldValue('CRM_Core_DAO_UFGroup', $profileID, 'is_active')) {
71 throw new API_Exception('Invalid value for profile_id : ' . $profileID);
72 }
73
74 $isContactActivityProfile = CRM_Core_BAO_UFField::checkContactActivityProfileType($profileID);
75
76 $profileFields = CRM_Core_BAO_UFGroup::getFields($profileID,
77 FALSE,
78 NULL,
79 NULL,
80 NULL,
81 FALSE,
82 NULL,
83 empty($params['check_permissions']) ? FALSE : TRUE,
84 NULL,
85 CRM_Core_Permission::EDIT
86 );
87
88
89 if ($isContactActivityProfile) {
90 civicrm_api3_verify_mandatory($params, NULL, array('activity_id'));
91
92 $errors = CRM_Profile_Form::validateContactActivityProfile($params['activity_id'],
93 $params['contact_id'],
94 $params['profile_id']
95 );
96 if (!empty($errors)) {
97 throw new API_Exception(array_pop($errors));
98 }
99
100 $contactFields = $activityFields = array();
101 foreach ($profileFields as $fieldName => $field) {
102 if (CRM_Utils_Array::value('field_type', $field) == 'Activity') {
103 $activityFields[$fieldName] = $field;
104 }
105 else {
106 $contactFields[$fieldName] = $field;
107 }
108 }
109
110 $ufGroupBAO->setProfileDefaults($params['contact_id'], $contactFields, $values[$profileID], TRUE);
111
112 if ($params['activity_id']) {
113 $ufGroupBAO->setComponentDefaults($activityFields, $params['activity_id'], 'Activity', $values[$profileID], TRUE);
114 }
115 }
116 elseif(!empty($params['contact_id'])) {
117 $ufGroupBAO->setProfileDefaults($params['contact_id'], $profileFields, $values[$profileID], TRUE);
118 }
119 else{
120 $values[$profileID] = array_fill_keys(array_keys($profileFields), '');
121 }
122 }
123 if($nonStandardLegacyBehaviour) {
124 $result = civicrm_api3_create_success();
125 $result['values'] = $values[$profileID];
126 return $result;
127 }
128 else {
129 return civicrm_api3_create_success($values, $params, 'Profile', 'Get');
130 }
131 }
132
133 function _civicrm_api3_profile_get_spec(&$params) {
134 $params['profile_id']['api.required'] = TRUE;
135 $params['contact_id']['description'] = 'If no contact is specified an array of defaults will be returned';
136 }
137
138 /**
139 * Submit a set of fields against a profile.
140 * Note choice of submit versus create is discussed CRM-13234 & related to the fact
141 * 'profile' is being treated as a data-entry entity
142 *
143 * @param array $params
144 *
145 * @throws API_Exception
146 * @return array API result array
147 */
148 function civicrm_api3_profile_submit($params) {
149 $profileID = _civicrm_api3_profile_getProfileID($params['profile_id']);
150
151 if (!CRM_Core_DAO::getFieldValue('CRM_Core_DAO_UFGroup', $profileID, 'is_active')) {
152 //@todo declare pseudoconstant & let api do this
153 throw new API_Exception('Invalid value for profile_id');
154 }
155
156 $isContactActivityProfile = CRM_Core_BAO_UFField::checkContactActivityProfileType($profileID);
157
158 if (!empty($params['id']) && CRM_Core_BAO_UFField::checkProfileType($profileID) && !$isContactActivityProfile) {
159 throw new API_Exception('Update profiles including more than one entity not currently supported');
160 }
161
162 $contactParams = $activityParams = $missingParams = array();
163
164 $profileFields = CRM_Core_BAO_UFGroup::getFields($profileID,
165 FALSE,
166 NULL,
167 NULL,
168 NULL,
169 FALSE,
170 NULL,
171 TRUE,
172 NULL,
173 CRM_Core_Permission::EDIT
174 );
175
176 if ($isContactActivityProfile) {
177 civicrm_api3_verify_mandatory($params, NULL, array('activity_id'));
178
179 $errors = CRM_Profile_Form::validateContactActivityProfile($params['activity_id'],
180 $params['contact_id'],
181 $profileID
182 );
183 if (!empty($errors)) {
184 throw new API_Exception(array_pop($errors));
185 }
186 }
187
188 foreach ($profileFields as $fieldName => $field) {
189 if (CRM_Utils_Array::value('is_required', $field)) {
190 if (!CRM_Utils_Array::value($fieldName, $params) || empty($params[$fieldName])) {
191 $missingParams[] = $fieldName;
192 }
193 }
194
195 if (!isset($params[$fieldName])) {
196 continue;
197 }
198
199 $value = $params[$fieldName];
200 if ($params[$fieldName] && isset($params[$fieldName . '_id'])) {
201 $value = $params[$fieldName . '_id'];
202 }
203
204 if ($isContactActivityProfile && CRM_Utils_Array::value('field_type', $field) == 'Activity') {
205 $activityParams[$fieldName] = $value;
206 }
207 else {
208 $contactParams[$fieldName] = $value;
209 }
210 }
211
212 if (!empty($missingParams)) {
213 throw new API_Exception("Missing required parameters for profile id {$params['profile_id']}: " . implode(', ', $missingParams));
214 }
215
216 $contactParams['contact_id'] = CRM_Utils_Array::value('contact_id', $params);
217 $contactParams['profile_id'] = $profileID;
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' => $profileID);
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 array 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 $profileFields = CRM_Core_BAO_UFGroup::getFields($params['profile_id'],
329 FALSE,
330 NULL,
331 NULL,
332 NULL,
333 FALSE,
334 NULL,
335 TRUE,
336 NULL,
337 CRM_Core_Permission::EDIT
338 );
339
340 list($data, $contactDetails) = CRM_Contact_BAO_Contact::formatProfileContactParams($params,
341 $profileFields,
342 CRM_Utils_Array::value('contact_id', $params),
343 $params['profile_id'],
344 CRM_Utils_Array::value('contact_type', $params),
345 CRM_Utils_Array::value('skip_custom', $params, FALSE)
346 );
347
348 if (empty($data)) {
349 throw new API_Exception('Enable to format profile parameters.');
350 }
351
352 return civicrm_api3_create_success($data);
353 }
354
355
356 /**
357 * This is a function to help us 'pretend' billing is a profile & treat it like it is one.
358 * It gets standard credit card address fields etc
359 * Note this is 'better' that the inbuilt version as it will pull in fallback values
360 * billing location -> is_billing -> primary
361 *
362 * Note that that since the existing code for deriving a blank profile is not easily accessible our
363 * interim solution is just to return an empty array
364 */
365 function _civicrm_api3_profile_getbillingpseudoprofile(&$params) {
366
367 $locations = civicrm_api3('address', 'getoptions', array('field' => 'location_type_id'));
368 $locationTypeID = array_search('Billing', $locations['values']);
369
370 if(empty($params['contact_id'])) {
371 $config = CRM_Core_Config::singleton();
372 $blanks = array(
373 'billing_first_name' => '',
374 'billing_middle_name' => '',
375 'billing_last_name' => '',
376 'email-' . $locationTypeID => '',
377 'billing_email-' . $locationTypeID => '',
378 'billing_city-' . $locationTypeID => '',
379 'billing_postal_code-' . $locationTypeID => '',
380 'billing_street_address-' . $locationTypeID => '',
381 'billing_country_id-' . $locationTypeID => $config->defaultContactCountry,
382 'billing_state_province_id-' . $locationTypeID => $config->defaultContactStateProvince,
383 );
384 return $blanks;
385 }
386
387 $addressFields = array('street_address', 'city', 'state_province_id', 'country_id', 'postal_code');
388 $result = civicrm_api3('contact', 'getsingle', array(
389 'id' => $params['contact_id'],
390 'api.address.get.1' => array('location_type_id' => 'Billing', 'return' => $addressFields),
391 // getting the is_billing required or not is an extra db call but probably cheap enough as this isn't an import api
392 'api.address.get.2' => array('is_billing' => True, 'return' => $addressFields),
393 'api.email.get.1' => array('location_type_id' => 'Billing',),
394 'api.email.get.2' => array('is_billing' => True,),
395 'return' => 'api.email.get, api.address.get, api.address.getoptions, country, state_province, email, first_name, last_name, middle_name, ' . implode($addressFields, ','),
396 )
397 );
398
399 $values = array(
400 'billing_first_name' => $result['first_name'],
401 'billing_middle_name' => $result['middle_name'],
402 'billing_last_name' => $result['last_name'],
403 );
404
405 if(!empty($result['api.address.get.1']['count'])) {
406 foreach ($addressFields as $fieldname) {
407 $values['billing_' . $fieldname . '-' . $locationTypeID] = isset($result['api.address.get.1']['values'][0][$fieldname]) ? $result['api.address.get.1']['values'][0][$fieldname] : '';
408 }
409 }
410 elseif(!empty($result['api.address.get.2']['count'])) {
411 foreach ($addressFields as $fieldname) {
412 $values['billing_' . $fieldname . '-' . $locationTypeID] = isset($result['api.address.get.2']['values'][0][$fieldname]) ? $result['api.address.get.2']['values'][0][$fieldname] : '';
413 }
414 }
415 else{
416 foreach ($addressFields as $fieldname) {
417 $values['billing_' . $fieldname . '-' . $locationTypeID] = isset($result[$fieldname]) ? $result[$fieldname] : '';
418 }
419 }
420
421 if(!empty($result['api.email.get.1']['count'])) {
422 $values['billing-email'. '-' . $locationTypeID] = $result['api.email.get.1']['values'][0]['email'];
423 }
424 elseif(!empty($result['api.email.get.2']['count'])) {
425 $values['billing-email'. '-' . $locationTypeID] = $result['api.email.get.2']['values'][0]['email'];
426 }
427 else{
428 $values['billing-email'. '-' . $locationTypeID] = $result['email'];
429 }
430 // return both variants of email to reflect inconsistencies in form layer
431 $values['email'. '-' . $locationTypeID] = $values['billing-email'. '-' . $locationTypeID];
432 return $values;
433 }
434
435 /**
436 * Here we will build up getfields type data for all the fields in the profile. Because the integration with the
437 * form layer in core is so hard-coded we are not going to attempt to re-use it
438 * However, as this function is unit-tested & hence 'locked in' we can aspire to extract sharable
439 * code out of the form-layer over time.
440 *
441 * The function deciphers which fields belongs to which entites & retrieves metadata about the entities
442 * Unfortunately we have inconsistencies such as 'contribution' uses contribution_status_id
443 * & participant has 'participant_status' so we have to standardise from the outside in here -
444 * find the oddities, 'mask them' at this layer, add tests & work to standardise over time so we can remove this handling
445 *
446 * @param integer $profileID
447 * @param integer $optionsBehaviour 0 = don't resolve, 1 = resolve non-aggressively, 2 = resolve aggressively - ie include country & state
448 */
449
450 function _civicrm_api3_buildprofile_submitfields($profileID, $optionsBehaviour = 1) {
451 static $profileFields = array();
452 if(isset($profileFields[$profileID])) {
453 return $profileFields[$profileID];
454 }
455 $fields = civicrm_api3('uf_field', 'get', array('uf_group_id' => $profileID));
456 $entities = array();
457
458 foreach ($fields['values'] as $field) {
459 if(!$field['is_active']) {
460 continue;
461 }
462 list($entity, $fieldName) = _civicrm_api3_map_profile_fields_to_entity($field);
463 $profileFields[$profileID][$fieldName] = array(
464 'api.required' => $field['is_required'],
465 'title' => $field['label'],
466 'help_pre' => CRM_Utils_Array::value('help_pre', $field),
467 'help_post' => CRM_Utils_Array::value('help_post', $field),
468 );
469
470 $realFieldName = $field['field_name'];
471 //see function notes
472 // as we build up a list of these we should be able to determine a generic approach
473 //
474 $hardCodedEntityFields = array(
475 'state_province' => 'state_province_id',
476 'country' => 'country_id',
477 'participant_status' => 'status_id',
478 'gender' => 'gender_id',
479 'financial_type' => 'financial_type_id',
480 'soft_credit' => 'soft_credit_to',
481 'group' => 'group_id',
482 'tag' => 'tag_id',
483 );
484
485 if(array_key_exists($realFieldName, $hardCodedEntityFields)) {
486 $realFieldName = $hardCodedEntityFields[$realFieldName];
487 }
488
489 $entities[$entity][$fieldName] = $realFieldName;
490 }
491
492 foreach ($entities as $entity => $entityFields) {
493 $result = civicrm_api3($entity, 'getfields', array('action' => 'create'));
494 $entityGetFieldsResult = _civicrm_api3_profile_appendaliases($result['values'], $entity);
495 foreach ($entityFields as $entityfield => $realName) {
496 $profileFields[$profileID][$entityfield] = $entityGetFieldsResult[$realName];
497 if($optionsBehaviour && !empty($entityGetFieldsResult[$realName]['pseudoconstant'])) {
498 if($optionsBehaviour > 1 || !in_array($realName, array('state_province_id', 'county_id', 'country_id'))) {
499 $options = civicrm_api3($entity, 'getoptions', array('field' => $realName));
500 $profileFields[$profileID][$entityfield]['options'] = $options['values'];
501 }
502 }
503 /**
504 * putting this on hold -this would cause the api to set the default - but could have unexpected behaviour
505 if(isset($result['values'][$realName]['default_value'])) {
506 //this would be the case for a custom field with a configured default
507 $profileFields[$profileID][$entityfield]['api.default'] = $result['values'][$realName]['default_value'];
508 }
509 */
510 }
511 }
512 return $profileFields[$profileID];
513 }
514
515 /**
516 * Here we map the profile fields as stored in the uf_field table to their 'real entity'
517 * we also return the profile fieldname
518 *
519 */
520 function _civicrm_api3_map_profile_fields_to_entity(&$field) {
521 $entity = $field['field_type'];
522 $contactTypes = civicrm_api3('contact', 'getoptions', array('field' => 'contact_type'));
523 if(in_array($entity, $contactTypes['values'])) {
524 $entity = 'Contact';
525 }
526 $fieldName = $field['field_name'];
527 if(!empty($field['location_type_id'])) {
528 if($fieldName == 'email') {
529 $entity = 'Email';
530 }
531 else{
532 $entity = 'Address';
533 }
534 $fieldName .= '-' . $field['location_type_id'];
535 }
536 if(!empty($field['phone_type_id'])) {
537 $fieldName .= '-' . $field['location_type_id'];
538 $entity = 'Phone';
539 }
540 // @todo - sort this out!
541 //here we do a hard-code list of known fields that don't map to where they are mapped to
542 // not a great solution but probably if we looked in the BAO we'd find a scary switch statement
543 // in a perfect world the uf_field table would hold the correct entity for each item
544 // & only the relationships between entities would need to be coded
545 $hardCodedEntityMappings = array(
546 'street_address' => 'Address',
547 'street_number' => 'Address',
548 'supplemental_address_1' => 'Address',
549 'supplemental_address_2' => 'Address',
550 'supplemental_address_3' => 'Address',
551 'postal_code' => 'Address',
552 'city' => 'Address',
553 'email' => 'Email',
554 'state_province' => 'Address',
555 'country' => 'Address',
556 'county' => 'Address',
557 //note that in discussions about how to restructure the api we discussed making these membership
558 // fields into 'membership_payment' fields - which would entail declaring them in getfields
559 // & renaming them in existing profiles
560 'financial_type' => 'Contribution',
561 'total_amount' => 'Contribution',
562 'receive_date' => 'Contribution',
563 'payment_instrument' => 'Contribution',
564 'check_number' => 'Contribution',
565 'contribution_status_id' => 'Contribution',
566 'soft_credit' => 'Contribution',
567 'group' => 'GroupContact',
568 'tag' => 'EntityTag',
569 );
570 if(array_key_exists($fieldName, $hardCodedEntityMappings)) {
571 $entity = $hardCodedEntityMappings[$fieldName];
572 }
573 return array($entity, $fieldName);
574 }
575
576 /**
577 * @todo this should be handled by the api wrapper using getfields info - need to check
578 * how we add a a pseudoconstant to this pseudoapi to make that work
579 */
580 function _civicrm_api3_profile_getProfileID($profileID) {
581 if(!empty($profileID) && strtolower($profileID) != 'billing' && !is_numeric($profileID)) {
582 $profileID = civicrm_api3('uf_group', 'getvalue', array('return' => 'id', 'name' => $profileID));
583 }
584 return $profileID;
585 }
586
587 /**
588 * helper function to add all aliases as keys to getfields response so we can look for keys within it
589 * since the relationship between profile fields & api / metadata based fields is a bit inconsistent
590 *
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 * @param $entity
596 *
597 * @return array
598 */
599 function _civicrm_api3_profile_appendaliases($values, $entity) {
600 foreach ($values as $field => $spec) {
601 if(!empty($spec['api.aliases'])) {
602 foreach ($spec['api.aliases'] as $alias) {
603 $values[$alias] = $spec;
604 }
605 }
606 if(!empty($spec['uniqueName'])) {
607 $values[$spec['uniqueName']] = $spec;
608 }
609 }
610 //special case on membership & contribution - can't see how to handle in a generic way
611 if(in_array($entity, array('Membership', 'Contribution'))) {
612 $values['send_receipt'] = array('title' => 'Send Receipt', 'type' => (int) 16);
613 }
614 return $values;
615 }