KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > Yasna > forum > util > SkinUtils


1 /**
2  * Copyright (C) 2001 Yasna.com. All rights reserved.
3  *
4  * ===================================================================
5  * The Apache Software License, Version 1.1
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  *
11  * 1. Redistributions of source code must retain the above copyright
12  * notice, this list of conditions and the following disclaimer.
13  *
14  * 2. Redistributions in binary form must reproduce the above copyright
15  * notice, this list of conditions and the following disclaimer in
16  * the documentation and/or other materials provided with the
17  * distribution.
18  *
19  * 3. The end-user documentation included with the redistribution,
20  * if any, must include the following acknowledgment:
21  * "This product includes software developed by
22  * Yasna.com (http://www.yasna.com)."
23  * Alternately, this acknowledgment may appear in the software itself,
24  * if and wherever such third-party acknowledgments normally appear.
25  *
26  * 4. The names "Yazd" and "Yasna.com" must not be used to
27  * endorse or promote products derived from this software without
28  * prior written permission. For written permission, please
29  * contact yazd@yasna.com.
30  *
31  * 5. Products derived from this software may not be called "Yazd",
32  * nor may "Yazd" appear in their name, without prior written
33  * permission of Yasna.com.
34  *
35  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
36  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
37  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
38  * DISCLAIMED. IN NO EVENT SHALL YASNA.COM OR
39  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
40  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
41  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
42  * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
43  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
44  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
45  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
46  * SUCH DAMAGE.
47  * ====================================================================
48  *
49  * This software consists of voluntary contributions made by many
50  * individuals on behalf of Yasna.com. For more information
51  * on Yasna.com, please see <http://www.yasna.com>.
52  */

53
54 /**
55  * Copyright (C) 2000 CoolServlets.com. All rights reserved.
56  *
57  * ===================================================================
58  * The Apache Software License, Version 1.1
59  *
60  * Redistribution and use in source and binary forms, with or without
61  * modification, are permitted provided that the following conditions
62  * are met:
63  *
64  * 1. Redistributions of source code must retain the above copyright
65  * notice, this list of conditions and the following disclaimer.
66  *
67  * 2. Redistributions in binary form must reproduce the above copyright
68  * notice, this list of conditions and the following disclaimer in
69  * the documentation and/or other materials provided with the
70  * distribution.
71  *
72  * 3. The end-user documentation included with the redistribution,
73  * if any, must include the following acknowledgment:
74  * "This product includes software developed by
75  * CoolServlets.com (http://www.coolservlets.com)."
76  * Alternately, this acknowledgment may appear in the software itself,
77  * if and wherever such third-party acknowledgments normally appear.
78  *
79  * 4. The names "Jive" and "CoolServlets.com" must not be used to
80  * endorse or promote products derived from this software without
81  * prior written permission. For written permission, please
82  * contact webmaster@coolservlets.com.
83  *
84  * 5. Products derived from this software may not be called "Jive",
85  * nor may "Jive" appear in their name, without prior written
86  * permission of CoolServlets.com.
87  *
88  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
89  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
90  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
91  * DISCLAIMED. IN NO EVENT SHALL COOLSERVLETS.COM OR
92  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
93  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
94  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
95  * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
96  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
97  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
98  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
99  * SUCH DAMAGE.
100  * ====================================================================
101  *
102  * This software consists of voluntary contributions made by many
103  * individuals on behalf of CoolServlets.com. For more information
104  * on CoolServlets.com, please see <http://www.coolservlets.com>.
105  */

