View Javadoc
1   /*
2    * Copyright (c) 2002-2020, City of Paris
3    * All rights reserved.
4    *
5    * Redistribution and use in source and binary forms, with or without
6    * modification, are permitted provided that the following conditions
7    * are met:
8    *
9    *  1. Redistributions of source code must retain the above copyright notice
10   *     and the following disclaimer.
11   *
12   *  2. Redistributions in binary form must reproduce the above copyright notice
13   *     and the following disclaimer in the documentation and/or other materials
14   *     provided with the distribution.
15   *
16   *  3. Neither the name of 'Mairie de Paris' nor 'Lutece' nor the names of its
17   *     contributors may be used to endorse or promote products derived from
18   *     this software without specific prior written permission.
19   *
20   * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
21   * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22   * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23   * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
24   * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
25   * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
26   * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
27   * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
28   * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
29   * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
30   * POSSIBILITY OF SUCH DAMAGE.
31   *
32   * License 1.0
33   */
34  package fr.paris.lutece.plugins.campagnebp.web;
35  
36  import java.util.HashMap;
37  import java.util.Map;
38  import java.util.Map.Entry;
39  import java.util.regex.Matcher;
40  import java.util.regex.Pattern;
41  
42  import javax.servlet.http.HttpServletRequest;
43  
44  import org.apache.commons.lang.StringUtils;
45  
46  import fr.paris.lutece.plugins.avatar.service.AvatarService;
47  import fr.paris.lutece.plugins.campagnebp.business.Civility;
48  import fr.paris.lutece.plugins.campagnebp.business.MyAccount;
49  import fr.paris.lutece.plugins.campagnebp.business.MyInfosForm;
50  import fr.paris.lutece.plugins.campagnebp.service.AccountService;
51  import fr.paris.lutece.plugins.campagnebp.service.CampagnesService;
52  import fr.paris.lutece.plugins.campagnebp.service.MyInfosListenerService;
53  import fr.paris.lutece.plugins.campagnebp.service.MyInfosService;
54  import fr.paris.lutece.plugins.campagnebp.service.avatar.CampagneAvatarService;
55  import fr.paris.lutece.plugins.campagnebp.uploadhandler.CampagneUploadHandler;
56  import fr.paris.lutece.plugins.campagnebp.utils.CampagneErrorJsonResponse;
57  import fr.paris.lutece.plugins.campagnebp.utils.CampagneResponse;
58  import fr.paris.lutece.plugins.campagnebp.utils.Constants;
59  import fr.paris.lutece.plugins.campagnebp.utils.ModelUtils;
60  import fr.paris.lutece.plugins.identitystore.web.rs.dto.AttributeDto;
61  import fr.paris.lutece.plugins.identitystore.web.rs.dto.AuthorDto;
62  import fr.paris.lutece.plugins.identitystore.web.rs.dto.IdentityChangeDto;
63  import fr.paris.lutece.plugins.identitystore.web.rs.dto.IdentityDto;
64  import fr.paris.lutece.plugins.identitystore.web.service.AuthorType;
65  import fr.paris.lutece.plugins.identitystore.web.service.IdentityService;
66  import fr.paris.lutece.plugins.mylutece.modules.openam.authentication.OpenamUser;
67  import fr.paris.lutece.plugins.openamidentityclient.business.CreateAccountResult;
68  import fr.paris.lutece.plugins.openamidentityclient.service.OpenamIdentityException;
69  import fr.paris.lutece.plugins.openamidentityclient.service.OpenamIdentityService;
70  import fr.paris.lutece.plugins.parisconnect.service.ParisConnectService;
71  import fr.paris.lutece.portal.service.captcha.CaptchaSecurityService;
72  import fr.paris.lutece.portal.service.datastore.DatastoreService;
73  import fr.paris.lutece.portal.service.i18n.I18nService;
74  import fr.paris.lutece.portal.service.message.SiteMessage;
75  import fr.paris.lutece.portal.service.message.SiteMessageException;
76  import fr.paris.lutece.portal.service.message.SiteMessageService;
77  import fr.paris.lutece.portal.service.plugin.PluginService;
78  import fr.paris.lutece.portal.service.portal.ThemesService;
79  import fr.paris.lutece.portal.service.security.LuteceUser;
80  import fr.paris.lutece.portal.service.security.SecurityService;
81  import fr.paris.lutece.portal.service.security.SecurityTokenService;
82  import fr.paris.lutece.portal.service.security.UserNotSignedException;
83  import fr.paris.lutece.portal.service.spring.SpringContextService;
84  import fr.paris.lutece.portal.service.util.AppLogService;
85  import fr.paris.lutece.portal.service.util.AppPathService;
86  import fr.paris.lutece.portal.service.util.AppPropertiesService;
87  import fr.paris.lutece.portal.util.mvc.commons.annotations.Action;
88  import fr.paris.lutece.portal.util.mvc.commons.annotations.View;
89  import fr.paris.lutece.portal.util.mvc.utils.MVCUtils;
90  import fr.paris.lutece.portal.util.mvc.xpage.MVCApplication;
91  import fr.paris.lutece.portal.util.mvc.xpage.annotations.Controller;
92  import fr.paris.lutece.portal.web.constants.Markers;
93  import fr.paris.lutece.portal.web.xpages.XPage;
94  import fr.paris.lutece.util.json.AbstractJsonResponse;
95  import fr.paris.lutece.util.json.ErrorJsonResponse;
96  import fr.paris.lutece.util.json.JsonResponse;
97  import fr.paris.lutece.util.json.JsonUtil;
98  import fr.paris.lutece.util.url.UrlItem;
99  
100 /**
101  * This class provides the user interface to manage ParisConnectUser xpages ( manage, create, modify, remove )
102  */
103 @Controller( xpageName = MyInfosXPage.PAGE_MY_INFOS, pageTitleI18nKey = "budgetparticipatif.xpage.myinfos.pageTitle", pagePathI18nKey = "budgetparticipatif.xpage.myInfos.pagePathLabel" )
104 public class MyInfosXPage extends MVCApplication
105 {
106 
107     /**
108      * Name of this application
109      */
110     public static final String TOKEN_DO_SEND_AVIS = "doSendAvis";
111     /**
112      * 
113      */
114     public static final String TOKEN_DO_SUBSCRIBE_ALERT = "doSubscribeAlert";
115     /**
116      * 
117      */
118     public static final String TOKEN_DO_SAVE_MY_INFOS = "doSaveMyInfos";
119     /**
120      * 
121      */
122     public static final String TOKEN_DO_CREATE_MY_INFOS = "doCreateMyInfos";
123     /**
124      * 
125      */
126     public static final String PAGE_MY_INFOS = "mesInfos";
127     private static final long serialVersionUID = -4316691400124512414L;
128     private static final String JCAPTCHA_PLUGIN = "jcaptcha";
129     // Templates
130     private static final String TEMPLATE_MES_INFOS = "/skin/plugins/campagnebp/mes_infos.html";
131     private static final String TEMPLATE_CREATE_MY_INFOS = "/skin/plugins/campagnebp/create_my_infos.html";
132     private static final String TEMPLATE_MES_INFOS_POPUP = "/skin/plugins/campagnebp/mes_infos_popup.html";
133     private static final String TEMPLATE_CHECKED_MY_INFOS_AFTER_LOGIN = "/skin/plugins/campagnebp/checked_my_infos_after_login.html";
134 
135     // Views
136     private static final String VIEW_MY_INFOS = "mesinfos";
137     private static final String VIEW_MY_VOTES = "myVotes";
138     private static final String VIEW_CREATE_MY_INFOS = "createMyInfos";
139 
140     // Actions
141     private static final String ACTION_SAVE = "save";
142     private static final String ACTION_DO_CREATE_INFOS = "doCreateInfos";
143 
144     // Infos
145     private static final String INFO_SAVED = "budgetparticipatif.info.saved";
146     private static final String INFO_VALIDATION_MAIL_SEND = "budgetparticipatif.info.validationMailSend";
147     private static final String ERROR_DURING_VALIDATION_MAIL_SEND = "budgetparticipatif.error.duringValidationMailSend";
148 
149     // Markers
150 
151     private static final String MARK_LOGIN = "login";
152     private static final String MARK_PASSWORD = "password";
153     private static final String MARK_CONFIRMATION_PASSWORD = "confirmation_password";
154     private static final String MARK_NICKNAME = "nickname";
155     private static final String MARK_FIRSTNAME = "firstname";
156     private static final String MARK_CIVILITY = "civility";
157     private static final String MARK_LASTNAME = "lastname";
158     private static final String MARK_ADDRESS = "address";
159     private static final String MARK_POSTAL_CODE = "postal_code";
160     private static final String MARK_BIRTHDATE = "birthdate";
161     private static final String MARK_ARRONDISSEMENT = "arrondissement";
162     private static final String MARK_ILIVEINPARIS = "iliveinparis";
163     private static final String MARK_STAYCONNECTED = "stayconnected";
164     private static final String MARK_ARRONDISSEMENTS_LIST = "arrondissements_list";
165     private static final String MARK_POSTAL_CODE_LIST = "postal_code_list";
166     private static final String MARK_COMPLETE_INFO = "completeInfos";
167     private static final String MARK_GEO_JSON = "geoJson";
168     private static final String MARK_TYPE_DOCUMENT = "document";
169     private static final String MARK_EXTENDABLERESOURCETYPE = "extendableResourceType";
170     private static final String MARK_PAGE = "page";
171     private static final String MARK_VOTEVALID = "voteValid";
172     private static final String MARK_SAVE_PERSONAL = "savePersonalData";
173     private static final String MARK_FORM = "form";
174     private static final String MARK_TRUE = "true";
175     private static final String MARK_URL_MONCOMPTE = "url_moncompte";
176 
177     private static final String MARK_THEME = "theme";
178     private static final String MARK_CAPTCHA = "captcha";
179     private static final String MARK_SEND_ACCOUNT_VALIDATION = "send_account_validation";
180     private static final String MARK_ACCOUNT_VERIFIED = "account_verified";
181     private static final String MARK_USER_VALID = "user_valid";
182     private static final String MARK_INIT_FORM = "init_form";
183     private static final String MARK_IS_FOR_POPUP = "is_for_popup";
184     private static final String MARK_AVATAR_URL = "avatar_url";
185     private static final String MARK_HANDLER = "handler";
186 
187     private static final String MARK_CAMPAGNE_SERVICE = "campagneService";
188 
189     // Jsp redirections
190     private static final String JSP_PORTAL = "jsp/site/Portal.jsp";
191 
192     // Messages
193     private static final String MESSAGE_INFO_USER_MUST_COMPLETE_PROFILE = "budgetparticipatif.labelUserMustCompleteProfile";
194     private static final String MESSAGE_CAPTCHA_NOT_VALIDATED = "budgetparticipatif.messageErrorCaptchaNotValidated";
195     private static final String MESSAGE_ERROR_CONFIRMATION_PASSWORD = "budgetparticipatif.messageErrorConfirmationPassword";
196     private static final String MESSAGE_ERROR_NICKNAME_ALREADY_EXIST = "budgetparticipatif.messageErrorNicknameAlreadyExist";
197     private static final String MESSAGE_ERROR_ADRESS_GEOLOC_FORMAT = "budgetparticipatif.messageErrorAdressGeolocFormat";
198     private static final String MESSAGE_ERROR_NICKNAME_MISSING = "budgetparticipatif.validation.nickname.notEmpty";
199     private static final String PROPERTY_CONFIRM_MODIFY_ARRAND = "budgetparticipatif.property_confirm_modify_arrand";
200     private static final String PROPERTY_CONFIRM_MODIFY_ARRAND_WITH_VOTES_DELETING = "budgetparticipatif.property_confirm_modify_arrand_with_votes_deleting";
201     private static final String PROPERTY_ERROR_MODIFY_ARRAND = "budgetparticipatif.property_error_changement_arrond";
202     private static final String PROPERTY_ERROR_END_PHASE = "budgetparticipatif.property_error_end_phase";
203     private static final String CAMPAGNE_BP_APP_CODE = AppPropertiesService.getProperty( "campagnebp.identity.application.code" );
204     private static final String CAMPAGNE_BP_APP_NAME = AppPropertiesService.getProperty( "campagnebp.identity.application.name" );
205     // Parameters
206     private static final String PARAMETER_COMPLETE_INFOS = "completeInfos";
207     private static final String PARAMETER_REFERER = "referer";
208     private static final String PARAMETER_MAIL = "mail";
209     private static final String PARAMETER_MESSAGE = "message";
210 
211     // Json ERROR CODE
212     // Json ERROR CODE
213     private static final String JSON_ERROR_CODE_USER_NOT_SIGNED = "USER_NOT_SIGNED";
214     private static final String JSON_ERROR_DURING_SEND_AVIS = "JSON_ERROR_DURING_SEND_AVIS";
215     private static final String JSON_ERROR_CODE_ACCOUNT_NOT_VERIFIED = "ACCOUNT_NOT_VERIFIED";
216 
217     // Properties
218     private static final String PROPERTY_URL_MONCOMPTE = "campagnebp.url.moncompte";
219 
220     // Key
221     private static final String KEY_ENABLE_CAPTCHA_USER_INFORMATIONS = "budgetparticipatif.site_property.enable_captcha_user_informations";
222     private static final String KEY_PARIS_CONNECT_SEND_AVIS_BACK_URL = "budgetparticipatif.site_property.paris_connect.send_avis_back_url";
223     private static final String IDS_KEY_USER_GENDER = AppPropertiesService.getProperty( "campagnebp.identity.user.gender" );
224     private static final String IDS_KEY_USER_FIRST_NAME = AppPropertiesService.getProperty( "campagnebp.identity.user.first_name" );
225     private static final String IDS_KEY_USER_LAST_NAME = AppPropertiesService.getProperty( "campagnebp.identity.user.last_name" );
226     private static final String IDS_KEY_USER_BIRTHDAY = AppPropertiesService.getProperty( "campagnebp.identity.user.birthday" );
227     private static final String IDS_KEY_USER_ADDRESS = AppPropertiesService.getProperty( "campagnebp.identity.user.address" );
228     private static final String IDS_KEY_USER_ADDRESS_POSTAL_CODE = AppPropertiesService.getProperty( "campagnebp.identity.user.postal_code" );
229     private static final String IDS_KEY_USER_ADDRESS_CITY = AppPropertiesService.getProperty( "campagnebp.identity.user.city" );
230     private static final String IDS_KEY_USER_ADDRESS_DETAIL = AppPropertiesService.getProperty( "campagnebp.identity.user.address_detail" );
231 
232     private static final String MARK_IDS_ATTRIBUTES = "ids_attributes";
233     private static final String MARK_LABEL_IDS_GENDER = "Civilité";
234     private static final String MARK_LABEL_IDS_FIRST_NAME = "Prénom";
235     private static final String MARK_LABEL_IDS_LAST_NAME = "Nom";
236     private static final String MARK_LABEL_IDS_BIRTHDAY = "Date de naissance";
237     private static final String MARK_LABEL_IDS_ADDRESS = "Adresse du domicile";
238 
239     private static final String COMMA = ", ";
240 
241     private static final Map<String, String> MAP_IDS_ATTRIBUTES = new HashMap<String, String>( )
242     {
243         {
244             put( MARK_LABEL_IDS_GENDER, IDS_KEY_USER_GENDER );
245             put( MARK_LABEL_IDS_FIRST_NAME, IDS_KEY_USER_FIRST_NAME );
246             put( MARK_LABEL_IDS_LAST_NAME, IDS_KEY_USER_LAST_NAME );
247             put( MARK_LABEL_IDS_BIRTHDAY, IDS_KEY_USER_BIRTHDAY );
248         }
249     };
250 
251     private static final Map<String, String> MAP_CIVILITY = new HashMap<String, String>( )
252     {
253         {
254             put( "0", "campagnebp.mes_infos.civilityNPR" );
255             put( "1", "campagnebp.mes_infos.civilityMme" );
256             put( "2", "campagnebp.mes_infos.civilityM" );
257         }
258     };
259 
260     // regex for address split
261     private static final String REGEX_ADDRESS = AppPropertiesService.getProperty( "campagnebp.address.suggestpoi.regex" );
262     private Pattern _patternAddress;
263 
264     // Local session variables
265     private MyInfosForm _form;
266     private MyAccount _accountForm;
267 
268     private CaptchaSecurityService _captchaService = new CaptchaSecurityService( );
269 
270     // private BudgetRatingService _budgetRating = SpringContextService.getBean(
271     // BudgetRatingService.BEAN_NAME );
272 
273     private static final String BEAN_IDENTITYSTORE_SERVICE = "campagnebp.identitystore.service";
274     private IdentityService _identityService;
275 
276     /**
277      * Constructor
278      */
279     public MyInfosXPage( )
280     {
281         super( );
282         _identityService = SpringContextService.getBean( BEAN_IDENTITYSTORE_SERVICE );
283         _patternAddress = Pattern.compile( REGEX_ADDRESS );
284     }
285 
286     /**
287      * Displays user's personal infos
288      * 
289      * @param request
290      *            The HTTP request
291      * @return The page
292      * @throws UserNotSignedException
293      *             if the user is not signed
294      */
295     @View( value = VIEW_CREATE_MY_INFOS )
296     public XPage getCreateMyInfos( HttpServletRequest request ) throws UserNotSignedException
297     {
298         Map<String, Object> model = getModel( );
299 
300         MyInfosForm myInfos = _form;
301 
302         if ( _accountForm != null )
303         {
304             model.put( MARK_LOGIN, _accountForm.getLogin( ) );
305             model.put( MARK_PASSWORD, _accountForm.getPassword( ) );
306             model.put( MARK_CONFIRMATION_PASSWORD, _accountForm.getConfirmationPassword( ) );
307 
308         }
309 
310         if ( myInfos != null )
311         {
312 
313             model.put( MARK_CIVILITY, myInfos.getCivility( ) );
314             model.put( MARK_NICKNAME, myInfos.getNickname( ) );
315             model.put( MARK_FIRSTNAME, myInfos.getFirstname( ) );
316             model.put( MARK_LASTNAME, myInfos.getLastname( ) );
317             model.put( MARK_ARRONDISSEMENT, myInfos.getArrondissement( ) );
318             model.put( MARK_ADDRESS, myInfos.getAddress( ) );
319             model.put( MARK_BIRTHDATE, myInfos.getBirthdate( ) );
320             model.put( MARK_POSTAL_CODE, myInfos.getPostalCode( ) );
321             model.put( MARK_ILIVEINPARIS, myInfos.getIliveinparis( ) );
322             model.put( MARK_STAYCONNECTED, myInfos.getStayconnected( ) );
323             model.put( MARK_SEND_ACCOUNT_VALIDATION, myInfos.getSendaccountvalidation( ) );
324             model.put( MARK_GEO_JSON, myInfos.getGeojson( ) );
325             model.put( MARK_INIT_FORM, false );
326 
327         }
328         else
329         {
330 
331             model.put( MARK_INIT_FORM, true );
332         }
333         model.put( MARK_HANDLER, SpringContextService.getBean( CampagneUploadHandler.BEAN_NAME ) );
334 
335         model.put( SecurityTokenService.MARK_TOKEN, SecurityTokenService.getInstance( ).getToken( request, MyInfosXPage.TOKEN_DO_CREATE_MY_INFOS ) );
336         model.put( MARK_ARRONDISSEMENTS_LIST, MyInfosService.getArrondissements( ) );
337         model.put( MARK_POSTAL_CODE_LIST, MyInfosService.getPostalCodes( ) );
338 
339         // Check if the submission/vote phases are open or not
340         model.put( MARK_CAMPAGNE_SERVICE, CampagnesService.getInstance( ) );
341 
342         return getXPage( TEMPLATE_CREATE_MY_INFOS, request.getLocale( ), model );
343 
344     }
345 
346     /**
347      * Handles the removal form of a parisconnectuser bm * @param request The Http request
348      * 
349      * @param request
350      *            The request
351      * @return the jsp URL to display the form to manage parisconnectusers
352      * @throws UserNotSignedException
353      *             if user not signed
354      */
355     @Action( ACTION_DO_CREATE_INFOS )
356     public XPage doCreateMyInfos( HttpServletRequest request ) throws UserNotSignedException
357     {
358         boolean bError = false;
359 
360         boolean bCapchaVerified = true;
361         MyInfosFormampagnebp/business/MyInfosForm.html#MyInfosForm">MyInfosForm form = new MyInfosForm( );
362         MyAccountbp/business/MyAccount.html#MyAccount">MyAccount formMyAccount = new MyAccount( );
363 
364         populate( formMyAccount, request );
365         populate( form, request );
366 
367         if ( isEnableCaptcha( ) )
368         {
369 
370             if ( !_captchaService.validate( request ) )
371             {
372                 bCapchaVerified = false;
373                 addError( MESSAGE_CAPTCHA_NOT_VALIDATED, getLocale( request ) );
374             }
375         }
376 
377         // !SecurityTokenService.getInstance().validate(request,
378         // MyInfosXPage.TOKEN_DO_SAVE_MY_INFOS)
379 
380         // Check constraints
381 
382         bError = !bCapchaVerified || !validateBean( formMyAccount, getLocale( request ) ) || !validateBean( form, getLocale( request ) );
383 
384         if ( !CampagnesService.getInstance( ).isDuring( Constants.VOTE ) && StringUtils.isBlank( form.getNickname( ) ) )
385         {
386             bError = true;
387             addError( MESSAGE_ERROR_NICKNAME_MISSING, getLocale( request ) );
388         }
389 
390         if ( !bError && !MyInfosService.setAdressValid( form ) )
391         {
392             bError = true;
393             addError( MESSAGE_ERROR_ADRESS_GEOLOC_FORMAT, getLocale( request ) );
394         }
395 
396         if ( !bError && MyInfosService.isNicknameAlreadyExist( form.getNickname( ) ) )
397         {
398             bError = true;
399             addError( MESSAGE_ERROR_NICKNAME_ALREADY_EXIST, getLocale( request ) );
400         }
401 
402         if ( !bError && !formMyAccount.getPassword( ).equals( formMyAccount.getConfirmationPassword( ) ) )
403         {
404             bError = true;
405             addError( MESSAGE_ERROR_CONFIRMATION_PASSWORD, getLocale( request ) );
406         }
407         CreateAccountResult createAccountResult = null;
408         String strEmail = null;
409         if ( !bError )
410         {
411 
412             try
413             {
414                 createAccountResult = AccountService.createAccountAndIdentity( form, formMyAccount );
415                 strEmail = OpenamIdentityService.getService( ).getAccount( createAccountResult.getUid( ) ).getLogin( );
416 
417             }
418             catch( OpenamIdentityException e )
419             {
420                 addError( OpenamIdentityService.getService( ).getApiErrorMessage( e.getErrorCode( ), getLocale( request ) ) );
421                 bError = true;
422 
423             }
424         }
425 
426         if ( bError || createAccountResult == null || strEmail == null )
427         {
428             _form = form;
429             _accountForm = formMyAccount;
430             return redirectView( request, VIEW_CREATE_MY_INFOS );
431         }
432 
433         MyInfosService.saveUserInfos( createAccountResult.getUid( ), createAccountResult.getTokenId( ), form );
434         MyInfosService.saveUserEmail( createAccountResult.getUid( ), strEmail );
435         // Save avatar
436         CampagneAvatarService.createAvatar( request, createAccountResult.getUid( ) );
437 
438         // Add message
439 
440         MyInfosService.sendAccountValidationMail( request, getLocale( request ), createAccountResult.getUid( ) );
441 
442         addInfo( INFO_VALIDATION_MAIL_SEND, getLocale( request ) );
443         // reint form
444         _form = null;
445         _accountForm = null;
446         return redirectView( request, VIEW_MY_INFOS );
447     }
448 
449     /**
450      * Displays user's personal infos
451      * 
452      * @param request
453      *            The HTTP request
454      * @return The page
455      * @throws UserNotSignedException
456      *             if the user is not signed
457      */
458     @View( value = VIEW_MY_INFOS, defaultView = true )
459     public XPage getMyInfos( HttpServletRequest request ) throws UserNotSignedException
460     {
461         return getMyInfos( request, false );
462     }
463 
464     /**
465      * Get the content of the my info page
466      * 
467      * @param request
468      *            the request
469      * @param bIsForPopup
470      *            True if the content should be formated to be displayed in a popup, false otherwise
471      * @return The required XPage
472      * @throws UserNotSignedException
473      *             If the user has not signed in
474      */
475     private XPage getMyInfos( HttpServletRequest request, boolean bIsForPopup ) throws UserNotSignedException
476     {
477         if ( SecurityService.isAuthenticationEnable( ) )
478         {
479             LuteceUser user = SecurityService.getInstance( ).getRegisteredUser( request );
480 
481             boolean bInitForm = false;
482             // ParisConnectUser user = getTestUser( );
483             if ( user != null )
484             {
485 
486                 MyAccount myAccountForm;
487                 if ( _accountForm != null )
488                 {
489                     myAccountForm = _accountForm;
490                     _accountForm = null;
491                 }
492                 else
493                 {
494                     myAccountForm = new MyAccount( );
495                 }
496 
497                 populate( myAccountForm, user );
498 
499                 MyInfosForm myInfos;
500 
501                 if ( _form != null )
502                 {
503                     myInfos = _form;
504                     _form = null;
505                 }
506                 else
507                 {
508                     bInitForm = true;
509                     myInfos = MyInfosService.loadUserInfos( user );
510                 }
511 
512                 boolean bCompleteInfos = Boolean.parseBoolean( request.getParameter( PARAMETER_COMPLETE_INFOS ) );
513                 // test if the user has validated his account
514                 // if the template is call for popup this test is already make
515                 if ( !bIsForPopup )
516                 {
517                     // MyInfosService.isAccountVerified(user);
518                 }
519 
520                 if ( bCompleteInfos )
521                 {
522                     addInfo( MESSAGE_INFO_USER_MUST_COMPLETE_PROFILE, request.getLocale( ) );
523                 }
524 
525                 Map<String, Object> model = getModel( );
526 
527                 if ( isEnableCaptcha( ) )
528                 {
529                     model.put( MARK_CAPTCHA, _captchaService.getHtmlCode( ) );
530                 }
531 
532                 if ( myAccountForm != null )
533                 {
534                     model.put( MARK_LOGIN, myAccountForm.getLogin( ) );
535                     model.put( MARK_PASSWORD, myAccountForm.getPassword( ) );
536                     model.put( MARK_CONFIRMATION_PASSWORD, myAccountForm.getConfirmationPassword( ) );
537 
538                 }
539                 model.put( MARK_HANDLER, SpringContextService.getBean( CampagneUploadHandler.BEAN_NAME ) );
540                 model.put( MARK_NICKNAME, myInfos.getNickname( ) );
541                 model.put( MARK_AVATAR_URL, AvatarService.getAvatarUrl( user.getName( ) ) );
542                 model.put( MARK_FIRSTNAME, myInfos.getFirstname( ) );
543                 model.put( MARK_LASTNAME, myInfos.getLastname( ) );
544                 model.put( MARK_ADDRESS, myInfos.getAddress( ) );
545                 model.put( MARK_BIRTHDATE, myInfos.getBirthdate( ) );
546                 model.put( MARK_ILIVEINPARIS, myInfos.getIliveinparis( ) );
547                 model.put( MARK_STAYCONNECTED, myInfos.getStayconnected( ) );
548                 model.put( MARK_ARRONDISSEMENT, myInfos.getArrondissement( ) );
549                 model.put( MARK_SEND_ACCOUNT_VALIDATION, myInfos.getSendaccountvalidation( ) );
550                 model.put( MARK_INIT_FORM, bInitForm );
551 
552                 model.put( MARK_ACCOUNT_VERIFIED, MyInfosService.isAccountVerified( user ) );
553                 model.put( MARK_ARRONDISSEMENTS_LIST, MyInfosService.getArrondissements( ) );
554                 model.put( MARK_POSTAL_CODE_LIST, MyInfosService.getPostalCodes( ) );
555 
556                 model.put( MARK_USER_VALID, myInfos.getIsValid( ) );
557 
558                 model.put( MARK_COMPLETE_INFO, bCompleteInfos );
559 
560                 model.put( MARK_IS_FOR_POPUP, bIsForPopup );
561 
562                 model.put( MARK_CIVILITY, myInfos.getCivility( ) );
563                 model.put( MARK_GEO_JSON, myInfos.getGeojson( ) );
564                 model.put( MARK_POSTAL_CODE, myInfos.getPostalCode( ) );
565 
566                 IdentityDto idsIdentity = _identityService.getIdentityByConnectionId( user.getName( ), CAMPAGNE_BP_APP_CODE );
567                 Map<String, AttributeDto> idsAttributes = idsIdentity.getAttributes( );
568                 Map<String, AttributeDto> idsAttributeMap = new HashMap<String, AttributeDto>( );
569 
570                 for ( Entry<String, String> attribute : MAP_IDS_ATTRIBUTES.entrySet( ) )
571                 {
572                     AttributeDto attr = idsAttributes.get( attribute.getValue( ) );
573                     if ( attr == null )
574                     {
575                         attr = new AttributeDto( );
576                         attr.setCertified( false );
577                         attr.setKey( attribute.getValue( ) );
578                         attr.setValue( StringUtils.EMPTY );
579                     }
580                     else
581                         if ( IDS_KEY_USER_GENDER.equals( attr.getKey( ) ) )
582                         {
583                             attr.setValue( I18nService.getLocalizedString( MAP_CIVILITY.get( attr.getValue( ) ), request.getLocale( ) ) );
584                         }
585 
586                     idsAttributeMap.put( attribute.getKey( ), attr );
587                 }
588 
589                 AttributeDto attrAddr = idsAttributes.get( IDS_KEY_USER_ADDRESS );
590                 AttributeDto attrCity = idsAttributes.get( IDS_KEY_USER_ADDRESS_CITY );
591                 AttributeDto attrCp = idsAttributes.get( IDS_KEY_USER_ADDRESS_POSTAL_CODE );
592 
593                 if ( attrAddr == null )
594                 {
595                     attrAddr = new AttributeDto( );
596                     attrAddr.setCertified( false );
597                     attrAddr.setKey( IDS_KEY_USER_ADDRESS );
598                     attrAddr.setValue( StringUtils.EMPTY );
599                 }
600 
601                 if ( attrCp != null )
602                 {
603                     attrAddr.setValue( attrAddr.getValue( ) + COMMA + attrCp.getValue( ) );
604                     if ( attrCp.isCertified( ) )
605                     {
606                         attrAddr.setCertified( true );
607                     }
608                 }
609 
610                 if ( attrCity != null )
611                 {
612                     attrAddr.setValue( attrAddr.getValue( ) + COMMA + attrCity.getValue( ) );
613                     if ( attrCity.isCertified( ) )
614                     {
615                         attrAddr.setCertified( true );
616                     }
617                 }
618 
619                 idsAttributeMap.put( MARK_LABEL_IDS_ADDRESS, attrAddr );
620 
621                 model.put( MARK_IDS_ATTRIBUTES, idsAttributeMap );
622 
623                 model.put( SecurityTokenService.MARK_TOKEN, SecurityTokenService.getInstance( ).getToken( request, MyInfosXPage.TOKEN_DO_SAVE_MY_INFOS ) );
624 
625                 model.put( MARK_URL_MONCOMPTE, AppPropertiesService.getProperty( PROPERTY_URL_MONCOMPTE ) );
626 
627                 // Check if the submission/vote phases are open or not
628                 model.put( MARK_CAMPAGNE_SERVICE, CampagnesService.getInstance( ) );
629 
630                 ModelUtils.storeUnauthorizedAddress( model, myInfos.getAddress( ), user );
631 
632                 return getXPage( bIsForPopup ? TEMPLATE_MES_INFOS_POPUP : TEMPLATE_MES_INFOS, request.getLocale( ), model );
633             }
634         }
635 
636         throw new UserNotSignedException( );
637     }
638 
639     /**
640      * Handles the removal form of a parisconnectuser
641      * 
642      * @param request
643      *            The Http request
644      * @return the jsp URL to display the form to manage parisconnectusers
645      * @throws UserNotSignedException
646      *             if user not signed
647      * @throws SiteMessageException
648      *             Site message exception
649      */
650     @Action( ACTION_SAVE )
651     public XPage doSave( HttpServletRequest request ) throws UserNotSignedException, SiteMessageException
652     {
653         if ( SecurityService.isAuthenticationEnable( ) )
654         {
655 
656             boolean bError = false;
657             OpenamUser user = (OpenamUser) SecurityService.getInstance( ).getRegisteredUser( request );
658 
659             // ParisConnectUser user = getTestUser( );
660             if ( user != null )
661             {
662                 String voteValid = request.getParameter( MARK_VOTEVALID );
663                 MyInfosForm./../../fr/paris/lutece/plugins/campagnebp/business/MyInfosForm.html#MyInfosForm">MyInfosForm formSession = (MyInfosForm) request.getSession( ).getAttribute( MARK_FORM );
664                 if ( StringUtils.isNotEmpty( voteValid ) && voteValid.equals( MARK_TRUE ) && formSession != null )
665                 {
666                     updateMyinfos( user, formSession, request );
667                     request.getSession( ).removeAttribute( MARK_FORM );
668                     MyInfosListenerService.deleteVotes( request );
669 
670                     return redirectView( request, VIEW_MY_INFOS );
671                 }
672 
673                 boolean bCapchaVerified = true;
674                 MyInfosFormampagnebp/business/MyInfosForm.html#MyInfosForm">MyInfosForm form = new MyInfosForm( );
675                 MyAccountbp/business/MyAccount.html#MyAccount">MyAccount myAccountForm = new MyAccount( );
676 
677                 populate( form, request );
678                 populate( myAccountForm, request );
679 
680                 if ( isEnableCaptcha( ) )
681                 {
682 
683                     if ( !_captchaService.validate( request ) )
684                     {
685                         bCapchaVerified = false;
686                         addError( MESSAGE_CAPTCHA_NOT_VALIDATED, getLocale( request ) );
687                     }
688                 }
689 
690                 // !SecurityTokenService.getInstance().validate(request,
691                 // MyInfosXPage.TOKEN_DO_SAVE_MY_INFOS)
692 
693                 // Check constraints
694                 bError = !bCapchaVerified || !validateBean( form, getLocale( request ) );
695 
696                 if ( !CampagnesService.getInstance( ).isDuring( Constants.VOTE ) && StringUtils.isBlank( form.getNickname( ) ) )
697                 {
698                     bError = true;
699                     addError( MESSAGE_ERROR_NICKNAME_MISSING, getLocale( request ) );
700                 }
701 
702                 if ( !bError && !MyInfosService.setAdressValid( form ) )
703                 {
704                     bError = true;
705                     addError( MESSAGE_ERROR_ADRESS_GEOLOC_FORMAT, getLocale( request ) );
706                 }
707 
708                 if ( !bError && ( form.getNickname( ) != null
709                         && ( MyInfosService.loadUserNickname( user.getName( ) ) != null
710                                 && !form.getNickname( ).equals( MyInfosService.loadUserNickname( user.getName( ) ) )
711                                 || MyInfosService.loadUserNickname( user.getName( ) ) == null )
712                         && MyInfosService.isNicknameAlreadyExist( form.getNickname( ) ) ) )
713                 {
714                     bError = true;
715                     addError( MESSAGE_ERROR_NICKNAME_ALREADY_EXIST, getLocale( request ) );
716                 }
717 
718                 if ( !bError )
719                 {
720 
721                     if ( MyInfosService.mustSendAccountValidationMail( user.getName( ), form ) )
722                     {
723                         // Add message if a mail have been send to the user
724                         if ( MyInfosService.sendAccountValidationMail( request, getLocale( request ), user.getName( ) ) )
725                         {
726                             addInfo( INFO_VALIDATION_MAIL_SEND, getLocale( request ) );
727 
728                         }
729                         else
730                         {
731                             bError = true;
732                             addError( ERROR_DURING_VALIDATION_MAIL_SEND, getLocale( request ) );
733 
734                         }
735 
736                     }
737 
738                 }
739 
740                 if ( !bError )
741                 {
742                     // update avatar
743                     CampagneAvatarService.updateAvatar( request, user.getName( ) );
744                     MyInfosService.saveUserEmail( user.getName( ), user.getEmail( ) );
745 
746                     if ( !StringUtils.isEmpty( myAccountForm.getLogin( ) ) )
747                     {
748                         bError = ( !StringUtils.isEmpty( myAccountForm.getPassword( ) ) && !validateBean( myAccountForm, getLocale( request ) ) );
749 
750                         if ( !bError && !myAccountForm.getPassword( ).equals( myAccountForm.getConfirmationPassword( ) ) )
751                         {
752                             // bError = true;
753                             // addError(MESSAGE_ERROR_CONFIRMATION_PASSWORD, getLocale(request));
754 
755                         }
756                         else
757                         {
758 
759                             if ( !StringUtils.isEmpty( myAccountForm.getLogin( ) ) )
760                             {
761                                 if ( !myAccountForm.getLogin( ).equals( user.getEmail( ) ) )
762                                 {
763                                     // Add message if a mail have been send to the user
764                                     if ( MyInfosService.sendAccountValidationMail( request, getLocale( request ), user.getName( ) ) )
765                                     {
766                                         addInfo( INFO_VALIDATION_MAIL_SEND, getLocale( request ) );
767 
768                                     }
769                                     else
770                                     {
771                                         bError = true;
772                                         addError( ERROR_DURING_VALIDATION_MAIL_SEND, getLocale( request ) );
773 
774                                     }
775                                     // update user info
776                                     user.setUserInfo( LuteceUser.HOME_INFO_ONLINE_EMAIL, myAccountForm.getLogin( ) );
777                                     user.setUserInfo( MyInfosService.LUTECE_USER_KEY_VERIFIED, "false" );
778                                 }
779                             }
780                             // reint account form
781                             myAccountForm = null;
782                         }
783                     }
784                 }
785 
786                 if ( !bError && MARK_TRUE.equals( request.getParameter( MARK_SAVE_PERSONAL ) ) )
787                 {
788                     // if no error and user say yes, save data
789                     savePersonalData( user, form );
790                 }
791 
792                 if ( bError )
793                 {
794                     _form = form;
795                     _accountForm = myAccountForm;
796                     String strReferer = request.getHeader( PARAMETER_REFERER );
797 
798                     if ( StringUtils.contains( strReferer, "view=" + VIEW_MY_VOTES ) )
799                     {
800                         redirectView( request, VIEW_MY_VOTES );
801                     }
802 
803                     Map<String, String> mapParameters = new HashMap<String, String>( );
804 
805                     return redirect( request, VIEW_MY_INFOS, mapParameters );
806                 }
807                 String strUserOldArrond = MyInfosService.loadUserInfos( user ).getArrondissement( );
808 
809                 if ( !strUserOldArrond.equals( request.getParameter( MARK_ARRONDISSEMENT ) ) )
810                 {
811                     int nRes = MyInfosListenerService.canChangeArrond( user );
812                     if ( nRes == 2 )
813                     {
814                         SiteMessageService.setMessage( request, PROPERTY_ERROR_END_PHASE, SiteMessage.TYPE_ERROR );
815                     }
816                     else
817                         if ( nRes == 1 )
818                         {
819                             Map<String, Object> requestParameters = new HashMap<String, Object>( );
820                             requestParameters.put( MARK_PAGE, PAGE_MY_INFOS );
821                             requestParameters.put( MVCUtils.PARAMETER_ACTION, ACTION_SAVE );
822                             requestParameters.put( MARK_EXTENDABLERESOURCETYPE, MARK_TYPE_DOCUMENT );
823                             request.getSession( ).setAttribute( MARK_FORM, form );
824                             requestParameters.put( MARK_VOTEVALID, MARK_TRUE );
825                             SiteMessageService.setMessage( request, PROPERTY_CONFIRM_MODIFY_ARRAND_WITH_VOTES_DELETING, SiteMessage.TYPE_CONFIRMATION,
826                                     JSP_PORTAL, requestParameters );
827 
828                         }
829                         else
830                             if ( nRes == 0 )
831                             {
832                                 Map<String, Object> requestParameters = new HashMap<String, Object>( );
833                                 requestParameters.put( MARK_PAGE, PAGE_MY_INFOS );
834                                 requestParameters.put( MVCUtils.PARAMETER_ACTION, ACTION_SAVE );
835                                 requestParameters.put( MARK_EXTENDABLERESOURCETYPE, MARK_TYPE_DOCUMENT );
836                                 request.getSession( ).setAttribute( MARK_FORM, form );
837                                 requestParameters.put( MARK_VOTEVALID, MARK_TRUE );
838                                 SiteMessageService.setMessage( request, PROPERTY_CONFIRM_MODIFY_ARRAND, SiteMessage.TYPE_CONFIRMATION, JSP_PORTAL,
839                                         requestParameters );
840 
841                             }
842                             else
843                                 if ( nRes == -1 )
844                                 {
845                                     SiteMessageService.setMessage( request, PROPERTY_ERROR_MODIFY_ARRAND, SiteMessage.TYPE_ERROR );
846                                 }
847 
848                 }
849 
850                 updateMyinfos( user, form, request );
851 
852                 String strReferer = request.getHeader( PARAMETER_REFERER );
853 
854                 if ( StringUtils.contains( strReferer, "view=" + VIEW_MY_VOTES ) )
855                 {
856                     redirectView( request, VIEW_MY_VOTES );
857                 }
858 
859                 return redirectView( request, VIEW_MY_INFOS );
860 
861             }
862         }
863 
864         throw new UserNotSignedException( );
865     }
866 
867     private void updateMyinfos( OpenamUser user, MyInfosForm form, HttpServletRequest request )
868     {
869         MyInfosService.saveUserInfos( user.getName( ), user.getSubjectId( ), form );
870         MyInfosService.saveUserEmail( user.getName( ), user.getEmail( ) );
871 
872         // update user info into luteceuser
873         user.setUserInfo( LuteceUser.NAME_FAMILY, form.getFirstname( ) );
874         user.setUserInfo( LuteceUser.NAME_GIVEN, form.getLastname( ) );
875         user.setUserInfo( LuteceUser.HOME_INFO_POSTAL_STREET, form.getAddress( ) );
876         user.setUserInfo( LuteceUser.BDATE, form.getBirthdate( ) );
877 
878         addInfo( INFO_SAVED, getLocale( request ) );
879 
880     }
881 
882     /**
883      * Check if the current user has a valid account
884      * 
885      * @param request
886      *            The request
887      * @return A JSON string containing true or false in the field result corresponding to the validity of the user account
888      * @throws SiteMessageException
889      *             Site message exception
890      */
891     public String isUserValid( HttpServletRequest request ) throws SiteMessageException
892     {
893         AbstractJsonResponse jsonResponse = null;
894 
895         boolean bIsValid;
896         boolean bIsAccountVerified;
897         LuteceUser user = null;
898 
899         if ( SecurityService.isAuthenticationEnable( ) )
900         {
901             user = SecurityService.getInstance( ).getRegisteredUser( request );
902             if ( user != null )
903             {
904                 {
905                     modifyUserEmail( user );
906 
907                     bIsValid = MyInfosService.loadUserInfos( user ).getIsValid( );
908                     bIsAccountVerified = MyInfosService.isAccountVerified( user );
909 
910                     if ( !bIsAccountVerified )
911                     {
912 
913                         jsonResponse = new ErrorJsonResponse( JSON_ERROR_CODE_ACCOUNT_NOT_VERIFIED );
914                     }
915                     else
916                         if ( !bIsValid )
917                         {
918                             jsonResponse = new JsonResponse( bIsValid && bIsAccountVerified );
919                         }
920                         else
921                         {
922                             jsonResponse = new JsonResponse( bIsAccountVerified );
923                         }
924                 }
925             }
926         }
927 
928         if ( user == null )
929         {
930             jsonResponse = new ErrorJsonResponse( JSON_ERROR_CODE_USER_NOT_SIGNED );
931         }
932 
933         return JsonUtil.buildJsonResponse( jsonResponse );
934     }
935 
936     /**
937      * Check if the current user has a valid account
938      * 
939      * @param request
940      *            The request
941      * @return A JSON string containing true or false in the field result corresponding to the validity of the user account
942      */
943     public String doSendValidationMail( HttpServletRequest request )
944     {
945         AbstractJsonResponse jsonResponse = null;
946 
947         LuteceUser user = null;
948 
949         if ( SecurityService.isAuthenticationEnable( ) )
950         {
951             user = SecurityService.getInstance( ).getRegisteredUser( request );
952 
953             if ( user != null )
954             {
955                 {
956                     boolean bSend = MyInfosService.sendAccountValidationMail( request, getLocale( request ), user.getName( ) );
957 
958                     jsonResponse = new JsonResponse( bSend );
959                 }
960             }
961         }
962 
963         if ( user == null )
964         {
965             jsonResponse = new ErrorJsonResponse( JSON_ERROR_CODE_USER_NOT_SIGNED );
966         }
967 
968         return JsonUtil.buildJsonResponse( jsonResponse );
969     }
970 
971     /**
972      * Get the URL to manage infos of the current user
973      * 
974      * @param strIdResource
975      *            The id of the resource
976      * @param strResourceType
977      *            The resource type
978      * @param dVoteValue
979      *            The value of the vote
980      * @return The URL to manage infos of the current user
981      */
982     public static String getUrlCompleteMyInfos( String strIdResource, String strResourceType, double dVoteValue )
983     {
984         UrlItem urlItem = new UrlItem( AppPathService.getPortalUrl( ) );
985         urlItem.addParameter( MVCUtils.PARAMETER_PAGE, PAGE_MY_INFOS );
986         urlItem.addParameter( MVCUtils.PARAMETER_VIEW, VIEW_MY_INFOS );
987         urlItem.addParameter( PARAMETER_COMPLETE_INFOS, Boolean.TRUE.toString( ) );
988 
989         return urlItem.getUrl( );
990     }
991 
992     /**
993      * Get the URL to manage infos of the current user
994      * 
995      * @return The URL to manage infos of the current user
996      */
997     public static String getUrlMyInfos( )
998     {
999         UrlItem urlItem = new UrlItem( AppPathService.getPortalUrl( ) );
1000         urlItem.addParameter( MVCUtils.PARAMETER_PAGE, PAGE_MY_INFOS );
1001         urlItem.addParameter( MVCUtils.PARAMETER_VIEW, VIEW_MY_INFOS );
1002         urlItem.addParameter( PARAMETER_COMPLETE_INFOS, Boolean.TRUE.toString( ) );
1003         return urlItem.getUrl( );
1004     }
1005 
1006     /**
1007      * Get the HTML content of the popup of the infos of the user
1008      * 
1009      * @param request
1010      *            The request
1011      * @return The HTML content
1012      */
1013     public String getMyInfosPanelForAjax( HttpServletRequest request )
1014     {
1015         try
1016         {
1017             if ( _form == null )
1018             {
1019                 addInfo( MESSAGE_INFO_USER_MUST_COMPLETE_PROFILE, request.getLocale( ) );
1020             }
1021 
1022             return getMyInfos( request, true ).getContent( );
1023         }
1024         catch( UserNotSignedException e )
1025         {
1026             return StringUtils.EMPTY;
1027         }
1028     }
1029 
1030     /**
1031      * Checked if the user have already set the info
1032      * 
1033      * @param request
1034      *            The request
1035      * @return The HTML content
1036      */
1037     public String getCheckedMyInfosAfterLogin( HttpServletRequest request )
1038     {
1039         Map<String, Object> model = getModel( );
1040         model.put( Markers.BASE_URL, AppPathService.getBaseUrl( request ) );
1041         model.put( MARK_THEME, ThemesService.getGlobalThemeObject( ) );
1042         model.put( Markers.PAGE_TITLE, getDefaultPageTitle( request.getLocale( ) ) );
1043         return getXPage( TEMPLATE_CHECKED_MY_INFOS_AFTER_LOGIN, request.getLocale( ), model ).getContent( );
1044     }
1045 
1046     /**
1047      * Do save infos entered by the user. This method should only be called when using the AJAX mode
1048      * 
1049      * @param request
1050      *            The request
1051      */
1052     public void doSaveForAjax( HttpServletRequest request )
1053     {
1054         boolean bCapchaVerified = true;
1055         boolean bError = false;
1056         if ( SecurityService.isAuthenticationEnable( ) )
1057         {
1058             OpenamUser user = (OpenamUser) SecurityService.getInstance( ).getRegisteredUser( request );
1059 
1060             if ( user != null )
1061             {
1062                 MyInfosFormampagnebp/business/MyInfosForm.html#MyInfosForm">MyInfosForm form = new MyInfosForm( );
1063                 populate( form, request );
1064 
1065                 if ( isEnableCaptcha( ) )
1066                 {
1067 
1068                     if ( !_captchaService.validate( request ) )
1069                     {
1070                         bCapchaVerified = false;
1071                         addError( MESSAGE_CAPTCHA_NOT_VALIDATED, getLocale( request ) );
1072                     }
1073                 }
1074 
1075                 // Check constraints
1076                 bError = !bCapchaVerified || !validateBean( form, getLocale( request ) );
1077 
1078                 if ( !CampagnesService.getInstance( ).isDuring( Constants.VOTE ) && StringUtils.isBlank( form.getNickname( ) ) )
1079                 {
1080                     bError = true;
1081                     addError( MESSAGE_ERROR_NICKNAME_MISSING, getLocale( request ) );
1082                 }
1083 
1084                 if ( !bError && !MyInfosService.setAdressValid( form ) )
1085                 {
1086                     bError = true;
1087                     addError( MESSAGE_ERROR_ADRESS_GEOLOC_FORMAT, getLocale( request ) );
1088                 }
1089 
1090                 if ( !bError && ( form.getNickname( ) != null
1091                         && ( MyInfosService.loadUserNickname( user.getName( ) ) != null
1092                                 && !form.getNickname( ).equals( MyInfosService.loadUserNickname( user.getName( ) ) )
1093                                 || MyInfosService.loadUserNickname( user.getName( ) ) == null )
1094                         && MyInfosService.isNicknameAlreadyExist( form.getNickname( ) ) ) )
1095                 {
1096                     bError = true;
1097                     addError( MESSAGE_ERROR_NICKNAME_ALREADY_EXIST, getLocale( request ) );
1098                 }
1099 
1100                 if ( !bError )
1101                 {
1102                     if ( MyInfosService.mustSendAccountValidationMail( user.getName( ), form ) )
1103                     {
1104                         // Add message if a mail have been send to the user
1105                         if ( MyInfosService.sendAccountValidationMail( request, getLocale( request ), user.getName( ) ) )
1106                         {
1107                             addInfo( INFO_VALIDATION_MAIL_SEND, getLocale( request ) );
1108 
1109                         }
1110                         else
1111                         {
1112                             bError = true;
1113                             addError( ERROR_DURING_VALIDATION_MAIL_SEND, getLocale( request ) );
1114 
1115                         }
1116 
1117                     }
1118                     // update avatar
1119                     CampagneAvatarService.updateAvatar( request, user.getName( ) );
1120                 }
1121 
1122                 // || !SecurityTokenService.getInstance().validate(request,
1123                 // MyInfosXPage.TOKEN_DO_SAVE_MY_INFOS)
1124                 // Check constraints
1125                 if ( bError )
1126                 {
1127                     _form = form;
1128 
1129                     return;
1130                 }
1131 
1132                 MyInfosService.saveUserInfos( user.getName( ), user.getSubjectId( ), form );
1133                 MyInfosService.saveUserEmail( user.getName( ), user.getEmail( ) );
1134 
1135                 // update user info into luteceuser
1136                 user.setUserInfo( LuteceUser.NAME_FAMILY, form.getFirstname( ) );
1137                 user.setUserInfo( LuteceUser.NAME_GIVEN, form.getLastname( ) );
1138                 user.setUserInfo( LuteceUser.HOME_INFO_POSTAL_STREET, form.getAddress( ) );
1139                 user.setUserInfo( LuteceUser.BDATE, form.getBirthdate( ) );
1140                 user.setUserInfo( LuteceUser.HOME_INFO_POSTAL_POSTALCODE, form.getPostalCode( ) );
1141 
1142                 // if no error and user say yes, save data
1143                 if ( MARK_TRUE.equals( request.getParameter( MARK_SAVE_PERSONAL ) ) )
1144                 {
1145                     savePersonalData( user, form );
1146                 }
1147 
1148             }
1149         }
1150     }
1151 
1152     /**
1153      * DoSend Avis using the AJAX mode
1154      * 
1155      * @param request
1156      *            The request
1157      * @return Data
1158      */
1159     public String doSendAvis( HttpServletRequest request )
1160     {
1161         String strMail = request.getParameter( PARAMETER_MAIL );
1162         String strMessage = request.getParameter( PARAMETER_MESSAGE );
1163         String strBackUrl = DatastoreService.getDataValue( KEY_PARIS_CONNECT_SEND_AVIS_BACK_URL, "https://budgetparticipatif.paris.fr/bp/" );
1164         AbstractJsonResponse jsonResponse = null;
1165 
1166         // if(SecurityTokenService.getInstance().validate(request,
1167         // TOKEN_DO_SEND_AVIS) )
1168         //
1169         // {
1170         //
1171         // AppLogService.error( "doSubscribeAlert: Token not validated" );
1172         //
1173         // jsonResponse=new
1174         // BudgetErrorJsonResponse(JSON_ERROR_DURING_SEND_AVIS,SecurityTokenService.getInstance().getToken(request,
1175         // TOKEN_DO_SEND_AVIS));
1176 
1177         // }else
1178         //
1179         //
1180 
1181         if ( StringUtils.isNotEmpty( strMessage ) && ParisConnectService.getInstance( ).sendMessageEmp( strMail, strMessage, strBackUrl, null ) )
1182         {
1183             jsonResponse = new JsonResponse(
1184                     new CampagneResponse( Boolean.TRUE, SecurityTokenService.getInstance( ).getToken( request, TOKEN_DO_SEND_AVIS ) ) );
1185 
1186         }
1187         else
1188         {
1189             jsonResponse = new CampagneErrorJsonResponse( JSON_ERROR_DURING_SEND_AVIS,
1190                     SecurityTokenService.getInstance( ).getToken( request, TOKEN_DO_SEND_AVIS ) );
1191         }
1192 
1193         return JsonUtil.buildJsonResponse( jsonResponse );
1194     }
1195 
1196     /**
1197      * 
1198      * @return true if the captcha is enable
1199      */
1200     private boolean isEnableCaptcha( )
1201     {
1202         return PluginService.isPluginEnable( JCAPTCHA_PLUGIN ) && new Boolean( DatastoreService.getDataValue( KEY_ENABLE_CAPTCHA_USER_INFORMATIONS, "false" ) );
1203     }
1204 
1205     /**
1206      * Modify the user email if it is different from the stored one
1207      * 
1208      * @param user
1209      *            the user
1210      */
1211     private void modifyUserEmail( LuteceUser user )
1212     {
1213         String strUserMailFromLocalMyInfos = MyInfosService.getUserEmail( user.getName( ) );
1214         String strUserMailFromConnectedUserInfos = user.getEmail( );
1215 
1216         if ( strUserMailFromConnectedUserInfos != null )
1217         {
1218             if ( strUserMailFromLocalMyInfos == null || !strUserMailFromLocalMyInfos.equals( strUserMailFromConnectedUserInfos ) )
1219             {
1220                 MyInfosService.saveUserEmail( user.getName( ), strUserMailFromConnectedUserInfos );
1221             }
1222         }
1223     }
1224 
1225     /**
1226      * Populates the specified {@code MyAccount} object with the data of the specified user
1227      * 
1228      * @param myAccountForm
1229      *            the {@code MyAccount} object
1230      * @param user
1231      *            the user
1232      */
1233     private void populate( MyAccount myAccountForm, LuteceUser user )
1234     {
1235         if ( StringUtils.isEmpty( myAccountForm.getLogin( ) ) )
1236         {
1237             myAccountForm.setLogin( user.getEmail( ) );
1238         }
1239     }
1240 
1241     /**
1242      * save personal data to identitystore
1243      * 
1244      * @param user
1245      */
1246     private void savePersonalData( OpenamUser user, MyInfosForm infoForm )
1247     {
1248         IdentityDto identityDto = new IdentityDto( );
1249         identityDto.setConnectionId( user.getName( ) );
1250         Map<String, AttributeDto> mapAttributes = new HashMap<String, AttributeDto>( );
1251         AttributeDto attribute;
1252 
1253         IdentityDto idsIdentity = _identityService.getIdentityByConnectionId( user.getName( ), CAMPAGNE_BP_APP_CODE );
1254         Map<String, AttributeDto> idsAttributes = idsIdentity.getAttributes( );
1255 
1256         if ( StringUtils.isNotBlank( infoForm.getCivility( ) )
1257                 && ( idsAttributes.get( IDS_KEY_USER_GENDER ) == null || !idsAttributes.get( IDS_KEY_USER_GENDER ).isCertified( ) ) )
1258         {
1259             attribute = new AttributeDto( );
1260             attribute.setKey( IDS_KEY_USER_GENDER );
1261             attribute.setValue( Civility.fromLabelCode( infoForm.getCivility( ).trim( ) ).getNumericCode( ) );
1262             mapAttributes.put( attribute.getKey( ), attribute );
1263         }
1264 
1265         if ( StringUtils.isNotBlank( infoForm.getFirstname( ) )
1266                 && ( idsAttributes.get( IDS_KEY_USER_FIRST_NAME ) == null || !idsAttributes.get( IDS_KEY_USER_FIRST_NAME ).isCertified( ) ) )
1267         {
1268             attribute = new AttributeDto( );
1269             attribute.setKey( IDS_KEY_USER_FIRST_NAME );
1270             attribute.setValue( infoForm.getFirstname( ).trim( ) );
1271             mapAttributes.put( attribute.getKey( ), attribute );
1272         }
1273 
1274         if ( StringUtils.isNotBlank( infoForm.getLastname( ) )
1275                 && ( idsAttributes.get( IDS_KEY_USER_LAST_NAME ) == null || !idsAttributes.get( IDS_KEY_USER_LAST_NAME ).isCertified( ) ) )
1276         {
1277             attribute = new AttributeDto( );
1278             attribute.setKey( IDS_KEY_USER_LAST_NAME );
1279             attribute.setValue( infoForm.getLastname( ).trim( ) );
1280             mapAttributes.put( attribute.getKey( ), attribute );
1281         }
1282 
1283         if ( StringUtils.isNotBlank( infoForm.getBirthdate( ) )
1284                 && ( idsAttributes.get( IDS_KEY_USER_BIRTHDAY ) == null || !idsAttributes.get( IDS_KEY_USER_BIRTHDAY ).isCertified( ) ) )
1285         {
1286             attribute = new AttributeDto( );
1287             attribute.setKey( IDS_KEY_USER_BIRTHDAY );
1288             attribute.setValue( infoForm.getBirthdate( ).trim( ) );
1289             mapAttributes.put( attribute.getKey( ), attribute );
1290         }
1291 
1292         if ( StringUtils.isNotBlank( infoForm.getAddress( ) )
1293                 && ( idsAttributes.get( IDS_KEY_USER_ADDRESS ) == null || !idsAttributes.get( IDS_KEY_USER_ADDRESS ).isCertified( ) )
1294                 && ( idsAttributes.get( IDS_KEY_USER_ADDRESS_POSTAL_CODE ) == null || !idsAttributes.get( IDS_KEY_USER_ADDRESS_POSTAL_CODE ).isCertified( ) )
1295                 && ( idsAttributes.get( IDS_KEY_USER_ADDRESS_CITY ) == null || !idsAttributes.get( IDS_KEY_USER_ADDRESS_CITY ).isCertified( ) ) )
1296         {
1297             Matcher matcher = _patternAddress.matcher( infoForm.getAddress( ).trim( ) );
1298             if ( !matcher.find( ) )
1299             {
1300                 AppLogService.error( "'" + infoForm.getAddress( ).trim( ) + "' doesn't match address pattern '" + REGEX_ADDRESS + "'", null );
1301                 return;
1302             }
1303             if ( matcher.groupCount( ) != 3 )
1304             {
1305                 AppLogService.error( "'" + infoForm.getAddress( ).trim( ) + "' doesn't return 3 groups with address pattern '" + REGEX_ADDRESS + "'", null );
1306                 return;
1307             }
1308 
1309             attribute = new AttributeDto( );
1310             attribute.setKey( IDS_KEY_USER_ADDRESS );
1311             attribute.setValue( matcher.group( 1 ).trim( ) );
1312             mapAttributes.put( attribute.getKey( ), attribute );
1313 
1314             if ( idsAttributes.get( IDS_KEY_USER_ADDRESS_DETAIL ) == null || !idsAttributes.get( IDS_KEY_USER_ADDRESS_DETAIL ).isCertified( ) )
1315             {
1316                 attribute = new AttributeDto( );
1317                 attribute.setKey( IDS_KEY_USER_ADDRESS_DETAIL );
1318                 attribute.setValue( StringUtils.EMPTY );
1319                 mapAttributes.put( attribute.getKey( ), attribute );
1320             }
1321 
1322             if ( idsAttributes.get( IDS_KEY_USER_ADDRESS_POSTAL_CODE ) == null || !idsAttributes.get( IDS_KEY_USER_ADDRESS_POSTAL_CODE ).isCertified( ) )
1323             {
1324                 attribute = new AttributeDto( );
1325                 attribute.setKey( IDS_KEY_USER_ADDRESS_POSTAL_CODE );
1326                 attribute.setValue( matcher.group( 2 ).trim( ) );
1327                 mapAttributes.put( attribute.getKey( ), attribute );
1328             }
1329 
1330             if ( idsAttributes.get( IDS_KEY_USER_ADDRESS_CITY ) == null || !idsAttributes.get( IDS_KEY_USER_ADDRESS_CITY ).isCertified( ) )
1331             {
1332                 attribute = new AttributeDto( );
1333                 attribute.setKey( IDS_KEY_USER_ADDRESS_CITY );
1334                 attribute.setValue( matcher.group( 3 ).trim( ) );
1335                 mapAttributes.put( attribute.getKey( ), attribute );
1336             }
1337         }
1338 
1339         if ( mapAttributes.size( ) > 0 )
1340         {
1341             identityDto.setAttributes( mapAttributes );
1342 
1343             AuthorDto author = new AuthorDto( );
1344             author.setApplicationCode( CAMPAGNE_BP_APP_CODE );
1345             author.setType( AuthorType.TYPE_USER_OWNER.getTypeValue( ) );
1346 
1347             IdentityChangeDto identityChangeDto = new IdentityChangeDto( );
1348             identityChangeDto.setIdentity( identityDto );
1349             identityChangeDto.setAuthor( author );
1350 
1351             try
1352             {
1353                 _identityService.updateIdentity( identityChangeDto, null );
1354             }
1355             catch( Exception e )
1356             {
1357                 // do nothing, just log
1358                 AppLogService.error( "Error occur while save data to identityStore", e );
1359             }
1360         }
1361     }
1362 }