View Javadoc
1   /*
2    * Copyright (c) 2002-2014, Mairie de 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.crm.web;
35  
36  import java.text.SimpleDateFormat;
37  import java.util.ArrayList;
38  import java.util.Date;
39  import java.util.HashMap;
40  import java.util.List;
41  import java.util.Map;
42  
43  import javax.servlet.http.HttpServletRequest;
44  
45  import org.apache.commons.lang3.StringUtils;
46  
47  import fr.paris.lutece.plugins.crm.business.demand.Demand;
48  import fr.paris.lutece.plugins.crm.business.demand.DemandFilter;
49  import fr.paris.lutece.plugins.crm.business.demand.DemandStatusCRM;
50  import fr.paris.lutece.plugins.crm.business.demand.DemandType;
51  import fr.paris.lutece.plugins.crm.business.demand.PaginationFilterSortManager;
52  import fr.paris.lutece.plugins.crm.business.notification.Notification;
53  import fr.paris.lutece.plugins.crm.business.notification.NotificationFilter;
54  import fr.paris.lutece.plugins.crm.business.user.CRMUser;
55  import fr.paris.lutece.plugins.crm.service.CRMPlugin;
56  import fr.paris.lutece.plugins.crm.service.category.CategoryService;
57  import fr.paris.lutece.plugins.crm.service.demand.DemandService;
58  import fr.paris.lutece.plugins.crm.service.demand.DemandStatusCRMService;
59  import fr.paris.lutece.plugins.crm.service.demand.DemandTypeService;
60  import fr.paris.lutece.plugins.crm.service.listener.CRMUserModificationListenerService;
61  import fr.paris.lutece.plugins.crm.service.notification.NotificationService;
62  import fr.paris.lutece.plugins.crm.service.parameters.AdvancedParametersService;
63  import fr.paris.lutece.plugins.crm.service.signrequest.CRMRequestAuthenticatorService;
64  import fr.paris.lutece.plugins.crm.service.user.CRMUserAttributesService;
65  import fr.paris.lutece.plugins.crm.service.user.CRMUserService;
66  import fr.paris.lutece.plugins.crm.util.ListUtils;
67  import fr.paris.lutece.plugins.crm.util.constants.CRMConstants;
68  import fr.paris.lutece.portal.service.i18n.I18nService;
69  import fr.paris.lutece.portal.service.message.SiteMessage;
70  import fr.paris.lutece.portal.service.message.SiteMessageException;
71  import fr.paris.lutece.portal.service.message.SiteMessageService;
72  import fr.paris.lutece.portal.service.page.PageNotFoundException;
73  import fr.paris.lutece.portal.service.plugin.Plugin;
74  import fr.paris.lutece.portal.service.security.LuteceUser;
75  import fr.paris.lutece.portal.service.security.SecurityService;
76  import fr.paris.lutece.portal.service.security.UserNotSignedException;
77  import fr.paris.lutece.portal.service.template.AppTemplateService;
78  import fr.paris.lutece.portal.service.util.AppPathService;
79  import fr.paris.lutece.portal.service.util.AppPropertiesService;
80  import fr.paris.lutece.portal.web.PortalJspBean;
81  import fr.paris.lutece.portal.web.xpages.XPage;
82  import fr.paris.lutece.portal.web.xpages.XPageApplication;
83  import fr.paris.lutece.util.html.HtmlTemplate;
84  import fr.paris.lutece.util.html.IPaginator;
85  import fr.paris.lutece.util.string.StringUtil;
86  import fr.paris.lutece.util.url.UrlItem;
87  
88  /**
89   *
90   * CRMApp
91   *
92   */
93  public class CRMApp implements XPageApplication
94  {
95      // JSP
96      private static final String JSP_PORTAL = "Portal.jsp";
97      private static final String JSP_SITE = "jsp/site/";
98  
99      // TEMPLATES
100     private static final String TEMPLATE_CRM_HOME_PAGE = "skin/plugins/crm/crm.html";
101     private static final String TEMPLATE_MANAGE_NOTIFICATIONS = "skin/plugins/crm/manage_notifications.html";
102     private static final String TEMPLATE_VIEW_NOTIFICATION = "skin/plugins/crm/view_notification.html";
103     private static final String TEMPLATE_MODIFY_CRM_USER = "skin/plugins/crm/modify_crm_user.html";
104 
105     // VARIABLES
106     private DemandTypeService _demandTypeService = DemandTypeService.getService( );
107     private DemandService _demandService = DemandService.getService( );
108     private CategoryService _categoryService = CategoryService.getService( );
109     private NotificationService _notificationService = NotificationService.getService( );
110     private DemandStatusCRMService _statusCRMService = DemandStatusCRMService.getService( );
111     private CRMUserService _crmUserService = CRMUserService.getService( );
112     private CRMUserAttributesService _crmUserAttributesService = CRMUserAttributesService.getService( );
113     private AdvancedParametersService _advancedParametersService = AdvancedParametersService.getService( );
114     // PROPERTIE
115     private static final String CRM_WEBB_APP_CODE_PROPERTY = "crm.webapp.code";
116 
117     /**
118      * Get the XPage of the plugin CRM
119      * 
120      * @param request
121      *            {@link HttpServletRequest}
122      * @param nMode
123      *            the mode
124      * @param plugin
125      *            {@link Plugin}
126      * @return a {@link XPage}
127      * @throws UserNotSignedException
128      *             exception when user is not connected
129      * @throws SiteMessageException
130      *             site message when displaying messages
131      */
132     @Override
133     public XPage getPage( HttpServletRequest request, int nMode, Plugin plugin ) throws UserNotSignedException, SiteMessageException
134     {
135         XPage page = null;
136         LuteceUser user = null;
137 
138         try
139         {
140             user = getUser( request );
141         }
142         catch( UserNotSignedException e )
143         {
144 
145         }
146 
147         createOrUpdateCRMAccount( user );
148 
149         String strAction = request.getParameter( CRMConstants.PARAMETER_ACTION );
150 
151         if ( StringUtils.isNotBlank( strAction ) )
152         {
153             if ( user == null )
154             {
155                 throw new UserNotSignedException( );
156             }
157 
158             if ( CRMConstants.ACTION_MANAGE_NOTIFICATIONS.equals( strAction ) )
159             {
160                 page = getManageNotificationsPage( request, user );
161             }
162             else
163                 if ( CRMConstants.ACTION_VIEW_NOTIFICATION.equals( strAction ) )
164                 {
165                     page = getViewNotificationPage( request, user );
166                 }
167                 else
168                     if ( CRMConstants.ACTION_REMOVE_DEMAND.equals( strAction ) )
169                     {
170                         getDemandRemovingConfirmationMessage( request, user );
171                     }
172                     else
173                         if ( CRMConstants.ACTION_MODIFY_CRM_USER.equals( strAction ) )
174                         {
175                             page = getModifyCRMUserPage( request, user );
176                         }
177                         else
178                             if ( CRMConstants.ACTION_DO_MODIFY_CRM_USER.equals( strAction ) )
179                             {
180                                 doModifyCRMUser( request, user );
181                                 page = getModifyCRMUserPage( request, user );
182                             }
183         }
184 
185         if ( page == null )
186         {
187             page = getCRMHomePage( request, user );
188         }
189 
190         return page;
191     }
192 
193     /**
194      * Get the home page
195      * 
196      * @param request
197      *            {@link HttpServletRequest}
198      * @param user
199      *            the {@link LuteceUser}
200      * @return a {@link XPage}
201      * @throws SiteMessageException
202      */
203     private XPage getCRMHomePage( HttpServletRequest request, LuteceUser user ) throws SiteMessageException
204     {
205         XPage page = null;
206         CRMUser crmUser = user != null ? _crmUserService.findByUserGuid( user.getName( ) ) : null;
207         page = new XPage( );
208         Map<String, Object> model = new HashMap<String, Object>( );
209         if ( crmUser != null )
210         {
211             // research by filter
212             DemandFilterusiness/demand/DemandFilter.html#DemandFilter">DemandFilter dFilter = new DemandFilter( );
213             dFilter.setIdCRMUser( crmUser.getIdCRMUser( ) );
214 
215             PaginationFilterSortManagerManager.html#PaginationFilterSortManager">PaginationFilterSortManager paginationFilterSortManager = new PaginationFilterSortManager( request );
216 
217             String strSession = (String) ( request.getParameter( CRMConstants.PARAMETER_SESSION ) );
218 
219             if ( StringUtils.isBlank( strSession ) )
220             {
221                 paginationFilterSortManager.cleanSession( );
222             }
223 
224             String strIdStatusToSort = (String) ( request.getParameter( CRMConstants.PARAMETER_ID_STATUS ) );
225             String strSortField = (String) ( request.getParameter( CRMConstants.PARAMETER_SORT_ATTRIBUTE ) );
226             String strSortOrder = (String) ( request.getParameter( CRMConstants.PARAMETER_SORT_ORDER ) );
227 
228             int nIdStatusToSort = -1;
229 
230             if ( StringUtils.isNotEmpty( strIdStatusToSort ) )
231             {
232                 nIdStatusToSort = Integer.parseInt( strIdStatusToSort );
233             }
234 
235             if ( StringUtils.isNotEmpty( strSortField ) && StringUtils.isNotEmpty( strSortOrder ) )
236             {
237                 paginationFilterSortManager.storeSort( nIdStatusToSort, strSortField, Boolean.parseBoolean( strSortOrder ) );
238             }
239 
240             String strModificationDate = request.getParameter( CRMConstants.PARAMETER_MODIFICATIONDATE );
241             String strDemandType = request.getParameter( CRMConstants.PARAMETER_DEMANDTYPE );
242             String strNotification = request.getParameter( CRMConstants.PARAMETER_NOTIFICATION );
243 
244             if ( StringUtils.isNotBlank( strModificationDate ) || StringUtils.isNotBlank( strDemandType ) || StringUtils.isNotBlank( strNotification ) )
245             {
246                 paginationFilterSortManager.cleanSessionFilter( );
247             }
248 
249             if ( StringUtils.isNotBlank( strModificationDate ) )
250             {
251                 Date modificationDate = checkFormatModificationDateFilter( strModificationDate, request );
252                 paginationFilterSortManager.storeFilterModificationDate( modificationDate );
253                 paginationFilterSortManager.storeFilterStringModificationDate( strModificationDate );
254             }
255 
256             if ( StringUtils.isNotBlank( strDemandType ) )
257             {
258                 int nIdDemandType = Integer.parseInt( strDemandType );
259                 paginationFilterSortManager.storeFilterDemandType( nIdDemandType );
260             }
261 
262             if ( StringUtils.isNotBlank( strNotification ) )
263             {
264                 paginationFilterSortManager.storeFilterNotification( strNotification );
265             }
266 
267             Date dateModificationSession = paginationFilterSortManager.retrieveFilterModificationDate( );
268 
269             if ( dateModificationSession != null )
270             {
271                 dFilter.setDateModification( dateModificationSession );
272                 model.put( CRMConstants.MARK_MODIFICATIONDATE, paginationFilterSortManager.retrieveFilterStringModificationDate( ) );
273             }
274 
275             Integer nIdDemandTypeSession = paginationFilterSortManager.retrieveFilterDemandType( );
276 
277             if ( ( nIdDemandTypeSession != null ) && ( nIdDemandTypeSession >= 0 ) )
278             {
279                 dFilter.setIdDemandType( nIdDemandTypeSession );
280             }
281 
282             String strNotificationSession = paginationFilterSortManager.retrieveFilterNotification( );
283 
284             if ( StringUtils.isNotBlank( strNotificationSession ) )
285             {
286                 dFilter.setNotification( strNotificationSession );
287             }
288 
289             model.put( CRMConstants.MARK_MAP_DEMANDS_LIST, _demandService.findByFilterMap( dFilter, request.getLocale( ), paginationFilterSortManager ) );
290             model.put( CRMConstants.MARK_FILTER, dFilter );
291 
292             Map<String, IPaginator<Demand>> mapPaginator = new HashMap<String, IPaginator<Demand>>( );
293             Map<String, String> mapNbItemsPerPage = new HashMap<String, String>( );
294             int nIdStatus;
295 
296             for ( DemandStatusCRM statusCRM : DemandStatusCRMService.getService( ).getAllStatusCRM( request.getLocale( ) ) )
297             {
298                 nIdStatus = statusCRM.getIdStatusCRM( );
299 
300                 IPaginator<Demand> paginator = paginationFilterSortManager.retrievePaginator( nIdStatus );
301                 int nItemsPerPage = paginationFilterSortManager.retrieveItemsPerPage( nIdStatus );
302 
303                 mapNbItemsPerPage.put( Integer.toString( nIdStatus ), Integer.toString( nItemsPerPage ) );
304                 mapPaginator.put( Integer.toString( nIdStatus ), paginator );
305             }
306             model.put( CRMConstants.MARK_STATUS_CRM_LIST, _statusCRMService.getAllStatusCRM( request.getLocale( ) ) );
307 
308             model.put( CRMConstants.MARK_MAP_PAGINATOR, mapPaginator );
309             model.put( CRMConstants.MARK_MAP_NB_ITEMS_PER_PAGE, mapNbItemsPerPage );
310             model.put( CRMConstants.MARK_DISPLAYDRAFT, _advancedParametersService.isParameterValueByKey( CRMConstants.CONSTANT_DISPLAYDRAFT ) );
311 
312         }
313         model.put( CRMConstants.MARK_LOCALE, request.getLocale( ) );
314         model.put( CRMConstants.MARK_MAP_DEMAND_TYPES_LIST, _demandTypeService.findForLuteceUser( request ) );
315         model.put( CRMConstants.MARK_CATEGORIES_LIST, _categoryService.getCategories( request.getLocale( ), false, true ) );
316         model.put( CRMConstants.MARK_DEMAND_TYPES_LIST, _demandTypeService.findAll( ) );
317 
318         model.put( CRMConstants.MARK_CRM_USER, crmUser );
319         List<DemandType> listAllOpenedDemandType = initListAllOpenedDemandType( );
320 
321         model.put( CRMConstants.MARK_DEMAND_TYPES_REFLIST, ListUtils.toReferenceList( listAllOpenedDemandType, "idDemandType", "label", "" ) );
322 
323         model.put( CRMConstants.MARK_MAP_DO_LOGIN, SecurityService.getInstance( ).getLoginPageUrl( ) );
324         model.put( CRMConstants.MARK_BASE_URL, AppPathService.getBaseUrl( request ) );
325         HtmlTemplate template = AppTemplateService.getTemplate( TEMPLATE_CRM_HOME_PAGE, request.getLocale( ), model );
326 
327         page.setTitle( I18nService.getLocalizedString( CRMConstants.PROPERTY_PAGE_TITLE, request.getLocale( ) ) );
328         page.setPathLabel( I18nService.getLocalizedString( CRMConstants.PROPERTY_PAGE_PATH, request.getLocale( ) ) );
329         page.setContent( template.getHtml( ) );
330 
331         return page;
332     }
333 
334     /**
335      * Get the page to manage the notifications of a resource
336      * 
337      * @param request
338      *            {@link HttpServletRequest}
339      * @param user
340      *            the {@link LuteceUser}
341      * @return a {@link XPage}
342      */
343     private XPage getManageNotificationsPage( HttpServletRequest request, LuteceUser user )
344     {
345         XPage page = null;
346         CRMUser crmUser = _crmUserService.findByUserGuid( user.getName( ) );
347         String strIdDemand = request.getParameter( CRMConstants.PARAMETER_ID_DEMAND );
348 
349         if ( ( crmUser != null ) && StringUtils.isNotBlank( strIdDemand ) && StringUtils.isNumeric( strIdDemand ) )
350         {
351             int nIdDemand = Integer.parseInt( strIdDemand );
352             Demand demand = _demandService.findByPrimaryKey( nIdDemand );
353 
354             if ( ( demand != null ) && ( crmUser.getIdCRMUser( ) == demand.getIdCRMUser( ) ) )
355             {
356                 // Check the existence of the demand and the owner of the demand is indeed the current user
357                 page = new XPage( );
358 
359                 NotificationFilters/notification/NotificationFilter.html#NotificationFilter">NotificationFilter nFilter = new NotificationFilter( );
360                 nFilter.setIdDemand( nIdDemand );
361 
362                 DemandType demandType = _demandTypeService.findByPrimaryKey( demand.getIdDemandType( ) );
363 
364                 Map<String, Object> model = new HashMap<String, Object>( );
365                 model.put( CRMConstants.MARK_NOTIFICATIONS_LIST, _notificationService.findByFilter( nFilter ) );
366                 model.put( CRMConstants.MARK_DEMAND_TYPE, demandType );
367 
368                 HtmlTemplate template = AppTemplateService.getTemplate( TEMPLATE_MANAGE_NOTIFICATIONS, request.getLocale( ), model );
369 
370                 page.setTitle( I18nService.getLocalizedString( CRMConstants.PROPERTY_MANAGE_NOTIFICATIONS_PAGE_TITLE, request.getLocale( ) ) );
371                 page.setPathLabel( I18nService.getLocalizedString( CRMConstants.PROPERTY_PAGE_PATH, request.getLocale( ) ) );
372                 page.setContent( template.getHtml( ) );
373             }
374         }
375 
376         return page;
377     }
378 
379     /**
380      * Get the page to view the notification
381      * 
382      * @param request
383      *            {@link HttpServletRequest}
384      * @param user
385      *            the {@link LuteceUser}
386      * @return a {@link XPage}
387      */
388     private XPage getViewNotificationPage( HttpServletRequest request, LuteceUser user )
389     {
390         XPage page = null;
391         CRMUser crmUser = _crmUserService.findByUserGuid( user.getName( ) );
392         String strIdNotification = request.getParameter( CRMConstants.PARAMETER_ID_NOTIFICATION );
393 
394         if ( ( crmUser != null ) && StringUtils.isNotBlank( strIdNotification ) && StringUtils.isNumeric( strIdNotification ) )
395         {
396             int nIdNotification = Integer.parseInt( strIdNotification );
397             Notification notification = _notificationService.findByPrimaryKey( nIdNotification );
398 
399             if ( notification != null )
400             {
401                 Demand demand = _demandService.findByPrimaryKey( notification.getIdDemand( ) );
402 
403                 if ( ( demand != null ) && ( crmUser.getIdCRMUser( ) == demand.getIdCRMUser( ) ) )
404                 {
405                     // Check the existence of the demand and the owner of the demand is indeed the current user
406                     if ( !notification.isRead( ) )
407                     {
408                         // Set the status of the notification to READ
409                         notification.setIsRead( true );
410                         _notificationService.update( notification );
411                     }
412 
413                     DemandType demandType = _demandTypeService.findByPrimaryKey( demand.getIdDemandType( ) );
414 
415                     page = new XPage( );
416 
417                     Map<String, Object> model = new HashMap<String, Object>( );
418                     model.put( CRMConstants.MARK_NOTIFICATION, notification );
419                     model.put( CRMConstants.MARK_DEMAND, demand );
420                     model.put( CRMConstants.MARK_DEMAND_TYPE, demandType );
421 
422                     HtmlTemplate template = AppTemplateService.getTemplate( TEMPLATE_VIEW_NOTIFICATION, request.getLocale( ), model );
423 
424                     page.setTitle( I18nService.getLocalizedString( CRMConstants.PROPERTY_VIEW_NOTIFICATION_PAGE_TITLE, request.getLocale( ) ) );
425                     page.setPathLabel( I18nService.getLocalizedString( CRMConstants.PROPERTY_PAGE_PATH, request.getLocale( ) ) );
426                     page.setContent( template.getHtml( ) );
427                 }
428             }
429         }
430 
431         return page;
432     }
433 
434     /**
435      * Get the modify crm account page
436      * 
437      * @param request
438      *            {@link HttpServletRequest}
439      * @param user
440      *            the {@link LuteceUser}
441      * @return a {@link XPage}
442      */
443     private XPage getModifyCRMUserPage( HttpServletRequest request, LuteceUser user )
444     {
445         XPage page = null;
446         CRMUser crmUser = _crmUserService.findByUserGuid( user.getName( ) );
447 
448         if ( crmUser != null )
449         {
450             page = new XPage( );
451 
452             Map<String, Object> model = new HashMap<String, Object>( );
453             model.put( CRMConstants.MARK_CRM_USER, crmUser );
454 
455             HtmlTemplate template = AppTemplateService.getTemplate( TEMPLATE_MODIFY_CRM_USER, request.getLocale( ), model );
456 
457             page.setTitle( I18nService.getLocalizedString( CRMConstants.PROPERTY_VIEW_NOTIFICATION_PAGE_TITLE, request.getLocale( ) ) );
458             page.setPathLabel( I18nService.getLocalizedString( CRMConstants.PROPERTY_PAGE_PATH, request.getLocale( ) ) );
459             page.setContent( template.getHtml( ) );
460         }
461 
462         return page;
463     }
464 
465     /**
466      * Do modify a crm user
467      * 
468      * @param request
469      *            the {@link HttpServletRequest}
470      * @param user
471      *            the {@link LuteceUser}
472      * @throws SiteMessageException
473      *             message if some info are not well filled
474      */
475     private void doModifyCRMUser( HttpServletRequest request, LuteceUser user ) throws SiteMessageException
476     {
477         CRMUser crmUser = _crmUserService.findByUserGuid( user.getName( ) );
478 
479         if ( crmUser != null )
480         {
481             UrlItem url = new UrlItem( JSP_SITE + JSP_PORTAL );
482             url.addParameter( CRMConstants.PARAMETER_PAGE, CRMPlugin.PLUGIN_NAME );
483             url.addParameter( CRMConstants.PARAMETER_ACTION, CRMConstants.ACTION_MODIFY_CRM_USER );
484 
485             int nMaxSize = AppPropertiesService.getPropertyInt( CRMConstants.PROPERTY_CRM_USER_MAX_SIZE, 255 );
486 
487             Map<String, String> userAttributes = new HashMap<String, String>( );
488 
489             for ( String strUserAttributeKey : _crmUserAttributesService.getUserAttributeKeys( ) )
490             {
491                 String strUserAttributeValue = request.getParameter( strUserAttributeKey );
492 
493                 if ( StringUtils.isNotBlank( strUserAttributeValue ) && ( strUserAttributeValue.length( ) > nMaxSize ) )
494                 {
495                     Object [ ] params = {
496                         nMaxSize
497                     };
498                     SiteMessageService.setMessage( request, CRMConstants.MESSAGE_SIZE_TOO_BIG, params, SiteMessage.TYPE_STOP );
499                 }
500 
501                 if ( StringUtils.isNotBlank( strUserAttributeKey ) && strUserAttributeKey.endsWith( CRMConstants.PARAMETER_EMAIL ) )
502                 {
503                     if ( !StringUtil.checkEmail( strUserAttributeValue ) )
504                     {
505                         SiteMessageService.setMessage( request, CRMConstants.MESSAGE_INVALID_EMAIL, SiteMessage.TYPE_STOP, url.getUrl( ) );
506                     }
507                     // If the user changed one of his emails
508                     if ( !StringUtils.equals( crmUser.getUserAttributeValue( strUserAttributeKey ), strUserAttributeValue ) )
509                     {
510                         if ( _crmUserAttributesService.isAttributeValueInUse( strUserAttributeValue, strUserAttributeKey ) )
511                         {
512                             SiteMessageService.setMessage( request, CRMConstants.MESSAGE_EMAIL_ALREADY_IN_USE, SiteMessage.TYPE_STOP, url.getUrl( ) );
513                         }
514                     }
515                 }
516 
517                 userAttributes.put( strUserAttributeKey, StringUtils.isNotBlank( strUserAttributeValue ) ? strUserAttributeValue : StringUtils.EMPTY );
518             }
519 
520             crmUser.setUserAttributes( userAttributes );
521 
522             _crmUserService.update( crmUser );
523             CRMUserModificationListenerService.getService( ).notifyListeners( crmUser, CRMConstants.EVENT_CRM_USER_MODIFIED );
524         }
525     }
526 
527     /**
528      * Get the confirmation message for removing the demand
529      * 
530      * @param request
531      *            {@link HttpServletRequest}
532      * @param user
533      *            the {@link LuteceUser}
534      * @throws SiteMessageException
535      *             the confirmation message
536      */
537     private void getDemandRemovingConfirmationMessage( HttpServletRequest request, LuteceUser user ) throws SiteMessageException
538     {
539         String strIdDemand = request.getParameter( CRMConstants.PARAMETER_ID_DEMAND );
540         String strWebAppCode = AppPropertiesService.getProperty( CRM_WEBB_APP_CODE_PROPERTY );
541         CRMUser crmUser = _crmUserService.findByUserGuid( user.getName( ) );
542 
543         if ( ( crmUser != null ) && StringUtils.isNotBlank( strIdDemand ) && StringUtils.isNumeric( strIdDemand ) )
544         {
545             int nIdDemand = Integer.parseInt( strIdDemand );
546             Demand demand = _demandService.findByPrimaryKey( nIdDemand );
547 
548             if ( ( demand != null ) && ( demand.getIdStatusCRM( ) == 0 ) && ( crmUser.getIdCRMUser( ) == demand.getIdCRMUser( ) ) )
549             {
550                 // Check the existence of the demand and the owner of the demand is indeed the current user and the demand is not validated
551                 DemandType demandType = _demandTypeService.findByPrimaryKey( demand.getIdDemandType( ) );
552 
553                 if ( demandType != null )
554                 {
555                     String strData = demand.getData( ).replace( "\"", "'" );
556 
557                     List<String> listElements = new ArrayList<String>( );
558                     listElements.add( Integer.toString( nIdDemand ) );
559                     if ( StringUtils.isNotBlank( strWebAppCode ) )
560                     {
561                         listElements.add( strWebAppCode );
562                     }
563 
564                     String strTimestamp = Long.toString( new Date( ).getTime( ) );
565                     String strSignature = CRMRequestAuthenticatorService.getRequestAuthenticatorForUrl( ).buildSignature( listElements, strTimestamp );
566 
567                     StringBuilder sbUrlReturn = new StringBuilder( AppPathService.getBaseUrl( request ) );
568 
569                     if ( !sbUrlReturn.toString( ).endsWith( CRMConstants.SLASH ) )
570                     {
571                         sbUrlReturn.append( CRMConstants.SLASH );
572                     }
573 
574                     sbUrlReturn.append( JSP_SITE + JSP_PORTAL );
575 
576                     UrlItem urlReturn = new UrlItem( sbUrlReturn.toString( ) );
577                     urlReturn.addParameter( CRMConstants.PARAMETER_PAGE, CRMPlugin.PLUGIN_NAME );
578 
579                     UrlItem url = new UrlItem( demandType.getUrlResource( ) );
580                     url.addParameter( CRMConstants.PARAMETER_ACTION, CRMConstants.ACTION_REMOVE_DRAFT );
581                     url.addParameter( CRMConstants.PARAMETER_ID_DEMAND, nIdDemand );
582                     url.addParameter( CRMConstants.PARAMETER_TIMESTAMP, strTimestamp );
583                     url.addParameter( CRMConstants.PARAMETER_SIGNATURE, strSignature );
584                     url.addParameter( CRMConstants.PARAMETER_DEMAND_DATA, strData );
585                     url.addParameter( CRMConstants.PARAMETER_URL_RETURN, urlReturn.getUrl( ) );
586                     if ( StringUtils.isNotBlank( strWebAppCode ) )
587                     {
588                         url.addParameter( CRMConstants.PARAMETER_CRM_WEBB_APP_CODE, strWebAppCode );
589                     }
590                     SiteMessageService.setMessage( request, CRMConstants.MESSAGE_CONFIRM_REMOVE_DEMAND, SiteMessage.TYPE_CONFIRMATION, url.getUrl( ) );
591                 }
592             }
593         }
594     }
595 
596     /**
597      * Create a CRM account if the current user does not have one
598      * 
599      * @param user
600      *            the LuteceUser
601      */
602     private void createOrUpdateCRMAccount( LuteceUser user )
603     {
604         if ( user != null )
605         {
606 
607             CRMUser crmUser = _crmUserService.findByUserGuid( user.getName( ) );
608 
609             if ( crmUser == null )
610             {
611                 crmUser = new CRMUser( );
612                 crmUser.setUserGuid( user.getName( ) );
613                 crmUser.setStatus( CRMUser.STATUS_ACTIVATED );
614 
615                 Map<String, String> userAttributes = new HashMap<String, String>( );
616 
617                 for ( String strUserAttributeKey : _crmUserAttributesService.getUserAttributeKeys( ) )
618                 {
619                     userAttributes.put( strUserAttributeKey, user.getUserInfo( strUserAttributeKey ) );
620                 }
621 
622                 crmUser.setUserAttributes( userAttributes );
623                 _crmUserService.create( crmUser );
624             }
625             else
626                 if ( crmUser.isMustBeUpdated( ) )
627                 {
628                     crmUser.setMustBeUpdated( false );
629                     crmUser.setStatus( CRMUser.STATUS_ACTIVATED );
630                     Map<String, String> userAttributes = new HashMap<String, String>( );
631                     for ( String strUserAttributeKey : _crmUserAttributesService.getUserAttributeKeys( ) )
632                     {
633                         userAttributes.put( strUserAttributeKey, user.getUserInfo( strUserAttributeKey ) );
634                     }
635 
636                     crmUser.setUserAttributes( userAttributes );
637                     _crmUserService.update( crmUser );
638 
639                 }
640         }
641     }
642 
643     /**
644      * Do open a demand type
645      * 
646      * @param request
647      *            the HTTP request
648      * @return the resource url of the demand type
649      */
650     public String doOpenDemandType( HttpServletRequest request )
651     {
652         String strUrl = AppPathService.getBaseUrl( request );
653         LuteceUser user;
654         String strWebAppCode = AppPropertiesService.getProperty( CRM_WEBB_APP_CODE_PROPERTY );
655         try
656         {
657 
658             String strIdDemandType = request.getParameter( CRMConstants.PARAMETER_ID_DEMAND_TYPE );
659             CRMUser crmUser = null;
660 
661             if ( StringUtils.isNotBlank( strIdDemandType ) && StringUtils.isNumeric( strIdDemandType ) )
662             {
663 
664                 int nIdDemandType = Integer.parseInt( strIdDemandType );
665                 DemandType demandType = _demandTypeService.findByPrimaryKey( nIdDemandType );
666 
667                 if ( ( demandType != null ) && demandType.isOpen( ) )
668                 {
669 
670                     if ( demandType.isIncludeIdCrmUser( ) )
671                     {
672                         user = getUser( request );
673                         crmUser = _crmUserService.findByUserGuid( user.getName( ) );
674                         // if crm user does not exist create crm user
675                         if ( user != null && crmUser == null )
676                         {
677                             crmUser = new CRMUser( );
678                             crmUser.setUserGuid( user.getName( ) );
679                             crmUser.setMustBeUpdated( true );
680                             crmUser.setIdCRMUser( _crmUserService.create( crmUser ) );
681                         }
682 
683                     }
684 
685                     List<String> listElements = new ArrayList<String>( );
686 
687                     listElements.add( Integer.toString( demandType.getIdDemandType( ) ) );
688                     if ( demandType.isIncludeIdCrmUser( ) )
689                     {
690                         listElements.add( Integer.toString( crmUser.getIdCRMUser( ) ) );
691 
692                     }
693 
694                     if ( StringUtils.isNotBlank( strWebAppCode ) )
695                     {
696                         listElements.add( strWebAppCode );
697                     }
698 
699                     String strTimestamp = Long.toString( new Date( ).getTime( ) );
700                     String strSignature = CRMRequestAuthenticatorService.getRequestAuthenticatorForUrl( ).buildSignature( listElements, strTimestamp );
701 
702                     UrlItem url = new UrlItem( demandType.getUrlResource( ) );
703                     url.addParameter( CRMConstants.PARAMETER_ID_DEMAND_TYPE, demandType.getIdDemandType( ) );
704                     if ( demandType.isIncludeIdCrmUser( ) )
705                     {
706                         url.addParameter( CRMConstants.PARAMETER_ID_CRM_USER, crmUser.getIdCRMUser( ) );
707                     }
708                     if ( StringUtils.isNotBlank( strWebAppCode ) )
709                     {
710                         url.addParameter( CRMConstants.PARAMETER_CRM_WEBB_APP_CODE, strWebAppCode );
711                     }
712 
713                     url.addParameter( CRMConstants.PARAMETER_TIMESTAMP, strTimestamp );
714                     url.addParameter( CRMConstants.PARAMETER_SIGNATURE, strSignature );
715 
716                     strUrl = url.getUrl( );
717                 }
718             }
719         }
720         catch( UserNotSignedException e )
721         {
722             strUrl = PortalJspBean.redirectLogin( request );
723         }
724 
725         return strUrl;
726     }
727 
728     /**
729      * Do edit a demand
730      * 
731      * @param request
732      *            the HTTP request
733      * @return the url resource to edit the resource
734      */
735     public String doEditDemand( HttpServletRequest request )
736     {
737         String strUrl = AppPathService.getBaseUrl( request );
738         LuteceUser user;
739         String strWebAppCode = AppPropertiesService.getProperty( CRM_WEBB_APP_CODE_PROPERTY );
740         try
741         {
742             user = getUser( request );
743 
744             CRMUser crmUser = _crmUserService.findByUserGuid( user.getName( ) );
745             String strIdDemand = request.getParameter( CRMConstants.PARAMETER_ID_DEMAND );
746 
747             if ( ( crmUser != null ) && StringUtils.isNotBlank( strIdDemand ) && StringUtils.isNumeric( strIdDemand ) )
748             {
749                 int nIdDemand = Integer.parseInt( strIdDemand );
750                 Demand demand = _demandService.findByPrimaryKey( nIdDemand );
751 
752                 if ( ( demand != null ) && ( crmUser.getIdCRMUser( ) == demand.getIdCRMUser( ) ) && ( demand.getIdStatusCRM( ) == 0 ) )
753                 {
754                     DemandType demandType = _demandTypeService.findByPrimaryKey( demand.getIdDemandType( ) );
755 
756                     if ( ( demandType != null ) && demandType.isOpen( ) )
757                     {
758                         List<String> listElements = new ArrayList<String>( );
759                         listElements.add( Integer.toString( demand.getIdDemand( ) ) );
760                         if ( StringUtils.isNotBlank( strWebAppCode ) )
761                         {
762                             listElements.add( strWebAppCode );
763                         }
764                         String strTimestamp = Long.toString( new Date( ).getTime( ) );
765                         String strSignature = CRMRequestAuthenticatorService.getRequestAuthenticatorForUrl( ).buildSignature( listElements, strTimestamp );
766 
767                         UrlItem url = new UrlItem( demandType.getUrlResource( ) );
768                         url.addParameter( CRMConstants.PARAMETER_ID_DEMAND, demand.getIdDemand( ) );
769                         if ( StringUtils.isNotBlank( strWebAppCode ) )
770                         {
771                             url.addParameter( CRMConstants.PARAMETER_CRM_WEBB_APP_CODE, strWebAppCode );
772                         }
773                         url.addParameter( CRMConstants.PARAMETER_DEMAND_DATA, demand.getData( ) );
774                         url.addParameter( CRMConstants.PARAMETER_TIMESTAMP, strTimestamp );
775                         url.addParameter( CRMConstants.PARAMETER_SIGNATURE, strSignature );
776 
777                         strUrl = url.getUrl( );
778                     }
779                 }
780             }
781         }
782         catch( UserNotSignedException e )
783         {
784             strUrl = PortalJspBean.redirectLogin( request );
785         }
786 
787         return strUrl;
788     }
789 
790     /**
791      * Gets the user from the request
792      * 
793      * @param request
794      *            The HTTP user
795      * @return The Lutece User
796      * @throws UserNotSignedException
797      *             exception if user not connected
798      */
799     public LuteceUser getUser( HttpServletRequest request ) throws UserNotSignedException
800     {
801         if ( SecurityService.isAuthenticationEnable( ) )
802         {
803             LuteceUser user = SecurityService.getInstance( ).getRemoteUser( request );
804             if ( user == null )
805             {
806                 throw new UserNotSignedException( );
807             }
808             return user;
809         }
810         else
811         {
812             throw new PageNotFoundException( );
813         }
814     }
815 
816     /**
817      * Get the list of all the opened demand types only
818      * 
819      * @return the list of opened demand types
820      */
821     private List<DemandType> initListAllOpenedDemandType( )
822     {
823         List<DemandType> listAllDemandType = _demandTypeService.findAll( );
824         List<DemandType> listAllOpenedDemandType = new ArrayList<DemandType>( );
825 
826         for ( DemandType demandType : listAllDemandType )
827         {
828             if ( demandType.isOpen( ) )
829             {
830                 listAllOpenedDemandType.add( demandType );
831             }
832         }
833 
834         return listAllOpenedDemandType;
835     }
836 
837     /**
838      * Check the format of the filter modification date
839      * 
840      * @throws SiteMessageException
841      */
842     private Date checkFormatModificationDateFilter( String strModificationDate, HttpServletRequest request ) throws SiteMessageException
843     {
844         SimpleDateFormat sdf = new SimpleDateFormat( "dd/MM/yyyy" );
845         sdf.setLenient( true );
846 
847         Date d = new Date( );
848 
849         try
850         {
851             d = sdf.parse( strModificationDate );
852         }
853         catch( Exception e )
854         {
855             SiteMessageService.setMessage( request, CRMConstants.MESSAGE_INVALID_FORMAT_DATE_MODIFICATION );
856         }
857 
858         String t = sdf.format( d );
859 
860         if ( t.compareTo( strModificationDate ) != 0 )
861         {
862             SiteMessageService.setMessage( request, CRMConstants.MESSAGE_INVALID_FORMAT_DATE_MODIFICATION );
863         }
864 
865         return d;
866     }
867 }