001/*
002    Licensed to the Apache Software Foundation (ASF) under one
003    or more contributor license agreements.  See the NOTICE file
004    distributed with this work for additional information
005    regarding copyright ownership.  The ASF licenses this file
006    to you under the Apache License, Version 2.0 (the
007    "License"); you may not use this file except in compliance
008    with the License.  You may obtain a copy of the License at
009
010       http://www.apache.org/licenses/LICENSE-2.0
011
012    Unless required by applicable law or agreed to in writing,
013    software distributed under the License is distributed on an
014    "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
015    KIND, either express or implied.  See the License for the
016    specific language governing permissions and limitations
017    under the License.
018 */
019package org.apache.wiki.preferences;
020
021import com.google.gson.Gson;
022import com.google.gson.JsonParseException;
023import org.apache.commons.lang3.LocaleUtils;
024import org.apache.commons.lang3.StringUtils;
025import org.apache.logging.log4j.LogManager;
026import org.apache.logging.log4j.Logger;
027import org.apache.wiki.InternalWikiException;
028import org.apache.wiki.api.core.Context;
029import org.apache.wiki.i18n.InternationalizationManager;
030import org.apache.wiki.util.HttpUtil;
031import org.apache.wiki.util.PropertyReader;
032import org.apache.wiki.util.TextUtil;
033
034import jakarta.servlet.http.HttpServletRequest;
035import jakarta.servlet.jsp.PageContext;
036import java.text.DateFormat;
037import java.text.SimpleDateFormat;
038import java.util.Date;
039import java.util.HashMap;
040import java.util.HashSet;
041import java.util.Locale;
042import java.util.Map;
043import java.util.MissingResourceException;
044import java.util.Properties;
045import java.util.ResourceBundle;
046import java.util.Set;
047import java.util.TimeZone;
048
049
050/**
051 *  Represents an object which is used to store user preferences.
052 */
053public class Preferences extends HashMap< String,String > {
054
055    private static final long serialVersionUID = 1L;
056
057    /** The names of the preferences whose value comes from the user's cookie, and not from the defaults. */
058    private final Set< String > setByUser = new HashSet<>();
059
060    /**
061     * The name under which a Preferences object is stored in the HttpSession. Its value is {@value}.
062     */
063    public static final String SESSIONPREFS = "prefs";
064
065    public static final String COOKIE_USER_PREFS_NAME = "JSPWikiUserPrefs";
066
067    private static final Logger LOG = LogManager.getLogger( Preferences.class );
068
069    /**
070     *  This is an utility method which is called to make sure that the
071     *  JSP pages do have proper access to any user preferences.  It should be
072     *  called from the commonheader.jsp.
073     *  <p>
074     *  This method reads user cookie preferences and mixes them up with any
075     *  default preferences (and in the future, any user-specific preferences)
076     *  and puts them all in the session, so that they do not have to be rewritten
077     *  again.
078     *  <p>
079     *  This method will remember if the user has already changed his prefs.
080     *
081     *  @param pageContext The JSP PageContext.
082     */
083    public static void setupPreferences( final PageContext pageContext ) {
084        //HttpSession session = pageContext.getSession();
085        //if( session.getAttribute( SESSIONPREFS ) == null )
086        //{
087            reloadPreferences( pageContext );
088        //}
089    }
090
091    /**
092     *  Reloads the preferences from the PageContext into the WikiContext.
093     *
094     *  @param pageContext The page context.
095     */
096    // FIXME: The way that date preferences are chosen is currently a bit wacky: it all gets saved to the cookie based on the browser state
097    //        with which the user happened to first arrive to the site with.  This, unfortunately, means that even if the user changes e.g.
098    //        language preferences (like in a web cafe), the old preferences still remain in a site cookie.
099    public static void reloadPreferences( final PageContext pageContext ) {
100        final Preferences prefs = new Preferences();
101        final Properties props = PropertyReader.loadWebAppProps( pageContext.getServletContext() );
102        final Context ctx = Context.findContext( pageContext );
103        final String dateFormat = ctx.getEngine().getManager( InternationalizationManager.class )
104                                           .get( InternationalizationManager.CORE_BUNDLE, getLocale( ctx ), "common.datetimeformat" );
105
106        prefs.put("SkinName", TextUtil.getStringProperty( props, "jspwiki.defaultprefs.template.skinname", "PlainVanilla" ) );
107        prefs.put("DateFormat", TextUtil.getStringProperty( props, "jspwiki.defaultprefs.template.dateformat", dateFormat ) );
108        prefs.put("TimeZone", TextUtil.getStringProperty( props, "jspwiki.defaultprefs.template.timezone", TimeZone.getDefault().getID() ) );
109        prefs.put("Orientation", TextUtil.getStringProperty( props, "jspwiki.defaultprefs.template.orientation", "fav-left" ) );
110        prefs.put("Sidebar", TextUtil.getStringProperty( props, "jspwiki.defaultprefs.template.sidebar", "active" ) );
111        prefs.put("Layout", TextUtil.getStringProperty( props, "jspwiki.defaultprefs.template.layout", "fluid" ) );
112        prefs.put("Language", TextUtil.getStringProperty( props, "jspwiki.defaultprefs.template.language", getLocale( ctx ).toString() ) );
113        prefs.put("SectionEditing", TextUtil.getStringProperty( props, "jspwiki.defaultprefs.template.sectionediting", "true" ) );
114        //prefs.put("Appearance", TextUtil.getStringProperty( props, "jspwiki.defaultprefs.template.appearance", "true" ) );
115
116        //editor cookies
117        prefs.put("autosuggest", TextUtil.getStringProperty( props, "jspwiki.defaultprefs.template.autosuggest", "true" ) );
118        prefs.put("tabcompletion", TextUtil.getStringProperty( props, "jspwiki.defaultprefs.template.tabcompletion", "true" ) );
119        prefs.put("smartpairs", TextUtil.getStringProperty( props, "jspwiki.defaultprefs.template.smartpairs", "false" ) );
120        prefs.put("livepreview", TextUtil.getStringProperty( props, "jspwiki.defaultprefs.template.livepreview", "true" ) );
121        prefs.put("previewcolumn", TextUtil.getStringProperty( props, "jspwiki.defaultprefs.template.previewcolumn", "true" ) );
122
123
124        // FIXME: editormanager reads jspwiki.editor -- which of both properties should continue
125        prefs.put("editor", TextUtil.getStringProperty( props, "jspwiki.defaultprefs.template.editor", "plain" ) );
126        parseJSONPreferences( (HttpServletRequest) pageContext.getRequest(), prefs );
127        pageContext.getSession().setAttribute( SESSIONPREFS, prefs );
128    }
129
130
131    /**
132     * Parses new-style preferences stored as JSON objects and stores them in the session.  Everything in the cookie is stored. The cookie
133     * comes from the client, so one that cannot be decoded or is not a JSON object is ignored and the default preferences stay.
134     *
135     * @param request
136     * @param prefs The default hashmap of preferences
137     */
138    static void parseJSONPreferences( final HttpServletRequest request, final Preferences prefs ) {
139        final String prefVal;
140        try {
141            prefVal = TextUtil.urlDecodeUTF8( HttpUtil.retrieveCookieValue( request, COOKIE_USER_PREFS_NAME ) );
142        } catch( final IllegalArgumentException e ) {
143            LOG.warn( "Ignoring the {} cookie, it cannot be decoded: {}", COOKIE_USER_PREFS_NAME, e.getMessage() );
144            return;
145        }
146        if( prefVal != null ) {
147            // Convert prefVal JSON to a generic hashmap
148            final Map< String, String > map;
149            try {
150                @SuppressWarnings( "unchecked" ) final Map< String, String > parsed = new Gson().fromJson( prefVal, Map.class );
151                map = parsed;
152            } catch( final JsonParseException e ) {
153                LOG.warn( "Ignoring the {} cookie, its value is not a JSON object: {}", COOKIE_USER_PREFS_NAME, e.getMessage() );
154                return;
155            }
156            if( map == null ) { // an empty value or the JSON literal null
157                return;
158            }
159            for( String key : map.keySet() ) {
160                key = TextUtil.replaceEntities( key );
161                // Sometimes this is not a String as it comes from the Cookie set by Javascript
162                final Object value = map.get( key );
163                if( value != null ) {
164                    prefs.put( key, value.toString() );
165                    prefs.setByUser.add( key );
166                }
167            }
168        }
169    }
170
171    /**
172     *  Tells whether the user chose the value of a preference, as opposed to getting the default one.
173     *
174     *  @param name the name of the preference.
175     *  @return {@code true} if the value comes from the user's cookie.
176     *  @since 3.0.1
177     */
178    public boolean isSetByUser( final String name ) {
179        return setByUser.contains( name );
180    }
181
182    /**
183     *  Returns a preference value programmatically.
184     *  FIXME
185     *
186     *  @param wikiContext
187     *  @param name
188     *  @return the preference value
189     */
190    public static String getPreference( final Context wikiContext, final String name ) {
191        final HttpServletRequest request = wikiContext.getHttpRequest();
192        if ( request == null ) {
193            return null;
194        }
195
196        final Preferences prefs = (Preferences)request.getSession().getAttribute( SESSIONPREFS );
197        if( prefs != null ) {
198            return prefs.get( name );
199        }
200
201        return null;
202    }
203
204    /**
205     *  Returns a preference value programmatically.
206     *
207     *  @param pageContext
208     *  @param name
209     *  @return the preference value
210     */
211    public static String getPreference( final PageContext pageContext, final String name ) {
212        final Preferences prefs = ( Preferences )pageContext.getSession().getAttribute( SESSIONPREFS );
213        if( prefs != null ) {
214            return prefs.get( name );
215        }
216
217        return null;
218    }
219
220    /**
221     * Get Locale according to user-preference settings or the user browser locale
222     *
223     * @param context The context to examine.
224     * @return a Locale object.
225     * @since 2.8
226     */
227    public static Locale getLocale( final Context context ) {
228        Locale loc = null;
229
230        final String langSetting = getPreference( context, "Language" );
231
232        // parse language and construct valid Locale object
233        if( langSetting != null ) {
234            String language = "";
235            String country  = "";
236            String variant  = "";
237
238            final String[] res = StringUtils.split( langSetting, "-_" );
239            final int resLength = res.length;
240            if( resLength > 2 ) {
241                variant = res[ 2 ];
242            }
243            if( resLength > 1 ) {
244                country = res[ 1 ];
245            }
246            if( resLength > 0 ) {
247                language = res[ 0 ];
248                loc = new Locale( language, country, variant );
249            }
250        }
251
252        // see if default locale is set server side
253        if( loc == null ) {
254            final String locale = context.getEngine().getWikiProperties().getProperty( "jspwiki.preferences.default-locale" );
255            if (locale != null) {
256                //this can be null under unit test/mock contexts but normally is
257                //not null under normal operating circumstances.
258                try {
259                    loc = LocaleUtils.toLocale( locale );
260                } catch( final IllegalArgumentException iae ) {
261                    LOG.error( iae.getMessage() );
262                }
263            }
264        }
265
266        // otherwise try to find out the browser's preferred language setting, or use the JVM's default
267        if( loc == null ) {
268            final HttpServletRequest request = context.getHttpRequest();
269            loc = ( request != null ) ? request.getLocale() : Locale.getDefault();
270        }
271        if ( loc == null) {
272            loc = Locale.getDefault();
273        }
274
275        LOG.debug( "using locale " + loc.toString() );
276        return loc;
277    }
278
279    /**
280     * Locates the i18n ResourceBundle given.  This method interprets the request locale, and uses that to figure out which language the
281     * user wants.
282     *
283     * @param context {@link Context} holding the user's locale
284     * @param bundle  The name of the bundle you are looking for.
285     * @return A localized string (or from the default language, if not found)
286     * @throws MissingResourceException If the bundle cannot be found
287     * @see org.apache.wiki.i18n.InternationalizationManager
288     */
289    public static ResourceBundle getBundle( final Context context, final String bundle ) throws MissingResourceException {
290        final Locale loc = getLocale( context );
291        final InternationalizationManager i18n = context.getEngine().getManager( InternationalizationManager.class );
292        return i18n.getBundle( bundle, loc );
293    }
294
295    /**
296     * Get SimpleTimeFormat according to user browser locale and preferred time formats. If not found, it will revert to whichever format
297     * is set for the default.
298     *
299     * @param context WikiContext to use for rendering.
300     * @param tf Which version of the dateformat you are looking for?
301     * @return A SimpleTimeFormat object which you can use to render
302     * @since 2.8
303     */
304    public static SimpleDateFormat getDateFormat( final Context context, final TimeFormat tf ) {
305        final InternationalizationManager imgr = context.getEngine().getManager( InternationalizationManager.class );
306        final Locale clientLocale = getLocale( context );
307        final String prefTimeZone = getPreference( context, "TimeZone" );
308        String prefDateFormat;
309
310        LOG.debug("Checking for preferences...");
311        switch( tf ) {
312            case DATETIME:
313                prefDateFormat = getPreference( context, "DateFormat" );
314                LOG.debug("Preferences fmt = "+prefDateFormat);
315                if( prefDateFormat == null ) {
316                    prefDateFormat = imgr.get( InternationalizationManager.CORE_BUNDLE, clientLocale,"common.datetimeformat" );
317                    LOG.debug("Using locale-format = "+prefDateFormat);
318                }
319                break;
320
321            case TIME:
322                prefDateFormat = imgr.get( "common.timeformat" );
323                break;
324
325            case DATE:
326                prefDateFormat = imgr.get( "common.dateformat" );
327                break;
328
329            default:
330                throw new InternalWikiException( "Got a TimeFormat for which we have no value!" );
331        }
332
333        try {
334            final SimpleDateFormat fmt = new SimpleDateFormat( prefDateFormat, clientLocale );
335            if( prefTimeZone != null ) {
336                final TimeZone tz = TimeZone.getTimeZone( prefTimeZone );
337                // TimeZone tz = TimeZone.getDefault();
338                // tz.setRawOffset(Integer.parseInt(prefTimeZone));
339                fmt.setTimeZone( tz );
340            }
341
342            return fmt;
343        } catch( final Exception e ) {
344            LOG.debug(e.getMessage(), e);
345            return null;
346        }
347    }
348
349    /**
350     * A simple helper function to render a date based on the user preferences. This is useful for example for all plugins.
351     *
352     * @param context  The context which is used to get the preferences
353     * @param date     The date to render.
354     * @param tf       In which format the date should be rendered.
355     * @return A ready-rendered date.
356     * @since 2.8
357     */
358    public static String renderDate( final Context context, final Date date, final TimeFormat tf ) {
359        final DateFormat df = getDateFormat( context, tf );
360        return df.format( date );
361    }
362
363    /**
364     *  Is used to choose between the different date formats that JSPWiki supports.
365     *  <ul>
366     *   <li>TIME: A time format, without  date</li>
367     *   <li>DATE: A date format, without a time</li>
368     *   <li>DATETIME: A date format, with a time</li>
369     *  </ul>
370     *
371     *  @since 2.8
372     */
373    public enum TimeFormat {
374        /** A time format, no date. */
375        TIME,
376
377        /** A date format, no time. */
378        DATE,
379
380        /** A date+time format. */
381        DATETIME
382    }
383
384}