106
107 package com.Yasna.forum.util;
108
109 import java.util.Date JavaDoc;
110 import java.util.Iterator JavaDoc;
111 import java.util.Locale JavaDoc;
112 import java.text.SimpleDateFormat JavaDoc;
113 import java.io.File JavaDoc;
114 import java.util.TimeZone JavaDoc;
115
116 import javax.servlet.*;
117 import javax.servlet.http.*;
118
119 import com.Yasna.forum.*;
120 import com.Yasna.forum.Tasks.SessionManager;
121 import com.Yasna.forum.locale.YazdLocale;
122 import com.Yasna.util.StringUtils;
123
124 /**
125  * A collection of utility methods for use in Yazd WebSkins. Because these
126  * methods make skin development much easier, skin authors should study them
127  * carefully.<p>
128  *
129  * Three major areas of funtionality are provided:<p><ol>
130  * <li> Methods that simplify Authorization tasks:
131  * <ul>
132  * <li>{@link #getUserAuthorization(HttpServletRequest, HttpServletResponse)}
133  * <li>{@link #getUserAuthorization(HttpServletRequest, HttpServletResponse, boolean)}
134  * <li>{@link #setUserAuthorization(HttpServletRequest, HttpServletResponse, String, String, boolean)}
135  * <li>{@link #removeUserAuthorization(HttpServletRequest, HttpServletResponse)}
136  * <li>{@link #isSystemAdmin(Authorization)}
137  * <li>{@link #isForumAdmin(Authorization)}
138  * <li>{@link #isForumAdmin(Authorization, Forum)}
139  * <li>{@link #isGroupAdmin(Authorization)}
140  * <li>{@link #isGroupAdmin(Authorization, Group)}
141  * </ul>
142  * <p>
143  * <li> Methods that get and set Session and cookie values.
144  * <ul>
145  * <li>{@link #getCookie(HttpServletRequest, String)}
146  * <li>{@link #getCookieValue(HttpServletRequest, String)}
147  * <li>{@link #invalidateCookie(HttpServletRequest, HttpServletResponse, String)}
148  * <li>{@link #remove(HttpServletRequest, HttpServletResponse, String)}
149  * <li>{@link #retrieve(HttpServletRequest, HttpServletResponse, String)}
150  * <li>{@link #retrieve(HttpServletRequest, HttpServletResponse, String, boolean)}
151  * <li>{@link #store(HttpServletRequest, HttpServletResponse, String, String)}
152  * <li>{@link #store(HttpServletRequest, HttpServletResponse, String, String, int)}
153  * <li>{@link #store(HttpServletRequest, HttpServletResponse, String, String, int boolean)}
154  * </ul>
155  * <p>
156  * <li> Other methods.
157  * <ul>
158  * <li>{@link #dateToText(Date)}
159  * <li>(@link #getLastVisisted(HttpServletRequest, HttpServletResponse)}
160  * <li>(@link #getLastVisisted(HttpServletRequest, HttpServletResponse, boolean)}
161  * <li>{@link #isNewMessage(ForumMessage, long)}
162  * <li>(@link #quoteOriginal(ForumMessage, String, int)}
163  * </ul>
164  * </ol>
165  *
166  * All methods conform to the Servlet 1.1 and JSP 1.0 specs for maximum
167  * compatibility with application servers. This may yield deprecation warnings
168  * if you compile with a newer Servlet/JSP spec; these should be ignored. This
169  * class will periodically be updated to the newer specs as app servers mature.
170  */

