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