KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > jahia > params > ParamBean


1 //
2
// ____.
3
// __/\ ______| |__/\. _______
4
// __ .____| | \ | +----+ \
5
// _______| /--| | | - \ _ | : - \_________
6
// \\______: :---| : : | : | \________>
7
// |__\---\_____________:______: :____|____:_____\
8
// /_____|
9
//
10
// . . . i n j a h i a w e t r u s t . . .
11
//
12

13 //
14
// ParamBean
15
// EV 03.11.2000
16
// EV 23.12.2000 SettingsBean now in ParamBean
17
// SH 24.01.2001 added getSession accessor
18
// SH 24.01.2001 added some debugging code and some comments about comportement under Orion
19
// DJ 30.01.2001 added an internal wrapper for FileUpload/HttpServletRequest getParameter.
20
// SH 04.02.2001 added some comments on InputStream, Parameters, WebApps problems + javadoc
21
// MJ 21.03.2001 replaced basic URL parameters with PathInfo elements
22
// NK 17.04.2001 added Multisite features
23
// NK 14.05.2001 Jump to requested site's home page when the actual requested page is not of this site
24
// instead of page not found Exception.
25
// NK 11.07.2001 Added last requested page parameter
26
// JB 25.10.2001 Added setOperationMode methode
27
// SH 01.02.2002 Added defaultParameterValues hashtable to reduce URL length
28
// when using default values for engine names, operation
29
// modes, etc...
30
// FH 15.08.2003 - javadoc fixes
31
// - removed redundant class casting
32
// - removed unused private attribute
33
//
34
// Development notes : for the moment this class does not handle the problematic
35
// of reading an input stream multiple times. This can cause problems if for
36
// example Jahia needs to read the InputStream object from the request before
37
// forwarding it to a web application. Also, under some server implementations,
38
// such as the Orion server, retrieving an InputStream object before reading the
39
// parameters will cause an error when trying to call a getParameter method.
40
// The main issue of all this is that we are very dependant on the implementation
41
// of these methods right now. A solution that was studied involved writing
42
// parsers for the content of the request and managing the body internally inside
43
// Jahia. This is probably the most solid way to do it, but it involves a lot of
44
// development, especially since there should be a significant performance hit
45
// if not done fully.
46
// Basically the solution would be something like this :
47
// 1. Jahia retrieves the InputStream (or Reader) object
48
// 2. Jahia retrieves the full content and stores it either in memory or on disk
49
// depending on some criteria to be defined (size, type of request ?)
50
// 3. Jahia parses the parameters included in the request body, making sure it
51
// then uses only the result of that parsing internally
52
// 4. Jahia's dispatching service can then emulate a full web container behaviour
53
// without much problems, since it can intercept everything, include the request
54
// body (which is the part of the emulation currently missing). So the application
55
// could indeed retrieve an InputStream or a Reader that is passed the body only
56
// of that application and that comes from memory or disk storage instead of the
57
// socket.
58
//
59
// Advantages :
60
// - Allows for a FULL implementation of a request object
61
// - Allows Jahia and web applications to process the request multiple times
62
// - Improved security because we could only pass the body that concerns the
63
// web application.
64
//
65
// Disadvantages :
66
// - Serious performance hit because the worst case is : Jahia processes the
67
// request body, parses it, forwards it to the app, that reprocesses it again !
68
// The current case is : Jahia forwards it directly to the webapp, not reading
69
// it most of the time.
70
// - Loss of security because in some cases an application can receive a GET
71
// request that actually has the body of a POST request (this is because the
72
// emulation replaces the URL but not the body currently, mostly for performance
73
// reasons).
74
// - More usage of resources, since request bodies should have to be stored
75
// in memory and/or on disk, probably multiple times.
76
// The current decision was not to go forward with this implementation since it
77
// will involve a lot of work and that the benefits are dependant on the applications
78
// that must run under it. If the applications do not undergo problems in the
79
// meantime the current solution should be sufficient.
80
//
81

82 package org.jahia.params;
83
84 import java.io.File JavaDoc;
85 import java.io.IOException JavaDoc;
86 import java.net.URL JavaDoc;
87 import java.util.ArrayList JavaDoc;
88 import java.util.Date JavaDoc;
89 import java.util.Enumeration JavaDoc;
90 import java.util.HashMap JavaDoc;
91 import java.util.HashSet JavaDoc;
92 import java.util.Iterator JavaDoc;
93 import java.util.LinkedList JavaDoc;
94 import java.util.ListIterator JavaDoc;
95 import java.util.Locale JavaDoc;
96 import java.util.Map JavaDoc;
97 import java.util.NoSuchElementException JavaDoc;
98 import java.util.Properties JavaDoc;
99 import java.util.Set JavaDoc;
100 import java.util.StringTokenizer JavaDoc;
101 import java.util.Vector JavaDoc;
102
103 import javax.servlet.ServletContext JavaDoc;
104 import javax.servlet.http.HttpServletRequest JavaDoc;
105 import javax.servlet.http.HttpServletResponse JavaDoc;
106 import javax.servlet.http.HttpSession JavaDoc;
107 import javax.servlet.jsp.jstl.core.Config;
108
109 import org.apache.commons.httpclient.Header;
110 import org.apache.commons.httpclient.HttpClient;
111 import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
112 import org.apache.commons.httpclient.methods.GetMethod;
113 import org.apache.commons.lang.math.NumberUtils;
114 import org.apache.log4j.Logger;
115 import org.apache.struts.Globals;
116 import org.jahia.bin.Jahia;
117 import org.jahia.content.ContentPageKey;
118 import org.jahia.engines.login.Login_Engine;
119 import org.jahia.exceptions.JahiaException;
120 import org.jahia.exceptions.JahiaForbiddenAccessException;
121 import org.jahia.exceptions.JahiaInitializationException;
122 import org.jahia.exceptions.JahiaPageNotFoundException;
123 import org.jahia.exceptions.JahiaSessionExpirationException;
124 import org.jahia.exceptions.JahiaSiteNotFoundException;
125 import org.jahia.exceptions.JahiaSiteAndPageIDMismatchException;
126 import org.jahia.pipelines.Pipeline;
127 import org.jahia.pipelines.PipelineException;
128 import org.jahia.registries.ServicesRegistry;
129 import org.jahia.services.applications.JahiaApplicationsDispatchingService;
130 import org.jahia.services.applications.ServletIncludeRequestWrapper;
131 import org.jahia.services.applications.ServletIncludeResponseWrapper;
132 import org.jahia.services.cache.CacheFactory;
133 import org.jahia.services.cache.HtmlCache;
134 import org.jahia.services.fields.ContentField;
135 import org.jahia.services.lock.LockKey;
136 import org.jahia.services.lock.LockService;
137 import org.jahia.services.pages.ContentPage;
138 import org.jahia.services.pages.JahiaPage;
139 import org.jahia.services.pages.PageProperty;
140 import org.jahia.services.sites.JahiaSite;
141 import org.jahia.services.sites.SiteLanguageMapping;
142 import org.jahia.services.sites.SiteLanguageSettings;
143 import org.jahia.services.usermanager.JahiaUser;
144 import org.jahia.services.usermanager.JahiaUserManagerService;
145 import org.jahia.services.version.EntryLoadRequest;
146 import org.jahia.services.version.StateModificationContext;
147 import org.jahia.settings.SettingsBean;
148 import org.jahia.utils.JahiaTools;
149 import org.jahia.utils.LanguageCodeConverters;
150
151 /**
152  * This object contains most of the request context, including object such as
153  * the request and response objects, sessions, engines, contexts, ... It also
154  * contains methods for generating URLs for output generation.
155  *
156  * @author Eric Vassalli
157  * @author Khue NGuyen
158  * @author Fulco Houkes
159  * @author David Jilli
160  * @author Serge Huber
161  * @author Mikhael Janson
162  *
163  * @todo Implement a system to store parameters either in the session or in the
164  * URL, transparently, in order to generate short URLs
165  * @todo Implement static (or search engine) friendly URLs, such as .html ending
166  * URLs
167  */

