View Javadoc
1   /*
2    * Copyright (c) 2002-2021, 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.newsletter.util;
35  
36  import fr.paris.lutece.plugins.newsletter.business.NewsLetterTemplate;
37  import fr.paris.lutece.plugins.newsletter.business.NewsLetterTemplateHome;
38  import fr.paris.lutece.portal.service.html.EncodingService;
39  import fr.paris.lutece.portal.service.i18n.I18nService;
40  import fr.paris.lutece.portal.service.plugin.Plugin;
41  import fr.paris.lutece.portal.service.util.AppPropertiesService;
42  import fr.paris.lutece.util.string.StringUtil;
43  import fr.paris.lutece.util.url.UrlItem;
44  
45  import javax.servlet.ServletRequest;
46  import javax.servlet.http.HttpServletRequest;
47  import javax.servlet.http.HttpServletResponse;
48  
49  import org.apache.commons.lang3.StringUtils;
50  
51  import java.util.Locale;
52  import java.util.Optional;
53  
54  /**
55   * This classe provides utility methods for newsletters.
56   */
57  public final class NewsletterUtils
58  {
59      /**
60       * Private constructor
61       */
62      private NewsletterUtils( )
63      {
64      }
65  
66      /**
67       * Retrieve the html template for the given template id
68       * 
69       * @param nTemplateId
70       *            the id of the template to retrieve
71       * @param plugin
72       *            the plugin
73       * @return the html template to use of null if no NewsletterTemplate found for this Id
74       */
75      public static String getHtmlTemplatePath( int nTemplateId, Plugin plugin )
76      {
77          NewsLetterTemplate newsletterTemplate = NewsLetterTemplateHome.findByPrimaryKey( nTemplateId, plugin );
78  
79          if ( ( newsletterTemplate == null ) || StringUtils.isEmpty( newsletterTemplate.getFileName( ) ) )
80          {
81              return null;
82          }
83  
84          String strTemplatePathName = AppPropertiesService.getProperty( NewsLetterConstants.PROPERTY_PATH_FILE_NEWSLETTER_TEMPLATE );
85          strTemplatePathName += NewsLetterConstants.CONSTANT_SLASH;
86          strTemplatePathName += newsletterTemplate.getFileName( );
87  
88          return strTemplatePathName;
89      }
90  
91      /**
92       * Cleans a string in order to make it usable in a javascript script
93       * 
94       * @param strIn
95       *            the string to clean
96       * @return the javascript escaped String
97       */
98      public static String convertForJavascript( String strIn )
99      {
100         // Convert problem characters to JavaScript Escaped values
101         if ( strIn == null )
102         {
103             return StringUtils.EMPTY;
104         }
105 
106         String strOut = strIn;
107 
108         strOut = StringUtil.substitute( strOut, "\\\\", "\\" ); // replace backslash with \\
109 
110         strOut = StringUtil.substitute( strOut, "\\\'", "'" ); // replace an single quote with \'
111 
112         strOut = StringUtil.substitute( strOut, "\\\"", "\"" ); // replace a double quote with \"
113 
114         strOut = StringUtil.substitute( strOut, "\\r", "\r\n" ); // replace CR // with \r;
115 
116         strOut = StringUtil.substitute( strOut, "\\n", "\n" ); // replace LF with \n;
117 
118         return strOut;
119     }
120 
121     /**
122      * Encode a string for passage in parameter in URL
123      * 
124      * @param strEntry
125      *            the string entry
126      * @return the string encoding
127      */
128     public static String encodeForURL( String strEntry )
129     {
130         return EncodingService.encodeUrl( strEntry );
131     }
132 
133     /**
134      * Addition of information as header of the http response
135      * 
136      * @param request
137      *            The Http Request
138      * @param response
139      *            The Http Response
140      * @param strFileName
141      *            THe filename of the file
142      * @param strFileExtension
143      *            The file extension
144      */
145     public static void addHeaderResponse( HttpServletRequest request, HttpServletResponse response, String strFileName, String strFileExtension )
146     {
147         response.setHeader( "Content-Disposition", "attachment ;filename=\"" + strFileName + "\"" );
148 
149         if ( strFileExtension.equals( ".csv" ) )
150         {
151             response.setContentType( "application/csv" );
152         }
153         else
154         {
155             String strMimeType = request.getSession( ).getServletContext( ).getMimeType( strFileName );
156 
157             if ( strMimeType != null )
158             {
159                 response.setContentType( strMimeType );
160             }
161             else
162             {
163                 response.setContentType( "application/octet-stream" );
164             }
165         }
166 
167         response.setHeader( "Pragma", "public" );
168         response.setHeader( "Expires", "0" );
169         response.setHeader( "Cache-Control", "must-revalidate,post-check=0,pre-check=0" );
170     }
171 
172     /**
173      * Adds all parameter values to the urlItem
174      * 
175      * @param urlItem
176      *            the urlItem
177      * @param strParameterName
178      *            the name of the parameter which has multiple values
179      * @param values
180      *            parameter values
181      */
182     public static void addParameters( UrlItem urlItem, String strParameterName, String [ ] values )
183     {
184         for ( String strParameterValue : values )
185         {
186             urlItem.addParameter( strParameterName, strParameterValue );
187         }
188     }
189 
190     /**
191      * Get the first String of a String array. If the array is null, or if it has no element, then return null.
192      * 
193      * @param strArrayValues
194      *            The string array to get the first element of.
195      * @return The first element of the array, or null if the array has no element or is null.
196      */
197     public static String getStringFromStringArray( String [ ] strArrayValues )
198     {
199         if ( strArrayValues != null )
200         {
201             return strArrayValues.length == 0 ? null : strArrayValues [0];
202         }
203         return null;
204     }
205 
206     /**
207      * Rewrite relatives url to absolutes urls
208      * 
209      * @param strContent
210      *            The content to analyze
211      * @param strBaseUrl
212      *            The base url
213      * @return The converted content
214      */
215     public static String rewriteUrls( String strContent, String strBaseUrl )
216     {
217         HtmlDomDocNewsletterr/util/HtmlDomDocNewsletter.html#HtmlDomDocNewsletter">HtmlDomDocNewsletter doc = new HtmlDomDocNewsletter( strContent, strBaseUrl );
218         doc.convertAllRelativesUrls( HtmlDomDocNewsletter.ELEMENT_IMG );
219         doc.convertAllRelativesUrls( HtmlDomDocNewsletter.ELEMENT_A );
220         doc.convertAllRelativesUrls( HtmlDomDocNewsletter.ELEMENT_FORM );
221         doc.convertAllRelativesUrls( HtmlDomDocNewsletter.ELEMENT_CSS );
222         doc.convertAllRelativesUrls( HtmlDomDocNewsletter.ELEMENT_JAVASCRIPT );
223 
224         return doc.getContent( );
225     }
226 
227     public static Locale getLocale( ServletRequest request )
228     {
229         return Optional.ofNullable( request ).map( ServletRequest::getLocale ).orElse( I18nService.getDefaultLocale( ) );
230     }
231 
232 }