171 public class SkinUtils {
172
173     /** Name of the authentication token (is stored in the user's session) */
174     public static final String JavaDoc YAZD_AUTH_TOKEN = "yazdAuthorization";
175
176     /** Name of the cookie used to store user info for auto-login purposes */
177     public static final String JavaDoc YAZD_AUTOLOGIN_COOKIE = "yazdAutoLogin";
178
179     /** Name of the last visited token (is stored in the user's session) */
180     public static final String JavaDoc YAZD_LASTVISITED_TOKEN = "yazdLastVisited";
181
182     /** Name of the cookie used to store last visited timestamp */
183     public static final String JavaDoc YAZD_LASTVISITED_COOKIE = "yazdLastVisited";
184
185     // XXX keep this ?
186
/** Name of the "use last visited" property (is stored in yazd.properties) */
187     public static final String JavaDoc YAZD_LASTVISITED_PROP = "Site.useLastVisited";
188
189     //Time constants (in milliseconds)
190
private static final long SECOND = 1000;
191     private static final long MINUTE = 60 * SECOND;
192     private static final long HOUR = 60 * MINUTE;
193     private static final long DAY = 24 * HOUR;
194     private static final long WEEK = 7 * DAY;
195
196     //Default cookie time to live (in seconds).
197
private static final int MAX_COOKIE_AGE = (int)(WEEK / 1000) * 8;
198
199     private static SessionManager sessionManager = new SessionManager();
200
201     //Days of the week
202
private static final String JavaDoc[] DAYS_OF_WEEK =
203         { "Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday" };
204
205     // SimpleDateFormat objects for use in the dateToText method
206
private static final SimpleDateFormat JavaDoc yesterdayFormatter =
207         new SimpleDateFormat JavaDoc("'Yesterday at' h:mm a");
208
209     //"Tweakable" parameters for the cookie encoding. NOTE: changing these
210
//and recompiling this class will essentially invalidate old cookies.
211
private final static int ENCODE_XORMASK = 0x5A;
212     private final static char ENCODE_DELIMETER = '\002';
213     private final static char ENCODE_CHAR_OFFSET1 = 'A';
214     private final static char ENCODE_CHAR_OFFSET2 = 'h';
215
216     /**
217      * Returns an Authorization token for the user. The following steps are
218      * performed to determine the token:<ol>
219      *
220      * <li>Check the session for the existence of a Yazd authorization token.
221      * If one is found, it is returned as we assume that the user has logged
222      * in and is authorized.
223      * <li>Check the Yazd authorization cookie for a username and password. If found,
224      * attempt to create a Yazd authorization token using that data. If
225      * successful, save the token to the session and return it.
226      * NOTE: This check can be skipped by setting
227      * <code>checkYazdCookie</code> to false.
228      * </ol><p>
229      *
230      * @param request the HttpServletRequest object, known as "request" in a
231      * JSP page.
232      * @param response the HttpServletResponse object, known as "response" in
233      * a JSP page.
234      * @param checkYazdCookie a boolean that indicates whether or not we want
235      * to use a cookie for authorization.
236      * @return the authorization token if authenticated, otherwise
237      * <code>null</code>.
238      * @see Authorization
239      */

240     public static Authorization getUserAuthorization(HttpServletRequest request,
241             HttpServletResponse response, boolean checkYazdCookie)
242     {
243         // we can get the session object from the request object:
244
HttpSession session = request.getSession();
245         //System.err.println("Aflatoon SkinUtils ID:"+session.getId());
246

247         // Check 1: check for the yazd authentication token in the user's session.
248
Authorization authToken = (Authorization)session.getAttribute(YAZD_AUTH_TOKEN);
249         if (authToken != null) {
250             sessionManager.addMessage(session.getId(),request.getRemoteAddr(),authToken.getUserID());
251             return authToken;
252         }
253
254         // Check 2: check the yazd cookie for username and password, if we're allowing that
255
if( checkYazdCookie ) {
256             Cookie cookie = getCookie(request, YAZD_AUTOLOGIN_COOKIE);
257             try {
258                 if( cookie != null ) {
259                     // at this point, we found a cookie so grab the username & password
260
// from it, create an authorization token and store that in the session
261
String JavaDoc[] values = decodePasswordCookie(cookie.getValue());
262                     String JavaDoc username = values[0];
263                     String JavaDoc password = values[1];
264                     // try to validate the user based on the info from the cookie
265
authToken = AuthorizationFactory.getAuthorization(username,password);
266
267                     // put that token in the user's session:
268
session.setAttribute( YAZD_AUTH_TOKEN, authToken );
269
270                     // return the authorization token
271
sessionManager.addMessage(session.getId(),request.getRemoteAddr(),authToken.getUserID());
272                     return authToken;
273                 }
274             }
275             catch( Exception JavaDoc e ) {
276                 //We want any exceptions in this block to be caught so that an
277
//anonymous authorization token can be returned. The
278
//getAuthorzation(username,password) method above throws an
279
//UnauthorizedException. In the case of this exception or others,
280
//the cookie holds invalid login info, so we should remove it:
281
cookie = new Cookie(YAZD_AUTOLOGIN_COOKIE,null);
282                 cookie.setMaxAge(0); // zero value causes cookie to be deleted
283
cookie.setPath("/");
284                 response.addCookie(cookie);
285             }
286         }
287
288         //Got this far, so return null.
289
sessionManager.addMessage(session.getId(),request.getRemoteAddr(),-1);
290         return null;
291     }
292
293     /**
294      * Returns an Authorization token for the user. This is a convenience method
295      * that that calls the other getUserAuthorization method with
296      * <code>checkYazdCookie</code set to true.
297      *
298      * @param request the HttpServletRequest object, known as "request" in a
299      * JSP page.
300      * @param response The HttpServletResponse object, known as "response" in
301      * a JSP page.
302      * @return The authorization token if authenticated, otherwise
303      * <code>null</code>.
304      * @see SkinUtils#getUserAuthorization(HttpServletRequest,HttpServletResponse,boolean)
305      */

306     public static Authorization getUserAuthorization
307             ( HttpServletRequest request, HttpServletResponse response )
308     {
309         return getUserAuthorization(request, response, true);
310     }
311
312     /**
313      * Validates the user and optionally enables auto-login by creating an
314      * auto-login cookie.
315      *
316      * @param request the HttpServletRequest object, known as "request" in a JSP page.
317      * @param response the HttpServletResponse object, known as "response" in a JSP page.
318      * @param username the username.
319      * @param password the password.
320      * @param autoLogin if <code>true</code> create a cookie that enables auto-login.
321      * @throws UserNotFoundException
322      * @throws UnauthorizedException
323      * @return The authorization token if authenticated, otherwise
324      * <code>null</code>
325      */

326     public static Authorization setUserAuthorization(HttpServletRequest request,
327             HttpServletResponse response, String JavaDoc username, String JavaDoc password,
328             boolean autoLogin) throws UserNotFoundException, UnauthorizedException
329     {
330         HttpSession session = request.getSession();
331         Authorization authToken = AuthorizationFactory.getAuthorization(username, password);
332         session.setAttribute(YAZD_AUTH_TOKEN, authToken);
333
334         if (autoLogin) {
335             Cookie cookie = new Cookie(YAZD_AUTOLOGIN_COOKIE, encodePasswordCookie(username, password));
336             cookie.setMaxAge(MAX_COOKIE_AGE);
337             cookie.setPath("/");
338             response.addCookie(cookie);
339         }
340
341         return authToken;
342     }
343
344     /**
345      * Invalidates the cookie that otherwise lets a user auto-login.
346      *
347      * @param request The HttpServletRequest object, known as "request" in a JSP page.
348      * @param response The HttpServletResponse object, known as "response" in a JSP page.
349      */

350     public static void removeUserAuthorization( HttpServletRequest request, HttpServletResponse response )
351     {
352         HttpSession session = request.getSession();
353         session.removeAttribute(YAZD_AUTH_TOKEN);
354         Cookie cookie = new Cookie(YAZD_AUTOLOGIN_COOKIE, null);
355         cookie.setMaxAge(0);
356         cookie.setPath("/");
357         response.addCookie(cookie);
358     }
359
360     /**
361      * Invalidate the specified cookie and delete it from the response object.
362      *
363      * @param request The HttpServletRequest object, known as "request" in a JSP page.
364      * @param response The HttpServletResponse object, known as "response" in a JSP page.
365      * @param cookieName The name of the cookie you want to delete.
366      */

367     public static void invalidateCookie( HttpServletRequest request, HttpServletResponse response, String JavaDoc cookieName ) {
368         Cookie cookie = new Cookie( cookieName, null ); // invalidate cookie
369
cookie.setMaxAge(0); // deletes cookie
370
cookie.setPath("/");
371         response.addCookie(cookie);
372     }
373
374     /**
375      * Persists a value for the length of the user's session.
376      *
377      * @see SkinUtils#store(HttpServletRequest,HttpServletResponse,String,String,int) store
378      */

379     public static void store( HttpServletRequest request, HttpServletResponse response,
380             String JavaDoc id, String JavaDoc value )
381     {
382         store( request,response,id,value,0,false );
383     }
384
385     /**
386      * Persists a value for the time (in seconds) specified
387      *
388      * @see SkinUtils#store(HttpServletRequest,HttpServletResponse,String,String,int) store
389      */

390     public static void store( HttpServletRequest request, HttpServletResponse response,
391             String JavaDoc id, String JavaDoc value, int secsToLive )
392     {
393         store( request,response,id,value,secsToLive,false );
394     }
395
396     /**
397      * This method should be used in a jsp skin to store an arbritary value.
398      * For example, we could persist the name of a user so that on a form page
399      * where they enter their name, that field could be auto-filled in with
400      * the stored value.
401      * <p>
402      * To indicate that the data should only be persisted for a session, pass
403      * in 0 as the <code>timeToLive</code>.
404      *
405      * @param request The HttpServletRequest object, known as "request" on a JSP page.
406      * @param response The HttpServletRequest object, known as "response" on a JSP page.
407      * @param id The name or identifier of the data you want to persist.
408      * @param value The value you wish to store.
409      * @param secsToLive The length (in seconds) this value will persist. Any value of 0 or
410      * less indicates this data should only persist for a session.
411      */

412     public static void store( HttpServletRequest request, HttpServletResponse response,
413             String JavaDoc id, String JavaDoc value, int secsToLive, boolean restoreInSession )
414     {
415         // This method uses sessions and cookies to persist data. We always store
416
// it in the user's session. We'll only set it in a cookie if the
417
// 'timeToLive' parameter is > 0.
418

419         // If the id is null, return
420
if( id == null ) {
421             return;
422         }
423
424         // Get the session object:
425
HttpSession session = request.getSession();
426
427         // check to see if the value already exists in the session -- if it does,
428
// don't restore it unless specified
429
if( ((String JavaDoc)session.getAttribute(id)) != null && !restoreInSession ) {
430             return;
431         }
432
433         // At this point, restore (or store for the first time) the value in the session
434
// Servlet API 2.1 call. Used to preserve compatibility with older app
435
// servers. You might get deprecation warnings.
436
session.setAttribute(id,value);
437
438         // if the timeToLive param is > 0, store to the cookie:
439
if( secsToLive > 0 ) {
440             Cookie cookie = new Cookie(id,value);
441             cookie.setMaxAge(secsToLive);
442             cookie.setPath("/");
443             response.addCookie(cookie);
444         }
445     }
446
447     /**
448      * Retrieves a user stored value. Values are set using the <code>store(...)</code>
449      * methods.
450      *
451      * @param request The HttpServletRequest object, known as "request" on a JSP page.
452      * @param response The HttpServletRequest object, known as "response" on a JSP page.
453      * @param id The id or name of the stored value.
454      * @return The value of the specified id, otherwise <code>null</code>.
455      */

456     public static String JavaDoc retrieve( HttpServletRequest request, HttpServletResponse response, String JavaDoc id ) {
457         // just retrieve the value, don't remove it from persistence
458
return( retrieve( request,response,id,false ) );
459     }
460
461     /**
462      * Retrieves a user stored value. Values are set using the <code>store(...)</code>
463      * methods. If <code>remove</code> is true, the value is also removed
464      * from persistence.
465      *
466      * @param request The HttpServletRequest object, known as "request" on a JSP page.
467      * @param response The HttpServletRequest object, known as "response" on a JSP page.
468      * @param id The id or name of the stored value.
469      * @return The value of the specified id, otherwise <code>null</code>.
470      */

471     public static String JavaDoc retrieve( HttpServletRequest request,
472             HttpServletResponse response, String JavaDoc id, boolean remove )
473     {
474         // First, check the session.
475
HttpSession session = request.getSession();
476         String JavaDoc value = (String JavaDoc)session.getAttribute(id);
477
478         // if it's not found, check the cookies
479
if( value == null ) {
480             value = getCookieValue(request,id);
481         }
482
483         // remove it from persistence if indicated
484
if( remove ) {
485             remove( request,response,id );
486         }
487
488         return value;
489     }
490
491     /**
492      * Removes a user stored value. Values are set using the <code>store(...)</code>
493      * methods.
494      *
495      * @param request the HttpServletRequest object, known as "request" on a JSP page.
496      * @param response the HttpServletRequest object, known as "response" on a JSP page.
497      * @param id the id or name of the stored value you wish to remove from persistence.
498      */

499     public static void remove( HttpServletRequest request, HttpServletResponse response, String JavaDoc id ) {
500         // First, remove it from the session:
501
HttpSession session = request.getSession();
502         session.removeAttribute(id);
503
504         // Invalidate the cookie by setting a null expired cookie in its place
505
Cookie cookie = new Cookie( id, null );
506         cookie.setMaxAge(0);
507         cookie.setPath("/");
508         response.addCookie(cookie);
509     }
510
511     /**
512      * Returns the time in milliseconds that the user last visited Yazd.
513      *
514      * @param request the HttpServletRequest object, known as "request" on a JSP page.
515      * @param response the HttpServletRequest object, known as "response" on a JSP page.
516      * @see SkinUtils#getLastVisited(HttpServletRequest,HttpServletResponse,boolean) getLastVisited
517      * @return The time (in milliseconds) that the suer last visited Yazd.
518      */

519     public static long getLastVisited(HttpServletRequest request,
520             HttpServletResponse response)
521     {
522         return getLastVisited(request,response,true);
523     }
524
525     /**
526      * Returns the time in milliseconds that the user last visited the Yazd system.
527      *
528      * @param request the HttpServletRequest object, known as "request" on a JSP page.
529      * @param response the HttpServletRequest object, known as "response" on a JSP page.
530      * @param updateLastVisitedTime Set to <code>true</code> if you wish to update
531      * the user's last visited time to the current time; set to <code>false</code> otherwise.
532      * @return The time (in milliseconds) that the suer last visited Yazd.
533      */

534     public static long getLastVisited(HttpServletRequest request,
535             HttpServletResponse response, boolean updateLastVisitedTime)
536     {
537         //Get session object
538
HttpSession session = request.getSession();
539
540         //The current instant in time.
541
long now = System.currentTimeMillis();
542
543         //First, try to retrieve the value from the session
544
String JavaDoc lastTime = (String JavaDoc)session.getAttribute(YAZD_LASTVISITED_TOKEN);
545
546         //Found a value in the session, so return it
547
if(lastTime != null) {
548             try {
549                 long time = Long.parseLong(lastTime);
550                 // update the last visited time to now, but don't update the
551
// last visited time in the session:
552
Cookie cookie = new Cookie(YAZD_LASTVISITED_TOKEN, Long.toString(now));
553                 cookie.setMaxAge(60*60*24*30);
554                 cookie.setPath("/");
555                 response.addCookie(cookie);
556                 // return the time value
557
return time;
558             }
559             catch(NumberFormatException JavaDoc e) {
560                 e.printStackTrace();
561             }
562         }
563
564         // getting to this point means no time value was found in the session,
565
// so look for it in the cookie:
566
long time = now;
567         lastTime = getCookieValue(request,YAZD_LASTVISITED_TOKEN);
568         if( lastTime != null ) {
569             try {
570                 time = Long.parseLong(lastTime);
571             } catch( NumberFormatException JavaDoc e ) {}
572         }
573
574          // set the value in the cookie, return the time
575
session.setAttribute(YAZD_LASTVISITED_TOKEN, Long.toString(time));
576         Cookie cookie = new Cookie(YAZD_LASTVISITED_TOKEN, Long.toString(now));
577         cookie.setMaxAge(60*60*24*30);
578         cookie.setPath("/");
579         response.addCookie(cookie);
580
581         return time;
582     }
583
584     /**
585      * Returns true if the message has been created or updated since
586      * the last time the user visisted.
587      *
588      * @param message the message to check.
589      * @param lastVisted the time the user last visisted the forum.
590      * @return true if the message has been created or updated since the user's
591      * last visit.
592      */

593     public static boolean isNewMessage(ForumMessage message, long lastVisited)
594     {
595         if (message.getModifiedDate().getTime() > lastVisited) {
596             return true;
597         }
598         else {
599             return false;
600         }
601     }
602
603     /**
604      * Returns the specified Cookie object, or null if the cookie does not exist.
605      *
606      * @param request The HttpServletRequest object, known as "request" in a
607      * JSP page.
608      * @param name the name of the cookie.
609      * @return the Cookie object if it exists, otherwise null.
610      */

611     public static Cookie getCookie( HttpServletRequest request, String JavaDoc name ) {
612         Cookie cookies[] = request.getCookies();
613         if(cookies == null || name == null || name.length() == 0) {
614             return null;
615         }
616         //Otherwise, we have to do a linear scan for the cookie.
617
for( int i = 0; i < cookies.length; i++ ) {
618             if(cookies[i].getName().equals(name) ) {
619                 return cookies[i];
620             }
621         }
622         return null;
623     }
624
625     /**
626      * Returns the value of the specified cookie as a String. If the cookie
627      * does not exist, the method returns null.
628      *
629      * @param request the HttpServletRequest object, known as "request" in a
630      * JSP page.
631      * @param name the name of the cookie
632      * @return the value of the cookie, or null if the cookie does not exist.
633      */

634     public static String JavaDoc getCookieValue(HttpServletRequest request, String JavaDoc name) {
635         Cookie cookie = getCookie(request,name);
636         if(cookie != null) {
637             return cookie.getValue();
638         }
639         return null;
640     }
641
642     /**
643      * Formats the unfiltered body of a message to make it appear in the "quote
644      * original" format. This is simply the body of the message with the
645      * delimiter appended to the beginning of each line. The delimiter
646      * is most often "> " by convention. A desired length for each line in the
647      * returned String can be specified to aid in formatting.<p>
648      *
649      * This method uses message.getUnfilteredBody() in order to get the body of
650      * the message. This usually yields better results for the formatting
651      * required by this method. However, it also has the potential of being
652      * a security risk if malicious HTML code is embedded in the body. Therefore,
653      * you should always filter HTML from the result of this method before
654      * showing it in an environment where HTML is interpreted. If you are
655      * showing the results of this method in an HTML &lt;textarea&gt;, there is
656      * no need to worry about malicious HTML.
657      *
658      * @param message the message to quote.
659      * @param delimiter a String that will start each line of the quoted
660      * message. For example, "> ";
661      * @param lineLength the desired length of each line in the quoted message.
662      * @return the unfiltered body of the message in the "quote original" format.
663      */

664     public static String JavaDoc quoteOriginal(String JavaDoc body, String JavaDoc delimiter,
665             int lineLength)
666     {
667         if (body == null || body.length() == 0) {
668             return "";
669         }
670         int length = body.length();
671         //Create a StringBuffer to hold the quoted body; approximate size.
672
StringBuffer JavaDoc buf = new StringBuffer JavaDoc(body.length());
673         //i maintains the current position in the String.
674
for (int i=0; i<length; ) {
675             String JavaDoc partialString =
676                 StringUtils.chopAtWord(
677                     body.substring(i),
678                     lineLength
679                 );
680             //System.out.println("--" + partialString);
681
i += partialString.length()+1;
682             buf.append(delimiter).append(partialString.trim()).append("\\n");
683         }
684         return buf.toString();
685     }
686
687     /**
688      * Returns a String describing the amount of time between now (current
689      * system time) and the passed in date time. Example output is "5 hours
690      * ago" or "Yesterday at 3:30 pm"
691      *
692      * @param date the Date to compare the current time with.
693      * @return a description of the difference in time, ie: "5 hours ago"
694      * or "Yesterday at 3:30pm"
695      */

696     public static String JavaDoc dateToText( Date JavaDoc date,Locale JavaDoc locale,TimeZone JavaDoc timezone ) {
697         if( date == null ) {
698             return "";
699         }
700
701         long delta = System.currentTimeMillis() - date.getTime();
702
703         // within the last hour
704
if( (delta / HOUR) < 1 ) {
705             long minutes = (delta/MINUTE);
706             if( minutes == 0 ) {
707                 return YazdLocale.getLocaleKey("Less_than_1_min_ago",locale);
708             }
709             else if( minutes == 1 ) {
710                 return YazdLocale.getLocaleKey("1_minute_ago",locale);
711             }
712             else {
713                 return ( minutes +" "+ YazdLocale.getLocaleKey("minutes_ago",locale) );
714             }
715         }
716
717         // sometime today
718
if( (delta / DAY) < 1 ) {
719             long hours = (delta/HOUR);
720             if( hours <= 1 ) {
721                 return YazdLocale.getLocaleKey("1_hour_ago",locale);
722             }
723             else {
724                 return ( hours + " "+YazdLocale.getLocaleKey("hours_ago",locale) );
725             }
726         }
727
728         // within the last week
729
if( (delta / WEEK) < 1 ) {
730             double days = ((double)delta/(double)DAY);
731             if( days <= 1.0 ) {
732                 SimpleDateFormat JavaDoc yestFormatter = new SimpleDateFormat JavaDoc("'"+YazdLocale.getLocaleKey("Yesterday_at",locale)+"' h:mm a",locale);
733                 return yestFormatter.format(date);
734             }
735             else {
736         SimpleDateFormat JavaDoc dateFormatter = new SimpleDateFormat JavaDoc("EEEE, MMM d '"+YazdLocale.getLocaleKey("at",locale)+"' h:mm a",locale);
737         dateFormatter.setTimeZone(timezone);
738                 return dateFormatter.format(date);
739             }
740         }
741
742         // before a week ago
743
else {
744         SimpleDateFormat JavaDoc dateFormatter = new SimpleDateFormat JavaDoc("EEEE, MMM d '"+YazdLocale.getLocaleKey("at",locale)+"' h:mm a",locale);
745         dateFormatter.setTimeZone(timezone);
746             return dateFormatter.format(date);
747         }
748     }
749
750     /**
751      * Returns true if the user is a system administrator.
752      *
753      * @param authToken the authentication token of the user
754      * @return true if the user is a system administrator, false otherwise.
755      */

756     public static boolean isSystemAdmin( Authorization authToken ) {
757         ForumFactory forumFactory = ForumFactory.getInstance(authToken);
758         ForumPermissions permissions = forumFactory.getPermissions(authToken);
759         return permissions.get(ForumPermissions.SYSTEM_ADMIN);
760     }
761
762     /**
763      * Returns true if the user is a forum adminstrator of any forum in the
764      * system. For example, if there are 3 forums in the system and the user
765      * is an adminstrator of any one or more of them, this method will return
766      * true.<p>
767      *
768      * Use the method <code>isForumAdmin( Authorization, Forum)</code> to
769      * check an individual forum for administrator status.)
770      *
771      * @param authToken the authentication token of the user
772      * @return true if the user is a forum administrator of any forum in the system.
773      * @see SkinUtils#isForumAdmin(Authorization, Forum)
774      */

775     public static boolean isForumAdmin( Authorization authToken ) {
776         ForumFactory forumFactory = ForumFactory.getInstance(authToken);
777         Iterator JavaDoc forumIterator = forumFactory.forums();
778         if( !forumIterator.hasNext() ) {
779             return false;
780         }
781         while( forumIterator.hasNext() ) {
782             Forum forum = (Forum)forumIterator.next();
783             if( forum.hasPermission(ForumPermissions.FORUM_ADMIN) ) {
784                 return true;
785             }
786         }
787         return false;
788     }
789
790     /**
791      * Returns true if the user is a forum moderator of any forum in the
792      * system. For example, if there are 3 forums in the system and the user
793      * is a moderator of any one or more of them, this method will return
794      * true.<p>
795      *
796      * Use the method <code>isForumModerator( Authorization, Forum)</code> to
797      * check an individual forum for moderator status.)
798      *
799      * @param authToken the authentication token of the user
800      * @return true if the user is a forum moderator of any forum in the system.
801      * @see SkinUtils#isForumModerator(Authorization, Forum)
802      */

803     public static boolean isForumModerator( Authorization authToken ) {
804         ForumFactory forumFactory = ForumFactory.getInstance(authToken);
805         Iterator JavaDoc forumIterator = forumFactory.forums();
806         if( !forumIterator.hasNext() ) {
807             return false;
808         }
809         while( forumIterator.hasNext() ) {
810             Forum forum = (Forum)forumIterator.next();
811             if( forum.hasPermission(ForumPermissions.MODERATOR) ) {
812                 return true;
813             }
814         }
815         return false;
816     }
817
818     /**
819      * Returns true if the user is a forum adminstrator of the given forum.
820      *
821      * @param authToken the authentication token of the user
822      * @param forum the forum to check administrator status on.
823      * @return true if the user is a forum administrator of the given forum.
824      */

825     public static boolean isForumAdmin( Authorization authToken, Forum forum ) {
826         return( forum.hasPermission(ForumPermissions.FORUM_ADMIN) );
827     }
828     /**
829      * Returns true if the user is a forum moderator of the given forum.
830      *
831      * @param authToken the authentication token of the user
832      * @param forum the forum to check moderator status on.
833      * @return true if the user is a forum moderator of the given forum.
834      */

835     public static boolean isForumModerator( Authorization authToken, Forum forum ) {
836         return( forum.hasPermission(ForumPermissions.MODERATOR) );
837     }
838
839     /**
840      * Returns true if the user is a group administrator of any group in the
841      * system. For example, if there are 3 groups in the system and the user
842      * is an adminstrator of any one or more of them, this method will return
843      * true.<p>
844      *
845      * Use the method <code>isGroupAdmin( Authorization, Group)</code> to check
846      * an individual group for administrator status.)
847      *
848      * @see SkinUtils#isGroupAdmin(Authorization, Group)
849      */

850     public static boolean isGroupAdmin( Authorization authToken ) {
851         ForumFactory forumFactory = ForumFactory.getInstance(authToken);
852         ProfileManager manager = forumFactory.getProfileManager();
853         Iterator JavaDoc groupIterator = manager.groups();
854         if( !groupIterator.hasNext() ) {
855             return false;
856         }
857         while( groupIterator.hasNext() ) {
858             Group group = (Group)groupIterator.next();
859             if( group.hasPermission(ForumPermissions.GROUP_ADMIN) ) {
860                 return true;
861             }
862         }
863         return false;
864     }
865
866     /**
867      * Returns true if the user is a group administrator of the given group.
868      *
869      * @param authToken the authentication token of the user
870      * @param group the group to check administrator status on.
871      * @return true if the user is a group administrator of the given group.
872      */

873     public static boolean isGroupAdmin( Authorization authToken, Group group ) {
874         return( group.hasPermission(ForumPermissions.GROUP_ADMIN) );
875     }
876
877     /**
878      * Builds a cookie string containing a username and password.<p>
879      *
880      * Note: with open source this is not really secure, but it prevents users
881      * from snooping the cookie file of others and by changing the XOR mask and
882      * character offsets, you can easily tweak results.
883      *
884      * @param username The username.
885      * @param password The password.
886      * @return String encoding the input parameters, an empty string if one of
887      * the arguments equals <code>null</code>.
888      */

889     private static String JavaDoc encodePasswordCookie (String JavaDoc username, String JavaDoc password)
890     {
891         StringBuffer JavaDoc buf = new StringBuffer JavaDoc();
892         if (username != null && password != null) {
893             byte[] bytes = (username + ENCODE_DELIMETER + password).getBytes();
894             int b;
895
896             for (int n = 0; n < bytes.length; n++) {
897                 b = bytes[n] ^ (ENCODE_XORMASK + n);
898                 buf.append((char)(ENCODE_CHAR_OFFSET1 + (b & 0x0F)));
899                 buf.append((char)(ENCODE_CHAR_OFFSET2 + ((b >> 4) & 0x0F)));
900             }
901         }
902         return buf.toString();
903     }
904
905     /**
906      * Unrafels a cookie string containing a username and password.
907      * @param value The cookie value.
908      * @return String[] containing the username at index 0 and the password at
909      * index 1, or <code>{ null, null }</code> if cookieVal equals
910      * <code>null</code> or the empty string.
911      */

912     private static String JavaDoc[] decodePasswordCookie( String JavaDoc cookieVal ) {
913
914         // check that the cookie value isn't null or zero-length
915
if( cookieVal == null || cookieVal.length() <= 0 ) {
916             return null;
917         }
918
919         // unrafel the cookie value
920
char[] chars = cookieVal.toCharArray();
921         byte[] bytes = new byte[chars.length / 2];
922         int b;
923         for (int n = 0, m = 0; n < bytes.length; n++) {
924             b = chars[m++] - ENCODE_CHAR_OFFSET1;
925             b |= (chars[m++] - ENCODE_CHAR_OFFSET2) << 4;
926             bytes[n] = (byte)(b ^ (ENCODE_XORMASK + n));
927         }
928         cookieVal = new String JavaDoc(bytes);
929         int pos = cookieVal.indexOf(ENCODE_DELIMETER);
930         String JavaDoc username = (pos < 0) ? "" : cookieVal.substring(0, pos);
931         String JavaDoc password = (pos < 0) ? "" : cookieVal.substring(pos + 1);
932
933         return new String JavaDoc[] { username, password };
934     }
935
936     /**
937      * test method for this class
938      */

939      /*
940     public static void main( String args[] ) {
941         Calendar cal = Calendar.getInstance();
942         System.out.println( "now:\t" + dateToText(cal.getTime()) );
943         for( int i=0; i<122; i++ ) {
944             cal.setTime( new Date(cal.getTime().getTime() - (30*MINUTE) ) );
945             System.out.println( (i+1) + " min ago:\t" + dateToText(cal.getTime()) + "\t" + cal.getTime() );
946         }
947     }
948     */

949     private static void UpdateSession(String JavaDoc sID,String JavaDoc ip, int uid){
950
951     }
952
953 }
954
Popular Tags