168 public class ParamBean {
169
170     private static final Logger logger = Logger.getLogger(ParamBean.class);
171
172     public static final String JavaDoc ENGINE_NAME_PARAMETER = "engineName";
173
174     public static final String JavaDoc SITE_KEY_PARAMETER = "site";
175     public static final String JavaDoc PAGE_ID_PARAMETER = "pid"; // refers to the same as current page or new requested page
176
public static final String JavaDoc CONTAINERLIST_ID_PARAMETER = "clid";
177     public static final String JavaDoc CONTAINER_ID_PARAMETER = "cid";
178     public static final String JavaDoc FIELD_ID_PARAMETER = "fid";
179
180     public static final String JavaDoc OPERATION_MODE_PARAMETER = "op";
181     public static final String JavaDoc CACHE_MODE_PARAMETER = "cache";
182     public static final String JavaDoc ENTRY_STATE_PARAMETER = "entrystate";
183     public static final String JavaDoc SHOW_REVISION_DIFF_PARAMETER = "showrevdiff";
184     public static final String JavaDoc VALIDATE_PARAMETER = "validate";
185     public static final String JavaDoc CONTAINER_SCROLL_PREFIX_PARAMETER = "ctnscroll_";
186     public static final String JavaDoc LANGUAGE_CODE = "lang";
187     public static final String JavaDoc STEAL_LOCK = "stealLock";
188     public static final String JavaDoc RELEASE_LOCK = "releaseLock";
189     public static final String JavaDoc TEMPLATE_PARAMETER = "template";
190
191     public static final String JavaDoc DEFAULT_SITE_PROPERTY = "defaultSite";
192
193     /** default page id */
194     public static final String JavaDoc DEFAULT_PAGE_ID = "1";
195
196     /** Engine core name */
197     public static final String JavaDoc CORE_ENGINE_NAME = "core";
198     // private static final String XMLSOURCE_ENGINE_NAME = "xmlsource";
199

200     // http modes
201
public static final int GET_METHOD = 1;
202     public static final int POST_METHOD = 2;
203
204     // navigation operations
205
public static final String JavaDoc NORMAL = "normal"; // normal navigation
206
public static final String JavaDoc EDIT = "edit"; // edit navigation
207
public static final String JavaDoc DEBUG = "debug"; // debug navigation
208
public static final String JavaDoc PREVIEW = "preview"; // preview staging navigation
209
public static final String JavaDoc COMPARE = "compare"; // show difference between staging and active
210

211     // cache modes
212
public static final String JavaDoc CACHE_ON = "on";
213     public static final String JavaDoc CACHE_ONLYUPDATE = "onlyupdate"; // means we only want to update the cache, not read from it
214
public static final String JavaDoc CACHE_OFFONCE = "offonce"; // off only for the current request, all the generated URLs will be cached
215
public static final String JavaDoc CACHE_BYPASS = "bypass"; // the request will be done completely ignoring cache, but all the URLs will have the cache activated
216
public static final String JavaDoc CACHE_OFF = "off";
217     
218     // session names
219
public static final String JavaDoc SESSION_USER = "org.jahia.usermanager.jahiauser";
220     public static final String JavaDoc SESSION_SITE = "org.jahia.services.sites.jahiasite";
221     public static final String JavaDoc SESSION_DEFAULT_SITE = "org.jahia.services.sites.jahiadefaultsite";
222     public static final String JavaDoc SESSION_LAST_REQUESTED_PAGE_ID = "org.jahia.params.lastrequestedpageid";
223     public static final String JavaDoc SESSION_LAST_ENGINE_NAME = "org.jahia.engines.lastenginename";
224     public static final String JavaDoc SESSION_JAHIA_RUNNING_MODE = "org.jahia.bin.jahiarunningmode";
225     public static final String JavaDoc SESSION_JAHIA_ENGINEMAP = "jahia_session_engineMap";
226     public static final String JavaDoc SESSION_LOCALE = "org.jahia.services.multilang.currentlocale";
227
228     private static HttpClient httpClient;
229     private long startTime = 0;
230     private int httpMethod = 0;
231     private String JavaDoc engineName = "";
232     private int fieldID = 0;
233     private int containerID = 0;
234     private int containerListID = 0;
235     private String JavaDoc opMode = "";
236     private HttpServletRequest JavaDoc mRealRequest;
237     private ServletIncludeRequestWrapper mRequest;
238     private HttpServletResponse JavaDoc mRealResponse;
239     // The new mResponse format is used for content caching.
240
private ServletIncludeResponseWrapper mResponse = null;
241     private ServletContext JavaDoc context;
242     private JahiaPage thePage;
243     private ContentPage contentPage;
244     private JahiaUser theUser = null;
245     private String JavaDoc userAgent = "";
246     protected Locale JavaDoc currentLocale = null;
247     // a list of Locale objects that contains the current user preferences
248
protected ArrayList JavaDoc localeList = null;
249     // private int jahiaID = -1; // FIXME_MULTISITE Hollis: jahiaID = siteID
250
// redondant info
251
// DaDa'S requested a Server key in the Datasourcing context
252
// So Sirdrake what is your opinion ? It's your baby so choose
253
// and let me know.
254
private String JavaDoc anchor = null;
255     private int siteID = -1;
256     private String JavaDoc siteKey = null;
257     private JahiaSite site;
258     private boolean siteResolvedByKeyOrPageId;
259     private boolean contentPageLoadedWhileTryingToFindSiteByPageID;
260
261     /**
262      * @associates String
263      */

264     private Map JavaDoc customParameters = new HashMap JavaDoc();
265
266     private int lastRequestedPageID = 0;
267     private boolean newPageRequest = false; // true , if a new page is requested
268
private String JavaDoc lastEngineName = null;
269     private boolean engineHasChanged = false; // true , if the current engine differs with the previous engine
270
private String JavaDoc cacheStatus = CACHE_ON; // cache is activated by default.
271
private String JavaDoc originalCacheStatus = cacheStatus; // this represents the original request cache status.
272
private Date JavaDoc cacheExpirationDate = null; // the date at which the current page cache will expire.
273

274     protected EntryLoadRequest entryLoadRequest = EntryLoadRequest.CURRENT;
275
276     private EntryLoadRequest substituteEntryLoadRequest = null;
277
278     private static Properties JavaDoc defaultParameterValues; // stores the default values for parameters.
279

280     private boolean useQueryStringParameterUrl = false;
281
282     private int diffVersionID = 0;
283
284     private ArrayList JavaDoc pageURLKeys = new ArrayList JavaDoc();
285     private long delayFromNow = -1;
286     private String JavaDoc responseMimeType = "text/html";
287
288     static {
289         /**
290          * @todo we might want to put this in a configuration file so the
291          * administrator can change it.
292          */

293         // static constructor for defaultParameterValues;
294
defaultParameterValues = new Properties JavaDoc();
295         defaultParameterValues.setProperty(ParamBean.ENGINE_NAME_PARAMETER, ParamBean.CORE_ENGINE_NAME);
296         defaultParameterValues.setProperty(ParamBean.OPERATION_MODE_PARAMETER, ParamBean.NORMAL);
297         defaultParameterValues.setProperty(ParamBean.SITE_KEY_PARAMETER, "");
298         defaultParameterValues.setProperty(ParamBean.CACHE_MODE_PARAMETER, ParamBean.CACHE_ON);
299         // defaultParameterValues.setProperty(ParamBean.PAGE_ID_PARAMETER,
300
// ParamBean.DEFAULT_PAGE_ID); // doesn't work yet because of logout
301
// engine URL mess
302

303         MultiThreadedHttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager();
304         httpClient = new HttpClient(connectionManager);
305         httpClient.setConnectionTimeout(Jahia.getSettings().getSiteServerNameTestConnectTimeout());
306     }
307
308     /**
309      * Initializes an instance of this class. This constructor is required by
310      * the {@link SerializableParamBean}.
311      */

312     ParamBean() {
313         // do nothing
314
}
315
316     /**
317      * This constructor is used by AdminParamBean to create a ParamBean with the
318      * minimum data requirement needed to work within JahiaAdministration
319      * Servlet Do not use this constructor within Jahia Servlet
320      *
321      * @param request
322      * the HTTP request reference
323      * @param response
324      * the HTTP response reference
325      * @param aContext
326      * the servlet context reference
327      * @param jSettings
328      * the Jahia settings
329      * @param aStartTime
330      * the start time in milliseconds
331      * @param aHttpMethod
332      * @param aSite
333      * @param user
334      * @param aContentPage
335      * @throws JahiaPageNotFoundException
336      * when the requested page could not be found
337      * @throws JahiaSessionExpirationException
338      * when the user session expired
339      * @throws JahiaSiteNotFoundException
340      * when the specified site could not be found
341      * @throws JahiaException
342      * when a general internal exception occured
343      */

344     ParamBean(HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response, ServletContext JavaDoc aContext, SettingsBean jSettings,
345             long aStartTime, int aHttpMethod, JahiaSite aSite, JahiaUser user, ContentPage aContentPage)
346             throws JahiaPageNotFoundException, JahiaSessionExpirationException, JahiaSiteNotFoundException,
347             JahiaException {
348         // default vars
349
this.engineName = CORE_ENGINE_NAME;
350         this.opMode = NORMAL;
351
352         // main vars
353
mRealRequest = request;
354         mRealResponse = response;
355
356         // mResponse = new ServletIncludeResponseWrapper(response);
357

358         this.context = aContext;
359         this.startTime = aStartTime;
360         this.httpMethod = aHttpMethod;
361
362         this.site = aSite;
363         this.siteID = aSite.getID();
364         this.siteKey = aSite.getSiteKey();
365
366         entryLoadRequest = EntryLoadRequest.STAGED;
367
368         if (getRequest() != null) {
369             HttpSession JavaDoc session = getRequest().getSession();
370
371             // last requested page
372
Integer JavaDoc lrpID = (Integer JavaDoc) session.getAttribute(SESSION_LAST_REQUESTED_PAGE_ID);
373             if ((lrpID == null)) {
374                 lrpID = new Integer JavaDoc(-1);
375             }
376             this.newPageRequest = (lrpID.intValue() != this.getPageID());
377             this.lastRequestedPageID = lrpID.intValue();
378
379             // Get the current user out of the session. If there is no user
380
// present, then assign the guest user to this session.
381
theUser = (JahiaUser) session.getAttribute(SESSION_USER);
382             if (theUser == null) {
383                 setUserGuest(this.getSiteID());
384             }
385
386             Enumeration JavaDoc userAgentValues = getRequest().getHeaders("user-agent");
387             if (userAgentValues.hasMoreElements()) {
388                 // we only take the first value.
389
userAgent = (String JavaDoc) userAgentValues.nextElement();
390             }
391
392             // keep the last language
393
Locale JavaDoc lastLocale = (Locale JavaDoc) session.getAttribute(ParamBean.SESSION_LOCALE);
394             if (lastLocale != null) {
395                 this.changeLanguage(lastLocale);
396             }
397         } else {
398             theUser = user;
399             if (theUser == null) {
400                 setUserGuest(this.getSiteID());
401             }
402         }
403         if (aContentPage != null) {
404             thePage = aContentPage.getPage(this.getEntryLoadRequest(), this.getOperationMode(), this.getUser());
405         }
406     }
407
408     /***************************************************************************
409      * constructor EV 03.11.2000 EV 04.11.2000 now request object in parameters
410      * EV 05.11.2000 invalid page passed from critical to error EV 20.11.2000
411      * okay, everything changed... old framework, get a life
412      */

413     public ParamBean(HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response, ServletContext JavaDoc aContext,
414             SettingsBean jSettings, long aStartTime, int aHttpMethod) throws JahiaPageNotFoundException,
415             JahiaSessionExpirationException, JahiaSiteNotFoundException, JahiaException {
416         Jahia.setThreadParamBean(this);
417         this.engineName = CORE_ENGINE_NAME;
418         this.opMode = NORMAL;
419         mRealRequest = request;
420         mRealResponse = response;
421         // mResponse = new ServletIncludeResponseWrapper(response);
422
this.context = aContext;
423         this.startTime = aStartTime;
424         this.httpMethod = aHttpMethod;
425         HttpSession JavaDoc session = getRequest().getSession();
426         // activate the following code to test reading the request
427
// testInputReader();
428

429         buildCustomParameterMapFromPathInfo(getRequest());
430
431         setEngineNameIfAvailable();
432
433         if (findSiteFromWhatWeHave() == false) {
434             throw new JahiaSiteNotFoundException("400 Bad Request : No site specified or site not found",
435                     JahiaException.CRITICAL_SEVERITY);
436         }
437
438         // do perform this check only if Apache is used as a front server
439
if (request.getServerPort() == 80 || request.getServerPort() == 443) {
440             // check if the site key, resolved from request
441
// parameters (pageId, site key etc.) matches the key, resolved
442
// by the host name
443
if (siteResolvedByKeyOrPageId) {
444                 JahiaSite siteByHostName = getSiteByHostName();
445                 if (siteByHostName != null && !site.getSiteKey().equals(siteByHostName.getSiteKey())) {
446                     throw new JahiaSiteAndPageIDMismatchException(site.getSiteKey(), siteByHostName.getSiteKey(), request
447                             .getServerName());
448                 }
449             }
450         }
451
452         setSiteInfoFromSiteFound();
453
454         if (contentPageLoadedWhileTryingToFindSiteByPageID == false) {
455             if (isPageRequestedByID()) {
456                 setContentPageToPageWithID();
457             } else if (isPageRequestedByKey()) {
458                 setContentPageToPageWithURLKey();
459             } else {
460                 contentPage = site.getHomeContentPage();
461             }
462         }
463
464         resolveUser(request, session);
465
466         setUserAgent();
467
468         setFieldIDIfAvailable();
469
470         setContainerIDIfAvailable();
471
472         setContainerListIDIfAvailable();
473
474         resolveOpMode(session);
475
476         resolveLocales(session);
477
478         processLockAction(response, contentPage.getID());
479
480         String JavaDoc verInfo = resolveEntryState();
481
482         resolveDiffVersionID(verInfo);
483
484         checkLocales();
485
486         checkPageAccess(session, contentPage.getID());
487
488         switchUserToGuestUserIfSiteChangedAndCurrentUserDoesntHaveReadAccess();
489
490         loadJahiaPageFromContentPage();
491
492         this.lastEngineName = (String JavaDoc) session.getAttribute(SESSION_LAST_ENGINE_NAME);
493
494         this.engineHasChanged = (this.lastEngineName == null || !this.lastEngineName.equals(getEngine()));
495
496         resolveCacheStatus();
497
498         processActivationAction();
499     } // end constructor
500

501     /**
502      * If current user doesnt have read access to the page, switch user to guest
503      * user.
504      */

505     private void switchUserToGuestUserIfSiteChangedAndCurrentUserDoesntHaveReadAccess() throws JahiaException {
506         if (siteChanged() == false)
507             return;
508
509         if (doesUserHaveReadAccessToContentPage() == false) {
510             // switch to guest user
511
setUserGuest(getSiteID());
512         }
513     }
514
515     /**
516      * @return true if user have read access to the current content page.
517      */

518     private boolean doesUserHaveReadAccessToContentPage() {
519         return contentPage.checkReadAccess(getUser());
520     }
521
522     private void setContainerListIDIfAvailable() {
523         String JavaDoc containerListIDStr = getParameter(CONTAINERLIST_ID_PARAMETER);
524         if (containerListIDStr == null)
525             return;
526         try {
527             containerListID = Integer.parseInt(containerListIDStr);
528         } catch (NumberFormatException JavaDoc nfe) {
529             logger.warn("Invalid container list ID [" + containerListIDStr + "] specified in request, ignoring...");
530             containerListID = 0;
531         }
532     }
533
534     private void setFieldIDIfAvailable() {
535         String JavaDoc fieldIDStr = getParameter(FIELD_ID_PARAMETER);
536         if (fieldIDStr == null)
537             return;
538         try {
539             fieldID = Integer.parseInt(fieldIDStr);
540         } catch (NumberFormatException JavaDoc nfe) {
541             logger.warn("Invalid field ID [" + fieldIDStr + "] specified in request, ignoring...");
542             fieldID = 0;
543         }
544     }
545
546     /**
547      *
548      *
549      */

550     private void setContainerIDIfAvailable() {
551         String JavaDoc containerIDStr = getParameter(CONTAINER_ID_PARAMETER);
552         if (containerIDStr == null)
553             return;
554         try {
555             containerID = Integer.parseInt(containerIDStr);
556         } catch (NumberFormatException JavaDoc nfe) {
557             logger.warn("Invalid container ID [" + containerIDStr + "] specified in request, ignoring...");
558             containerID = 0;
559         }
560     }
561
562     /**
563      * Extract the user agent from request headers and set our instance var
564      * userAgent to only one value.???
565      */

566     private void setUserAgent() {
567         Enumeration JavaDoc userAgentValues = getRequest().getHeaders("user-agent");
568         if (userAgentValues.hasMoreElements()) {
569             // we only use the first value.
570
userAgent = (String JavaDoc) userAgentValues.nextElement();
571         }
572     }
573
574     /**
575      * Set instance var contentPage to loaded content page from page id
576      * specified in URL.
577      *
578      * @throws JahiaException
579      */

580     private void setContentPageToPageWithID() throws JahiaException {
581         int pageID = NumberUtils.stringToInt(getParameter(PAGE_ID_PARAMETER), 0);
582         contentPage = ServicesRegistry.getInstance().getJahiaPageService().lookupContentPage(pageID, true);
583     }
584
585     /**
586      * Retrieve page properties that have value equals to key specified in URL
587      * and the name PAGE_URL_KEY_PROPNAME. Multiple result can happen since an
588      * URL key is unique in only one site. Load page props that we want and get
589      * page associated with this property via the page cache. N.b: site must be
590      * resolved before calling this, since we need the siteID.
591      *
592      * @throws JahiaException
593      */

594     private void setContentPageToPageWithURLKey() throws JahiaException {
595         String JavaDoc pageURLKey = (String JavaDoc) pageURLKeys.get(pageURLKeys.size() - 1);
596         int pageID = ServicesRegistry.getInstance().getJahiaPageService().getPageIDFromPageKeyAndSiteID(pageURLKey,
597                 siteID);
598         contentPage = ContentPage.getPage(pageID);
599     }
600
601     /**
602      * Set siteHasChanged if old site ID isnt equal to current site ID or if old
603      * site isnt available.
604      */

605     private boolean siteChanged() {
606         JahiaSite oldSite = (JahiaSite) mRequest.getSession().getAttribute(SESSION_SITE);
607
608         if (oldSite == null) {
609             return true;
610         } else if (oldSite.getID() != site.getID()) {
611             return true;
612         } else {
613             return false;
614         }
615     }
616
617     /**
618      * Populate some variables from the site retrieved earlier ( this.site ).
619      */

620     private void setSiteInfoFromSiteFound() {
621         this.siteID = site.getID();
622         this.siteKey = site.getSiteKey();
623         mRequest.getSession().setAttribute(SESSION_SITE, site);
624
625         if (settings().isSiteIDInURL() == false) {
626             JahiaSite defaultSite = getDefaultSite();
627             if ((defaultSite != null) && (defaultSite.getID() == site.getID())) {
628                 // This line will cause jahia URL's generation to NOT include
629
// the site ID
630
ParamBean.defaultParameterValues.setProperty(ParamBean.SITE_KEY_PARAMETER, site.getSiteKey());
631             }
632         }
633     }
634
635     /**
636      * Try to find site via ... - site key - host name - page ID - default site -
637      * from session
638      *
639      * @return true if site was found.
640      */

641     private boolean findSiteFromWhatWeHave() throws JahiaException {
642         if (findSiteByItsKey()) {
643             return true;
644         } else if (isPageRequestedByID() && findSiteByPageID()) {
645             return true;
646         } else if (findSiteByHostName()) {
647             return true;
648         } else if (findSiteByRequestParam()) {
649             return true;
650         } else if (findSiteFromSession()) {
651             return true;
652         } else if (findDefaultSite()) {
653             return true;
654         }
655
656         return false;
657     }
658
659     private boolean findSiteFromSession() {
660         site = (JahiaSite) mRequest.getSession().getAttribute(SESSION_SITE);
661         if (site == null)
662             return false;
663         return true;
664     }
665
666     /**
667      * @return true if default site was found successfully.
668      */

669     private boolean findDefaultSite() {
670         logger.debug("No site found in URL, serverName or via page ID, trying default site...");
671         site = getDefaultSite();
672         if (site == null)
673             return false;
674         return true;
675     }
676
677     /**
678      * Tells if page id was passed in URL. ( Page requested by ID )
679      *
680      * @return true if PAGE_ID_PARAMETER is in URL and its a number bigger then
681      * 0.
682      */

683     private boolean isPageRequestedByID() {
684         String JavaDoc pageIDStr = getParameter(PAGE_ID_PARAMETER);
685         if (pageIDStr == null)
686             return false;
687         return NumberUtils.stringToInt(pageIDStr, 0) > 0;
688     }
689
690     /**
691      * @return true if page was requested by key.
692      */

693     private boolean isPageRequestedByKey() {
694         return isPageRequestedByID() == false && (pageURLKeys.size() > 0);
695     }
696
697     /**
698      * Find site via the page id. this.site will be set if its found.
699      *
700      * @return true if site was found using page id
701      * @throws JahiaException
702      */

703     private boolean findSiteByPageID() throws JahiaException {
704         int pageID = NumberUtils.stringToInt(getParameter(PAGE_ID_PARAMETER), 0);
705         contentPage = ServicesRegistry.getInstance().getJahiaPageService().lookupContentPage(pageID, true);
706         if (contentPage == null)
707             return false;
708
709         contentPageLoadedWhileTryingToFindSiteByPageID = true;
710         this.site = ServicesRegistry.getInstance().getJahiaSitesService().getSite(contentPage.getJahiaID());
711
712         if (site == null)
713             return false;
714
715         siteResolvedByKeyOrPageId = true;
716
717         return true;
718     }
719
720     /**
721      * Returns site by the host name.
722      *
723      * @return site by the host name
724      * @throws JahiaException
725      * in case of an error
726      */

727     private JahiaSite getSiteByHostName() throws JahiaException {
728         JahiaSite resolvedSite = null;
729         String JavaDoc serverName = getRequest().getServerName().toLowerCase();
730
731         if (isValidServerName(serverName)) {
732             resolvedSite = ServicesRegistry.getInstance().getJahiaSitesService().getSite(getRequest().getServerName());
733         }
734
735         return resolvedSite;
736     }
737
738     /**
739      * Find site by the host name. this.site will be set if its found.
740      *
741      * @return true if site was found from host name.
742      * @throws JahiaException
743      */

744     private boolean findSiteByHostName() throws JahiaException {
745         site = getSiteByHostName();
746
747         return (site != null);
748     }
749
750     /**
751      * @param serverName
752      * @return true if servername supplied is valid.
753      */

754     private boolean isValidServerName(String JavaDoc serverName) {
755         if (serverName == null)
756             return false;
757         if (serverName.equals("localhost"))
758             return false;
759         if (serverName.equals("127.0.0.1"))
760             return false;
761         return true;
762     }
763
764     /**
765      * Find site by its key. this.site will be set if its found.
766      *
767      * @return true if site was found from site key specified in url.
768      * @throws JahiaException
769      */

770     private boolean findSiteByItsKey() throws JahiaException {
771         if (!isSiteKeyPresent())
772             return false;
773         site = ServicesRegistry.getInstance().getJahiaSitesService().getSiteByKey(getParameter(SITE_KEY_PARAMETER));
774         if (site == null)
775             return false;
776         logger.debug("Found site info in parameters...");
777
778         siteResolvedByKeyOrPageId = true;
779
780         return true;
781     }
782
783     /**
784      * Find site by its key which is passed as arequest paramter with name
785      * "siteKey" this.site will be set if its found.
786      *
787      * @return true if site was found from site key specified in url.
788      * @throws JahiaException
789      */

790     private boolean findSiteByRequestParam() throws JahiaException {
791         String JavaDoc paramSiteKey = getRequest().getParameter("siteKey");
792
793         if (paramSiteKey == null || paramSiteKey.length() == 0)
794             return false;
795
796         this.site = ServicesRegistry.getInstance().getJahiaSitesService().getSiteByKey(paramSiteKey);
797
798         if (site == null)
799             return false;
800
801         logger.debug("Found site info in parameters...");
802
803         siteResolvedByKeyOrPageId = true;
804
805         return true;
806     }
807
808     private boolean isSiteKeyPresent() {
809         return getParameter(SITE_KEY_PARAMETER) != null;
810     }
811
812     /**
813      * Set the engine name if it was specified in request.
814      */

815     private void setEngineNameIfAvailable() {
816         if (getParameter(ENGINE_NAME_PARAMETER) == null)
817             return;
818         this.engineName = getParameter(ENGINE_NAME_PARAMETER);
819     }
820
821     // -------------------------------------------------------------------------
822
// DJ 08.02.2001
823
/**
824      * Sets the current user to GUEST, in the params and in the session. Also,
825      * comes back in NORMAL mode.
826      */

827     public void setUserGuest(int siteId) throws JahiaSessionExpirationException, JahiaException {
828         HttpSession JavaDoc session = getRequest().getSession(false);
829         if (session == null) {
830             throw new JahiaSessionExpirationException();
831         }
832
833         // get the User Manager service instance.
834
JahiaUserManagerService userMgr = ServicesRegistry.getInstance().getJahiaUserManagerService();
835         theUser = userMgr.lookupUser(siteId, JahiaUserManagerService.GUEST_USERNAME);
836         session.setAttribute(SESSION_USER, theUser);
837         setOperationMode(NORMAL);
838     }
839
840     /**
841      * Sets the current user, in the params and in the session. Also, comes back
842      * in NORMAL mode.
843      */

844     public void setUser(JahiaUser user) throws JahiaSessionExpirationException, JahiaException {
845         HttpSession JavaDoc session = getRequest().getSession(false);
846         if (session == null) {
847             throw new JahiaSessionExpirationException();
848         }
849
850         theUser = user;
851         session.setAttribute(SESSION_USER, theUser);
852         flushLocaleListCache();
853         this.entryLoadRequest.setLocales(getLocales());
854         setOperationMode(NORMAL);
855     }
856
857     /***************************************************************************
858      * accessor methods EV 03.11.2000
859      */

860     public SettingsBean settings() {
861         return Jahia.getSettings();
862     }
863
864     public HttpServletRequest JavaDoc getRequest() {
865         return getRequestWrapper();
866     }
867
868     public ServletIncludeRequestWrapper getRequestWrapper() {
869         if (mRequest == null) {
870             HttpServletRequest JavaDoc request = getRealRequest();
871             if (request != null)
872                 mRequest = new ServletIncludeRequestWrapper(request, this);
873         }
874         return mRequest;
875     }
876
877     public HttpServletRequest JavaDoc getRealRequest() {
878         return mRealRequest;
879     }
880
881     public ServletIncludeResponseWrapper getResponseWrapper() {
882         if (mResponse == null) {
883             String JavaDoc forceEncoding = null;
884             if (settings().isUtf8Encoding()) {
885                 forceEncoding = "UTF-8";
886             }
887             mResponse = new ServletIncludeResponseWrapper(getRealResponse(), true, forceEncoding);
888         }
889         return mResponse;
890     }
891
892     public HttpServletResponse JavaDoc getResponse() {
893         return getResponseWrapper();
894     }
895
896     public HttpServletResponse JavaDoc getRealResponse() {
897         return mRealResponse;
898     }
899
900     public ServletContext JavaDoc getContext() {
901         return context;
902     }
903
904     public int getHttpMethod() {
905         return httpMethod;
906     }
907
908     public long getStartTime() {
909         return startTime;
910     }
911
912     public String JavaDoc getEngine() {
913         return engineName;
914     }
915
916     public String JavaDoc getOperationMode() {
917         return opMode;
918     }
919
920     public ContentPage getContentPage() {
921         return contentPage;
922     }
923
924     public JahiaPage getPage() {
925         return thePage;
926     }
927
928     public int getPageID() {
929         if (contentPage == null)
930             return -1;
931         return contentPage.getID();
932     }
933
934     public int getLastRequestedPageID() {
935         return lastRequestedPageID;
936     }
937
938     public boolean newPageRequest() {
939         return newPageRequest;
940     }
941
942     public String JavaDoc getLastEngineName() {
943         return lastEngineName;
944     }
945
946     public boolean engineHasChanged() {
947         return engineHasChanged;
948     }
949
950     public JahiaUser getUser() {
951         return theUser;
952     }
953
954     public String JavaDoc getUserAgent() {
955         return userAgent;
956     }
957
958     public int getFieldID() {
959         return fieldID;
960     }
961
962     public int getContainerID() {
963         return containerID;
964     }
965
966     public int getContainerListID() {
967         return containerListID;
968     }
969
970     public int getSiteID() {
971         return siteID;
972     }
973
974     public String JavaDoc getSiteKey() {
975         return siteKey;
976     }
977
978     public int getJahiaID() {
979         return getSiteID();
980     } // Hollis : For backward compatibility, but ...
981

982     public JahiaSite getSite() {
983         return site;
984     }
985
986     public EntryLoadRequest getEntryLoadRequest() {
987         if (substituteEntryLoadRequest != null) {
988             return substituteEntryLoadRequest;
989         } else {
990             return entryLoadRequest;
991         }
992     }
993
994     public void setSubstituteEntryLoadRequest(EntryLoadRequest anEntryLoadRequest) {
995         this.substituteEntryLoadRequest = anEntryLoadRequest;
996     }
997
998     public void resetSubstituteEntryLoadRequest() {
999         this.substituteEntryLoadRequest = null;
1000    }
1001
1002    public int getDiffVersionID() {
1003        return this.diffVersionID;
1004    }
1005
1006    public boolean showRevisionDiff() {
1007        return (this.diffVersionID != 0);
1008    }
1009
1010    // @author Serge Huber shuber@jahia.org
1011
/**
1012     * Returns the current cache status mode. The caching mode may be specified
1013     * in the request URL by specifying the following : /cache/on,
1014     * /cache/onlyupdate, /cache/offonce, /cache/bypass, /cache/off. If it isn't
1015     * specified in the URL the default mode is /cache/on. It may also be
1016     * changed during a request by the setCacheStatus call in order to control
1017     * the ParamBean's URL generation code. In order to retrieve the original
1018     * request cache status mode, see the getOriginalCacheStatus method.
1019     *
1020     * @return a String of one of the following values : ParamBean.CACHE_ON
1021     * meaning the caching system should be fully active caching and
1022     * updating cache, ParamBean.CACHE_ONLYUPDATE meaning only the
1023     * updates in the cache are made but every request to a page will be
1024     * fully processed without looking up in the cache first,
1025     * ParamBean.CACHE_OFFONCE meaning that the cache is deactivated for
1026     * this request ONLY but that the result of the request will be
1027     * stored in the cache nonetheless. All the generated URLs will be
1028     * set to the CACHE_ON value, ParamBean.CACHE_BYPASS meaning that
1029     * the cache is deactivated for this request ONLY and the output of
1030     * the request will not be stored in the cache. All the generated
1031     * URLs will be set to the CACHE_ON value, ParamBean.CACHE_OFF
1032     * meaning the caching system is completely bypassed and not at all
1033     * processed, and all the generated URLs will have a CACHE_OFF
1034     * parameter
1035     */

1036    public String JavaDoc getCacheStatus() {
1037        return cacheStatus;
1038    }
1039
1040    // @author Serge Huber shuber@jahia.org
1041
/**
1042     * Returns the original cache status request mode. This method returns the
1043     * cache status as it was specified in the request URL or the default value,
1044     * ignoring all the current cache status that could have been set by the
1045     * setCacheStatus method. The caching mode may be specified in the request
1046     * URL by specifying the following : /cache/on, /cache/onlyupdate,
1047     * /cache/offonce, /cache/bypass, /cache/off. If it isn't specified in the
1048     * URL the default mode is /cache/on
1049     *
1050     * @return a String of one of the following values : ParamBean.CACHE_ON
1051     * meaning the caching system should be fully active caching and
1052     * updating cache, ParamBean.CACHE_ONLYUPDATE meaning only the
1053     * updates in the cache are made but every request to a page will be
1054     * fully processed without looking up in the cache first,
1055     * ParamBean.CACHE_OFFONCE meaning that the cache is deactivated for
1056     * this request ONLY but that the result of the request will be
1057     * stored in the cache nonetheless. All the generated URLs will be
1058     * set to the CACHE_ON value, ParamBean.CACHE_BYPASS meaning that
1059     * the cache is deactivated for this request ONLY and the output of
1060     * the request will not be stored in the cache. All the generated
1061     * URLs will be set to the CACHE_ON value, ParamBean.CACHE_OFF
1062     * meaning the caching system is completely bypassed and not at all
1063     * processed, and all the generated URLs will have a CACHE_OFF
1064     * parameter
1065     */

1066    public String JavaDoc getOriginalCacheStatus() {
1067        return originalCacheStatus;
1068    }
1069
1070    // @author Jerome Bedat
1071
/**
1072     * Sets the Operation Mode for this request to the specified value.
1073     */

1074    public void setOperationMode(String JavaDoc newOperationMode) throws JahiaException {
1075        opMode = newOperationMode;
1076        EntryLoadRequest newLoadRequest = new EntryLoadRequest(EntryLoadRequest.ACTIVE_WORKFLOW_STATE, 0, getLocales());
1077        // compute version info
1078
if (this.getSiteID() != -1) {
1079            if ((opMode == EDIT || opMode == PREVIEW || opMode == COMPARE)
1080                    && (ServicesRegistry.getInstance().getJahiaVersionService().isStagingEnabled(this.getSiteID()))) {
1081                newLoadRequest = new EntryLoadRequest(EntryLoadRequest.STAGING_WORKFLOW_STATE, 0, getLocales());
1082                // this.cacheStatus = ParamBean.CACHE_OFF; deactivated because
1083
// we can't see a reason to have this here.
1084
}
1085        }
1086        if (opMode == COMPARE) {
1087            newLoadRequest.setWithMarkedForDeletion(true);
1088        }
1089        if (this.entryLoadRequest.getWorkflowState() > 0) {
1090            this.entryLoadRequest = newLoadRequest;
1091        }
1092    }
1093
1094    /**
1095     * Sets the cacheStatus for this request to the specified value. Be careful
1096     * when using this setter. If you generate URLs before you set this value,
1097     * they will differ from the ones after this call has been made.
1098     *
1099     * @param newCacheStatus
1100     * may have only a value of ParamBean.CACHE_ON,
1101     * ParamBean.CACHE_ONLYUPDATE, ParamBean.CACHE_OFFONCE,
1102     * ParamBean.CACHE_BYPASS, ParamBean.CACHE_OFF. Any other value
1103     * will not be set, and the call will return a false value.
1104     * @return true if the new status has an acceptable value, false otherwise
1105     */

1106    public boolean setCacheStatus(String JavaDoc newCacheStatus) {
1107        if (ParamBean.CACHE_ON.equals(newCacheStatus) || ParamBean.CACHE_ONLYUPDATE.equals(newCacheStatus)
1108                || ParamBean.CACHE_OFFONCE.equals(newCacheStatus) || ParamBean.CACHE_BYPASS.equals(newCacheStatus)
1109                || ParamBean.CACHE_OFF.equals(newCacheStatus)) {
1110            this.cacheStatus = newCacheStatus;
1111            return true;
1112        } else {
1113            return false;
1114        }
1115    }
1116
1117    // -------------------------------------------------------------------------
1118
// @author NK
1119
/**
1120     * Return true if the current user is an admin member of the current site
1121     *
1122     * @return boolean
1123     */

1124    public boolean userIsAdmin() {
1125
1126        return getUser().isAdminMember(getSiteID());
1127
1128    }
1129
1130    // -------------------------------------------------------------------------
1131
// @author Khue NGuyen
1132
/**
1133     * Return the current mode in which Jahia is running. There is two main mode
1134     * in which Jahia is running JahiaInterface.CORE_MODE or
1135     * JahiaInterface.ADMIN_MODE ( we are in administration mode ) Return -1 if
1136     * not defined This mode is stored in the session as an attribute with the
1137     * name : ParamBean.SESSION_JAHIA_RUNNING_MODE
1138     *
1139     * @see org.jahia.bin.JahiaInterface#ADMIN_MODE
1140     * @see org.jahia.bin.JahiaInterface#CORE_MODE
1141     * @return int the Jahia running mode or -1 if not defined.
1142     * @exception JahiaSessionExpirationException
1143     * Throw this exception when the session is null. This
1144     * happens usually when the session expired.
1145     */

1146
1147    public int getJahiaRunningMode() throws JahiaSessionExpirationException {
1148        HttpSession JavaDoc session = getRequest().getSession(false);
1149        if (session == null) {
1150            throw new JahiaSessionExpirationException();
1151        }
1152        Integer JavaDoc I = (Integer JavaDoc) session.getAttribute(SESSION_JAHIA_RUNNING_MODE);
1153        if (I == null)
1154            return -1;
1155        return I.intValue();
1156    }
1157
1158    // -------------------------------------------------------------------------
1159
// @author Khue NGuyen
1160
/**
1161     * Return true if the current running mode is JahiaInterface.ADMIN_MODE ( we
1162     * are in administration mode ).
1163     *
1164     * @see org.jahia.bin.JahiaInterface#ADMIN_MODE
1165     * @see org.jahia.bin.JahiaInterface#CORE_MODE
1166     * @return boolean
1167     * @exception JahiaSessionExpirationException
1168     * Throw this exception when the session is null. This
1169     * happens usually when the session expired.
1170     */

1171
1172    public final boolean isInAdminMode() throws JahiaSessionExpirationException {
1173        HttpSession JavaDoc session = getRequest().getSession(false);
1174        if (session == null) {
1175            throw new JahiaSessionExpirationException();
1176        }
1177        Integer JavaDoc I = (Integer JavaDoc) session.getAttribute(SESSION_JAHIA_RUNNING_MODE);
1178        if (I == null)
1179            return false;
1180        return (I.intValue() == Jahia.ADMIN_MODE);
1181    }
1182
1183    // -------------------------------------------------------------------------
1184
/**
1185     * Return the session ID.
1186     *
1187     * @return Return the session ID.
1188     * @exception JahiaSessionExpirationException
1189     * Throw this exception when the session is null. This
1190     * happens usually when the session expired.
1191     */

1192    public String JavaDoc getSessionID() throws JahiaSessionExpirationException {
1193        HttpSession JavaDoc session = getRequest().getSession(false);
1194        if (session == null) {
1195            throw new JahiaSessionExpirationException();
1196        }
1197        return session.getId();
1198    }
1199
1200    // -------------------------------------------------------------------------
1201
/**
1202     * Return the reference on the current session.
1203     *
1204     * @return Return the session reference.
1205     * @exception JahiaSessionExpirationException
1206     * Throw this exception when the session is null. This
1207     * happens usually when the session expired.
1208     */

1209
1210    public HttpSession JavaDoc getSession() throws JahiaSessionExpirationException {
1211        HttpSession JavaDoc session = getRequest().getSession(false);
1212        if (session == null) {
1213            throw new JahiaSessionExpirationException();
1214        }
1215        return session;
1216    }
1217
1218    // -------------------------------------------------------------------------
1219
/**
1220     * Return the reference on the current session.
1221     *
1222     * @return Return the session reference.
1223     * @exception JahiaSessionExpirationException
1224     * Throw this exception when the session is null. This
1225     * happens usually when the session expired.
1226     */

1227
1228    public HttpSession JavaDoc getSession(boolean create) throws JahiaSessionExpirationException {
1229        HttpSession JavaDoc session = getRequest().getSession(create);
1230        if (session == null)
1231            throw new JahiaSessionExpirationException();
1232        return session;
1233    }
1234
1235    // -------------------------------------------------------------------------
1236
/**
1237     * Invalidates the current session and replaces it with a new one, avoiding
1238     * a call to getSession for the Jahia developper.
1239     */

1240    public void invalidateSession() throws JahiaSessionExpirationException {
1241        HttpSession JavaDoc session = getRequest().getSession(false);
1242        if (session == null) {
1243            throw new JahiaSessionExpirationException();
1244        }
1245
1246        session.invalidate();
1247        session = getRequest().getSession(true);
1248    }
1249
1250    /**
1251     * Removes all objects that are stored in the session, but does NOT call a
1252     * session.invalidate. This should work better for login / logout.
1253     *
1254     * @throws JahiaSessionExpirationException
1255     * if the session cannot be retrieved from the request object.
1256     */

1257    public void purgeSession() throws JahiaSessionExpirationException {
1258        HttpSession JavaDoc session = getRequest().getSession(false);
1259        if (session == null) {
1260            throw new JahiaSessionExpirationException();
1261        }
1262
1263        logger.debug("Purging session of all objects...");
1264
1265        // a little hack to be able to remove objects later, because during an
1266
// enumeration we can't remove objects.
1267
Enumeration JavaDoc attributeNamesEnum = session.getAttributeNames();
1268        Vector JavaDoc attributeNames = new Vector JavaDoc();
1269        while (attributeNamesEnum.hasMoreElements()) {
1270            String JavaDoc curAttributeName = (String JavaDoc) attributeNamesEnum.nextElement();
1271            attributeNames.add(curAttributeName);
1272        }
1273
1274        attributeNamesEnum = attributeNames.elements();
1275        while (attributeNamesEnum.hasMoreElements()) {
1276            String JavaDoc curAttributeName = (String JavaDoc) attributeNamesEnum.nextElement();
1277            /*
1278             * logger.debug("Removing attribute " + curAttributeName + " from
1279             * session " + session.getId());
1280             */

1281            session.removeAttribute(curAttributeName);
1282        }
1283
1284        // keep the last language
1285
session.setAttribute(ParamBean.SESSION_LOCALE, this.currentLocale);
1286        // added by PAP: for Struts and JSTL applications
1287
session.setAttribute(Globals.LOCALE_KEY, this.currentLocale);
1288        Config.set(session, Config.FMT_LOCALE, this.currentLocale);
1289
1290    }
1291
1292    /**
1293     * The purpose of this method is to quickly test if the localeList is empty,
1294     * and in that case to insert a "default" locale so that we never return an
1295     * empty list.
1296     *
1297     * @param locales
1298     */

1299    private void testLocaleList(ArrayList JavaDoc locales, boolean isMixLanguageActive) throws JahiaException {
1300        if (locales != null) {
1301            if (locales.size() == 1 && locales.get(0).toString().equals(ContentField.SHARED_LANGUAGE)
1302                    && this.getSite().getLanguageSettings().size() == 0) {
1303                // let's add the default locale as english a last resort locale
1304
// SettingsBean settings = Jahia.getSettings();
1305
SettingsBean settings = Jahia.getSettings();
1306                if (settings != null) {
1307                    logger.debug("Using jahia.properties default language code : " + settings.getDefaultLanguageCode());
1308                    locales.add(LanguageCodeConverters.languageCodeToLocale(settings.getDefaultLanguageCode()));
1309                } else {
1310                    logger
1311                            .warn("Warning : Couldn't find default language settings in jahia.properties, using english as default locale");
1312                    locales.add(Locale.ENGLISH);
1313                }
1314            }
1315            if (locales.size() == 0 || !locales.get(0).toString().equals(ContentField.SHARED_LANGUAGE)) {
1316                locales.add(0, new Locale JavaDoc(ContentField.SHARED_LANGUAGE, ""));
1317            }
1318            if (!isMixLanguageActive) {
1319                // we must now check the length of the locale list. It should
1320
// only have two elements. The shared language and the current
1321
// language.
1322
if (locales.size() > 2) {
1323                    ArrayList JavaDoc newLocaleList = new ArrayList JavaDoc();
1324                    newLocaleList.add(locales.get(0));
1325                    newLocaleList.add(locales.get(1));
1326                    locales.clear();
1327                    locales.addAll(newLocaleList);
1328                }
1329            }
1330            // now let's insert the locale mappings in the list so that we
1331
// make sure we match all the site defined languages.
1332
locales = insertLocaleMappings(locales);
1333        }
1334    }
1335
1336    /**
1337     * Inserts all the mappings just after the languages if we have them for the
1338     * languages. Basically if we have the following mappings : fr -> fr_CH en ->
1339     * en_US and in the locale list we have : fr en en_US the locale list will
1340     * be completed to become : fr fr_CH en en_US
1341     *
1342     * @param source
1343     * the source array list without the mappings inserted.
1344     * @return an array list of Locales including the mappings. This is only
1345     * possible if the site has already been resolved. Otherwise the
1346     * locale list is returned unmodified.
1347     */

1348    private ArrayList JavaDoc insertLocaleMappings(ArrayList JavaDoc source) {
1349        ArrayList JavaDoc result = new ArrayList JavaDoc();
1350        if (site == null) {
1351            logger.debug("Site unknown, can't add mappings...");
1352            return source;
1353        }
1354        Vector JavaDoc languageMappings;
1355        try {
1356            languageMappings = site.getLanguageMappings();
1357        } catch (JahiaException je) {
1358            logger.debug("Error while retrieving site mappings, returning unmodified locale list.", je);
1359            return source;
1360        }
1361
1362        // we quickly build a hashtable of the mappings in order to be able
1363
// to do faster lookups.
1364
Map JavaDoc languageMappingsHashtable = new HashMap JavaDoc();
1365        Enumeration JavaDoc mappingsEnum = languageMappings.elements();
1366        while (mappingsEnum.hasMoreElements()) {
1367            SiteLanguageMapping curMapping = (SiteLanguageMapping) mappingsEnum.nextElement();
1368            languageMappingsHashtable.put(curMapping.getFromLanguageCode(), curMapping);
1369        }
1370
1371        // now let's build the new array list by inserting the mappings
1372
// immediately after the language, or not at all if the next entry is
1373
// already the mapped target language or if it was previously in the
1374
// list in a higher priority level.
1375
Set JavaDoc previousLocales = new HashSet JavaDoc();
1376        ListIterator JavaDoc sourceIter = source.listIterator();
1377        while (sourceIter.hasNext()) {
1378            Locale JavaDoc curSourceLocale = (Locale JavaDoc) sourceIter.next();
1379            // let's copy the locale to the result.
1380
result.add(curSourceLocale);
1381            previousLocales.add(curSourceLocale.toString());
1382            if (curSourceLocale.getCountry().equals("")) {
1383                // no country, let's see if we have a mapping for this locale.
1384
if (languageMappingsHashtable.containsKey(curSourceLocale.getLanguage())) {
1385                    SiteLanguageMapping curMapping = (SiteLanguageMapping) languageMappingsHashtable
1386                            .get(curSourceLocale.getLanguage());
1387                    Locale JavaDoc targetLocale = LanguageCodeConverters.languageCodeToLocale(curMapping.getToLanguageCode());
1388                    // yes, let's see if we can insert it by testing the next
1389
// element if it exists to see if it matches the target
1390
// locale of this mapping.
1391
if (sourceIter.hasNext()) {
1392                        Locale JavaDoc nextSourceLocale = (Locale JavaDoc) sourceIter.next();
1393                        if (!nextSourceLocale.equals(targetLocale)
1394                                && !previousLocales.contains(targetLocale.toString())) {
1395                            result.add(targetLocale);
1396                            previousLocales.add(targetLocale.toString());
1397                        } else {
1398                            logger.debug("Not inserting locale " + targetLocale.toString()
1399                                    + " since it already exists in locale list...");
1400                        }
1401                        // let's restore the position to the current element.
1402
sourceIter.previous();
1403                    } else {
1404                        // we are at the end of the list, and we never had it
1405
// before, let's add it.
1406
if (!previousLocales.contains(targetLocale.toString())) {
1407                            result.add(targetLocale);
1408                            previousLocales.add(targetLocale.toString());
1409                        } else {
1410                            logger.debug("Not inserting locale " + targetLocale.toString()
1411                                    + " since it already exists in locale list...");
1412                        }
1413                    }
1414                }
1415            }
1416        }
1417
1418        return result;
1419    }
1420
1421    /**
1422     * Change the current Locale Reinit the locales list and the entry load
1423     * request too !
1424     *
1425     * @param locale
1426     */

1427    public void changeLanguage(Locale JavaDoc locale) throws JahiaSessionExpirationException, JahiaException {
1428        if (locale == null) {
1429            return;
1430        }
1431
1432        // reset the locales
1433
this.localeList = null;
1434        this.getSession().setAttribute(SESSION_LOCALE, locale);
1435        this.entryLoadRequest = new EntryLoadRequest(this.entryLoadRequest.getWorkflowState(), this.entryLoadRequest
1436                .getVersionID(), this.getLocales());
1437        this.resetSubstituteEntryLoadRequest();
1438        this.setParameter(ParamBean.LANGUAGE_CODE, this.currentLocale.toString());
1439
1440        // added by PAP: for Struts and JSTL applications
1441
this.getSession().setAttribute(Globals.LOCALE_KEY, locale);
1442        Config.set(this.getSession(), Config.FMT_LOCALE, locale);
1443
1444    }
1445
1446    /**
1447     * Jahia's redefinition of the Servlet APIs getLocales code. This method
1448     * actually builds a list that is a concatenation of multiple sources :
1449     *
1450     * 1. the session locale representing the locales the user has chosen to
1451     * surf with 2. the list of locales extracted from the users' preferences 3.
1452     * the list of locales extracted from the browser settings 4. the list of
1453     * locales that are setup in the site settings
1454     *
1455     * The construction of this list should be configurable, notably to be able
1456     * from the site settings to say that we want to avoid mixing languages, or
1457     * that the user never wants to see languages that are not in his settings.
1458     *
1459     * Warning, this method supposes that the current data has been already
1460     * initialized and is available : - JahiaSite - JahiaUser - Session
1461     *
1462     * @return an ArrayList of Locale objects that contain the list of locale
1463     * that are active for the current session, user and site.
1464     */

1465    public ArrayList JavaDoc getLocales() throws JahiaException {
1466        return getLocales(getSite().isMixLanguagesActive());
1467    }
1468
1469    /**
1470     * Jahia's redefinition of the Servlet APIs getLocales code. This method
1471     * actually builds a list that is a concatenation of multiple sources :
1472     *
1473     * 1. the session locale representing the locales the user has chosen to
1474     * surf with 2. the list of locales extracted from the users' preferences 3.
1475     * the list of locales extracted from the browser settings 4. the list of
1476     * locales that are setup in the site settings
1477     *
1478     * The construction of this list should be configurable, notably to be able
1479     * from the site settings to say that we want to avoid mixing languages, or
1480     * that the user never wants to see languages that are not in his settings.
1481     *
1482     * Warning, this method supposes that the current data has been already
1483     * initialized and is available : - JahiaSite - JahiaUser - Session
1484     *
1485     * @return an ArrayList of Locale objects that contain the list of locale
1486     * that are active for the current session, user and site.
1487     */

1488    public ArrayList JavaDoc getLocales(boolean allowMixLanguages) throws JahiaException {
1489
1490        // first we test if we have already this list once, as this method
1491
// is going to be called a lot.
1492
if (localeList != null) {
1493            return localeList;
1494        }
1495
1496        localeList = new ArrayList JavaDoc();
1497
1498        ArrayList JavaDoc siteLanguages = new ArrayList JavaDoc();
1499        try {
1500            siteLanguages = this.getSite().getLanguageSettingsAsLocales(true);
1501        } catch (Throwable JavaDoc t) {
1502            logger.debug("getLanguageSettingsAsLocales failed", t);
1503        }
1504
1505        if (getRequest() != null) {
1506            // STEP 1 : let's retrieve the current session locale
1507
try {
1508                currentLocale = (Locale JavaDoc) this.getSession().getAttribute(SESSION_LOCALE);
1509                if (currentLocale != null && siteLanguages.contains(currentLocale)) {
1510                    localeList.add(currentLocale);
1511                }
1512            } catch (JahiaSessionExpirationException jsee) {
1513                logger.debug("Session expiration, cannot add language setting from session", jsee);
1514            }
1515
1516            /*
1517                 // @todo : Implement user language preferences before activate these check
1518                 if (!getUser().isMixLanguagesActive()) {
1519            testLocaleList(localeList);
1520            return localeList;
1521                 }
1522                 // STEP 2 : let's retrieve the user settings locales
1523                 Vector userLanguageCodes = this.getUser().getLanguageCodes();
1524                 if (userLanguageCodes != null) {
1525            for (int i = 0; i < userLanguageCodes.size(); i++) {
1526                Locale tempLocale = LanguageCodeConverters.languageCodeToLocale((String) userLanguageCodes.elementAt(i));
1527                localeList.add(tempLocale);
1528            }
1529                 }
1530                 if (getUser().isUserLanguagesOnlyActive()) {
1531            testLocaleList(localeList);
1532            return localeList;
1533                 }
1534             */

1535
1536            // STEP 3 : retrieve the browser locales
1537
Enumeration JavaDoc browserLocales = getRequest().getLocales();
1538            while (browserLocales.hasMoreElements()) {
1539                Locale JavaDoc curLocale = (Locale JavaDoc) browserLocales.nextElement();
1540                if (siteLanguages.contains(curLocale)) {
1541                    localeList.add(curLocale);
1542                } else if (curLocale.getCountry().length() != 0) {
1543                    Locale JavaDoc langOnlyLocale = new Locale JavaDoc(curLocale.getLanguage());
1544                    if (siteLanguages.contains(langOnlyLocale)) {
1545                        localeList.add(langOnlyLocale);
1546                    }
1547                }
1548            }
1549        }
1550        // STEP 4 : retrieve the site settings locales
1551
try {
1552            Vector JavaDoc siteLanguageSettings = this.getSite().getLanguageSettings();
1553            if (siteLanguageSettings != null) {
1554                boolean firstSiteActiveLanguage = true;
1555                for (int i = 0; i < siteLanguageSettings.size(); i++) {
1556                    SiteLanguageSettings curSetting = (SiteLanguageSettings) siteLanguageSettings.elementAt(i);
1557                    if (curSetting.isActivated()) {
1558                        Locale JavaDoc tempLocale = LanguageCodeConverters.languageCodeToLocale(curSetting.getCode());
1559                        localeList.add(tempLocale);
1560                        if (firstSiteActiveLanguage) {
1561                            ParamBean.defaultParameterValues.setProperty(ParamBean.LANGUAGE_CODE, curSetting.getCode());
1562                            firstSiteActiveLanguage = false;
1563                        }
1564                    } else {
1565                        logger.debug("Not adding language " + curSetting.getCode()
1566                                + " because it is currently deactivated.");
1567                    }
1568                }
1569            }
1570        } catch (JahiaException je) {
1571            logger.debug("Cannot retrieve site language settings", je);
1572        }
1573
1574        testLocaleList(localeList, allowMixLanguages);
1575        return localeList;
1576    }
1577
1578    // --------------------------------------------------------------------------
1579
// @author NK
1580
/**
1581     * Actually use the client preferred locale if found, else returns the
1582     * Locale.getDefault() value.
1583     *
1584     * This function provides a full accept-language implementation, but caches
1585     * the result. Therefore it assumes that the language is NOT changed during
1586     * a request other by methods provided by the ParamBean class.
1587     *
1588     * Warning, this method supposes that the current data has been already
1589     * initialized and is available : - JahiaSite - JahiaUser - Session
1590     *
1591     * @return Locale the current locale in the current request
1592     */

1593    public Locale JavaDoc getLocale() {
1594
1595        // first we check if we had previously determined the value of the
1596
// locale in order to avoid doing unnecessary processing.
1597
if (this.currentLocale != null) {
1598            // we have a Locale already determined, let's return it...
1599
return currentLocale;
1600        }
1601
1602        // no currently defined, locale, let's start by retrieving the default
1603
// locale for the system.
1604
try {
1605            ArrayList JavaDoc locales = getLocales();
1606            if (locales.size() >= 2) {
1607                currentLocale = (Locale JavaDoc) locales.get(1);
1608            }
1609        } catch (Throwable JavaDoc t) {
1610            t.printStackTrace();
1611        }
1612        if (currentLocale == null) {
1613            currentLocale = Locale.getDefault();
1614        }
1615        return currentLocale;
1616    }
1617
1618    // --------------------------------------------------------------------------
1619
/**
1620     * Change the page Used ind Logout_Engine.java
1621     *
1622     * @param page
1623     */

1624    public void changePage(ContentPage page) throws JahiaException {
1625        if (page == null)
1626            return;
1627        if (contentPage == null) {
1628            lastRequestedPageID = -1;
1629            newPageRequest = true;
1630        } else if (contentPage.getID() != page.getID()) {
1631            lastRequestedPageID = contentPage.getID();
1632            newPageRequest = true;
1633        }
1634        contentPage = page;
1635        thePage = contentPage.getPage(getEntryLoadRequest(), getOperationMode(), getUser());
1636    }
1637
1638    public void flushLocaleListCache() {
1639        localeList = null;
1640    }
1641
1642    // -------------------------------------------------------------------------
1643
// * @author DJ 30.01.2001 - Original implementation
1644
/**
1645     * get the parameter from the request object specified with
1646     * specifyrequestObj
1647     */

1648    public String JavaDoc getParameter(String JavaDoc sParameter) {
1649
1650        if (customParameters.get(sParameter) != null) {
1651            return (String JavaDoc) customParameters.get(sParameter);
1652        } else {
1653            return getRequest().getParameter(sParameter);
1654        }
1655    }
1656
1657    // @author Serge Huber 20.1.02
1658
/**
1659     * Insert a new parameter into Jahia's paramBean internal parameters. This
1660     * is used for internal in-request communication.
1661     *
1662     * @param parameterName
1663     * name of the parameter. If this is an existing parameter
1664     * name-value pair, the value specified will replace the old one
1665     * so be careful.
1666     * @param parameterValue
1667     * a String value for the parameter name specified.
1668     */

1669    public void setParameter(String JavaDoc parameterName, String JavaDoc parameterValue) {
1670        customParameters.put(parameterName, parameterValue);
1671    }
1672
1673    // -------------------------------------------------------------------------
1674
// MJ 20.03.2001
1675
// NK 18.05.2001 Catch malformed pathinfo exception. Stop parsing it.
1676
/**
1677     * parse the PathInfo elements and convert them to emultated request
1678     * parameters. the parameters are stored in a HashMap (customParameters)
1679     * where they can be looked up by a customized version of
1680     * this.getParameter().
1681     *
1682     * @todo we might want to extend this in order to store parameter info
1683     * either in the session or in the URL. Session for shorter URLs and
1684     * URL for bookmarking. This should be configurable in the properties,
1685     * or maybe even for the page.
1686     * @param request
1687     * the HttpRequest object
1688     */

1689    private void buildCustomParameterMapFromPathInfo(HttpServletRequest JavaDoc request) {
1690        // Parse the PathInfo and build a custom parameter map
1691
String JavaDoc pathInfo = request.getPathInfo();
1692
1693        if (pathInfo != null) {
1694
1695            if (pathInfo.endsWith(".html")) {
1696                // let's remove false static ending.
1697
int lastSlash = pathInfo.lastIndexOf("/");
1698                if (lastSlash != -1) {
1699                    String JavaDoc fakeStaticName = pathInfo.substring(lastSlash + 1);
1700                    pathInfo = pathInfo.substring(0, lastSlash);
1701                    logger.debug("Removed fake static ending. pathInfo=[" + pathInfo + "] fakeEnding=["
1702                            + fakeStaticName + "]");
1703                }
1704            }
1705
1706            try {
1707                StringTokenizer JavaDoc st = new StringTokenizer JavaDoc(pathInfo, "/");
1708                boolean inPageResolving = true;
1709                while (st.hasMoreTokens()) {
1710                    String JavaDoc token = st.nextToken();
1711                    if (ParamBean.isReservedKeyword(token)) {
1712                        inPageResolving = false;
1713                        customParameters.put(token, st.nextToken());
1714                    } else if (inPageResolving) {
1715                        pageURLKeys.add(token);
1716                    }
1717                }
1718            } catch (NoSuchElementException JavaDoc nee) {
1719                // stop parsing token
1720
}
1721        }
1722
1723        // Hollis : In case we have Multipart request
1724
// Append other parameters parsed from query string
1725
if (isMultipartRequest(request)) {
1726            Map JavaDoc queryStringParams = new HashMap JavaDoc();
1727            ServletIncludeRequestWrapper.parseStringParameters(queryStringParams, request.getQueryString(), request
1728                    .getCharacterEncoding(), true);
1729            customParameters.putAll(queryStringParams);
1730        }
1731    }
1732
1733    // --------------------------------------------------------------------------
1734
/**
1735     * Generates engine url's parameters in queryString or Path info. By
1736     * default, use path info.
1737     *
1738     * @param val
1739     */

1740    public void setUseQueryStringParameterUrl(boolean val) {
1741        this.useQueryStringParameterUrl = val;
1742    }
1743
1744    /**
1745     * Return true if the engine URL's parameters are generated in the
1746     * querystring. &engineName=code&pid=10 False if using path info format:
1747     * /engineName/core/pid/10
1748     *
1749     * @return true if the engine URL's parameters are generated in the
1750     * querystring.
1751     */

1752    public boolean useQueryStringParameterUrl() {
1753        return this.useQueryStringParameterUrl;
1754    }
1755
1756    // -------------------------------------------------------------------------
1757
// @author Khue Nguyen
1758
/**
1759     * Return the default site or null if not found or undefined
1760     *
1761     * @return JahiaSite the default site
1762     */

1763    public static JahiaSite getDefaultSite() {
1764
1765        // logger.debug("getDefaultSite started");
1766

1767        JahiaSite site = null;
1768        String JavaDoc siteKey = null;
1769
1770        // try to load from storage
1771
SettingsBean settings = Jahia.getSettings();
1772        if (settings != null) {
1773            siteKey = settings.getDefaultSite();
1774            if (siteKey == null || siteKey.trim().equals("")) {
1775                return null;
1776            }
1777        }
1778
1779        if (siteKey != null) {
1780            try {
1781                site = ServicesRegistry.getInstance().getJahiaSitesService().getSiteByKey(siteKey);
1782            } catch (JahiaException je) {
1783                return null;
1784            }
1785        }
1786
1787        return site;
1788    }
1789
1790    /**
1791     * Returns an URL only if the parameterValue for the parameterName is
1792     * different from its defined default value, or if it has no default value.
1793     *
1794     * @param parameterName
1795     * name of the parameter to add in the URL
1796     * @param parameterValue
1797     * value of the parameter to add in the URL
1798     * @return an empty string if the value is equal to the default value,
1799     * otherwise it returns a composition as follow : "/" +
1800     * parameterName + "/" + parameterValue
1801     */

1802    private String JavaDoc condAppendURL(String JavaDoc parameterName, String JavaDoc parameterValue) {
1803        String JavaDoc defaultValue = defaultParameterValues.getProperty(parameterName);
1804        String JavaDoc result = appendParam(parameterName, parameterValue);
1805
1806        if (defaultValue == null) {
1807            return result.toString();
1808        } else {
1809            if (defaultValue.equals(parameterValue)) {
1810                return "";
1811            } else {
1812                return result.toString();
1813            }
1814        }
1815    }
1816
1817    private String JavaDoc appendParam(String JavaDoc parameterName, String JavaDoc parameterValue) {
1818        StringBuffer JavaDoc result = new StringBuffer JavaDoc();
1819        if (!this.useQueryStringParameterUrl()) {
1820            result.append("/");
1821        }
1822
1823        result.append(parameterName);
1824        if (!this.useQueryStringParameterUrl()) {
1825            result.append("/");
1826        } else {
1827            result.append("=");
1828        }
1829        result.append(parameterValue);
1830        return result.toString();
1831    }
1832
1833    // -------------------------------------------------------------------------
1834
// EV 20 Nov. 2000 : Original implementation
1835
// FH 22 Jan. 2001 : - Changed += operation on a String to a StringBuffer.
1836
// - added error check.
1837
// MJ 29 May. 2001 : get http path from request instead of settings,
1838

1839    /**
1840     * Compose an URL by adding default parameters (like the page id, the
1841     * session id, ...) to the passed in parameter string.
1842     *
1843     * @param params
1844     * String of parameters.
1845     * @return Return a valid URL by adding default parameters. Return an
1846     * non-null empty string on any error.
1847     */

1848    public String JavaDoc composeUrl(String JavaDoc params) throws JahiaException {
1849        StringBuffer JavaDoc theUrl = new StringBuffer JavaDoc(this.getJahiaCoreHttpPath());
1850
1851        if (contentPage != null) {
1852            theUrl.append(getPageURLKeyPart(contentPage.getID()));
1853        }
1854        theUrl.append(getEngineURLPart(CORE_ENGINE_NAME));
1855        theUrl.append(getSiteURLPart(site.getSiteKey()));
1856        theUrl.append(getOpModeURLPart(opMode));
1857        theUrl.append(getCacheModeURLPart(cacheStatus));
1858        // theUrl.append (getLastRequestedPageURLPart (thePage.getID()));
1859
if (contentPage != null)
1860            theUrl.append(getPageURLPart(contentPage.getID()));
1861
1862        appendParams(theUrl, params);
1863
1864        appendAnchor(theUrl);
1865
1866        return encodeURL(theUrl.toString());
1867    } // end composeUrl
1868

1869    /**
1870     * Compose an URL by adding default parameters (like the page id, the
1871     * session id, ...) to the passed in parameter string.
1872     *
1873     * @param pageUrlKey
1874     * the url key of the page
1875     * @param params
1876     * String of parameters.
1877     * @return Return a valid URL by adding default parameters. Return an
1878     * non-null empty string on any error.
1879     */

1880    public String JavaDoc composeUrl(String JavaDoc pageUrlKey, String JavaDoc params) throws JahiaException {
1881        StringBuffer JavaDoc theUrl = new StringBuffer JavaDoc(this.getJahiaCoreHttpPath());
1882
1883        theUrl.append("/" + pageUrlKey);
1884        theUrl.append(getEngineURLPart(CORE_ENGINE_NAME));
1885        theUrl.append(getSiteURLPart(site.getSiteKey()));
1886        theUrl.append(getOpModeURLPart(opMode));
1887        theUrl.append(getCacheModeURLPart(cacheStatus));
1888        // theUrl.append (getLastRequestedPageURLPart (thePage.getID()));
1889

1890        appendParams(theUrl, params);
1891
1892        appendAnchor(theUrl);
1893
1894        return encodeURL(theUrl.toString());
1895    } // end composeUrl
1896

1897    // -------------------------------------------------------------------------
1898
// EV 20 Nov. 2000 : Original implementation
1899
// FH 22 Jan. 2001 : Changed += operation on a String to a StringBuffer.
1900
// MJ 29 May. 2001 : get http path from request instead of settings,
1901
// MJ 24 Jul. 2001 : dirty hack to hide catalina bug in HttpServletResponse
1902
// .encodeURL(String URL)
1903
// (bug description : reference to response object is
1904
// sometimes lost after intensive calls to this method)
1905
// Affected version : Tomcat 4.0 beta 1
1906
/**
1907     *
1908     */

1909    public String JavaDoc composePageUrl(int pageID, String JavaDoc languageCode) throws JahiaException {
1910        StringBuffer JavaDoc theUrl = new StringBuffer JavaDoc(this.getJahiaCoreHttpPath());
1911        theUrl.append(getPageURLKeyPart(pageID));
1912        theUrl.append(getEngineURLPart(CORE_ENGINE_NAME));
1913        theUrl.append(getSiteURLPart(site.getSiteKey()));
1914        theUrl.append(getOpModeURLPart(opMode));
1915        theUrl.append(getCacheModeURLPart(cacheStatus));
1916        if (languageCode != null) {
1917            theUrl.append(condAppendURL(LANGUAGE_CODE, languageCode));
1918        }
1919        theUrl.append(getPageURLPart(pageID));
1920        try {
1921            return encodeURL(theUrl.toString());
1922        } catch (NullPointerException JavaDoc npe) {
1923            return theUrl.toString();
1924        }
1925    }
1926
1927    /**
1928     *
1929     */

1930
1931    public String JavaDoc composePageUrl(String JavaDoc pageUrlKey, String JavaDoc languageCode) throws JahiaException {
1932        StringBuffer JavaDoc theUrl = new StringBuffer JavaDoc(this.getJahiaCoreHttpPath());
1933        theUrl.append("/" + pageUrlKey);
1934        theUrl.append(getEngineURLPart(CORE_ENGINE_NAME));
1935        theUrl.append(getSiteURLPart(site.getSiteKey()));
1936        theUrl.append(getOpModeURLPart(opMode));
1937        theUrl.append(getCacheModeURLPart(cacheStatus));
1938        if (languageCode != null) {
1939            theUrl.append(condAppendURL(LANGUAGE_CODE, languageCode));
1940        }
1941        try {
1942            return encodeURL(theUrl.toString());
1943        } catch (NullPointerException JavaDoc npe) {
1944            return theUrl.toString();
1945        }
1946    }
1947
1948    /**
1949     * @deprecated
1950     *
1951     * @param pageID
1952     * @throws JahiaException
1953     */

1954    public String JavaDoc composePageUrl(int pageID) throws JahiaException {
1955        return composePageUrl(pageID, this.getLocale().toString());
1956    }
1957
1958    // -------------------------------------------------------------------------
1959
// MJ 27 Feb. 2001 : Overloaded method without params besides engineName
1960
// MJ 29 May. 2001 : get http path from request instead of settings,
1961

1962    /**
1963     * composeEngineUrl MJ 27.02.2001
1964     */

1965    public String JavaDoc composeEngineUrl(String JavaDoc theEngineName) throws JahiaException {
1966
1967        StringBuffer JavaDoc theUrl = new StringBuffer JavaDoc(this.getJahiaCoreHttpPath());
1968
1969        if (contentPage != null) {
1970            theUrl.append(getPageURLKeyPart(contentPage.getID()));
1971        }
1972        if (theEngineName != null) {
1973            theUrl.append(getEngineURLPart(theEngineName));
1974        }
1975
1976        theUrl.append(getSiteURLPart());
1977        theUrl.append(getOpModeURLPart(opMode));
1978        if (contentPage != null)
1979            theUrl.append(getPageURLPart(contentPage.getID()));
1980
1981        appendAnchor(theUrl);
1982
1983        return encodeURL(theUrl.toString());
1984    } // end composeEngineUrl
1985

1986    // -------------------------------------------------------------------------
1987
// EV 20 Nov. 2000 : Original implementation
1988
// FH 22 Jan. 2001 : Changed += operation on a String to a StringBuffer.
1989
// MJ 29 May. 2001 : get http path from request instead of settings,
1990

1991    /**
1992     * composeEngineUrl EV 20.11.2000
1993     */

1994    public String JavaDoc composeEngineUrl(String JavaDoc theEngineName, String JavaDoc params) throws JahiaException {
1995        // logger.debug("Generating engine url for engine:"+engine + " with
1996
// params:" + params);
1997
StringBuffer JavaDoc theUrl = new StringBuffer JavaDoc(this.getJahiaCoreHttpPath());
1998        // logger.debug("jahiaCoreHttpPath="+theUrl.toString());
1999
if (contentPage != null) {
2000            theUrl.append(getPageURLKeyPart(contentPage.getID()));
2001        }
2002        if (theEngineName != null) {
2003            theUrl.append(getEngineURLPart(theEngineName));
2004        }
2005        // logger.debug("jahiaCoreHttpPath="+theUrl.toString());
2006

2007        theUrl.append(getSiteURLPart());
2008        theUrl.append(getOpModeURLPart(opMode));
2009        if (contentPage != null)
2010            theUrl.append(getPageURLPart(contentPage.getID()));
2011
2012        appendParams(theUrl, params);
2013
2014        appendAnchor(theUrl);
2015
2016        return encodeURL(theUrl.toString());
2017    } // end composeEngineUrl
2018

2019    // @author Khue Nguyen
2020
/**
2021     * Supplementary version that allows us to add parameters in standard Jahia
2022     * parameter form.
2023     *
2024     * @param strutsAction
2025     * the Struts Action part of the URL to generate. the queryString
2026     * @param params
2027     * standard URL parameters in the form of a string that starts
2028     * with &
2029     * @return String containing the generated URL.
2030     * @throws JahiaException
2031     */

2032    public String JavaDoc composeStrutsUrl(String JavaDoc strutsAction, String JavaDoc params) throws JahiaException {
2033        return composeStrutsUrl(strutsAction, new Properties JavaDoc(), params);
2034    }
2035
2036    /**
2037     * Supplementary version that allows us to add parameters in standard Jahia
2038     * parameter form.
2039     *
2040     * @param strutsAction
2041     * the Struts Action part of the URL to generate.
2042     * @param extraJahiaParams
2043     * additional name=value parameter to insert in the queryString
2044     * @param params
2045     * standard URL parameters in the form of a string that starts
2046     * with &
2047     * @return String containing the generated URL.
2048     * @throws JahiaException
2049     */

2050    public String JavaDoc composeStrutsUrl(String JavaDoc strutsAction, Properties JavaDoc extraJahiaParams, String JavaDoc params)
2051            throws JahiaException {
2052        if (extraJahiaParams == null) {
2053            extraJahiaParams = new Properties JavaDoc();
2054        }
2055
2056        this.setUseQueryStringParameterUrl(true);
2057
2058        StringBuffer JavaDoc theUrl = new StringBuffer JavaDoc();
2059
2060        // Removed ADMIN mode check and the prefix /do/ and
2061
// shifted to extension .do to enable Struts modules
2062
//
2063
// if (!this.isInAdminMode()) {
2064
// theUrl.append(this.getJahiaCoreHttpPath());
2065
// } else {
2066
theUrl.append(this.getRequest().getContextPath());
2067        // }
2068
if (!strutsAction.startsWith("/")) {
2069            theUrl.append("/");
2070        }
2071        theUrl.append(strutsAction);
2072
2073        if (!strutsAction.endsWith(".do"))
2074            theUrl.append(".do");
2075
2076        String JavaDoc paramValue = getSiteURLPart();
2077        String JavaDoc paramSep = "?";
2078        if (paramValue != null && !paramValue.trim().equals("")) {
2079            if (!paramValue.startsWith("/")) {
2080                theUrl.append(paramSep);
2081                theUrl.append(paramValue);
2082                paramSep = "&";
2083            }
2084        }
2085        paramValue = getOpModeURLPart(opMode);
2086        if (paramValue != null && !paramValue.trim().equals("")) {
2087            theUrl.append(paramSep);
2088            theUrl.append(paramValue);
2089            paramSep = "&";
2090        }
2091        if (contentPage != null) {
2092            paramValue = getPageURLPart(contentPage.getID());
2093            if (paramValue != null && !paramValue.trim().equals("")) {
2094                theUrl.append(paramSep);
2095                theUrl.append(paramValue);
2096                paramSep = "&";
2097            }
2098        }
2099        Enumeration JavaDoc propertyNames = extraJahiaParams.propertyNames();
2100        while (propertyNames.hasMoreElements()) {
2101            String JavaDoc propertyName = (String JavaDoc) propertyNames.nextElement();
2102            String JavaDoc propertyValue = extraJahiaParams.getProperty(propertyName);
2103            paramValue = condAppendURL(propertyName, propertyValue);
2104            if (paramValue != null && !paramValue.trim().equals("")) {
2105                theUrl.append(paramSep);
2106                theUrl.append(paramValue);
2107                paramSep = "&";
2108            }
2109        }
2110
2111        appendParams(theUrl, params);
2112
2113        appendAnchor(theUrl);
2114
2115        this.setUseQueryStringParameterUrl(false);
2116
2117        String JavaDoc val = encodeURL(theUrl.toString());
2118        return val;
2119    }
2120
2121    /**
2122     * Supplementary version that allows us to add parameters in standard Jahia
2123     * parameter form.
2124     *
2125     * @param engine
2126     * the name of the engine for which to generate the URL
2127     * @param extraJahiaParams
2128     * additional /name/value parameter to insert in the url
2129     * @param params
2130     * standard URL parameters in the form of a string that starts
2131     * with ?
2132     * @return String containing the generated URL.
2133     * @throws JahiaException
2134     */

2135    public String JavaDoc composeEngineUrl(String JavaDoc engine, Properties JavaDoc extraJahiaParams, String JavaDoc params) throws JahiaException {
2136        // logger.debug("Generating url for engine:" + engineName + " with
2137
// params:" + params + " and extra params (properties) ");
2138
StringBuffer JavaDoc theUrl = new StringBuffer JavaDoc(this.getJahiaCoreHttpPath());
2139        // logger.debug("jahiaCoreHttpPath="+theUrl.toString());
2140
if (contentPage != null) {
2141            theUrl.append(getPageURLKeyPart(contentPage.getID()));
2142        }
2143        if (engine != null) {
2144            theUrl.append(getEngineURLPart(engine));
2145        }
2146        // logger.debug("jahiaCoreHttpPath="+theUrl.toString());
2147

2148        theUrl.append(getSiteURLPart());
2149        theUrl.append(getOpModeURLPart(opMode));
2150        if ((contentPage != null) && (!extraJahiaParams.containsKey(PAGE_ID_PARAMETER))) {
2151            theUrl.append(getPageURLPart(contentPage.getID()));
2152        }
2153
2154        Enumeration JavaDoc propertyNames = extraJahiaParams.propertyNames();
2155        while (propertyNames.hasMoreElements()) {
2156            String JavaDoc propertyName = (String JavaDoc) propertyNames.nextElement();
2157            String JavaDoc propertyValue = extraJahiaParams.getProperty(propertyName);
2158            theUrl.append(condAppendURL(propertyName, propertyValue));
2159        }
2160
2161        appendParams(theUrl, params);
2162
2163        appendAnchor(theUrl);
2164
2165        return encodeURL(theUrl.toString());
2166    } // end composeEngineUrl
2167

2168    /**
2169     * composeEngineUrl NK compose an engine url with the field id information
2170     */

2171    public String JavaDoc composeEngineUrl(String JavaDoc theEngineName, String JavaDoc params, int fieldId) throws JahiaException {
2172        // logger.debug("Generating engine url for engine:" + engineName + "
2173
// with params:" + params + " and field:" + fieldID);
2174
StringBuffer JavaDoc theUrl = new StringBuffer JavaDoc(this.getJahiaCoreHttpPath());
2175        if (contentPage != null) {
2176            theUrl.append(getPageURLKeyPart(contentPage.getID()));
2177        }
2178        // logger.debug("jahiaCoreHttpPath="+theUrl.toString());
2179
if (theEngineName != null) {
2180            theUrl.append(getEngineURLPart(theEngineName));
2181        }
2182        // logger.debug("jahiaCoreHttpPath="+theUrl.toString());
2183

2184        theUrl.append(getSiteURLPart());
2185        theUrl.append(getOpModeURLPart(opMode));
2186        if (contentPage != null)
2187            theUrl.append(getPageURLPart(contentPage.getID()));
2188        theUrl.append(getFieldURLPart(fieldId));
2189
2190        appendParams(theUrl, params);
2191
2192        appendAnchor(theUrl);
2193
2194        return encodeURL(theUrl.toString());
2195    } // end composeEngineUrl
2196

2197    // -------------------------------------------------------------------------
2198
// EV 20 Nov. 2000 : Original implementation
2199
// FH 22 Jan. 2001 : Changed += operation on a String to a StringBuffer.
2200
// MJ 29 May. 2001 : get http path from request instead of settings,
2201

2202    /**
2203     * composeOperationUrl EV 21.11.2000
2204     */

2205    public String JavaDoc composeOperationUrl(String JavaDoc operationMode, String JavaDoc params) throws JahiaException {
2206        StringBuffer JavaDoc theUrl = new StringBuffer JavaDoc(getJahiaCoreHttpPath());
2207
2208        // ISM: edit/preview/etc modes access check:
2209
if (!NORMAL.equals(operationMode) && !canEditCurrentPage()) {
2210            operationMode = NORMAL;
2211        }
2212        if (!EDIT.equals(operationMode) && contentPage != null) {
2213            theUrl.append(getPageURLKeyPart(contentPage.getID()));
2214        }
2215        theUrl.append(getEngineURLPart(CORE_ENGINE_NAME));
2216        theUrl.append(getSiteURLPart());
2217        if (operationMode != null) {
2218            theUrl.append(getOpModeURLPart(operationMode));
2219        }
2220        // theUrl.append (getCacheModeURLPart(cacheStatus));
2221
if (contentPage != null) {
2222            theUrl.append(getPageURLPartWithOperationMode(operationMode, contentPage.getID()));
2223        }
2224
2225        appendParams(theUrl, params);
2226
2227        return encodeURL(theUrl.toString());
2228    } // end composeOperationUrl
2229

2230    /**
2231     * composeOperationUrl EV 21.11.2000
2232     *
2233     * @param revisionDiffID
2234     * 0 to compare with staging, 1 with active
2235     * @param operationMode
2236     * @param params
2237     * @throws JahiaException
2238     */

2239    public String JavaDoc composeRevDifferenceUrl(int revisionDiffID, String JavaDoc operationMode, String JavaDoc params)
2240            throws JahiaException {
2241        StringBuffer JavaDoc theUrl = new StringBuffer JavaDoc(this.getJahiaCoreHttpPath());
2242
2243        if (contentPage != null) {
2244            theUrl.append(getPageURLKeyPart(contentPage.getID()));
2245        }
2246        theUrl.append(getEngineURLPart(CORE_ENGINE_NAME));
2247        theUrl.append(getSiteURLPart());
2248        if (operationMode != null) {
2249            theUrl.append(getOpModeURLPart(ParamBean.COMPARE));
2250        }
2251        theUrl.append(getCacheModeURLPart(ParamBean.CACHE_OFFONCE));
2252        if (contentPage != null) {
2253            theUrl.append(getPageURLPart(contentPage.getID()));
2254            if (revisionDiffID == 0) {
2255                theUrl.append(this.getEntryStateURLPart("a"));
2256            } else {
2257                theUrl.append(this.getEntryStateURLPart("s"));
2258            }
2259            theUrl.append(this.getShowRevisionDiffURLPart(revisionDiffID));
2260        }
2261        appendParams(theUrl, params);
2262        return encodeURL(theUrl.toString());
2263    } // end composeOperationUrl
2264

2265    /**
2266     * @return The URL page containing "lang/'code'"
2267     * @throws JahiaException
2268     */

2269    public String JavaDoc composeLanguageURL(String JavaDoc code) throws JahiaException {
2270
2271        StringBuffer JavaDoc theUrl = new StringBuffer JavaDoc(this.getJahiaCoreHttpPath());
2272        if (contentPage != null) {
2273            theUrl.append(getPageURLKeyPart(contentPage.getID()));
2274        }
2275        theUrl.append(getEngineURLPart(CORE_ENGINE_NAME));
2276        theUrl.append(getSiteURLPart());
2277        theUrl.append(getOpModeURLPart(this.opMode));
2278        theUrl.append(appendParam(LANGUAGE_CODE, code));
2279        if (contentPage != null)
2280            theUrl.append(getPageURLPart(contentPage.getID()));
2281
2282        if ( this.getRequest() != null ){
2283            String JavaDoc queryString = this.getRequest().getQueryString();
2284            if ( queryString != null && !"".equals(queryString) ){
2285                theUrl.append("?").append(queryString);
2286            }
2287        }
2288        return encodeURL(theUrl.toString());
2289    }
2290
2291    // #ifdef LOCK
2292
public String JavaDoc composeStealLockURL(LockKey lockKey) throws JahiaException {
2293        StringBuffer JavaDoc theURL = new StringBuffer JavaDoc();
2294        theURL.append(getRequest().getRequestURI());
2295        theURL.append("/" + ParamBean.CACHE_MODE_PARAMETER + "/" + ParamBean.CACHE_OFF);
2296        theURL.append("/" + ParamBean.STEAL_LOCK + "/" + lockKey.toString());
2297        theURL.append("?");
2298        theURL.append(getRequest().getQueryString());
2299        return encodeURL(theURL.toString());
2300    }
2301
2302    public String JavaDoc composeReleaseLockURL(LockKey lockKey) throws JahiaException {
2303        StringBuffer JavaDoc theURL = new StringBuffer JavaDoc();
2304        theURL.append(getRequest().getRequestURI());
2305        theURL.append("/" + ParamBean.CACHE_MODE_PARAMETER + "/" + ParamBean.CACHE_OFF);
2306        theURL.append("/" + ParamBean.RELEASE_LOCK + "/" + lockKey.toString());
2307        theURL.append("?");
2308        theURL.append(getRequest().getQueryString());
2309        return encodeURL(theURL.toString());
2310    }
2311
2312    // #endif
2313

2314    // -------------------------------------------------------------------------
2315
// MJ 29 May. 2001 : get http path from request instead of settings,
2316
// NK 16 Apr. 2001
2317
/**
2318     * compose a Jahia site url
2319     */

2320    public String JavaDoc composeSiteUrl(JahiaSite jahiaSite) {
2321        StringBuffer JavaDoc theUrl = new StringBuffer JavaDoc(this.getJahiaCoreHttpPath());
2322
2323        theUrl.append(getPageURLKeyPart(jahiaSite.getHomePageID()));
2324        theUrl.append(getEngineURLPart(CORE_ENGINE_NAME));
2325        theUrl.append(getSiteURLPart(jahiaSite.getSiteKey()));
2326        theUrl.append(getOpModeURLPart(ParamBean.NORMAL));
2327        theUrl.append(getPageURLPart(jahiaSite.getHomePageID()));
2328
2329        return encodeURL(theUrl.toString());
2330    }
2331
2332    // -------------------------------------------------------------------------
2333
// MJ 29 May. 2001 : get http path from request instead of settings,
2334
// NK 16 Apr. 2001
2335
/**
2336     * compose a Jahia site url with the current site
2337     */

2338    public String JavaDoc composeSiteUrl() {
2339        StringBuffer JavaDoc theUrl = new StringBuffer JavaDoc(this.getJahiaCoreHttpPath());
2340
2341        theUrl.append(getPageURLKeyPart(this.site.getHomePageID()));
2342        theUrl.append(getEngineURLPart(CORE_ENGINE_NAME));
2343        theUrl.append(getSiteURLPart(this.site.getSiteKey()));
2344        theUrl.append(getOpModeURLPart(ParamBean.NORMAL));
2345        theUrl.append(getPageURLPart(this.site.getHomePageID()));
2346
2347        return encodeURL(theUrl.toString());
2348    }
2349
2350    // -------------------------------------------------------------------------
2351
// @author NK
2352
/**
2353     * append params to a url
2354     *
2355     * @param theUrl
2356     * the url
2357     * @param params
2358     * the params to append to the url
2359     */

2360    protected void appendParams(StringBuffer JavaDoc theUrl, String JavaDoc params) {
2361
2362        if (params != null && (params.length() > 0)) {
2363            if (theUrl.toString().indexOf("?") == -1) {
2364                if (params.startsWith("&")) {
2365                    params = "?" + params.substring(1, params.length());
2366                } else if (!params.startsWith("?")) {
2367                    if (!params.startsWith("/")) {
2368                        params = "?" + params;
2369                    }
2370                }
2371            } else {
2372                if (!params.startsWith("&")) {
2373                    if (!params.startsWith("/")) {
2374                        params = "&" + params;
2375                    }
2376                }
2377            }
2378            theUrl.append(params);
2379        } else {
2380            if (theUrl.toString().indexOf("?") == -1) {
2381                theUrl.append("?matrix=");
2382            } else {
2383                theUrl.append("&matrix=");
2384            }
2385            theUrl.append(String.valueOf(System.currentTimeMillis()));
2386        }
2387
2388    }
2389
2390    // -------------------------------------------------------------------------
2391
// @author NK
2392
/**
2393     * append an anchor to the url, used with application field
2394     *
2395     * @param theUrl
2396     * the url
2397     */

2398    protected void appendAnchor(StringBuffer JavaDoc theUrl) {
2399
2400        if (this.anchor != null) {
2401            theUrl.append("#");
2402            theUrl.append(anchor);
2403
2404            // reset the anchorID
2405
this.anchor = null;
2406        }
2407    }
2408
2409    // -------------------------------------------------------------------------
2410
/**
2411     * Set the active anchor, that is the field id
2412     *
2413     * @param val
2414     * the anchor
2415     */

2416    public void setAnchor(String JavaDoc val) {
2417        this.anchor = val;
2418    }
2419
2420    // -------------------------------------------------------------------------
2421
/**
2422     */

2423    public String JavaDoc getAnchor() {
2424        return this.anchor;
2425    }
2426
2427    // -------------------------------------------------------------------------
2428
// @author NK
2429
/**
2430     * Used to get the templates jahiafiles disk path for the current site.
2431     *
2432     * @return The templates jahiafiles disk path.
2433     */

2434    public String JavaDoc getJahiaFilesTemplatesDiskPath() {
2435
2436        StringBuffer JavaDoc buff = new StringBuffer JavaDoc(settings().getJahiaFilesTemplatesDiskPath());
2437        buff.append(File.separator);
2438        buff.append("site_");
2439        buff.append(getSite().getID());
2440        // check if the dir exist
2441
File JavaDoc f = new File JavaDoc(buff.toString());
2442        if (!f.isDirectory()) {
2443            f.mkdirs();
2444        }
2445        return f.getAbsolutePath();
2446
2447    } // end getJahiaFilesTemplatesDiskPath
2448

2449    /**
2450     * Returns a String containing the full content generated by Jahia so far.
2451     * Please note that calling this before all processing if finished will
2452     * returns incomplete content.
2453     *
2454     * @return a String containing the generated content.
2455     * @throws IOException
2456     * if there was an error during output of content.
2457     */

2458    public String JavaDoc getGeneratedOutput() throws IOException JavaDoc {
2459        return getResponseWrapper().getStringBuffer();
2460    }
2461
2462    /**
2463     * Returns the location set in a response redirect call.
2464     *
2465     * @return a String object that contains the location to which to redirect,
2466     * or null if no redirect call has been made.
2467     */

2468    public String JavaDoc getRedirectLocation() {
2469        return getResponseWrapper().getRedirectLocation();
2470    }
2471
2472    /**
2473     * Returns a String containing the actual content type used by Jahia so far.
2474     * Please note that this may change over time if multiple calls to the
2475     * wrapper response setContentType call are made (not good :( ).
2476     *
2477     * @return a String containing the current content type.
2478     */

2479    public String JavaDoc getContentType() {
2480        return getResponseWrapper().getContentType();
2481    }
2482
2483    // -------------------------------------------------------------------------
2484
// @author NK
2485
/**
2486     * If the form data is non-multipart (simple), it returns true, otherwise
2487     * returns false.
2488     *
2489     * @param req
2490     * An HttpServletRequest.
2491     * @return True if the form data is non-multipart (simple).
2492     */

2493    public static boolean isMultipartRequest(HttpServletRequest JavaDoc req) {
2494        String JavaDoc contentType = req.getHeader("Content-Type");
2495
2496        if (contentType != null && contentType.indexOf("multipart/form-data") >= 0) {
2497            return true;
2498        }
2499
2500        return false;
2501    }
2502
2503    /**
2504     * @return ArrayList a list of String objects that contain the page URL keys
2505     * if any were included in the URL. Page keys are a more readable
2506     * way of naming a page. Here is an example of an URL containing
2507     * page keys :
2508     * http://localhost:8080/jahia/Jahia/marketing/products/cache/offonce
2509     * The result of a call to this method for the above URL would
2510     * return: { "marketing", "products" }
2511     */

2512    public ArrayList JavaDoc getPageURLKeys() {
2513        return pageURLKeys;
2514    }
2515
2516    // -------------------------------------------------------------------------
2517
// FH 21 Jan. 2001 : Original implementation
2518
// MJ 21 Mar. 2001 : replaced URL params with context PathInfo elements
2519
protected final String JavaDoc getEngineURLPart(String JavaDoc theEngineName) {
2520        return condAppendURL(ENGINE_NAME_PARAMETER, theEngineName);
2521    }
2522
2523    // -------------------------------------------------------------------------
2524
// NK 17 Avr. 2001 :
2525
protected final String JavaDoc getSiteURLPart(String JavaDoc val) {
2526        return condAppendURL(SITE_KEY_PARAMETER, val);
2527
2528    }
2529
2530    // -------------------------------------------------------------------------
2531
// NK 17 Avr. 2001 :
2532
protected final String JavaDoc getSiteURLPart() {
2533        return condAppendURL(SITE_KEY_PARAMETER, getSite().getSiteKey());
2534    }
2535
2536    // -------------------------------------------------------------------------
2537
// FH 21 Jan. 2001 : Original implementation
2538
// MJ 21 Mar. 2001 : replaced URL params with context PathInfo elements
2539
protected final String JavaDoc getPageURLPart(int id) {
2540        boolean mustRender = true;
2541
2542        if (!EDIT.equals(opMode)) {
2543            try {
2544                PageProperty pageProperty = ContentPage.getPage(id).getPageLocalProperty(
2545                        PageProperty.PAGE_URL_KEY_PROPNAME);
2546                if (pageProperty != null) {
2547                    mustRender = false;
2548                }
2549            } catch (JahiaException je) {
2550                logger.error("Error while testing existing of page URL key for page " + id, je);
2551            }
2552        }
2553
2554        if (mustRender) {
2555            return condAppendURL(PAGE_ID_PARAMETER, Integer.toString(id));
2556        } else {
2557            return "";
2558        }
2559    }
2560
2561    protected final String JavaDoc getPageURLPartWithOperationMode(String JavaDoc operationMode, int id) {
2562        boolean mustRender = true;
2563
2564        if (operationMode.equals(EDIT) == false) {
2565            try {
2566                PageProperty pageProperty = ContentPage.getPage(id).getPageLocalProperty(
2567                        PageProperty.PAGE_URL_KEY_PROPNAME);
2568                if (pageProperty != null) {
2569                    mustRender = false;
2570                }
2571            } catch (JahiaException je) {
2572                logger.error("Error while testing existing of page URL key for page " + id, je);
2573            }
2574        }
2575
2576        if (mustRender) {
2577            return condAppendURL(PAGE_ID_PARAMETER, Integer.toString(id));
2578        } else {
2579            return "";
2580        }
2581    }
2582
2583    protected final String JavaDoc getPageURLKeyPart(int id) {
2584        StringBuffer JavaDoc pageURLKeysPartBuf = new StringBuffer JavaDoc();
2585
2586        // first we must find all parent pages and their URL keys.
2587
LinkedList JavaDoc urlKeys = new LinkedList JavaDoc();
2588        try {
2589            ContentPage curContentPage = ContentPage.getPage(id);
2590            Enumeration JavaDoc pagePathEnum = curContentPage.getContentPagePath(this);
2591            while (pagePathEnum.hasMoreElements()) {
2592                ContentPage curParentPage = (ContentPage) pagePathEnum.nextElement();
2593                PageProperty urlKeyProp = curParentPage.getPageLocalProperty(PageProperty.PAGE_URL_KEY_PROPNAME);
2594                if (urlKeyProp != null) {
2595                    urlKeys.add(urlKeyProp.getValue());
2596                }
2597            }
2598            if (urlKeys.size() > 0) {
2599                Iterator JavaDoc urlKeyIter = urlKeys.iterator();
2600                while (urlKeyIter.hasNext()) {
2601                    String JavaDoc curURLKey = (String JavaDoc) urlKeyIter.next();
2602                    pageURLKeysPartBuf.append("/");
2603                    pageURLKeysPartBuf.append(curURLKey);
2604                }
2605            }
2606        } catch (JahiaException je) {
2607            logger.error("Error while retrieving page path for page " + id, je);
2608        }
2609
2610        return pageURLKeysPartBuf.toString();
2611    }
2612
2613    // -------------------------------------------------------------------------
2614
// NK
2615
protected final String JavaDoc getContainerListURLPart(int id) {
2616        return condAppendURL(CONTAINERLIST_ID_PARAMETER, Integer.toString(id));
2617    }
2618
2619    protected final String JavaDoc getContainerURLPart(int id) {
2620        return condAppendURL(CONTAINER_ID_PARAMETER, Integer.toString(id));
2621    }
2622
2623    protected final String JavaDoc getFieldURLPart(int id) {
2624        return condAppendURL(FIELD_ID_PARAMETER, Integer.toString(id));
2625    }
2626
2627    // -------------------------------------------------------------------------
2628
// FH 21 Jan. 2001 : Original implementation
2629
// MJ 21 Mar. 2001 : replaced URL params with context PathInfo elements
2630
protected final String JavaDoc getOpModeURLPart(String JavaDoc mode) {
2631        return condAppendURL(OPERATION_MODE_PARAMETER, mode);
2632    }
2633
2634    // -------------------------------------------------------------------------
2635
// SH 12 Oct. 2001 : Original implementation
2636
protected final String JavaDoc getCacheModeURLPart(String JavaDoc mode) {
2637        return condAppendURL(CACHE_MODE_PARAMETER, mode);
2638    }
2639
2640    // --------------------------------------------------------------------------
2641
protected final String JavaDoc getEntryStateURLPart(int versionID) {
2642        return condAppendURL(ParamBean.ENTRY_STATE_PARAMETER, String.valueOf(versionID));
2643    }
2644
2645    // --------------------------------------------------------------------------
2646
/**
2647     * @param status
2648     * "s" for staging, "a" for active
2649     */

2650    protected final String JavaDoc getEntryStateURLPart(String JavaDoc status) {
2651        return condAppendURL(ParamBean.ENTRY_STATE_PARAMETER, status);
2652    }
2653
2654    // --------------------------------------------------------------------------
2655
/**
2656     * by default show revision difference with the staging first else with the
2657     * active version
2658     */

2659    protected final String JavaDoc getShowRevisionDiffURLPart() {
2660        return getShowRevisionDiffURLPart(2);
2661    }
2662
2663    // --------------------------------------------------------------------------
2664
/**
2665     * by default show revision difference. If the versionID == 0 -> show diff
2666     * with staging ( active if not exists )
2667     *
2668     * @param versionID
2669     */

2670    protected final String JavaDoc getShowRevisionDiffURLPart(int versionID) {
2671        String JavaDoc value = "";
2672        if (versionID == 2) {
2673            value = condAppendURL(ParamBean.SHOW_REVISION_DIFF_PARAMETER, "s");
2674        } else if (versionID == 1) {
2675            value = condAppendURL(ParamBean.SHOW_REVISION_DIFF_PARAMETER, "a");
2676        } else {
2677            value = condAppendURL(ParamBean.SHOW_REVISION_DIFF_PARAMETER, String.valueOf(versionID));
2678        }
2679        return value;
2680    }
2681
2682    // -------------------------------------------------------------------------
2683
// @author MJ
2684
/**
2685     * Build an http path containing the server name for the current site,
2686     * instead of the path from JahiaPrivateSettings. This does NOT end with a
2687     * "/" character.
2688     *
2689     * @return An http path leading to Jahia, built with the server name, and
2690     * the server port if nonstandard.
2691     */

2692    protected final String JavaDoc getJahiaCoreHttpPath() {
2693        //logger.debug(" request.getServername = " + mRequest.getServerName() );
2694
//logger.debug(" request.getContextPath = " + mRequest.getContextPath() );
2695
//logger.debug(" request.getServletPath = " + mRequest.getServletPath() );
2696
//logger.debug(" request.getRequestURI = " + mRequest.getRequestURI() );
2697
StringBuffer JavaDoc buffer = new StringBuffer JavaDoc();
2698
2699        if (Jahia.getContextPath() != null) {
2700            buffer.append(Jahia.getContextPath());
2701        } else {
2702            buffer.append(getRequest().getContextPath());
2703        }
2704
2705        if (Jahia.getServletPath() != null) {
2706            buffer.append(Jahia.getServletPath());
2707        } else {
2708            // should only happen when the Jahia servlet hasn't been called at
2709
// least once !
2710
buffer.append(getRequest().getServletPath());
2711        }
2712
2713        return buffer.toString();
2714    }
2715
2716    /**
2717     * Special wrap around response.encodeURL to deactivate the cache in case
2718     * jsessionid parameters are generated. This method modifies the internal
2719     * cacheStatus variable to modify the state.
2720     *
2721     * @param inputURL
2722     * the string for the URL to encode
2723     * @return the encoded URL string.
2724     */

2725    private String JavaDoc encodeURL(String JavaDoc inputURL) {
2726        if (inputURL.indexOf(";jsessionid=") != -1) {
2727            this.cacheStatus = ParamBean.CACHE_OFFONCE;
2728            logger.debug("jsession ALREADY in URL, returning URL unmodified...");
2729            return inputURL;
2730        }
2731        if (getRealResponse() == null) {
2732            return inputURL;
2733        }
2734        String JavaDoc encodedURL = getResponse().encodeURL(inputURL);
2735        int sessionIDPos = encodedURL.indexOf(";jsessionid=");
2736        if (sessionIDPos != -1) {
2737            if (!ParamBean.CACHE_OFFONCE.equals(this.cacheStatus)) {
2738                logger.debug("jsessionid in URL, setting cache to off_once...");
2739                this.cacheStatus = ParamBean.CACHE_OFFONCE;
2740                this.originalCacheStatus = ParamBean.CACHE_OFF;
2741            }
2742        }
2743        return encodedURL;
2744    }
2745
2746    public String JavaDoc getSiteURL() {
2747        if (getPage() != null) {
2748            return getSiteURL(getPageID(), true, true);
2749        }
2750        return getSiteURL(-1, true, true);
2751    }
2752
2753    /**
2754     * Generates a complete URL for a site. Uses the site URL serverName to
2755     * generate the URL *only* it is resolves in a DNS. Otherwise it simply uses
2756     * the current serverName and generates a URL with a /site/ parameter
2757     *
2758     * @param pageID
2759     * A site page ID on which the URL should point to.
2760     * @param withSessionID
2761     * a boolean that specifies whether we should call the encodeURL
2762     * method on the generated URL. Most of the time we will just
2763     * want to set this to true, but in the case of URLs sent by
2764     * email we do not, otherwise we have a security problem since we
2765     * are sending SESSION IDs to people that should not have them.
2766     * @param withOperationMode
2767     * a boolean that specifies whether we should include the
2768     * operation mode in the URL or not.
2769     * @return String a full URL to the site using the currently set values in
2770     * the ParamBean.
2771     */

2772    public String JavaDoc getSiteURL(int pageID, boolean withSessionID, boolean withOperationMode) {
2773        // let's test if the URL entered for the site is valid, and generate
2774
// an URL
2775
JahiaSite theSite = getSite();
2776        if (theSite == null) {
2777            return "";
2778        }
2779
2780        String JavaDoc siteServerName = theSite.getServerName();
2781        boolean serverNameValid = false;
2782        String JavaDoc sessionIDStr = null;
2783
2784        // let's check if we can resolve the site's server name address and if
2785
// it points to a Jahia installation. For this we connect to an URL and
2786
// try to retrieve a header specific to Jahia.
2787
GetMethod method = null;
2788        try {
2789
2790            Map JavaDoc contextVars = new HashMap JavaDoc();
2791            contextVars.put("request", getRequest());
2792            contextVars.put("siteServerName", siteServerName);
2793            String JavaDoc testURL = JahiaTools.evaluateExpressions(settings().getSiteServerNameTestURLExpr(), contextVars);
2794            URL JavaDoc targetURL = new URL JavaDoc(testURL);
2795
2796            // Create a method instance.
2797
method = new GetMethod(targetURL.toString());
2798
2799            // Execute the method.
2800
httpClient.executeMethod(method);
2801
2802            // Read the response body.
2803
Header javaVersionHeader = method.getResponseHeader("jahia-version");
2804            if (javaVersionHeader != null) {
2805                serverNameValid = true;
2806            }
2807
2808        } catch (Throwable JavaDoc t) {
2809            logger.error("Unable to check server name validity: " + siteServerName);
2810            serverNameValid = false;
2811        } finally {
2812            if (method != null)
2813                method.releaseConnection();
2814        }
2815
2816        StringBuffer JavaDoc newSiteURL = new StringBuffer JavaDoc(getRequest().getScheme() + "://");
2817        if (serverNameValid) {
2818            // let's construct an URL by deconstruct our current URL and
2819
// using the site name as a server name
2820
newSiteURL.append(siteServerName);
2821            if (!siteServerName.equals(getRequest().getServerName())) {
2822                // serverName has changed, we must transfer cookie information
2823
// for sessionID if there is some.
2824
try {
2825                    HttpSession JavaDoc session = getSession();
2826                    sessionIDStr = ";jsessionid=" + session.getId();
2827                } catch (JahiaSessionExpirationException jsee) {
2828                }
2829            }
2830            if (getRequest().getServerPort() != 80 && siteServerName.indexOf(":") == -1) {
2831                newSiteURL.append(":");
2832                newSiteURL.append(getRequest().getServerPort());
2833            }
2834            newSiteURL.append(getRequest().getContextPath());
2835            newSiteURL.append(Jahia.getServletPath());
2836        } else {
2837            // let's construct an URL by deconstruct our current URL and insering
2838
// the site id key as a parameter
2839
newSiteURL.append(getRequest().getServerName());
2840            if (getRequest().getServerPort() != 80) {
2841                newSiteURL.append(":");
2842                newSiteURL.append(getRequest().getServerPort());
2843            }
2844            newSiteURL.append(getRequest().getContextPath());
2845            newSiteURL.append(Jahia.getServletPath());
2846            newSiteURL.append("/site/");
2847            newSiteURL.append(theSite.getSiteKey());
2848        }
2849        if (pageID != -1) {
2850            newSiteURL.append("/pid/");
2851            newSiteURL.append(pageID);
2852        }
2853
2854        if (withOperationMode) {
2855            try {
2856                HttpSession JavaDoc session = this.getSession();
2857                if (session.getAttribute(OPERATION_MODE_PARAMETER) != null) {
2858                    if (session.getAttribute(OPERATION_MODE_PARAMETER) instanceof String JavaDoc) {
2859                        String JavaDoc oldOpMode = (String JavaDoc) session.getAttribute(OPERATION_MODE_PARAMETER);
2860                        newSiteURL.append(getOpModeURLPart(oldOpMode));
2861                    }
2862                } else {
2863                    if (this.getOperationMode() != null) {
2864                        newSiteURL.append(getOpModeURLPart(this.getOperationMode()));
2865                    }
2866                }
2867            } catch (JahiaSessionExpirationException jsee) {
2868                // this is not an error, we simply don't add the operation mode
2869
// if we don't find it in the session.
2870
}
2871        }
2872
2873        if (withSessionID) {
2874            String JavaDoc serverURL = encodeURL(newSiteURL.toString());
2875            if (sessionIDStr != null) {
2876                if (serverURL.indexOf("jsessionid") == -1) {
2877                    serverURL += sessionIDStr;
2878                }
2879            }
2880            return serverURL;
2881        } else {
2882            return newSiteURL.toString();
2883        }
2884    }
2885
2886    /**
2887     * @return a date which is the expiration date at which the page cache will
2888     * expire. If null, the page cache will never expire on a basis of
2889     * time (but may be flush upon content changes or other events).
2890     */

2891    public java.util.Date JavaDoc getCacheExpirationDate() {
2892        if (cacheExpirationDate != null)
2893            return cacheExpirationDate;
2894        else if (delayFromNow > -1) {
2895            return new Date JavaDoc(System.currentTimeMillis() + delayFromNow);
2896        }
2897        return null;
2898    }
2899
2900    public String JavaDoc getResponseMimeType() {
2901        return responseMimeType;
2902    }
2903
2904    /**
2905     * Sets the current page's cache expiration date.
2906     *
2907     * @param aCacheExpirationDate
2908     * a date which is the expiration date at which the page cache
2909     * will expire. If set to null or never set, the page cache will
2910     * never expire on a basis of time (but may be flush upon content
2911     * changes or other events).
2912     */

2913    final public void setCacheExpirationDate(java.util.Date JavaDoc aCacheExpirationDate) {
2914        this.cacheExpirationDate = aCacheExpirationDate;
2915    }
2916
2917    /**
2918     * Sets the current page's cache expiration delay, starting from the current
2919     * locale time.
2920     *
2921     * @param aDelayFromNow
2922     * an long value specifying the delay in milliseconds from now
2923     * for the expiration of the current page's cache.
2924     */

2925    final public void setCacheExpirationDelay(long aDelayFromNow) {
2926        this.delayFromNow = aDelayFromNow;
2927    }
2928
2929    /**
2930     * Gets the current page's cache expiration delay, starting from the current
2931     * locale time.
2932     *
2933     * @return The current page's cache expiration delay, starting from the
2934     * current locale time.
2935     */

2936    final public long getCacheExpirationDelay() {
2937        return delayFromNow;
2938    }
2939
2940    private void processActivationAction() throws JahiaException {
2941        // read validate as parameter
2942
String JavaDoc validate = getParameter(VALIDATE_PARAMETER);
2943        if (validate != null) {
2944            if (validate.equals("on")) {
2945                if ((contentPage != null) && (theUser != null)) {
2946                    logger.debug("Validating page");
2947                    Map JavaDoc languageStates = contentPage.getLanguagesStates(true);
2948                    Set JavaDoc languageCodes = languageStates.keySet();
2949                    ServicesRegistry.getInstance().getJahiaVersionService()
2950                            .activateStagedPage(
2951                                    contentPage.getID(),
2952                                    theUser,
2953                                    this,
2954                                    new StateModificationContext(new ContentPageKey(contentPage.getID()),
2955                                            languageCodes, false));
2956                    this.cacheStatus = ParamBean.CACHE_OFFONCE;
2957                } else {
2958                    logger.debug("Can't validate page, user or page not found");
2959                }
2960            }
2961        }
2962    }
2963
2964    private void resolveCacheStatus() {
2965        // read cache status
2966
String JavaDoc newCacheStatus = getParameter(CACHE_MODE_PARAMETER);
2967        if (newCacheStatus != null) {
2968            if (CACHE_ON.equals(newCacheStatus)) {
2969                this.cacheStatus = ParamBean.CACHE_ON;
2970            } else if (CACHE_ONLYUPDATE.equals(newCacheStatus)) {
2971                this.cacheStatus = ParamBean.CACHE_ONLYUPDATE;
2972            } else if (CACHE_OFFONCE.equals(newCacheStatus)) {
2973                this.cacheStatus = ParamBean.CACHE_OFFONCE;
2974            } else if (CACHE_BYPASS.equals(newCacheStatus)) {
2975                this.cacheStatus = ParamBean.CACHE_BYPASS;
2976            } else if (CACHE_OFF.equals(newCacheStatus)) {
2977                this.cacheStatus = ParamBean.CACHE_OFF;
2978            } else {
2979                this.cacheStatus = ParamBean.CACHE_ON;
2980            }
2981        } else {
2982            this.cacheStatus = ParamBean.CACHE_ON;
2983        }
2984        this.originalCacheStatus = this.cacheStatus;
2985    }
2986
2987    private void loadJahiaPageFromContentPage() throws JahiaException {
2988        if (contentPage != null) {
2989            thePage = contentPage.getPage(this.getEntryLoadRequest(), this.getOperationMode(), this.getUser());
2990        }
2991    }
2992
2993    private void checkPageAccess(HttpSession JavaDoc session, int pageID) throws JahiaException {
2994
2995        if (contentPage != null) {
2996            int deleteVersionID = contentPage.getDeleteVersionID();
2997            if ((deleteVersionID != -1)) {
2998
2999                // page has been recently deleted, let's check if we can
3000
// display it or not.
3001

3002                if (NORMAL.equals(opMode)) {
3003                    // this is the case of try to access a deleted page in NORMAL
3004
// mode which is not allowed.
3005
throw new JahiaPageNotFoundException(pageID);
3006                }
3007
3008                if (EDIT.equals(opMode) && (!contentPage.hasStagingEntries() || contentPage.isMarkedForDelete())) {
3009                    // try to access a deleted page or yet market for delete in EDIT
3010
// mode is not allowed.
3011
throw new JahiaPageNotFoundException(pageID);
3012                }
3013
3014                if ((COMPARE.equals(opMode) || (PREVIEW.equals(opMode)))
3015                        && (!contentPage.checkWriteAccess(theUser))) {
3016                    // we can view a deleted page in compare and preview mode
3017
// only if we can do edition operations on the page.
3018
throw new JahiaPageNotFoundException(pageID);
3019                }
3020            }
3021
3022            // if the page is not found, throw the associated exception
3023
if ((NORMAL.equals(opMode) || COMPARE.equals(opMode)) && !contentPage.hasActiveEntries()
3024                    && (deleteVersionID == -1)) {
3025
3026                opMode = EDIT;
3027                entryLoadRequest = new EntryLoadRequest(EntryLoadRequest.STAGING_WORKFLOW_STATE, 0, getLocales());
3028                // reset substitute entry load request
3029
resetSubstituteEntryLoadRequest();
3030                if (!getEngine().equals(Login_Engine.ENGINE_NAME)) {
3031                    throw new JahiaForbiddenAccessException();
3032                }
3033            }
3034        }
3035
3036        if ((contentPage == null)
3037                || ((NORMAL.equals(opMode) || COMPARE.equals(opMode))
3038                        && getEntryLoadRequest().isCurrent() && !contentPage.hasActiveEntries())
3039                || ((NORMAL.equals(opMode) || COMPARE.equals(opMode))
3040                        && getEntryLoadRequest().isCurrent() && (contentPage.getTitle(getEntryLoadRequest()) == null))) {
3041            throw new JahiaPageNotFoundException(pageID);
3042        }
3043        // Ensure if the requested page is a page of the current site
3044
if (contentPage.getJahiaID() != getSiteID()) {
3045            contentPage = site.getHomeContentPage();
3046        }
3047
3048        // last requested page
3049
Integer JavaDoc lrpID = (Integer JavaDoc) session.getAttribute(SESSION_LAST_REQUESTED_PAGE_ID);
3050        if (lrpID == null) {
3051            lrpID = new Integer JavaDoc(-1);
3052        }
3053        newPageRequest = (lrpID.intValue() != getPageID());
3054        lastRequestedPageID = lrpID.intValue();
3055    }
3056
3057    private void checkLocales() throws JahiaException {
3058        if ((NORMAL.equals(opMode) || COMPARE.equals(opMode))
3059                && !contentPage.hasEntries(ContentPage.ACTIVE_PAGE_INFOS, getLocale().toString())) {
3060            ArrayList JavaDoc siteLanguages = site.getLanguageSettingsAsLocales(true);
3061            boolean skip = false;
3062            for (int i = 0; i < siteLanguages.size(); i++) {
3063                Locale JavaDoc locale = (Locale JavaDoc) siteLanguages.get(i);
3064                if (!skip && contentPage.hasEntries(ContentPage.ACTIVE_PAGE_INFOS, locale.toString())) {
3065                    changeLanguage(locale);
3066                    skip = true;
3067                }
3068            }
3069        }
3070    }
3071
3072    private void resolveDiffVersionID(String JavaDoc verInfo) {
3073        // read difference version id
3074
verInfo = getParameter(ParamBean.SHOW_REVISION_DIFF_PARAMETER);
3075        if (verInfo != null) {
3076            if (verInfo.equals("s")) {
3077                this.diffVersionID = 2; // staging
3078
} else if (verInfo.equals("a")) {
3079                this.diffVersionID = 1; // active
3080
} else {
3081                try {
3082                    int ver = Integer.parseInt(verInfo);
3083                    this.diffVersionID = ver;
3084                } catch (NumberFormatException JavaDoc nfe) {
3085                    logger.debug("Diff VersionID format exception", nfe);
3086                }
3087            }
3088        }
3089    }
3090
3091    private String JavaDoc resolveEntryState() throws JahiaException {
3092        // read version info as parameter
3093
String JavaDoc verInfo = getParameter(ENTRY_STATE_PARAMETER);
3094        if (verInfo != null) {
3095            if (verInfo.equals("s")) {
3096                this.entryLoadRequest = new EntryLoadRequest(EntryLoadRequest.STAGING_WORKFLOW_STATE, 0, getLocales());
3097                this.cacheStatus = ParamBean.CACHE_OFFONCE;
3098                this.originalCacheStatus = this.cacheStatus;
3099            } else if (verInfo.equals("a")) {
3100                this.entryLoadRequest = new EntryLoadRequest(EntryLoadRequest.ACTIVE_WORKFLOW_STATE, 0, getLocales());
3101                this.cacheStatus = ParamBean.CACHE_OFFONCE;
3102                this.originalCacheStatus = this.cacheStatus;
3103            } else {
3104                try {
3105                    int ver = Integer.parseInt(verInfo);
3106                    this.entryLoadRequest = new EntryLoadRequest(EntryLoadRequest.VERSIONED_WORKFLOW_STATE, ver,
3107                            getLocales());
3108                    logger.debug("Using entry load request specified : " + this.entryLoadRequest);
3109                    this.cacheStatus = ParamBean.CACHE_OFFONCE;
3110                    this.originalCacheStatus = this.cacheStatus;
3111                } catch (NumberFormatException JavaDoc nfe) {
3112                    logger.debug("VersionID format exception", nfe);
3113                }
3114            }
3115        }
3116        return verInfo;
3117    }
3118
3119    private void processLockAction(HttpServletResponse JavaDoc response, int pageID) throws JahiaException {
3120        // #ifdef LOCK
3121
// let's unlock the object
3122
try {
3123            LockService lockRegistry = ServicesRegistry.getInstance().getLockService();
3124            String JavaDoc lockKeyStr = getParameter(ParamBean.STEAL_LOCK);
3125            LockKey lockKey;
3126            if (lockKeyStr != null) {
3127                lockKey = LockKey.composeLockKey(lockKeyStr);
3128                lockRegistry.steal(lockKey, getUser(), getSessionID());
3129                response.sendRedirect(composePageUrl(pageID));
3130            } else {
3131                lockKeyStr = getParameter(ParamBean.RELEASE_LOCK);
3132                if (lockKeyStr != null) {
3133                    lockKey = LockKey.composeLockKey(lockKeyStr);
3134                    lockRegistry.release(lockKey, getUser(), getSessionID());
3135                    response.sendRedirect(composePageUrl(pageID));
3136                }
3137            }
3138        } catch (java.io.IOException JavaDoc ioe) {
3139            logger.error("Problem with sendRedirect response", ioe);
3140        }
3141        // #endif
3142
}
3143
3144    private void resolveLocales(HttpSession JavaDoc session) throws JahiaException {
3145        // let's try to get the current locale if it was in the session.
3146
String JavaDoc languageCode = getParameter(LANGUAGE_CODE);
3147
3148        if (languageCode != null) {
3149            Locale JavaDoc previousLocale = (Locale JavaDoc) session.getAttribute(SESSION_LOCALE);
3150            Locale JavaDoc newLocale = LanguageCodeConverters.languageCodeToLocale(languageCode);
3151            if (previousLocale == null || !previousLocale.equals(newLocale)) {
3152                // if the locale has changed, we must reevaluate the full
3153
// locale list.
3154
localeList = null;
3155            }
3156            session.setAttribute(SESSION_LOCALE, newLocale);
3157        }
3158        if (session.getAttribute(SESSION_LOCALE) != null) {
3159            currentLocale = (Locale JavaDoc) session.getAttribute(SESSION_LOCALE);
3160        } else {
3161            // it's not in the session, let's try to determine what it should
3162
// be...
3163
currentLocale = null;
3164            localeList = null;
3165            getLocale();
3166            session.setAttribute(SESSION_LOCALE, currentLocale);
3167        }
3168
3169        // CHECK LOCALE INTEGRITY
3170
this.currentLocale = (Locale JavaDoc) getLocales().get(1); // 0=shared,
3171
// 1=resolved locale
3172
session.setAttribute(SESSION_LOCALE, currentLocale);
3173
3174        this.entryLoadRequest = new EntryLoadRequest(EntryLoadRequest.ACTIVE_WORKFLOW_STATE, 0, getLocales());
3175        // compute version info
3176
if (this.getSiteID() != -1) {
3177            if (((opMode == EDIT) || (opMode == PREVIEW) || (opMode == COMPARE))
3178                    && (ServicesRegistry.getInstance().getJahiaVersionService().isStagingEnabled(this.getSiteID()))) {
3179                this.entryLoadRequest = new EntryLoadRequest(EntryLoadRequest.STAGING_WORKFLOW_STATE, 0, getLocales());
3180                this.cacheStatus = ParamBean.CACHE_OFFONCE;
3181                this.originalCacheStatus = this.cacheStatus;
3182            }
3183        }
3184        // reset the Struts locale
3185
session.setAttribute(Globals.LOCALE_KEY, currentLocale);
3186        // reset the JSTL locale
3187
Config.set(session, Config.FMT_LOCALE, currentLocale);
3188
3189    }
3190
3191    private Boolean JavaDoc canEdit = null;
3192
3193    public boolean canEditCurrentPage() {
3194        if (canEdit == null) {
3195            // JahiaBaseACL cpAcl = contentPage.getACL();
3196
canEdit = Boolean.valueOf(contentPage.checkWriteAccess(theUser, true)
3197                    || contentPage.checkAdminAccess(theUser, true));
3198        }
3199        return canEdit.booleanValue();
3200    }
3201
3202    private void resolveOpMode(HttpSession JavaDoc session) throws JahiaInitializationException,
3203            JahiaSessionExpirationException {
3204        // Define the requested Operation
3205
String JavaDoc paramOpMode = getParameter(OPERATION_MODE_PARAMETER);
3206        if (paramOpMode != null) {
3207            if (NORMAL.equals(paramOpMode))
3208                opMode = NORMAL;
3209            else if (COMPARE.equals(paramOpMode))
3210                opMode = canEditCurrentPage() ? COMPARE : NORMAL;
3211            else if (EDIT.equals(paramOpMode))
3212                opMode = canEditCurrentPage() ? EDIT : NORMAL;
3213            else if (PREVIEW.equals(paramOpMode))
3214                opMode = canEditCurrentPage() ? PREVIEW : NORMAL;
3215            else if (DEBUG.equals(paramOpMode))
3216                opMode = contentPage.checkAdminAccess(theUser) ? DEBUG : NORMAL;
3217        }
3218
3219        if ((NORMAL.equals(opMode) || COMPARE.equals(opMode)) && !contentPage.hasActiveEntries()
3220                && canEditCurrentPage()) {
3221            try {
3222                int deleteVersionID = contentPage.getDeleteVersionID();
3223                if (deleteVersionID == -1) {
3224                    // switch to edit mode because no active version available
3225
opMode = EDIT;
3226                }
3227            } catch (JahiaException je) {
3228                logger.error("Error while trying to test if page was deleted", je);
3229            }
3230        }
3231
3232        String JavaDoc oldOpMode;
3233        if (session.getAttribute(OPERATION_MODE_PARAMETER) instanceof String JavaDoc) {
3234            oldOpMode = (String JavaDoc) session.getAttribute(OPERATION_MODE_PARAMETER);
3235        } else {
3236            oldOpMode = NORMAL;
3237        }
3238
3239        // only store mode in session if we are not in administration
3240
// servlet.
3241
if (!isInAdminMode()) {
3242            session.setAttribute(OPERATION_MODE_PARAMETER, opMode);
3243        }
3244        if (!oldOpMode.equals(opMode)) {
3245            logger.debug("Mode switch detected.");
3246            // We detected a mode switch, let's flush both the HTML cache and
3247
// the application cache...
3248
JahiaApplicationsDispatchingService dispatcher = ServicesRegistry.getInstance()
3249                    .getJahiaApplicationsDispatchingService();
3250            if (dispatcher != null) {
3251                dispatcher.flushAllSessionsCaches(session);
3252            }
3253
3254            // We flush all the pages for the current user.
3255
HtmlCache htmlCache = CacheFactory.getHtmlCache();
3256            if (htmlCache != null)
3257                htmlCache.invalidateUserEntries(getUser().getUsername());
3258            else
3259                logger.warn("Could not get the HTML cache instance!!");
3260        }
3261    }
3262
3263    private void resolveUser(HttpServletRequest JavaDoc request, HttpSession JavaDoc session) throws JahiaException {
3264
3265        Pipeline authPipeline = Jahia.getAuthPipeline();
3266        try {
3267            authPipeline.invoke(this);
3268        } catch (PipelineException pe) {
3269            logger.error("Error while authorizing user", pe);
3270            theUser = null;
3271        }
3272
3273        // sanity check for user guest, in case we're in the context of
3274
// concurrent requests on multiple sites
3275
if (theUser != null) {
3276            if (theUser.getUsername().equals(JahiaUserManagerService.GUEST_USERNAME)
3277                    && theUser.getSiteID() != this.getSiteID()) {
3278                // guest user coming from different site, let's ignore it.
3279
theUser = null;
3280            }
3281        }
3282
3283        if (theUser == null) {
3284            setUserGuest(getSiteID());
3285        }
3286    }
3287
3288    public void setSite(JahiaSite jahiaSite) {
3289        this.site = jahiaSite;
3290        this.siteID = jahiaSite.getID();
3291        this.siteKey = jahiaSite.getSiteKey();
3292    }
3293
3294    /**
3295     * Used internally by authorization pipeline. Do not call this method from
3296     * somewhere else (such as templates)
3297     *
3298     * @param aUser
3299     * JahiaUser
3300     */

3301    public void setTheUser(JahiaUser aUser) {
3302        this.theUser = aUser;
3303    }
3304
3305    public void setResponseMimeType(String JavaDoc aResponseMimeType) {
3306        this.responseMimeType = aResponseMimeType;
3307    }
3308
3309    /**
3310     * Returns true if str passed is a reserved keyword. Added by Intellogix
3311     *
3312     * @param str
3313     * @return true if str passed is a reserved keyword.
3314     */

3315    public static boolean isReservedKeyword(String JavaDoc str) {
3316        if (ParamBean.ENGINE_NAME_PARAMETER.equals(str) || ParamBean.SITE_KEY_PARAMETER.equals(str)
3317                || ParamBean.PAGE_ID_PARAMETER.equals(str) || ParamBean.CONTAINERLIST_ID_PARAMETER.equals(str)
3318                || ParamBean.CONTAINER_ID_PARAMETER.equals(str) || ParamBean.FIELD_ID_PARAMETER.equals(str)
3319                || ParamBean.OPERATION_MODE_PARAMETER.equals(str) || ParamBean.ENTRY_STATE_PARAMETER.equals(str)
3320                || ParamBean.SHOW_REVISION_DIFF_PARAMETER.equals(str) || ParamBean.VALIDATE_PARAMETER.equals(str)
3321                || ParamBean.LANGUAGE_CODE.equals(str) || ParamBean.RELEASE_LOCK.equals(str)
3322                || ParamBean.STEAL_LOCK.equals(str) || ParamBean.TEMPLATE_PARAMETER.equals(str)
3323                || ParamBean.CACHE_MODE_PARAMETER.equals(str))
3324            return true;
3325        else if (isContainerScroll(str) == true)
3326            return true;
3327        return false;
3328    }
3329
3330    public static boolean isContainerScroll(String JavaDoc str) {
3331        if (str.startsWith(CONTAINER_SCROLL_PREFIX_PARAMETER))
3332            return true;
3333        return false;
3334    }
3335
3336    public String JavaDoc toString() {
3337        return "ParamBean{user: " + theUser + "; siteId: " + siteID + "; locale: " + currentLocale + "; session: "
3338                + mRequest.getSession(false) + "; ...}";
3339    }
3340
3341    protected void setData(JahiaSite jSite, JahiaUser jUser) {
3342        site = jSite;
3343        siteID = jSite.getID();
3344        siteKey = jSite.getSiteKey();
3345        theUser = jUser;
3346    }
3347} // end ParamBean
3348
Popular Tags