1   /**
2    * Copyright (c) 2000-2008 Liferay, Inc. All rights reserved.
3    *
4    * Permission is hereby granted, free of charge, to any person obtaining a copy
5    * of this software and associated documentation files (the "Software"), to deal
6    * in the Software without restriction, including without limitation the rights
7    * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8    * copies of the Software, and to permit persons to whom the Software is
9    * furnished to do so, subject to the following conditions:
10   *
11   * The above copyright notice and this permission notice shall be included in
12   * all copies or substantial portions of the Software.
13   *
14   * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15   * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16   * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17   * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18   * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19   * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
20   * SOFTWARE.
21   */
22  
23  package com.liferay.portal.util;
24  
25  import com.germinus.easyconf.Filter;
26  
27  import com.liferay.portal.NoSuchLayoutException;
28  import com.liferay.portal.NoSuchUserException;
29  import com.liferay.portal.PortalException;
30  import com.liferay.portal.SystemException;
31  import com.liferay.portal.kernel.language.LanguageUtil;
32  import com.liferay.portal.kernel.portlet.FriendlyURLMapper;
33  import com.liferay.portal.kernel.portlet.LiferayPortletMode;
34  import com.liferay.portal.kernel.servlet.StringServletResponse;
35  import com.liferay.portal.kernel.util.ArrayUtil;
36  import com.liferay.portal.kernel.util.CalendarFactoryUtil;
37  import com.liferay.portal.kernel.util.CharPool;
38  import com.liferay.portal.kernel.util.ContentTypes;
39  import com.liferay.portal.kernel.util.GetterUtil;
40  import com.liferay.portal.kernel.util.Http;
41  import com.liferay.portal.kernel.util.HttpUtil;
42  import com.liferay.portal.kernel.util.InstancePool;
43  import com.liferay.portal.kernel.util.JavaConstants;
44  import com.liferay.portal.kernel.util.LocaleUtil;
45  import com.liferay.portal.kernel.util.ParamUtil;
46  import com.liferay.portal.kernel.util.StringComparator;
47  import com.liferay.portal.kernel.util.StringMaker;
48  import com.liferay.portal.kernel.util.StringPool;
49  import com.liferay.portal.kernel.util.StringUtil;
50  import com.liferay.portal.kernel.util.Validator;
51  import com.liferay.portal.model.ClassName;
52  import com.liferay.portal.model.Company;
53  import com.liferay.portal.model.Group;
54  import com.liferay.portal.model.Layout;
55  import com.liferay.portal.model.LayoutSet;
56  import com.liferay.portal.model.LayoutTypePortlet;
57  import com.liferay.portal.model.Portlet;
58  import com.liferay.portal.model.PortletApp;
59  import com.liferay.portal.model.User;
60  import com.liferay.portal.model.impl.GroupImpl;
61  import com.liferay.portal.model.impl.LayoutImpl;
62  import com.liferay.portal.model.impl.RoleImpl;
63  import com.liferay.portal.plugin.PluginPackageUtil;
64  import com.liferay.portal.security.permission.ActionKeys;
65  import com.liferay.portal.security.permission.PermissionCheckerFactory;
66  import com.liferay.portal.security.permission.PermissionCheckerImpl;
67  import com.liferay.portal.service.ClassNameServiceUtil;
68  import com.liferay.portal.service.CompanyLocalServiceUtil;
69  import com.liferay.portal.service.GroupLocalServiceUtil;
70  import com.liferay.portal.service.LayoutLocalServiceUtil;
71  import com.liferay.portal.service.PortletLocalServiceUtil;
72  import com.liferay.portal.service.UserLocalServiceUtil;
73  import com.liferay.portal.service.UserServiceUtil;
74  import com.liferay.portal.service.permission.UserPermissionUtil;
75  import com.liferay.portal.theme.ThemeDisplay;
76  import com.liferay.portlet.ActionResponseImpl;
77  import com.liferay.portlet.PortletBag;
78  import com.liferay.portlet.PortletBagPool;
79  import com.liferay.portlet.PortletConfigFactory;
80  import com.liferay.portlet.PortletPreferencesImpl;
81  import com.liferay.portlet.PortletPreferencesWrapper;
82  import com.liferay.portlet.PortletRequestImpl;
83  import com.liferay.portlet.PortletResponseImpl;
84  import com.liferay.portlet.PortletURLImpl;
85  import com.liferay.portlet.RenderRequestImpl;
86  import com.liferay.portlet.RenderResponseImpl;
87  import com.liferay.portlet.UserAttributes;
88  import com.liferay.util.BeanUtil;
89  import com.liferay.util.Encryptor;
90  import com.liferay.util.JS;
91  import com.liferay.util.servlet.SessionErrors;
92  
93  import java.io.IOException;
94  
95  import java.net.URL;
96  
97  import java.rmi.RemoteException;
98  
99  import java.util.Arrays;
100 import java.util.Calendar;
101 import java.util.Date;
102 import java.util.Enumeration;
103 import java.util.HashMap;
104 import java.util.HashSet;
105 import java.util.Iterator;
106 import java.util.List;
107 import java.util.Locale;
108 import java.util.Map;
109 import java.util.Properties;
110 import java.util.ResourceBundle;
111 import java.util.Set;
112 import java.util.TimeZone;
113 
114 import javax.portlet.ActionRequest;
115 import javax.portlet.ActionResponse;
116 import javax.portlet.PortletConfig;
117 import javax.portlet.PortletMode;
118 import javax.portlet.PortletPreferences;
119 import javax.portlet.PortletRequest;
120 import javax.portlet.PortletResponse;
121 import javax.portlet.PortletURL;
122 import javax.portlet.PreferencesValidator;
123 import javax.portlet.RenderRequest;
124 import javax.portlet.ValidatorException;
125 import javax.portlet.WindowState;
126 import javax.portlet.filter.PortletRequestWrapper;
127 import javax.portlet.filter.PortletResponseWrapper;
128 
129 import javax.servlet.RequestDispatcher;
130 import javax.servlet.ServletContext;
131 import javax.servlet.ServletException;
132 import javax.servlet.http.HttpServletRequest;
133 import javax.servlet.http.HttpServletRequestWrapper;
134 import javax.servlet.http.HttpServletResponse;
135 import javax.servlet.http.HttpSession;
136 
137 import org.apache.commons.logging.Log;
138 import org.apache.commons.logging.LogFactory;
139 import org.apache.struts.Globals;
140 
141 /**
142  * <a href="PortalImpl.java.html"><b><i>View Source</i></b></a>
143  *
144  * @author Brian Wing Shun Chan
145  * @author Brian Myunghun Kim
146  * @author Jorge Ferrer
147  *
148  */
149 public class PortalImpl implements Portal {
150 
151     public PortalImpl() {
152 
153         // Computer name
154 
155         _computerName = System.getProperty("env.COMPUTERNAME");
156 
157         if (Validator.isNull(_computerName)) {
158             _computerName = System.getProperty("env.HOST");
159         }
160 
161         if (Validator.isNull(_computerName)) {
162             _computerName = System.getProperty("env.HOSTNAME");
163         }
164 
165         // Portal lib directory
166 
167         ClassLoader classLoader = getClass().getClassLoader();
168 
169         URL url = classLoader.getResource(
170             "com/liferay/portal/util/PortalUtil.class");
171 
172         String file = url.getFile();
173 
174         if (_log.isInfoEnabled()) {
175             _log.info("Portal lib url " + file);
176         }
177 
178         int pos = file.indexOf("/com/liferay/portal/util/");
179 
180         _portalLibDir = file.substring(0, pos + 1);
181 
182         if (_portalLibDir.endsWith("/WEB-INF/classes/")) {
183             _portalLibDir = _portalLibDir.substring(
184                 0, _portalLibDir.length() - 8) + "lib/";
185         }
186         else {
187             pos = _portalLibDir.indexOf("/WEB-INF/lib/");
188 
189             if (pos != -1) {
190                 _portalLibDir =
191                     _portalLibDir.substring(0, pos) + "/WEB-INF/lib/";
192             }
193         }
194 
195         if (_portalLibDir.startsWith("file:/")) {
196             _portalLibDir = _portalLibDir.substring(5, _portalLibDir.length());
197         }
198 
199         if (_log.isInfoEnabled()) {
200             _log.info("Portal lib directory " + _portalLibDir);
201         }
202 
203         // CDN host
204 
205         _cdnHost = PropsUtil.get(PropsUtil.CDN_HOST);
206 
207         // Paths
208 
209         _pathContext = PropsUtil.get(PropsUtil.PORTAL_CTX);
210 
211         if (_pathContext.equals(StringPool.SLASH)) {
212             _pathContext = StringPool.BLANK;
213         }
214 
215         _pathFriendlyURLPrivateGroup =
216             _pathContext +
217                 PropsValues.LAYOUT_FRIENDLY_URL_PRIVATE_GROUP_SERVLET_MAPPING;
218         _pathFriendlyURLPrivateUser =
219             _pathContext +
220                 PropsValues.LAYOUT_FRIENDLY_URL_PRIVATE_USER_SERVLET_MAPPING;
221         _pathFriendlyURLPublic =
222             _pathContext +
223                 PropsValues.LAYOUT_FRIENDLY_URL_PUBLIC_SERVLET_MAPPING;
224         _pathImage = _cdnHost + _pathContext + PATH_IMAGE;
225         _pathMain = _pathContext + PATH_MAIN;
226 
227         // Groups
228 
229         String customSystemGroups[] =
230             PropsUtil.getArray(PropsUtil.SYSTEM_GROUPS);
231 
232         if ((customSystemGroups == null) || (customSystemGroups.length == 0)) {
233             _allSystemGroups = GroupImpl.SYSTEM_GROUPS;
234         }
235         else {
236             _allSystemGroups = ArrayUtil.append(
237                 GroupImpl.SYSTEM_GROUPS, customSystemGroups);
238         }
239 
240         _sortedSystemGroups = new String[_allSystemGroups.length];
241 
242         System.arraycopy(
243             _allSystemGroups, 0, _sortedSystemGroups, 0,
244             _allSystemGroups.length);
245 
246         Arrays.sort(_sortedSystemGroups, new StringComparator());
247 
248         // Regular roles
249 
250         String customSystemRoles[] = PropsUtil.getArray(PropsUtil.SYSTEM_ROLES);
251 
252         if ((customSystemRoles == null) || (customSystemRoles.length == 0)) {
253             _allSystemRoles = RoleImpl.SYSTEM_ROLES;
254         }
255         else {
256             _allSystemRoles = ArrayUtil.append(
257                 RoleImpl.SYSTEM_ROLES, customSystemRoles);
258         }
259 
260         _sortedSystemRoles = new String[_allSystemRoles.length];
261 
262         System.arraycopy(
263             _allSystemRoles, 0, _sortedSystemRoles, 0, _allSystemRoles.length);
264 
265         Arrays.sort(_sortedSystemRoles, new StringComparator());
266 
267         // Community roles
268 
269         String customSystemCommunityRoles[] =
270             PropsUtil.getArray(PropsUtil.SYSTEM_COMMUNITY_ROLES);
271 
272         if ((customSystemCommunityRoles == null) ||
273             (customSystemCommunityRoles.length == 0)) {
274 
275             _allSystemCommunityRoles = RoleImpl.SYSTEM_COMMUNITY_ROLES;
276         }
277         else {
278             _allSystemCommunityRoles = ArrayUtil.append(
279                 RoleImpl.SYSTEM_COMMUNITY_ROLES, customSystemCommunityRoles);
280         }
281 
282         _sortedSystemCommunityRoles =
283             new String[_allSystemCommunityRoles.length];
284 
285         System.arraycopy(
286             _allSystemCommunityRoles, 0, _sortedSystemCommunityRoles, 0,
287                 _allSystemCommunityRoles.length);
288 
289         Arrays.sort(_sortedSystemCommunityRoles, new StringComparator());
290 
291         // Organization Roles
292 
293         String customSystemOrganizationRoles[] =
294             PropsUtil.getArray(PropsUtil.SYSTEM_ORGANIZATION_ROLES);
295 
296         if ((customSystemOrganizationRoles == null) ||
297             (customSystemOrganizationRoles.length == 0)) {
298 
299             _allSystemOrganizationRoles = RoleImpl.SYSTEM_ORGANIZATION_ROLES;
300         }
301         else {
302             _allSystemOrganizationRoles = ArrayUtil.append(
303                 RoleImpl.SYSTEM_ORGANIZATION_ROLES,
304                 customSystemOrganizationRoles);
305         }
306 
307         _sortedSystemOrganizationRoles =
308             new String[_allSystemOrganizationRoles.length];
309 
310         System.arraycopy(
311             _allSystemOrganizationRoles, 0, _sortedSystemOrganizationRoles, 0,
312                 _allSystemOrganizationRoles.length);
313 
314         Arrays.sort(_sortedSystemOrganizationRoles, new StringComparator());
315 
316         // Reserved parameter names
317 
318         _reservedParams = new HashSet<String>();
319 
320         _reservedParams.add("p_l_id");
321         _reservedParams.add("p_l_reset");
322         _reservedParams.add("p_p_id");
323         _reservedParams.add("p_p_lifecycle");
324         _reservedParams.add("p_p_state");
325         _reservedParams.add("p_p_mode");
326         _reservedParams.add("p_p_resource_id");
327         _reservedParams.add("p_p_cacheability");
328         _reservedParams.add("p_p_width");
329         _reservedParams.add("p_p_col_id");
330         _reservedParams.add("p_p_col_pos");
331         _reservedParams.add("p_p_col_count");
332         _reservedParams.add("p_p_static");
333     }
334 
335     public void clearRequestParameters(RenderRequest req) {
336 
337         // Clear the render parameters if they were set during processAction
338 
339         ThemeDisplay themeDisplay = (ThemeDisplay)req.getAttribute(
340             WebKeys.THEME_DISPLAY);
341 
342         if (themeDisplay.isLifecycleAction()) {
343             ((RenderRequestImpl)req).getRenderParameters().clear();
344         }
345     }
346 
347     public void copyRequestParameters(ActionRequest req, ActionResponse res) {
348         try {
349             ActionResponseImpl resImpl = (ActionResponseImpl)res;
350 
351             Map<String, String[]> renderParameters =
352                 resImpl.getRenderParameterMap();
353 
354             res.setRenderParameter("p_p_lifecycle", "1");
355 
356             Enumeration<String> enu = req.getParameterNames();
357 
358             while (enu.hasMoreElements()) {
359                 String param = enu.nextElement();
360                 String[] values = req.getParameterValues(param);
361 
362                 if (renderParameters.get(
363                         resImpl.getNamespace() + param) == null) {
364 
365                     res.setRenderParameter(param, values);
366                 }
367             }
368         }
369         catch (IllegalStateException ise) {
370 
371             // This should only happen if the developer called
372             // sendRedirect of javax.portlet.ActionResponse
373 
374         }
375     }
376 
377     public String getCDNHost() {
378         return _cdnHost;
379     }
380 
381     public String getClassName(long classNameId) {
382         try {
383             ClassName className = ClassNameServiceUtil.getClassName(
384                 classNameId);
385 
386             return className.getValue();
387         }
388         catch (Exception e) {
389             throw new RuntimeException(
390                 "Unable to get class name from id " + classNameId);
391         }
392     }
393 
394     public long getClassNameId(Class<?> classObj) {
395         return getClassNameId(classObj.getName());
396     }
397 
398     public long getClassNameId(String value) {
399         try {
400             ClassName className = ClassNameServiceUtil.getClassName(value);
401 
402             return className.getClassNameId();
403         }
404         catch (Exception e) {
405             throw new RuntimeException(
406                 "Unable to get class name from value " + value);
407         }
408     }
409 
410     public String getClassNamePortletId(String className) {
411         String portletId = StringPool.BLANK;
412 
413         if (className.startsWith("com.liferay.portlet.blogs")) {
414             portletId = PortletKeys.BLOGS;
415         }
416         else if (className.startsWith("com.liferay.portlet.bookmarks")) {
417             portletId = PortletKeys.BOOKMARKS;
418         }
419         else if (className.startsWith("com.liferay.portlet.documentlibrary")) {
420             portletId = PortletKeys.DOCUMENT_LIBRARY;
421         }
422         else if (className.startsWith("com.liferay.portlet.imagegallery")) {
423             portletId = PortletKeys.IMAGE_GALLERY;
424         }
425         else if (className.startsWith("com.liferay.portlet.journal")) {
426             portletId = PortletKeys.JOURNAL;
427         }
428         else if (className.startsWith("com.liferay.portlet.messageboards")) {
429             portletId = PortletKeys.MESSAGE_BOARDS;
430         }
431         else if (className.startsWith("com.liferay.portlet.wiki")) {
432             portletId = PortletKeys.WIKI;
433         }
434 
435         return portletId;
436     }
437 
438     public Company getCompany(HttpServletRequest req)
439         throws PortalException, SystemException {
440 
441         long companyId = getCompanyId(req);
442 
443         if (companyId <= 0) {
444             return null;
445         }
446 
447         Company company = (Company)req.getAttribute(WebKeys.COMPANY);
448 
449         if (company == null) {
450             company = CompanyLocalServiceUtil.getCompanyById(companyId);
451 
452             req.setAttribute(WebKeys.COMPANY, company);
453         }
454 
455         return company;
456     }
457 
458     public Company getCompany(ActionRequest req)
459         throws PortalException, SystemException {
460 
461         return getCompany(getHttpServletRequest(req));
462     }
463 
464     public Company getCompany(RenderRequest req)
465         throws PortalException, SystemException {
466 
467         return getCompany(getHttpServletRequest(req));
468     }
469 
470     public long getCompanyId(HttpServletRequest req) {
471         return PortalInstances.getCompanyId(req);
472     }
473 
474     public long getCompanyId(ActionRequest req) {
475         return getCompanyId(getHttpServletRequest(req));
476     }
477 
478     public long getCompanyId(PortletRequest req) {
479         long companyId = 0;
480 
481         if (req instanceof ActionRequest) {
482             companyId = getCompanyId((ActionRequest)req);
483         }
484         else {
485             companyId = getCompanyId((RenderRequest)req);
486         }
487 
488         return companyId;
489     }
490 
491     public long getCompanyId(RenderRequest req) {
492         return getCompanyId(getHttpServletRequest(req));
493     }
494 
495     public long getCompanyIdByWebId(ServletContext ctx) {
496         String webId = GetterUtil.getString(
497             ctx.getInitParameter("company_web_id"));
498 
499         return getCompanyIdByWebId(webId);
500     }
501 
502     public long getCompanyIdByWebId(String webId) {
503         long companyId = 0;
504 
505         try {
506             Company company = CompanyLocalServiceUtil.getCompanyByWebId(webId);
507 
508             companyId = company.getCompanyId();
509         }
510         catch (Exception e) {
511             _log.error(e.getMessage());
512         }
513 
514         return companyId;
515     }
516 
517     public String getComputerName() {
518         return _computerName;
519     }
520 
521     public String getCurrentURL(HttpServletRequest req) {
522         String currentURL = (String)req.getAttribute(WebKeys.CURRENT_URL);
523 
524         if (currentURL == null) {
525             currentURL = ParamUtil.getString(req, "currentURL");
526 
527             if (Validator.isNull(currentURL)) {
528                 if (true) {
529                     currentURL = HttpUtil.getCompleteURL(req);
530                 }
531                 else {
532 
533                     // Do we need to trim redirects?
534 
535                     currentURL = _getCurrentURL(req);
536                 }
537 
538                 if ((Validator.isNotNull(currentURL)) &&
539                     (currentURL.indexOf("j_security_check") == -1)) {
540 
541                     currentURL = currentURL.substring(
542                         currentURL.indexOf("://") + 3, currentURL.length());
543 
544                     currentURL = currentURL.substring(
545                         currentURL.indexOf("/"), currentURL.length());
546                 }
547             }
548 
549             if (Validator.isNull(currentURL)) {
550                 currentURL = getPathMain();
551             }
552 
553             req.setAttribute(WebKeys.CURRENT_URL, currentURL);
554         }
555 
556         return currentURL;
557     }
558 
559     public String getCurrentURL(PortletRequest req) {
560         return (String)req.getAttribute(WebKeys.CURRENT_URL);
561     }
562 
563     public Date getDate(int month, int day, int year, PortalException pe)
564         throws PortalException {
565 
566         return getDate(month, day, year, null, pe);
567     }
568 
569     public Date getDate(
570             int month, int day, int year, TimeZone timeZone, PortalException pe)
571         throws PortalException {
572 
573         return getDate(month, day, year, -1, -1, timeZone, pe);
574     }
575 
576     public Date getDate(
577             int month, int day, int year, int hour, int min, PortalException pe)
578         throws PortalException {
579 
580         return getDate(month, day, year, hour, min, null, pe);
581     }
582 
583     public Date getDate(
584             int month, int day, int year, int hour, int min, TimeZone timeZone,
585             PortalException pe)
586         throws PortalException {
587 
588         if (!Validator.isGregorianDate(month, day, year)) {
589             throw pe;
590         }
591         else {
592             Calendar cal = null;
593 
594             if (timeZone == null) {
595                 cal = CalendarFactoryUtil.getCalendar();
596             }
597             else {
598                 cal = CalendarFactoryUtil.getCalendar(timeZone);
599             }
600 
601             if ((hour == -1) || (min == -1)) {
602                 cal.set(year, month, day);
603             }
604             else {
605                 cal.set(year, month, day, hour, min, 0);
606             }
607 
608             Date date = cal.getTime();
609 
610             /*if (timeZone != null &&
611                 cal.before(CalendarFactoryUtil.getCalendar(timeZone))) {
612 
613                 throw pe;
614             }*/
615 
616             return date;
617         }
618     }
619 
620     public String getHost(HttpServletRequest req) {
621         req = getOriginalServletRequest(req);
622 
623         String host = req.getHeader("Host");
624 
625         if (host != null) {
626             host = host.trim().toLowerCase();
627 
628             int pos = host.indexOf(':');
629 
630             if (pos >= 0) {
631                 host = host.substring(0, pos);
632             }
633         }
634         else {
635             host = null;
636         }
637 
638         return host;
639     }
640 
641     public String getHost(ActionRequest req) {
642         return getHost(getHttpServletRequest(req));
643     }
644 
645     public String getHost(RenderRequest req) {
646         return getHost(getHttpServletRequest(req));
647     }
648 
649     public HttpServletRequest getHttpServletRequest(PortletRequest req) {
650         if (req instanceof PortletRequestImpl) {
651             PortletRequestImpl reqImpl = (PortletRequestImpl)req;
652 
653             return reqImpl.getHttpServletRequest();
654         }
655         else if (req instanceof PortletRequestWrapper) {
656             PortletRequestWrapper reqWrapper = (PortletRequestWrapper)req;
657 
658             return getHttpServletRequest(reqWrapper.getRequest());
659         }
660         else {
661             throw new RuntimeException(
662                 "Unable to get the HTTP servlet request from " +
663                     req.getClass().getName());
664         }
665     }
666 
667     public HttpServletResponse getHttpServletResponse(PortletResponse res) {
668         if (res instanceof ActionResponseImpl) {
669             ActionResponseImpl resImpl = (ActionResponseImpl)res;
670 
671             return resImpl.getHttpServletResponse();
672         }
673         else if (res instanceof RenderResponseImpl) {
674             RenderResponseImpl resImpl = (RenderResponseImpl)res;
675 
676             return resImpl.getHttpServletResponse();
677         }
678         else if (res instanceof PortletResponseWrapper) {
679             PortletResponseWrapper resWrapper = (PortletResponseWrapper)res;
680 
681             return getHttpServletResponse(resWrapper.getResponse());
682         }
683         else {
684             PortletResponseImpl resImpl =
685                 PortletResponseImpl.getPortletResponseImpl(res);
686 
687             return resImpl.getHttpServletResponse();
688         }
689     }
690 
691     public String getLayoutEditPage(Layout layout) {
692         return PropsUtil.getComponentProperties().getString(
693             PropsUtil.LAYOUT_EDIT_PAGE, Filter.by(layout.getType()));
694     }
695 
696     public String getLayoutViewPage(Layout layout) {
697         return PropsUtil.getComponentProperties().getString(
698             PropsUtil.LAYOUT_VIEW_PAGE, Filter.by(layout.getType()));
699     }
700 
701     public String getLayoutURL(ThemeDisplay themeDisplay)
702         throws PortalException, SystemException {
703 
704         return getLayoutURL(themeDisplay.getLayout(), themeDisplay);
705     }
706 
707     public String getLayoutURL(Layout layout, ThemeDisplay themeDisplay)
708         throws PortalException, SystemException {
709 
710         return getLayoutURL(layout, themeDisplay, true);
711     }
712 
713     public String getLayoutURL(
714             Layout layout, ThemeDisplay themeDisplay, boolean doAsUser)
715         throws PortalException, SystemException {
716 
717         if (layout == null) {
718             return themeDisplay.getPathMain() + PATH_PORTAL_LAYOUT;
719         }
720 
721         if (!layout.getType().equals(LayoutImpl.TYPE_URL)) {
722             String layoutFriendlyURL = getLayoutFriendlyURL(
723                 layout, themeDisplay);
724 
725             if (Validator.isNotNull(layoutFriendlyURL)) {
726                 if (doAsUser &&
727                     Validator.isNotNull(themeDisplay.getDoAsUserId())) {
728 
729                     layoutFriendlyURL = HttpUtil.addParameter(
730                         layoutFriendlyURL, "doAsUserId",
731                         themeDisplay.getDoAsUserId());
732                 }
733 
734                 return layoutFriendlyURL;
735             }
736         }
737 
738         String layoutURL = getLayoutActualURL(layout);
739 
740         if (doAsUser && Validator.isNotNull(themeDisplay.getDoAsUserId())) {
741             layoutURL = HttpUtil.addParameter(
742                 layoutURL, "doAsUserId", themeDisplay.getDoAsUserId());
743         }
744 
745         return layoutURL;
746     }
747 
748     public String getLayoutActualURL(Layout layout)
749         throws PortalException, SystemException {
750 
751         return getLayoutActualURL(layout, getPathMain());
752     }
753 
754     public String getLayoutActualURL(Layout layout, String mainPath)
755         throws PortalException, SystemException {
756 
757         Map<Object, Object> vars = new HashMap<Object, Object>();
758 
759         vars.put("liferay:mainPath", mainPath);
760         vars.put("liferay:plid", String.valueOf(layout.getPlid()));
761         vars.putAll(layout.getLayoutType().getTypeSettingsProperties());
762 
763         String href = PropsUtil.getComponentProperties().getString(
764             PropsUtil.LAYOUT_URL,
765             Filter.by(layout.getType()).setVariables(vars));
766 
767         return href;
768     }
769 
770     public String getLayoutActualURL(
771             long groupId, boolean privateLayout, String mainPath,
772             String friendlyURL)
773         throws PortalException, SystemException {
774 
775         return getLayoutActualURL(
776             groupId, privateLayout, mainPath, friendlyURL, null);
777     }
778 
779     public String getLayoutActualURL(
780             long groupId, boolean privateLayout, String mainPath,
781             String friendlyURL, Map<String, String[]> params)
782         throws PortalException, SystemException {
783 
784         Layout layout = null;
785         String queryString = StringPool.BLANK;
786 
787         if (Validator.isNull(friendlyURL)) {
788             List<Layout> layouts = LayoutLocalServiceUtil.getLayouts(
789                 groupId, privateLayout, LayoutImpl.DEFAULT_PARENT_LAYOUT_ID);
790 
791             if (layouts.size() > 0) {
792                 layout = layouts.get(0);
793             }
794             else {
795                 throw new NoSuchLayoutException(
796                     "{groupId=" + groupId + ",privateLayout=" + privateLayout +
797                         "} does not have any layouts");
798             }
799         }
800         else {
801             Object[] friendlyURLMapper = getPortletFriendlyURLMapper(
802                 groupId, privateLayout, friendlyURL, params);
803 
804             layout = (Layout)friendlyURLMapper[0];
805             queryString = (String)friendlyURLMapper[1];
806         }
807 
808         String layoutActualURL = getLayoutActualURL(layout, mainPath);
809 
810         if (Validator.isNotNull(queryString)) {
811             layoutActualURL = layoutActualURL + queryString;
812         }
813 
814         return layoutActualURL;
815     }
816 
817     public String getLayoutFriendlyURL(Layout layout, ThemeDisplay themeDisplay)
818         throws PortalException, SystemException {
819 
820         if (!isLayoutFriendliable(layout)) {
821             return null;
822         }
823 
824         String layoutFriendlyURL = layout.getFriendlyURL();
825 
826         LayoutSet layoutSet = layout.getLayoutSet();
827 
828         if (Validator.isNotNull(layoutSet.getVirtualHost())) {
829             String portalURL = getPortalURL(
830                 layoutSet.getVirtualHost(), themeDisplay.getServerPort(),
831                 themeDisplay.isSecure());
832 
833             // Use the layout set's virtual host setting only if the layout set
834             // is already used for the current request
835 
836             long curLayoutSetId =
837                 themeDisplay.getLayout().getLayoutSet().getLayoutSetId();
838 
839             if ((layoutSet.getLayoutSetId() != curLayoutSetId) ||
840                     (portalURL.startsWith(themeDisplay.getURLPortal()))) {
841 
842                 return portalURL + getPathContext() + layoutFriendlyURL;
843             }
844         }
845 
846         Group group = layout.getGroup();
847 
848         String friendlyURL = null;
849 
850         if (layout.isPrivateLayout()) {
851             if (group.isUser()) {
852                 friendlyURL = getPathFriendlyURLPrivateUser();
853             }
854             else {
855                 friendlyURL = getPathFriendlyURLPrivateGroup();
856             }
857         }
858         else {
859             friendlyURL = getPathFriendlyURLPublic();
860         }
861 
862         return friendlyURL + group.getFriendlyURL() + layoutFriendlyURL;
863     }
864 
865     public String getLayoutTarget(Layout layout) {
866         Properties typeSettingsProps = layout.getTypeSettingsProperties();
867 
868         String target = typeSettingsProps.getProperty("target");
869 
870         if (Validator.isNull(target)) {
871             target = StringPool.BLANK;
872         }
873         else {
874             target = "target=\"" + target + "\"";
875         }
876 
877         return target;
878     }
879 
880     public String getJsSafePortletId(String portletId) {
881         return JS.getSafeName(portletId);
882     }
883 
884     public Locale getLocale(HttpServletRequest req) {
885         return (Locale)req.getSession().getAttribute(Globals.LOCALE_KEY);
886     }
887 
888     public Locale getLocale(RenderRequest req) {
889         return getLocale(getHttpServletRequest(req));
890     }
891 
892     public HttpServletRequest getOriginalServletRequest(
893         HttpServletRequest req) {
894 
895         HttpServletRequest originalReq = req;
896 
897         while (originalReq.getClass().getName().startsWith("com.liferay.")) {
898 
899             // Get original request so that portlets inside portlets render
900             // properly
901 
902             originalReq = (HttpServletRequest)
903                 ((HttpServletRequestWrapper)originalReq).getRequest();
904         }
905 
906         return originalReq;
907     }
908 
909     public String getPathContext() {
910         return _pathContext;
911     }
912 
913     public String getPathFriendlyURLPrivateGroup() {
914         return _pathFriendlyURLPrivateGroup;
915     }
916 
917     public String getPathFriendlyURLPrivateUser() {
918         return _pathFriendlyURLPrivateUser;
919     }
920 
921     public String getPathFriendlyURLPublic() {
922         return _pathFriendlyURLPublic;
923     }
924 
925     public String getPathImage() {
926         return _pathImage;
927     }
928 
929     public String getPathMain() {
930         return _pathMain;
931     }
932 
933     public long getPlidIdFromFriendlyURL(long companyId, String friendlyURL) {
934         String[] urlParts = friendlyURL.split("\\/", 4);
935 
936         if ((friendlyURL.charAt(0) != CharPool.SLASH) &&
937             (urlParts.length != 4)) {
938 
939             return LayoutImpl.DEFAULT_PLID;
940         }
941 
942         boolean privateLayout = true;
943 
944         String urlPrefix = StringPool.SLASH + urlParts[1];
945 
946         if (getPathFriendlyURLPublic().equals(urlPrefix)) {
947             privateLayout = false;
948         }
949         else if (getPathFriendlyURLPrivateGroup().equals(urlPrefix) ||
950                  getPathFriendlyURLPrivateUser().equals(urlPrefix)) {
951 
952             privateLayout = true;
953         }
954         else {
955             return LayoutImpl.DEFAULT_PLID;
956         }
957 
958         Group group = null;
959 
960         try {
961             group = GroupLocalServiceUtil.getFriendlyURLGroup(
962                 companyId, StringPool.SLASH + urlParts[2]);
963         }
964         catch (Exception e) {
965         }
966 
967         if (group != null) {
968             Layout layout = null;
969 
970             try {
971                 layout = LayoutLocalServiceUtil.getFriendlyURLLayout(
972                     group.getGroupId(), privateLayout,
973                     StringPool.SLASH + urlParts[3]);
974 
975                 return layout.getPlid();
976             }
977             catch (Exception e) {
978             }
979         }
980 
981         return LayoutImpl.DEFAULT_PLID;
982     }
983 
984     public String getPortalLibDir() {
985         return _portalLibDir;
986     }
987 
988     public String getPortalURL(ThemeDisplay themeDisplay) {
989         String serverName = themeDisplay.getServerName();
990 
991         Layout layout = themeDisplay.getLayout();
992 
993         if (layout != null) {
994             LayoutSet layoutSet = layout.getLayoutSet();
995 
996             if (Validator.isNotNull(layoutSet.getVirtualHost())) {
997                 serverName = layoutSet.getVirtualHost();
998             }
999         }
1000
1001        return getPortalURL(
1002            serverName, themeDisplay.getServerPort(), themeDisplay.isSecure());
1003    }
1004
1005    public String getPortalURL(HttpServletRequest req) {
1006        return getPortalURL(req, req.isSecure());
1007    }
1008
1009    public String getPortalURL(HttpServletRequest req, boolean secure) {
1010        return getPortalURL(req.getServerName(), req.getServerPort(), secure);
1011    }
1012
1013    public String getPortalURL(PortletRequest req) {
1014        return getPortalURL(req, req.isSecure());
1015    }
1016
1017    public String getPortalURL(PortletRequest req, boolean secure) {
1018        return getPortalURL(req.getServerName(), req.getServerPort(), secure);
1019    }
1020
1021    public String getPortalURL(
1022        String serverName, int serverPort, boolean secure) {
1023
1024        StringMaker sm = new StringMaker();
1025
1026        if (secure || Http.HTTPS.equals(PropsValues.WEB_SERVER_PROTOCOL)) {
1027            sm.append(Http.HTTPS_WITH_SLASH);
1028        }
1029        else {
1030            sm.append(Http.HTTP_WITH_SLASH);
1031        }
1032
1033        if (Validator.isNull(PropsValues.WEB_SERVER_HOST)) {
1034            sm.append(serverName);
1035        }
1036        else {
1037            sm.append(PropsValues.WEB_SERVER_HOST);
1038        }
1039
1040        if (!secure) {
1041            if (PropsValues.WEB_SERVER_HTTP_PORT == -1) {
1042                if ((serverPort != Http.HTTP_PORT) &&
1043                    (serverPort != Http.HTTPS_PORT)) {
1044
1045                    sm.append(StringPool.COLON);
1046                    sm.append(serverPort);
1047                }
1048            }
1049            else {
1050                if ((PropsValues.WEB_SERVER_HTTP_PORT != serverPort) ||
1051                    (PropsValues.WEB_SERVER_HTTP_PORT != Http.HTTP_PORT)) {
1052
1053                    sm.append(StringPool.COLON);
1054                    sm.append(PropsValues.WEB_SERVER_HTTP_PORT);
1055                }
1056            }
1057        }
1058
1059        if (secure) {
1060            if (PropsValues.WEB_SERVER_HTTPS_PORT == -1) {
1061                if ((serverPort != Http.HTTP_PORT) &&
1062                    (serverPort != Http.HTTPS_PORT)) {
1063
1064                    sm.append(StringPool.COLON);
1065                    sm.append(serverPort);
1066                }
1067            }
1068            else {
1069                if ((PropsValues.WEB_SERVER_HTTPS_PORT != serverPort) ||
1070                    (PropsValues.WEB_SERVER_HTTPS_PORT != Http.HTTPS_PORT)) {
1071
1072                    sm.append(StringPool.COLON);
1073                    sm.append(PropsValues.WEB_SERVER_HTTPS_PORT);
1074                }
1075            }
1076        }
1077
1078        return sm.toString();
1079    }
1080
1081    public Object[] getPortletFriendlyURLMapper(
1082            long groupId, boolean privateLayout, String url)
1083        throws PortalException, SystemException {
1084
1085        return getPortletFriendlyURLMapper(groupId, privateLayout, url, null);
1086    }
1087
1088    public Object[] getPortletFriendlyURLMapper(
1089            long groupId, boolean privateLayout, String url,
1090            Map<String, String[]> params)
1091        throws PortalException, SystemException {
1092
1093        String friendlyURL = url;
1094        String queryString = StringPool.BLANK;
1095
1096        List<FriendlyURLMapper> friendlyURLMappers =
1097            PortletLocalServiceUtil.getFriendlyURLMappers();
1098
1099        Iterator<FriendlyURLMapper> itr = friendlyURLMappers.iterator();
1100
1101        while (itr.hasNext()) {
1102            FriendlyURLMapper friendlyURLMapper = itr.next();
1103
1104            if (url.endsWith(
1105                    StringPool.SLASH + friendlyURLMapper.getMapping())) {
1106
1107                url += StringPool.SLASH;
1108            }
1109
1110            int pos = url.indexOf(
1111                StringPool.SLASH + friendlyURLMapper.getMapping() +
1112                    StringPool.SLASH);
1113
1114            if (pos != -1) {
1115                friendlyURL = url.substring(0, pos);
1116
1117                Map<String, String[]> actualParams = null;
1118
1119                if (params != null) {
1120                    actualParams = new HashMap<String, String[]>(params);
1121                }
1122                else {
1123                    actualParams = new HashMap<String, String[]>();
1124                }
1125
1126                /*Object lifecycle = actualParams.get("p_p_lifecycle");
1127
1128                if ((lifecycle == null) ||
1129                    (((String[])lifecycle).length == 0)) {
1130
1131                    actualParams.put("p_p_lifecycle", "0");
1132                }
1133
1134                Object state = actualParams.get("p_p_state");
1135
1136                if ((state == null) || (((String[])state).length == 0)) {
1137                    actualParams.put(
1138                        "p_p_state", WindowState.MAXIMIZED.toString());
1139                }*/
1140
1141                friendlyURLMapper.populateParams(
1142                    url.substring(pos), actualParams);
1143
1144                queryString =
1145                    StringPool.AMPERSAND +
1146                        HttpUtil.parameterMapToString(actualParams, false);
1147
1148                break;
1149            }
1150        }
1151
1152        friendlyURL = StringUtil.replace(
1153            friendlyURL, StringPool.DOUBLE_SLASH, StringPool.SLASH);
1154
1155        if (friendlyURL.endsWith(StringPool.SLASH)) {
1156            friendlyURL = friendlyURL.substring(0, friendlyURL.length() - 1);
1157        }
1158
1159        Layout layout = LayoutLocalServiceUtil.getFriendlyURLLayout(
1160            groupId, privateLayout, friendlyURL);
1161
1162        return new Object[] {layout, queryString};
1163    }
1164
1165    public long getPortletGroupId(long plid) {
1166        Layout layout = null;
1167
1168        try {
1169            layout = LayoutLocalServiceUtil.getLayout(plid);
1170        }
1171        catch (Exception e) {
1172        }
1173
1174        return getPortletGroupId(layout);
1175    }
1176
1177    public long getPortletGroupId(Layout layout) {
1178        if (layout == null) {
1179            return 0;
1180        }
1181        else {
1182            return layout.getGroupId();
1183        }
1184    }
1185
1186    public long getPortletGroupId(HttpServletRequest req) {
1187        Layout layout = (Layout)req.getAttribute(WebKeys.LAYOUT);
1188
1189        return getPortletGroupId(layout);
1190    }
1191
1192    public long getPortletGroupId(ActionRequest req) {
1193        return getPortletGroupId(getHttpServletRequest(req));
1194    }
1195
1196    public long getPortletGroupId(RenderRequest req) {
1197        return getPortletGroupId(getHttpServletRequest(req));
1198    }
1199
1200    public String getPortletNamespace(String portletId) {
1201        StringMaker sm = new StringMaker();
1202
1203        sm.append(StringPool.UNDERLINE);
1204        sm.append(portletId);
1205        sm.append(StringPool.UNDERLINE);
1206
1207        return sm.toString();
1208    }
1209
1210    public String getPortletTitle(
1211        String portletId, long companyId, String languageId) {
1212
1213        Locale locale = LocaleUtil.fromLanguageId(languageId);
1214
1215        return getPortletTitle(portletId, companyId, locale);
1216    }
1217
1218    public String getPortletTitle(
1219        String portletId, long companyId, Locale locale) {
1220
1221        StringMaker sm = new StringMaker();
1222
1223        sm.append(JavaConstants.JAVAX_PORTLET_TITLE);
1224        sm.append(StringPool.PERIOD);
1225        sm.append(portletId);
1226
1227        return LanguageUtil.get(companyId, locale, sm.toString());
1228    }
1229
1230    public String getPortletTitle(String portletId, User user) {
1231        StringMaker sm = new StringMaker();
1232
1233        sm.append(JavaConstants.JAVAX_PORTLET_TITLE);
1234        sm.append(StringPool.PERIOD);
1235        sm.append(portletId);
1236
1237        return LanguageUtil.get(
1238            user.getCompanyId(), user.getLocale(), sm.toString());
1239    }
1240
1241    public String getPortletTitle(
1242        Portlet portlet, ServletContext ctx, Locale locale) {
1243
1244        PortletConfig portletConfig = PortletConfigFactory.create(portlet, ctx);
1245
1246        ResourceBundle resourceBundle = portletConfig.getResourceBundle(locale);
1247
1248        return resourceBundle.getString(JavaConstants.JAVAX_PORTLET_TITLE);
1249    }
1250
1251    public String getPortletXmlFileName()
1252        throws PortalException, SystemException {
1253
1254        if (PrefsPropsUtil.getBoolean(
1255                PropsUtil.AUTO_DEPLOY_CUSTOM_PORTLET_XML,
1256                PropsValues.AUTO_DEPLOY_CUSTOM_PORTLET_XML)) {
1257
1258            return PORTLET_XML_FILE_NAME_CUSTOM;
1259        }
1260        else {
1261            return PORTLET_XML_FILE_NAME_STANDARD;
1262        }
1263    }
1264
1265    public PortletPreferences getPreferences(HttpServletRequest req) {
1266        RenderRequest renderRequest = (RenderRequest)req.getAttribute(
1267            JavaConstants.JAVAX_PORTLET_REQUEST);
1268
1269        PortletPreferences prefs = null;
1270
1271        if (renderRequest != null) {
1272            PortletPreferencesWrapper prefsWrapper =
1273                (PortletPreferencesWrapper)renderRequest.getPreferences();
1274
1275            prefs = prefsWrapper.getPreferencesImpl();
1276        }
1277
1278        return prefs;
1279    }
1280
1281    public PreferencesValidator getPreferencesValidator(Portlet portlet) {
1282        PortletApp portletApp = portlet.getPortletApp();
1283
1284        if (portletApp.isWARFile()) {
1285            PortletBag portletBag = PortletBagPool.get(
1286                portlet.getRootPortletId());
1287
1288            return portletBag.getPreferencesValidatorInstance();
1289        }
1290        else {
1291            PreferencesValidator prefsValidator = null;
1292
1293            if (Validator.isNotNull(portlet.getPreferencesValidator())) {
1294                prefsValidator =
1295                    (PreferencesValidator)InstancePool.get(
1296                        portlet.getPreferencesValidator());
1297            }
1298
1299            return prefsValidator;
1300        }
1301    }
1302
1303    public User getSelectedUser(HttpServletRequest req)
1304        throws PortalException, RemoteException, SystemException {
1305
1306        return getSelectedUser(req, true);
1307    }
1308
1309    public User getSelectedUser(HttpServletRequest req, boolean checkPermission)
1310        throws PortalException, RemoteException, SystemException {
1311
1312        long userId = ParamUtil.getLong(req, "p_u_i_d");
1313
1314        User user = null;
1315
1316        try {
1317            if (checkPermission) {
1318                user = UserServiceUtil.getUserById(userId);
1319            }
1320            else {
1321                user = UserLocalServiceUtil.getUserById(userId);
1322            }
1323        }
1324        catch (NoSuchUserException nsue) {
1325        }
1326
1327        return user;
1328    }
1329
1330    public User getSelectedUser(ActionRequest req)
1331        throws PortalException, RemoteException, SystemException {
1332
1333        return getSelectedUser(req, true);
1334    }
1335
1336    public User getSelectedUser(ActionRequest req, boolean checkPermission)
1337        throws PortalException, RemoteException, SystemException {
1338
1339        return getSelectedUser(getHttpServletRequest(req), checkPermission);
1340    }
1341
1342    public User getSelectedUser(RenderRequest req)
1343        throws PortalException, RemoteException, SystemException {
1344
1345        return getSelectedUser(req, true);
1346    }
1347
1348    public User getSelectedUser(RenderRequest req, boolean checkPermission)
1349        throws PortalException, RemoteException, SystemException {
1350
1351        return getSelectedUser(getHttpServletRequest(req), checkPermission);
1352    }
1353
1354    public String getStrutsAction(HttpServletRequest req) {
1355        String strutsAction = ParamUtil.getString(req, "struts_action");
1356
1357        if (Validator.isNotNull(strutsAction)) {
1358
1359            // This method should only return a Struts action if you're dealing
1360            // with a regular HTTP servlet request, not a portlet HTTP servlet
1361            // request.
1362
1363            return StringPool.BLANK;
1364        }
1365
1366        int strutsActionCount = 0;
1367
1368        Enumeration<String> enu = req.getParameterNames();
1369
1370        while (enu.hasMoreElements()) {
1371            String name = enu.nextElement();
1372
1373            int pos = name.indexOf("_struts_action");
1374
1375            if (pos != -1) {
1376                strutsActionCount++;
1377
1378                // There should never be more than one Struts action
1379
1380                if (strutsActionCount > 1) {
1381                    return StringPool.BLANK;
1382                }
1383
1384                String curStrutsAction = ParamUtil.getString(req, name);
1385
1386                if (Validator.isNotNull(curStrutsAction)) {
1387
1388                    // The Struts action must be for the correct portlet
1389
1390                    String portletId1 = name.substring(1, pos);
1391                    String portletId2 = ParamUtil.getString(req, "p_p_id");
1392
1393                    if (portletId1.equals(portletId2)) {
1394                        strutsAction = curStrutsAction;
1395                    }
1396                }
1397            }
1398        }
1399
1400        return strutsAction;
1401    }
1402
1403    public String[] getSystemCommunityRoles() {
1404        return _allSystemCommunityRoles;
1405    }
1406
1407    public String[] getSystemGroups() {
1408        return _allSystemGroups;
1409    }
1410
1411    public String[] getSystemOrganizationRoles() {
1412        return _allSystemOrganizationRoles;
1413    }
1414
1415    public String[] getSystemRoles() {
1416        return _allSystemRoles;
1417    }
1418
1419    public Date getUptime() {
1420        return UP_TIME;
1421    }
1422
1423    public String getURLWithSessionId(String url, String sessionId) {
1424
1425        // LEP-4787
1426
1427        int x = url.indexOf(StringPool.SEMICOLON);
1428
1429        if (x != -1) {
1430            return url;
1431        }
1432
1433        x = url.indexOf(StringPool.QUESTION);
1434
1435        if (x != -1) {
1436            StringMaker sm = new StringMaker();
1437
1438            sm.append(url.substring(0, x));
1439            sm.append(_JSESSIONID);
1440            sm.append(sessionId);
1441            sm.append(url.substring(x));
1442
1443            return sm.toString();
1444        }
1445
1446        // In IE6, http://www.abc.com;jsessionid=XYZ does not work,
1447        // but http://www.abc.com/;jsessionid=XYZ does work.
1448
1449        x = url.indexOf(StringPool.DOUBLE_SLASH);
1450
1451        StringMaker sm = new StringMaker();
1452
1453        sm.append(url);
1454
1455        if (x != -1) {
1456            int y = url.lastIndexOf(StringPool.SLASH);
1457
1458            if (x + 1 == y) {
1459                sm.append(StringPool.SLASH);
1460            }
1461        }
1462
1463        sm.append(_JSESSIONID);
1464        sm.append(sessionId);
1465
1466        return sm.toString();
1467    }
1468
1469    public User getUser(HttpServletRequest req)
1470        throws PortalException, SystemException {
1471
1472        long userId = getUserId(req);
1473
1474        if (userId <= 0) {
1475
1476            // Portlet WARs may have the correct remote user and not have the
1477            // correct user id because the user id is saved in the session
1478            // and may not be accessible by the portlet WAR's session. This
1479            // behavior is inconsistent across different application servers.
1480
1481            String remoteUser = req.getRemoteUser();
1482
1483            if (remoteUser == null) {
1484                return null;
1485            }
1486
1487            userId = GetterUtil.getLong(remoteUser);
1488        }
1489
1490        User user = (User)req.getAttribute(WebKeys.USER);
1491
1492        if (user == null) {
1493            user = UserLocalServiceUtil.getUserById(userId);
1494
1495            req.setAttribute(WebKeys.USER, user);
1496        }
1497
1498        return user;
1499    }
1500
1501    public User getUser(ActionRequest req)
1502        throws PortalException, SystemException {
1503
1504        return getUser(getHttpServletRequest(req));
1505    }
1506
1507    public User getUser(RenderRequest req)
1508        throws PortalException, SystemException {
1509
1510        return getUser(getHttpServletRequest(req));
1511    }
1512
1513    public long getUserId(HttpServletRequest req) {
1514        Long userIdObj = (Long)req.getAttribute(WebKeys.USER_ID);
1515
1516        if (userIdObj != null) {
1517            return userIdObj.longValue();
1518        }
1519
1520        if (!PropsValues.PORTAL_JAAS_ENABLE &&
1521            PropsValues.PORTAL_IMPERSONATION_ENABLE) {
1522
1523            String doAsUserIdString = ParamUtil.getString(req, "doAsUserId");
1524
1525            try {
1526                long doAsUserId = getDoAsUserId(req, doAsUserIdString);
1527
1528                if (doAsUserId > 0) {
1529                    if (_log.isDebugEnabled()) {
1530                        _log.debug("Impersonating user " + doAsUserId);
1531                    }
1532
1533                    return doAsUserId;
1534                }
1535            }
1536            catch (Exception e) {
1537                _log.error("Unable to impersonate user " + doAsUserIdString, e);
1538            }
1539        }
1540
1541        HttpSession ses = req.getSession();
1542
1543        userIdObj = (Long)ses.getAttribute(WebKeys.USER_ID);
1544
1545        if (userIdObj != null) {
1546            req.setAttribute(WebKeys.USER_ID, userIdObj);
1547
1548            return userIdObj.longValue();
1549        }
1550        else {
1551            return 0;
1552        }
1553    }
1554
1555    public long getUserId(ActionRequest req) {
1556        return getUserId(getHttpServletRequest(req));
1557    }
1558
1559    public long getUserId(RenderRequest req) {
1560        return getUserId(getHttpServletRequest(req));
1561    }
1562
1563    public String getUserName(long userId, String defaultUserName) {
1564        return getUserName(
1565            userId, defaultUserName, UserAttributes.USER_NAME_FULL);
1566    }
1567
1568    public String getUserName(
1569        long userId, String defaultUserName, String userAttribute) {
1570
1571        return getUserName(userId, defaultUserName, userAttribute, null);
1572    }
1573
1574    public String getUserName(
1575        long userId, String defaultUserName, HttpServletRequest req) {
1576
1577        return getUserName(
1578            userId, defaultUserName, UserAttributes.USER_NAME_FULL, req);
1579    }
1580
1581    public String getUserName(
1582        long userId, String defaultUserName, String userAttribute,
1583        HttpServletRequest req) {
1584
1585        String userName = defaultUserName;
1586
1587        try {
1588            User user = UserLocalServiceUtil.getUserById(userId);
1589
1590            if (userAttribute.equals(UserAttributes.USER_NAME_FULL)) {
1591                userName = user.getFullName();
1592            }
1593            else {
1594                userName = user.getScreenName();
1595            }
1596
1597            if (req != null) {
1598                Layout layout = (Layout)req.getAttribute(WebKeys.LAYOUT);
1599
1600                PortletURL portletURL = new PortletURLImpl(
1601                    req, PortletKeys.DIRECTORY, layout.getPlid(),
1602                    PortletRequest.RENDER_PHASE);
1603
1604                portletURL.setWindowState(WindowState.MAXIMIZED);
1605                portletURL.setPortletMode(PortletMode.VIEW);
1606
1607                portletURL.setParameter(
1608                    "struts_action", "/directory/edit_user");
1609                portletURL.setParameter(
1610                    "p_u_i_d", String.valueOf(user.getUserId()));
1611
1612                userName =
1613                    "<a href=\"" + portletURL.toString() + "\">" + userName +
1614                        "</a>";
1615            }
1616        }
1617        catch (Exception e) {
1618        }
1619
1620        return userName;
1621    }
1622
1623    public String getUserPassword(HttpSession ses) {
1624        return (String)ses.getAttribute(WebKeys.USER_PASSWORD);
1625    }
1626
1627    public String getUserPassword(HttpServletRequest req) {
1628        return getUserPassword(req.getSession());
1629    }
1630
1631    public String getUserPassword(ActionRequest req) {
1632        return getUserPassword(getHttpServletRequest(req));
1633    }
1634
1635    public String getUserPassword(RenderRequest req) {
1636        return getUserPassword(getHttpServletRequest(req));
1637    }
1638
1639    public String getUserValue(long userId, String param, String defaultValue)
1640        throws SystemException {
1641
1642        if (Validator.isNotNull(defaultValue)) {
1643            return defaultValue;
1644        }
1645        else {
1646            try {
1647                User user = UserLocalServiceUtil.getUserById(userId);
1648
1649                return BeanUtil.getString(user, param, defaultValue);
1650            }
1651            catch (PortalException pe) {
1652                return StringPool.BLANK;
1653            }
1654        }
1655    }
1656
1657    public boolean isMethodGet(PortletRequest req) {
1658        HttpServletRequest httpReq = getHttpServletRequest(req);
1659
1660        String method = GetterUtil.getString(httpReq.getMethod());
1661
1662        if (method.equalsIgnoreCase(_METHOD_GET)) {
1663            return true;
1664        }
1665        else {
1666            return false;
1667        }
1668    }
1669
1670    public boolean isMethodPost(PortletRequest req) {
1671        HttpServletRequest httpReq = getHttpServletRequest(req);
1672
1673        String method = GetterUtil.getString(httpReq.getMethod());
1674
1675        if (method.equalsIgnoreCase(_METHOD_POST)) {
1676            return true;
1677        }
1678        else {
1679            return false;
1680        }
1681    }
1682
1683    public boolean isLayoutFriendliable(Layout layout) {
1684        return PropsUtil.getComponentProperties().getBoolean(
1685            PropsUtil.LAYOUT_URL_FRIENDLIABLE,
1686            Filter.by(layout.getType()), true);
1687    }
1688
1689    public boolean isLayoutParentable(Layout layout) {
1690        return isLayoutParentable(layout.getType());
1691    }
1692
1693    public boolean isLayoutParentable(String type) {
1694        return PropsUtil.getComponentProperties().getBoolean(
1695            PropsUtil.LAYOUT_PARENTABLE, Filter.by(type), true);
1696    }
1697
1698    public boolean isLayoutSitemapable(Layout layout) {
1699        if (layout.isPrivateLayout()) {
1700            return false;
1701        }
1702
1703        return PropsUtil.getComponentProperties().getBoolean(
1704            PropsUtil.LAYOUT_SITEMAPABLE, Filter.by(layout.getType()), true);
1705    }
1706
1707    public boolean isReservedParameter(String name) {
1708        return _reservedParams.contains(name);
1709    }
1710
1711    public boolean isSystemGroup(String groupName) {
1712        if (groupName == null) {
1713            return false;
1714        }
1715
1716        groupName = groupName.trim();
1717
1718        int pos = Arrays.binarySearch(
1719            _sortedSystemGroups, groupName, new StringComparator());
1720
1721        if (pos >= 0) {
1722            return true;
1723        }
1724        else {
1725            return false;
1726        }
1727    }
1728
1729    public boolean isSystemRole(String roleName) {
1730        if (roleName == null) {
1731            return false;
1732        }
1733
1734        roleName = roleName.trim();
1735
1736        int pos = Arrays.binarySearch(
1737            _sortedSystemRoles, roleName, new StringComparator());
1738
1739        if (pos >= 0) {
1740            return true;
1741        }
1742        else {
1743            pos = Arrays.binarySearch(
1744                _sortedSystemCommunityRoles, roleName, new StringComparator());
1745
1746            if (pos >= 0) {
1747                return true;
1748            }
1749            else {
1750                pos = Arrays.binarySearch(
1751                    _sortedSystemOrganizationRoles, roleName,
1752                    new StringComparator());
1753
1754                if (pos >= 0) {
1755                    return true;
1756                }
1757            }
1758        }
1759
1760        return false;
1761    }
1762
1763    public boolean isUpdateAvailable()
1764        throws PortalException, SystemException {
1765
1766        return PluginPackageUtil.isUpdateAvailable();
1767    }
1768
1769    public void renderPage(
1770            StringMaker sm, ServletContext ctx, HttpServletRequest req,
1771            HttpServletResponse res, String path)
1772        throws IOException, ServletException {
1773
1774        RequestDispatcher rd = ctx.getRequestDispatcher(path);
1775
1776        StringServletResponse stringServletRes =
1777            new StringServletResponse(res);
1778
1779        rd.include(req, stringServletRes);
1780
1781        sm.append(stringServletRes.getString());
1782    }
1783
1784    public void renderPortlet(
1785            StringMaker sm, ServletContext ctx, HttpServletRequest req,
1786            HttpServletResponse res, Portlet portlet, String queryString)
1787        throws IOException, ServletException {
1788
1789        renderPortlet(
1790            sm, ctx, req, res, portlet, queryString, null, null, null);
1791    }
1792
1793    public void renderPortlet(
1794            StringMaker sm, ServletContext ctx, HttpServletRequest req,
1795            HttpServletResponse res, Portlet portlet, String queryString,
1796            String columnId, Integer columnPos, Integer columnCount)
1797        throws IOException, ServletException {
1798
1799        renderPortlet(
1800            sm, ctx, req, res, portlet, queryString, columnId, columnPos,
1801            columnCount, null);
1802    }
1803
1804    public void renderPortlet(
1805            StringMaker sm, ServletContext ctx, HttpServletRequest req,
1806            HttpServletResponse res, Portlet portlet, String queryString,
1807            String columnId, Integer columnPos, Integer columnCount,
1808            String path)
1809        throws IOException, ServletException {
1810
1811        queryString = GetterUtil.getString(queryString);
1812        columnId = GetterUtil.getString(columnId);
1813
1814        if (columnPos == null) {
1815            columnPos = new Integer(0);
1816        }
1817
1818        if (columnCount == null) {
1819            columnCount = new Integer(0);
1820        }
1821
1822        req.setAttribute(WebKeys.RENDER_PORTLET, portlet);
1823        req.setAttribute(WebKeys.RENDER_PORTLET_QUERY_STRING, queryString);
1824        req.setAttribute(WebKeys.RENDER_PORTLET_COLUMN_ID, columnId);
1825        req.setAttribute(WebKeys.RENDER_PORTLET_COLUMN_POS, columnPos);
1826        req.setAttribute(WebKeys.RENDER_PORTLET_COLUMN_COUNT, columnCount);
1827
1828        if (path == null) {
1829            path = "/html/portal/render_portlet.jsp";
1830        }
1831
1832        RequestDispatcher rd = ctx.getRequestDispatcher(path);
1833
1834        if (sm != null) {
1835            StringServletResponse stringServletRes =
1836                new StringServletResponse(res);
1837
1838            rd.include(req, stringServletRes);
1839
1840            sm.append(stringServletRes.getString());
1841        }
1842        else {
1843
1844            // LEP-766
1845
1846            res.setContentType(ContentTypes.TEXT_HTML_UTF8);
1847
1848            rd.include(req, res);
1849        }
1850    }
1851
1852    public void sendError(
1853            int status, Exception e, HttpServletRequest req,
1854            HttpServletResponse res)
1855        throws IOException, ServletException {
1856
1857        ServletContext ctx = req.getSession().getServletContext();
1858
1859        String mainPath = getPathMain();
1860
1861        String redirect = mainPath + "/portal/status";
1862
1863        if (e instanceof NoSuchLayoutException &&
1864            Validator.isNotNull(
1865                PropsValues.LAYOUT_FRIENDLY_URL_PAGE_NOT_FOUND)) {
1866
1867            res.setStatus(status);
1868
1869            redirect = PropsValues.LAYOUT_FRIENDLY_URL_PAGE_NOT_FOUND;
1870
1871            RequestDispatcher rd = ctx.getRequestDispatcher(redirect);
1872
1873            if (rd != null) {
1874                rd.forward(req, res);
1875            }
1876        }
1877        else if (PropsValues.LAYOUT_SHOW_HTTP_STATUS) {
1878            res.setStatus(status);
1879
1880            SessionErrors.add(req, e.getClass().getName(), e);
1881
1882            RequestDispatcher rd = ctx.getRequestDispatcher(redirect);
1883
1884            if (rd != null) {
1885                rd.forward(req, res);
1886            }
1887        }
1888        else {
1889            if (e != null) {
1890                res.sendError(status, e.getMessage());
1891            }
1892            else {
1893                res.sendError(status);
1894            }
1895        }
1896    }
1897
1898    /**
1899     * Sets the subtitle for a page. This is just a hint and can be overridden
1900     * by subsequent calls. The last call to this method wins.
1901     *
1902     * @param       subtitle the subtitle for a page
1903     * @param       req the HTTP servlet request
1904     */
1905    public void setPageSubtitle(String subtitle, HttpServletRequest req) {
1906        req.setAttribute(WebKeys.PAGE_SUBTITLE, subtitle);
1907    }
1908
1909    /**
1910     * Sets the whole title for a page. This is just a hint and can be
1911     * overridden by subsequent calls. The last call to this method wins.
1912     *
1913     * @param       title the whole title for a page
1914     * @param       req the HTTP servlet request
1915     */
1916    public void setPageTitle(String title, HttpServletRequest req) {
1917        req.setAttribute(WebKeys.PAGE_TITLE, title);
1918    }
1919
1920    public void storePreferences(PortletPreferences prefs)
1921        throws IOException, ValidatorException {
1922
1923        PortletPreferencesWrapper prefsWrapper =
1924            (PortletPreferencesWrapper)prefs;
1925
1926        PortletPreferencesImpl prefsImpl = prefsWrapper.getPreferencesImpl();
1927
1928        prefsImpl.store();
1929    }
1930
1931    public PortletMode updatePortletMode(
1932            String portletId, User user, Layout layout, PortletMode portletMode,
1933            HttpServletRequest req)
1934        throws PortalException, RemoteException, SystemException {
1935
1936        LayoutTypePortlet layoutType =
1937            (LayoutTypePortlet)layout.getLayoutType();
1938
1939        if (portletMode == null || Validator.isNull(portletMode.toString())) {
1940            if (layoutType.hasModeAboutPortletId(portletId)) {
1941                return LiferayPortletMode.ABOUT;
1942            }
1943            else if (layoutType.hasModeConfigPortletId(portletId)) {
1944                return LiferayPortletMode.CONFIG;
1945            }
1946            else if (layoutType.hasModeEditPortletId(portletId)) {
1947                return PortletMode.EDIT;
1948            }
1949            else if (layoutType.hasModeEditDefaultsPortletId(portletId)) {
1950                return LiferayPortletMode.EDIT_DEFAULTS;
1951            }
1952            else if (layoutType.hasModeEditGuestPortletId(portletId)) {
1953                return LiferayPortletMode.EDIT_GUEST;
1954            }
1955            else if (layoutType.hasModeHelpPortletId(portletId)) {
1956                return PortletMode.HELP;
1957            }
1958            else if (layoutType.hasModePreviewPortletId(portletId)) {
1959                return LiferayPortletMode.PREVIEW;
1960            }
1961            else if (layoutType.hasModePrintPortletId(portletId)) {
1962                return LiferayPortletMode.PRINT;
1963            }
1964            else {
1965                return PortletMode.VIEW;
1966            }
1967        }
1968        else {
1969            boolean updateLayout = false;
1970
1971            if (portletMode.equals(LiferayPortletMode.ABOUT) &&
1972                !layoutType.hasModeAboutPortletId(portletId)) {
1973
1974                layoutType.addModeAboutPortletId(portletId);
1975
1976                updateLayout = true;
1977            }
1978            else if (portletMode.equals(LiferayPortletMode.CONFIG) &&
1979                     !layoutType.hasModeConfigPortletId(portletId)) {
1980
1981                layoutType.addModeConfigPortletId(portletId);
1982
1983                updateLayout = true;
1984            }
1985            else if (portletMode.equals(PortletMode.EDIT) &&
1986                     !layoutType.hasModeEditPortletId(portletId)) {
1987
1988                layoutType.addModeEditPortletId(portletId);
1989
1990                updateLayout = true;
1991            }
1992            else if (portletMode.equals(LiferayPortletMode.EDIT_DEFAULTS) &&
1993                     !layoutType.hasModeEditDefaultsPortletId(portletId)) {
1994
1995                layoutType.addModeEditDefaultsPortletId(portletId);
1996
1997                updateLayout = true;
1998            }
1999            else if (portletMode.equals(LiferayPortletMode.EDIT_GUEST) &&
2000                     !layoutType.hasModeEditGuestPortletId(portletId)) {
2001
2002                layoutType.addModeEditGuestPortletId(portletId);
2003
2004                updateLayout = true;
2005            }
2006            else if (portletMode.equals(PortletMode.HELP) &&
2007                     !layoutType.hasModeHelpPortletId(portletId)) {
2008
2009                layoutType.addModeHelpPortletId(portletId);
2010
2011                updateLayout = true;
2012            }
2013            else if (portletMode.equals(LiferayPortletMode.PREVIEW) &&
2014                     !layoutType.hasModePreviewPortletId(portletId)) {
2015
2016                layoutType.addModePreviewPortletId(portletId);
2017
2018                updateLayout = true;
2019            }
2020            else if (portletMode.equals(LiferayPortletMode.PRINT) &&
2021                     !layoutType.hasModePrintPortletId(portletId)) {
2022
2023                layoutType.addModePrintPortletId(portletId);
2024
2025                updateLayout = true;
2026            }
2027            else if (portletMode.equals(PortletMode.VIEW) &&
2028                     !layoutType.hasModeViewPortletId(portletId)) {
2029
2030                layoutType.removeModesPortletId(portletId);
2031
2032                updateLayout = true;
2033            }
2034
2035            if (updateLayout) {
2036                LayoutClone layoutClone = LayoutCloneFactory.getInstance();
2037
2038                if (layoutClone != null) {
2039                    layoutClone.update(
2040                        req, layout.getPlid(), layout.getTypeSettings());
2041                }
2042            }
2043
2044            return portletMode;
2045        }
2046    }
2047
2048    public WindowState updateWindowState(
2049            String portletId, User user, Layout layout, WindowState windowState,
2050            HttpServletRequest req)
2051        throws PortalException, RemoteException, SystemException {
2052
2053        LayoutTypePortlet layoutType =
2054            (LayoutTypePortlet)layout.getLayoutType();
2055
2056        if ((windowState == null) ||
2057            (Validator.isNull(windowState.toString()))) {
2058
2059            if (layoutType.hasStateMaxPortletId(portletId)) {
2060                return WindowState.MAXIMIZED;
2061            }
2062            else if (layoutType.hasStateMinPortletId(portletId)) {
2063                return WindowState.MINIMIZED;
2064            }
2065            else {
2066                return WindowState.NORMAL;
2067            }
2068        }
2069        else {
2070            boolean updateLayout = false;
2071
2072            if (windowState.equals(WindowState.MAXIMIZED) &&
2073                !layoutType.hasStateMaxPortletId(portletId)) {
2074
2075                layoutType.addStateMaxPortletId(portletId);
2076
2077                updateLayout = false;
2078            }
2079            else if (windowState.equals(WindowState.MINIMIZED) &&
2080                     !layoutType.hasStateMinPortletId(portletId)) {
2081
2082                layoutType.addStateMinPortletId(portletId);
2083
2084                updateLayout = true;
2085            }
2086            else if (windowState.equals(WindowState.NORMAL) &&
2087                     !layoutType.hasStateNormalPortletId(portletId)) {
2088
2089                layoutType.removeStatesPortletId(portletId);
2090
2091                updateLayout = true;
2092            }
2093
2094            if (updateLayout) {
2095                LayoutClone layoutClone = LayoutCloneFactory.getInstance();
2096
2097                if (layoutClone != null) {
2098                    layoutClone.update(
2099                        req, layout.getPlid(), layout.getTypeSettings());
2100                }
2101            }
2102
2103            return windowState;
2104        }
2105    }
2106
2107    protected long getDoAsUserId(
2108            HttpServletRequest req, String doAsUserIdString)
2109        throws Exception {
2110
2111        if (Validator.isNull(doAsUserIdString)) {
2112            return 0;
2113        }
2114
2115        long doAsUserId = 0;
2116
2117        try {
2118            Company company = getCompany(req);
2119
2120            doAsUserId = GetterUtil.getLong(
2121                Encryptor.decrypt(company.getKeyObj(), doAsUserIdString));
2122        }
2123        catch (Exception e) {
2124            if (_log.isWarnEnabled()) {
2125                _log.warn(
2126                    "Unable to impersonate " + doAsUserIdString +
2127                        " because the string cannot be decrypted",
2128                    e);
2129            }
2130
2131            return 0;
2132        }
2133
2134        String path = GetterUtil.getString(req.getPathInfo());
2135
2136        if (_log.isDebugEnabled()) {
2137            _log.debug("doAsUserId path " + path);
2138        }
2139
2140        String strutsAction = getStrutsAction(req);
2141
2142        if (_log.isDebugEnabled()) {
2143            _log.debug("Struts action " + strutsAction);
2144        }
2145
2146        boolean alwaysAllowDoAsUser = false;
2147
2148        if (path.equals("/portal/fckeditor") ||
2149            strutsAction.equals("/document_library/edit_file_entry") ||
2150            strutsAction.equals("/image_gallery/edit_image") ||
2151            strutsAction.equals("/wiki/edit_page_attachment")) {
2152
2153            alwaysAllowDoAsUser = true;
2154        }
2155
2156        if (_log.isDebugEnabled()) {
2157            if (alwaysAllowDoAsUser) {
2158                _log.debug(
2159                    "doAsUserId path or Struts action is always allowed");
2160            }
2161            else {
2162                _log.debug(
2163                    "doAsUserId path is Struts action not always allowed");
2164            }
2165        }
2166
2167        if (alwaysAllowDoAsUser) {
2168            req.setAttribute(WebKeys.USER_ID, new Long(doAsUserId));
2169
2170            return doAsUserId;
2171        }
2172
2173        HttpSession ses = req.getSession();
2174
2175        Long realUserIdObj = (Long)ses.getAttribute(WebKeys.USER_ID);
2176
2177        if (realUserIdObj == null) {
2178            return 0;
2179        }
2180
2181        User doAsUser = UserLocalServiceUtil.getUserById(doAsUserId);
2182
2183        long[] organizationIds = doAsUser.getOrganizationIds();
2184
2185        User realUser = UserLocalServiceUtil.getUserById(
2186            realUserIdObj.longValue());
2187        boolean checkGuest = true;
2188
2189        PermissionCheckerImpl permissionChecker = null;
2190
2191        try {
2192            permissionChecker = PermissionCheckerFactory.create(
2193                realUser, checkGuest);
2194
2195            if (doAsUser.isDefaultUser() ||
2196                UserPermissionUtil.contains(
2197                    permissionChecker, doAsUserId, organizationIds,
2198                    ActionKeys.IMPERSONATE)) {
2199
2200                req.setAttribute(WebKeys.USER_ID, new Long(doAsUserId));
2201
2202                return doAsUserId;
2203            }
2204            else {
2205                _log.error(
2206                    "User " + realUserIdObj + " does not have the permission " +
2207                        "to impersonate " + doAsUserId);
2208
2209                return 0;
2210            }
2211        }
2212        finally {
2213            try {
2214                PermissionCheckerFactory.recycle(permissionChecker);
2215            }
2216            catch (Exception e) {
2217            }
2218        }
2219    }
2220
2221    private String _getCurrentURL(HttpServletRequest req) {
2222        StringMaker sm = new StringMaker();
2223
2224        StringBuffer requestURL = req.getRequestURL();
2225
2226        if (requestURL != null) {
2227            sm.append(requestURL.toString());
2228        }
2229
2230        String queryString = req.getQueryString();
2231
2232        if (Validator.isNull(queryString)) {
2233            return sm.toString();
2234        }
2235
2236        String portletId = req.getParameter("p_p_id");
2237
2238        String redirectParam = "redirect";
2239
2240        if (Validator.isNotNull(portletId)) {
2241            redirectParam = getPortletNamespace(portletId) + redirectParam;
2242        }
2243
2244        Map<String, String[]> parameterMap = HttpUtil.parameterMapFromString(
2245            queryString);
2246
2247        String[] redirectValues = parameterMap.get(redirectParam);
2248
2249        if ((redirectValues != null) && (redirectValues.length > 0)) {
2250
2251            // Prevent the redirect for GET requests from growing indefinitely
2252            // and using up all the available space by remembering only the
2253            // first redirect.
2254
2255            String redirect = HttpUtil.decodeURL(
2256                GetterUtil.getString(redirectValues[0]));
2257
2258            int pos = redirect.indexOf(StringPool.QUESTION);
2259
2260            if (pos != -1) {
2261                String subqueryString = redirect.substring(
2262                    pos + 1, redirect.length());
2263
2264                Map<String, String[]> subparameterMap =
2265                    HttpUtil.parameterMapFromString(subqueryString);
2266
2267                String[] subredirectValues = subparameterMap.get(redirectParam);
2268
2269                if ((subredirectValues != null) &&
2270                    (subredirectValues.length > 0)) {
2271
2272                    String subredirect = HttpUtil.decodeURL(
2273                        GetterUtil.getString(subredirectValues[0]));
2274
2275                    parameterMap.put(redirectParam, new String[] {subredirect});
2276
2277                    queryString = HttpUtil.parameterMapToString(
2278                        parameterMap, false);
2279                }
2280            }
2281        }
2282
2283        sm.append(StringPool.QUESTION);
2284        sm.append(queryString);
2285
2286        return sm.toString();
2287    }
2288
2289    private static final String _JSESSIONID = ";jsessionid=";
2290
2291    private static final String _METHOD_GET = "get";
2292
2293    private static final String _METHOD_POST = "post";
2294
2295    private static Log _log = LogFactory.getLog(PortalImpl.class);
2296
2297    private String _computerName;
2298    private String _portalLibDir;
2299    private String _cdnHost;
2300    private String _pathContext;
2301    private String _pathFriendlyURLPrivateGroup;
2302    private String _pathFriendlyURLPrivateUser;
2303    private String _pathFriendlyURLPublic;
2304    private String _pathImage;
2305    private String _pathMain;
2306    private String[] _allSystemCommunityRoles;
2307    private String[] _allSystemGroups;
2308    private String[] _allSystemOrganizationRoles;
2309    private String[] _allSystemRoles;
2310    private String[] _sortedSystemCommunityRoles;
2311    private String[] _sortedSystemGroups;
2312    private String[] _sortedSystemOrganizationRoles;
2313    private String[] _sortedSystemRoles;
2314    private Set<String> _reservedParams;
2315
2316}