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.portlet.LiferayWindowState;
35  import com.liferay.portal.kernel.portlet.PortletRequestWrapper;
36  import com.liferay.portal.kernel.portlet.PortletResponseWrapper;
37  import com.liferay.portal.kernel.security.permission.ActionKeys;
38  import com.liferay.portal.kernel.servlet.StringServletResponse;
39  import com.liferay.portal.kernel.util.ArrayUtil;
40  import com.liferay.portal.kernel.util.CalendarFactoryUtil;
41  import com.liferay.portal.kernel.util.CharPool;
42  import com.liferay.portal.kernel.util.ContentTypes;
43  import com.liferay.portal.kernel.util.GetterUtil;
44  import com.liferay.portal.kernel.util.InstancePool;
45  import com.liferay.portal.kernel.util.JavaConstants;
46  import com.liferay.portal.kernel.util.LocaleUtil;
47  import com.liferay.portal.kernel.util.MethodCache;
48  import com.liferay.portal.kernel.util.ParamUtil;
49  import com.liferay.portal.kernel.util.StringComparator;
50  import com.liferay.portal.kernel.util.StringMaker;
51  import com.liferay.portal.kernel.util.StringPool;
52  import com.liferay.portal.kernel.util.StringUtil;
53  import com.liferay.portal.kernel.util.Validator;
54  import com.liferay.portal.model.ClassName;
55  import com.liferay.portal.model.Company;
56  import com.liferay.portal.model.Group;
57  import com.liferay.portal.model.Layout;
58  import com.liferay.portal.model.LayoutSet;
59  import com.liferay.portal.model.LayoutTypePortlet;
60  import com.liferay.portal.model.Portlet;
61  import com.liferay.portal.model.User;
62  import com.liferay.portal.model.impl.GroupImpl;
63  import com.liferay.portal.model.impl.LayoutImpl;
64  import com.liferay.portal.model.impl.RoleImpl;
65  import com.liferay.portal.plugin.PluginPackageUtil;
66  import com.liferay.portal.security.permission.PermissionCheckerFactory;
67  import com.liferay.portal.security.permission.PermissionCheckerImpl;
68  import com.liferay.portal.service.ClassNameServiceUtil;
69  import com.liferay.portal.service.CompanyLocalServiceUtil;
70  import com.liferay.portal.service.GroupLocalServiceUtil;
71  import com.liferay.portal.service.LayoutLocalServiceUtil;
72  import com.liferay.portal.service.PortletLocalServiceUtil;
73  import com.liferay.portal.service.UserLocalServiceUtil;
74  import com.liferay.portal.service.UserServiceUtil;
75  import com.liferay.portal.service.permission.UserPermissionUtil;
76  import com.liferay.portal.servlet.PortletContextPool;
77  import com.liferay.portal.servlet.PortletContextWrapper;
78  import com.liferay.portal.theme.ThemeDisplay;
79  import com.liferay.portlet.ActionRequestImpl;
80  import com.liferay.portlet.ActionResponseImpl;
81  import com.liferay.portlet.CachePortlet;
82  import com.liferay.portlet.PortletConfigFactory;
83  import com.liferay.portlet.PortletPreferencesImpl;
84  import com.liferay.portlet.PortletPreferencesWrapper;
85  import com.liferay.portlet.PortletURLImpl;
86  import com.liferay.portlet.RenderRequestImpl;
87  import com.liferay.portlet.RenderResponseImpl;
88  import com.liferay.portlet.UserAttributes;
89  import com.liferay.portlet.wsrp.URLGeneratorImpl;
90  import com.liferay.util.BeanUtil;
91  import com.liferay.util.CollectionFactory;
92  import com.liferay.util.Encryptor;
93  import com.liferay.util.Http;
94  import com.liferay.util.HttpUtil;
95  import com.liferay.util.JS;
96  import com.liferay.util.servlet.DynamicServletRequest;
97  import com.liferay.util.servlet.SessionErrors;
98  import com.liferay.util.servlet.UploadPortletRequest;
99  import com.liferay.util.servlet.UploadServletRequest;
100 import com.liferay.util.xml.XMLSafeReader;
101 
102 import java.io.File;
103 import java.io.IOException;
104 import java.io.InputStream;
105 
106 import java.lang.reflect.Method;
107 
108 import java.net.URL;
109 
110 import java.rmi.RemoteException;
111 
112 import java.security.Key;
113 
114 import java.util.Arrays;
115 import java.util.Calendar;
116 import java.util.Date;
117 import java.util.Enumeration;
118 import java.util.HashMap;
119 import java.util.Iterator;
120 import java.util.List;
121 import java.util.Locale;
122 import java.util.Map;
123 import java.util.Properties;
124 import java.util.ResourceBundle;
125 import java.util.Set;
126 import java.util.TimeZone;
127 
128 import javax.portlet.ActionRequest;
129 import javax.portlet.ActionResponse;
130 import javax.portlet.PortletConfig;
131 import javax.portlet.PortletMode;
132 import javax.portlet.PortletPreferences;
133 import javax.portlet.PortletRequest;
134 import javax.portlet.PortletResponse;
135 import javax.portlet.PortletURL;
136 import javax.portlet.PreferencesValidator;
137 import javax.portlet.RenderRequest;
138 import javax.portlet.RenderResponse;
139 import javax.portlet.ValidatorException;
140 import javax.portlet.WindowState;
141 
142 import javax.servlet.RequestDispatcher;
143 import javax.servlet.ServletContext;
144 import javax.servlet.ServletException;
145 import javax.servlet.ServletRequest;
146 import javax.servlet.http.HttpServletRequest;
147 import javax.servlet.http.HttpServletRequestWrapper;
148 import javax.servlet.http.HttpServletResponse;
149 import javax.servlet.http.HttpSession;
150 
151 import org.apache.commons.logging.Log;
152 import org.apache.commons.logging.LogFactory;
153 import org.apache.struts.Globals;
154 
155 import org.dom4j.Document;
156 import org.dom4j.DocumentException;
157 import org.dom4j.io.SAXReader;
158 
159 import org.hibernate.util.FastHashMap;
160 
161 /**
162  * <a href="PortalUtil.java.html"><b><i>View Source</i></b></a>
163  *
164  * @author Brian Wing Shun Chan
165  * @author Brian Myunghun Kim
166  * @author Jorge Ferrer
167  *
168  */
169 public class PortalUtil {
170 
171     public static final String PATH_IMAGE = "/image";
172 
173     public static final String PATH_MAIN = "/c";
174 
175     public static final String PATH_PORTAL_LAYOUT = "/portal/layout";
176 
177     public static final String PORTLET_XML_FILE_NAME_STANDARD = "portlet.xml";
178 
179     public static final String PORTLET_XML_FILE_NAME_CUSTOM =
180         "portlet-custom.xml";
181 
182     public static final Date UP_TIME = new Date();
183 
184     public static void clearRequestParameters(RenderRequest req) {
185 
186         // Clear the render parameters if they were set during processAction
187 
188         boolean action = ParamUtil.getBoolean(req, "p_p_action");
189 
190         if (action) {
191             ((RenderRequestImpl)req).getRenderParameters().clear();
192         }
193     }
194 
195     public static void copyRequestParameters(
196         ActionRequest req, ActionResponse res) {
197 
198         try {
199             ActionResponseImpl resImpl = (ActionResponseImpl)res;
200 
201             Map renderParameters = resImpl.getRenderParameters();
202 
203             res.setRenderParameter("p_p_action", "1");
204 
205             Enumeration enu = req.getParameterNames();
206 
207             while (enu.hasMoreElements()) {
208                 String param = (String)enu.nextElement();
209                 String[] values = req.getParameterValues(param);
210 
211                 if (renderParameters.get(
212                         resImpl.getNamespace() + param) == null) {
213 
214                     res.setRenderParameter(param, values);
215                 }
216             }
217         }
218         catch (IllegalStateException ise) {
219 
220             // This should only happen if the developer called
221             // sendRedirect of javax.portlet.ActionResponse
222 
223         }
224     }
225 
226     public static String createSecureProxyURL(
227         String url, Key key, boolean secure) {
228 
229         // Use this method to fetch external content that may not be available
230         // in secure mode. See how the Weather portlet fetches images.
231 
232         if (!secure) {
233             return url;
234         }
235         else {
236             Map params = CollectionFactory.getHashMap();
237 
238             params.put(org.apache.wsrp4j.util.Constants.URL, url);
239 
240             return URLGeneratorImpl.getResourceProxyURL(params, key);
241         }
242     }
243 
244     public static String getCDNHost() {
245         return _instance._getCDNHost();
246     }
247 
248     public static String getClassName(long classNameId) {
249         try {
250             ClassName className = ClassNameServiceUtil.getClassName(
251                 classNameId);
252 
253             return className.getValue();
254         }
255         catch (Exception e) {
256             throw new RuntimeException(
257                 "Unable to get class name from id " + classNameId);
258         }
259     }
260 
261     public static long getClassNameId(Class classObj) {
262         return getClassNameId(classObj.getName());
263     }
264 
265     public static long getClassNameId(String value) {
266         try {
267             ClassName className = ClassNameServiceUtil.getClassName(value);
268 
269             return className.getClassNameId();
270         }
271         catch (Exception e) {
272             throw new RuntimeException(
273                 "Unable to get class name from value " + value);
274         }
275     }
276 
277     public static String getClassNamePortletId(String className) {
278         String portletId = StringPool.BLANK;
279 
280         if (className.startsWith("com.liferay.portlet.blogs")) {
281             portletId = PortletKeys.BLOGS;
282         }
283         else if (className.startsWith("com.liferay.portlet.bookmarks")) {
284             portletId = PortletKeys.BOOKMARKS;
285         }
286         else if (className.startsWith("com.liferay.portlet.documentlibrary")) {
287             portletId = PortletKeys.DOCUMENT_LIBRARY;
288         }
289         else if (className.startsWith("com.liferay.portlet.imagegallery")) {
290             portletId = PortletKeys.IMAGE_GALLERY;
291         }
292         else if (className.startsWith("com.liferay.portlet.journal")) {
293             portletId = PortletKeys.JOURNAL;
294         }
295         else if (className.startsWith("com.liferay.portlet.messageboards")) {
296             portletId = PortletKeys.MESSAGE_BOARDS;
297         }
298         else if (className.startsWith("com.liferay.portlet.wiki")) {
299             portletId = PortletKeys.WIKI;
300         }
301 
302         return portletId;
303     }
304 
305     public static Company getCompany(HttpServletRequest req)
306         throws PortalException, SystemException {
307 
308         long companyId = getCompanyId(req);
309 
310         if (companyId <= 0) {
311             return null;
312         }
313 
314         Company company = (Company)req.getAttribute(WebKeys.COMPANY);
315 
316         if (company == null) {
317             company = CompanyLocalServiceUtil.getCompanyById(companyId);
318 
319             req.setAttribute(WebKeys.COMPANY, company);
320         }
321 
322         return company;
323     }
324 
325     public static Company getCompany(ActionRequest req)
326         throws PortalException, SystemException {
327 
328         return getCompany(getHttpServletRequest(req));
329     }
330 
331     public static Company getCompany(RenderRequest req)
332         throws PortalException, SystemException {
333 
334         return getCompany(getHttpServletRequest(req));
335     }
336 
337     public static long getCompanyId(HttpServletRequest req) {
338         return PortalInstances.getCompanyId(req);
339     }
340 
341     public static long getCompanyId(ActionRequest req) {
342         return getCompanyId(getHttpServletRequest(req));
343     }
344 
345     public static long getCompanyId(PortletRequest req) {
346         long companyId = 0;
347 
348         if (req instanceof ActionRequest) {
349             companyId = getCompanyId((ActionRequest)req);
350         }
351         else {
352             companyId = getCompanyId((RenderRequest)req);
353         }
354 
355         return companyId;
356     }
357 
358     public static long getCompanyId(RenderRequest req) {
359         return getCompanyId(getHttpServletRequest(req));
360     }
361 
362     public static long getCompanyIdByWebId(ServletContext ctx) {
363         String webId = GetterUtil.getString(
364             ctx.getInitParameter("company_web_id"));
365 
366         return getCompanyIdByWebId(webId);
367     }
368 
369     public static long getCompanyIdByWebId(String webId) {
370         long companyId = 0;
371 
372         try {
373             Company company = CompanyLocalServiceUtil.getCompanyByWebId(webId);
374 
375             companyId = company.getCompanyId();
376         }
377         catch (Exception e) {
378             _log.error(e.getMessage());
379         }
380 
381         return companyId;
382     }
383 
384     public static String getComputerName() {
385         return _instance._computerName;
386     }
387 
388     public static String getCurrentURL(HttpServletRequest req) {
389         String currentURL = (String)req.getAttribute(WebKeys.CURRENT_URL);
390 
391         if (currentURL == null) {
392             currentURL = ParamUtil.getString(req, "currentURL");
393 
394             if (Validator.isNull(currentURL)) {
395                 if (true) {
396                     currentURL = Http.getCompleteURL(req);
397                 }
398                 else {
399 
400                     // Do we need to trim redirects?
401 
402                     currentURL = _getCurrentURL(req);
403                 }
404 
405                 if ((Validator.isNotNull(currentURL)) &&
406                     (currentURL.indexOf("j_security_check") == -1)) {
407 
408                     currentURL = currentURL.substring(
409                         currentURL.indexOf("://") + 3, currentURL.length());
410 
411                     currentURL = currentURL.substring(
412                         currentURL.indexOf("/"), currentURL.length());
413                 }
414             }
415 
416             if (Validator.isNull(currentURL)) {
417                 currentURL = getPathMain();
418             }
419 
420             req.setAttribute(WebKeys.CURRENT_URL, currentURL);
421         }
422 
423         return currentURL;
424     }
425 
426     public static String getCurrentURL(PortletRequest req) {
427         return (String)req.getAttribute(WebKeys.CURRENT_URL);
428     }
429 
430     public static Date getDate(
431             int month, int day, int year, PortalException pe)
432         throws PortalException {
433 
434         return getDate(month, day, year, null, pe);
435     }
436 
437     public static Date getDate(
438             int month, int day, int year, TimeZone timeZone, PortalException pe)
439         throws PortalException {
440 
441         return getDate(month, day, year, -1, -1, timeZone, pe);
442     }
443 
444     public static Date getDate(
445             int month, int day, int year, int hour, int min, PortalException pe)
446         throws PortalException {
447 
448         return getDate(month, day, year, hour, min, null, pe);
449     }
450 
451     public static Date getDate(
452             int month, int day, int year, int hour, int min, TimeZone timeZone,
453             PortalException pe)
454         throws PortalException {
455 
456         if (!Validator.isGregorianDate(month, day, year)) {
457             throw pe;
458         }
459         else {
460             Calendar cal = null;
461 
462             if (timeZone == null) {
463                 cal = CalendarFactoryUtil.getCalendar();
464             }
465             else {
466                 cal = CalendarFactoryUtil.getCalendar(timeZone);
467             }
468 
469             if ((hour == -1) || (min == -1)) {
470                 cal.set(year, month, day);
471             }
472             else {
473                 cal.set(year, month, day, hour, min, 0);
474             }
475 
476             Date date = cal.getTime();
477 
478             /*if (timeZone != null &&
479                 cal.before(CalendarFactoryUtil.getCalendar(timeZone))) {
480 
481                 throw pe;
482             }*/
483 
484             return date;
485         }
486     }
487 
488     public static String getHost(HttpServletRequest req) {
489         String host = req.getHeader("Host");
490 
491         if (host != null) {
492             host = host.trim().toLowerCase();
493 
494             int pos = host.indexOf(':');
495 
496             if (pos >= 0) {
497                 host = host.substring(0, pos);
498             }
499         }
500         else {
501             host = null;
502         }
503 
504         return host;
505     }
506 
507     public static String getHost(ActionRequest req) {
508         return getHost(getHttpServletRequest(req));
509     }
510 
511     public static String getHost(RenderRequest req) {
512         return getHost(getHttpServletRequest(req));
513     }
514 
515     public static HttpServletRequest getHttpServletRequest(PortletRequest req) {
516         if (req instanceof ActionRequestImpl) {
517             ActionRequestImpl reqImpl = (ActionRequestImpl)req;
518 
519             return reqImpl.getHttpServletRequest();
520         }
521         else if (req instanceof RenderRequestImpl) {
522             RenderRequestImpl reqImpl = (RenderRequestImpl)req;
523 
524             return reqImpl.getHttpServletRequest();
525         }
526         else if (req instanceof PortletRequestWrapper) {
527             PortletRequestWrapper reqWrapper = (PortletRequestWrapper)req;
528 
529             return getHttpServletRequest(reqWrapper.getPortletRequest());
530         }
531         else {
532             throw new RuntimeException(
533                 "Unable to get the HTTP servlet request from " +
534                     req.getClass().getName());
535         }
536     }
537 
538     public static HttpServletResponse getHttpServletResponse(
539         PortletResponse res) {
540 
541         if (res instanceof ActionResponseImpl) {
542             ActionResponseImpl resImpl = (ActionResponseImpl)res;
543 
544             return resImpl.getHttpServletResponse();
545         }
546         else if (res instanceof RenderResponseImpl) {
547             RenderResponseImpl resImpl = (RenderResponseImpl)res;
548 
549             return resImpl.getHttpServletResponse();
550         }
551         else if (res instanceof PortletResponseWrapper) {
552             PortletResponseWrapper resWrapper = (PortletResponseWrapper)res;
553 
554             return getHttpServletResponse(resWrapper.getPortletResponse());
555         }
556         else if (res instanceof RenderResponse) {
557             RenderResponseImpl resImpl = getRenderResponseImpl(
558                 (RenderResponse)res);
559 
560             return resImpl.getHttpServletResponse();
561         }
562         else {
563             throw new RuntimeException(
564                 "Unable to get the HTTP servlet resuest from " +
565                     res.getClass().getName());
566         }
567     }
568 
569     public static String getLayoutEditPage(Layout layout) {
570         return PropsUtil.getComponentProperties().getString(
571             PropsUtil.LAYOUT_EDIT_PAGE, Filter.by(layout.getType()));
572     }
573 
574     public static String getLayoutViewPage(Layout layout) {
575         return PropsUtil.getComponentProperties().getString(
576             PropsUtil.LAYOUT_VIEW_PAGE, Filter.by(layout.getType()));
577     }
578 
579     public static String getLayoutURL(ThemeDisplay themeDisplay)
580         throws PortalException, SystemException {
581 
582         return getLayoutURL(themeDisplay.getLayout(), themeDisplay);
583     }
584 
585     public static String getLayoutURL(Layout layout, ThemeDisplay themeDisplay)
586         throws PortalException, SystemException {
587 
588         return getLayoutURL(layout, themeDisplay, true);
589     }
590 
591     public static String getLayoutURL(
592             Layout layout, ThemeDisplay themeDisplay, boolean doAsUser)
593         throws PortalException, SystemException {
594 
595         if (layout == null) {
596             return themeDisplay.getPathMain() + PATH_PORTAL_LAYOUT;
597         }
598 
599         if (!layout.getType().equals(LayoutImpl.TYPE_URL)) {
600             String layoutFriendlyURL = getLayoutFriendlyURL(
601                 layout, themeDisplay);
602 
603             if (Validator.isNotNull(layoutFriendlyURL)) {
604                 if (doAsUser &&
605                     Validator.isNotNull(themeDisplay.getDoAsUserId())) {
606 
607                     layoutFriendlyURL = Http.addParameter(
608                         layoutFriendlyURL, "doAsUserId",
609                         themeDisplay.getDoAsUserId());
610                 }
611 
612                 return layoutFriendlyURL;
613             }
614         }
615 
616         String layoutURL = getLayoutActualURL(layout);
617 
618         if (doAsUser && Validator.isNotNull(themeDisplay.getDoAsUserId())) {
619             layoutURL = Http.addParameter(
620                 layoutURL, "doAsUserId", themeDisplay.getDoAsUserId());
621         }
622 
623         return layoutURL;
624     }
625 
626     public static String getLayoutActualURL(Layout layout)
627         throws PortalException, SystemException {
628 
629         return getLayoutActualURL(layout, getPathMain());
630     }
631 
632     public static String getLayoutActualURL(Layout layout, String mainPath)
633         throws PortalException, SystemException {
634 
635         Map vars = new FastHashMap();
636 
637         vars.put("liferay:mainPath", mainPath);
638         vars.put("liferay:plid", String.valueOf(layout.getPlid()));
639         vars.putAll(layout.getLayoutType().getTypeSettingsProperties());
640 
641         String href = PropsUtil.getComponentProperties().getString(
642             PropsUtil.LAYOUT_URL,
643             Filter.by(layout.getType()).setVariables(vars));
644 
645         return href;
646     }
647 
648     public static String getLayoutActualURL(
649             long groupId, boolean privateLayout, String mainPath,
650             String friendlyURL)
651         throws PortalException, SystemException {
652 
653         return getLayoutActualURL(
654             groupId, privateLayout, mainPath, friendlyURL, null);
655     }
656 
657     public static String getLayoutActualURL(
658             long groupId, boolean privateLayout, String mainPath,
659             String friendlyURL, Map params)
660         throws PortalException, SystemException {
661 
662         Layout layout = null;
663         String queryString = StringPool.BLANK;
664 
665         if (Validator.isNull(friendlyURL)) {
666             List layouts = LayoutLocalServiceUtil.getLayouts(
667                 groupId, privateLayout, LayoutImpl.DEFAULT_PARENT_LAYOUT_ID);
668 
669             if (layouts.size() > 0) {
670                 layout = (Layout)layouts.get(0);
671             }
672             else {
673                 throw new NoSuchLayoutException(
674                     "{groupId=" + groupId + ",privateLayout=" + privateLayout +
675                         "} does not have any layouts");
676             }
677         }
678         else {
679             Object[] friendlyURLMapper = getPortletFriendlyURLMapper(
680                 groupId, privateLayout, friendlyURL, params);
681 
682             layout = (Layout)friendlyURLMapper[0];
683             queryString = (String)friendlyURLMapper[1];
684         }
685 
686         String layoutActualURL = getLayoutActualURL(layout, mainPath);
687 
688         if (Validator.isNotNull(queryString)) {
689             layoutActualURL = layoutActualURL + queryString;
690         }
691 
692         return layoutActualURL;
693     }
694 
695     public static String getLayoutFriendlyURL(
696             Layout layout, ThemeDisplay themeDisplay)
697         throws PortalException, SystemException {
698 
699         if (!isLayoutFriendliable(layout)) {
700             return null;
701         }
702 
703         String layoutFriendlyURL = layout.getFriendlyURL();
704 
705         if (Validator.isNull(layoutFriendlyURL)) {
706             layoutFriendlyURL = layout.getDefaultFriendlyURL();
707         }
708 
709         LayoutSet layoutSet = layout.getLayoutSet();
710 
711         if (Validator.isNotNull(layoutSet.getVirtualHost())) {
712             String portalURL = getPortalURL(
713                 layoutSet.getVirtualHost(), themeDisplay.getServerPort(),
714                 themeDisplay.isSecure());
715 
716             // Use the layout set's virtual host setting only if the layout set
717             // is already used for the current request
718 
719             long curLayoutSetId =
720                 themeDisplay.getLayout().getLayoutSet().getLayoutSetId();
721 
722             if ((layoutSet.getLayoutSetId() != curLayoutSetId) ||
723                     (portalURL.startsWith(themeDisplay.getURLPortal()))) {
724 
725                 return portalURL + getPathContext() + layoutFriendlyURL;
726             }
727         }
728 
729         Group group = layout.getGroup();
730 
731         String parentFriendlyURL = group.getFriendlyURL();
732 
733         if (Validator.isNull(parentFriendlyURL)) {
734             parentFriendlyURL = group.getDefaultFriendlyURL(
735                 layout.isPrivateLayout());
736         }
737 
738         String friendlyURL = null;
739 
740         if (layout.isPrivateLayout()) {
741             if (group.isUser()) {
742                 friendlyURL = getPathFriendlyURLPrivateUser();
743             }
744             else {
745                 friendlyURL = getPathFriendlyURLPrivateGroup();
746             }
747         }
748         else {
749             friendlyURL = getPathFriendlyURLPublic();
750         }
751 
752         return friendlyURL + parentFriendlyURL + layoutFriendlyURL;
753     }
754 
755     public static String getLayoutTarget(Layout layout) {
756         Properties typeSettingsProps = layout.getTypeSettingsProperties();
757 
758         String target = typeSettingsProps.getProperty("target");
759 
760         if (Validator.isNull(target)) {
761             target = StringPool.BLANK;
762         }
763         else {
764             target = "target=\"" + target + "\"";
765         }
766 
767         return target;
768     }
769 
770     public static String getJsSafePortletId(String portletId) {
771         return JS.getSafeName(portletId);
772     }
773 
774     /**
775      * @deprecated Use <code>getJsSafePortletId</code>.
776      */
777     public static String getJsSafePortletName(String portletName) {
778         return JS.getSafeName(portletName);
779     }
780 
781     public static Locale getLocale(HttpServletRequest req) {
782         return (Locale)req.getSession().getAttribute(Globals.LOCALE_KEY);
783     }
784 
785     public static Locale getLocale(RenderRequest req) {
786         return getLocale(getHttpServletRequest(req));
787     }
788 
789     public static HttpServletRequest getOriginalServletRequest(
790         HttpServletRequest req) {
791 
792         HttpServletRequest originalReq = req;
793 
794         while (originalReq.getClass().getName().startsWith("com.liferay.")) {
795 
796             // Get original request so that portlets inside portlets render
797             // properly
798 
799             originalReq = (HttpServletRequest)
800                 ((HttpServletRequestWrapper)originalReq).getRequest();
801         }
802 
803         return originalReq;
804     }
805 
806     public static String getPathContext() {
807         return _instance._getPathContext();
808     }
809 
810     public static String getPathFriendlyURLPrivateGroup() {
811         return _instance._getPathFriendlyURLPrivateGroup();
812     }
813 
814     public static String getPathFriendlyURLPrivateUser() {
815         return _instance._getPathFriendlyURLPrivateUser();
816     }
817 
818     public static String getPathFriendlyURLPublic() {
819         return _instance._getPathFriendlyURLPublic();
820     }
821 
822     public static String getPathImage() {
823         return _instance._getPathImage();
824     }
825 
826     public static String getPathMain() {
827         return _instance._getPathMain();
828     }
829 
830     public static long getPlidIdFromFriendlyURL(
831         long companyId, String friendlyURL) {
832 
833         String[] urlParts = friendlyURL.split("\\/", 4);
834 
835         if ((friendlyURL.charAt(0) != CharPool.SLASH) &&
836             (urlParts.length != 4)) {
837 
838             return LayoutImpl.DEFAULT_PLID;
839         }
840 
841         boolean privateLayout = true;
842 
843         String urlPrefix = StringPool.SLASH + urlParts[1];
844 
845         if (getPathFriendlyURLPublic().equals(urlPrefix)) {
846             privateLayout = false;
847         }
848         else if (getPathFriendlyURLPrivateGroup().equals(urlPrefix) ||
849                  getPathFriendlyURLPrivateUser().equals(urlPrefix)) {
850 
851             privateLayout = true;
852         }
853         else {
854             return LayoutImpl.DEFAULT_PLID;
855         }
856 
857         Group group = null;
858 
859         try {
860             group = GroupLocalServiceUtil.getFriendlyURLGroup(
861                 companyId, StringPool.SLASH + urlParts[2]);
862         }
863         catch (Exception e) {
864         }
865 
866         if (group != null) {
867             Layout layout = null;
868 
869             try {
870 
871                 // Try parsing the last of the url parts as a layoutId
872                 // because it's faster to eliminate this possibility first
873 
874                 long layoutId = GetterUtil.getLong(urlParts[3]);
875 
876                 layout = LayoutLocalServiceUtil.getLayout(
877                     group.getGroupId(), privateLayout, layoutId);
878 
879                 return layout.getPlid();
880             }
881             catch (Exception e1) {
882                 try {
883 
884                     // Try the last part as a friendly url
885 
886                     layout = LayoutLocalServiceUtil.getFriendlyURLLayout(
887                         group.getGroupId(), privateLayout,
888                         StringPool.SLASH + urlParts[3]);
889                 }
890                 catch (Exception e2) {
891                 }
892             }
893 
894             if (layout != null) {
895                 return layout.getPlid();
896             }
897         }
898 
899         return LayoutImpl.DEFAULT_PLID;
900     }
901 
902     public static String getPortalLibDir() {
903         return _instance._portalLibDir;
904     }
905 
906     public static String getPortalURL(ThemeDisplay themeDisplay) {
907         String serverName = themeDisplay.getServerName();
908 
909         Layout layout = themeDisplay.getLayout();
910 
911         if (layout != null) {
912             LayoutSet layoutSet = layout.getLayoutSet();
913 
914             if (Validator.isNotNull(layoutSet.getVirtualHost())) {
915                 serverName = layoutSet.getVirtualHost();
916             }
917         }
918 
919         return getPortalURL(
920             serverName, themeDisplay.getServerPort(), themeDisplay.isSecure());
921     }
922 
923     public static String getPortalURL(HttpServletRequest req) {
924         return getPortalURL(req, req.isSecure());
925     }
926 
927     public static String getPortalURL(HttpServletRequest req, boolean secure) {
928         return getPortalURL(req.getServerName(), req.getServerPort(), secure);
929     }
930 
931     public static String getPortalURL(PortletRequest req) {
932         return getPortalURL(req, req.isSecure());
933     }
934 
935     public static String getPortalURL(PortletRequest req, boolean secure) {
936         return getPortalURL(req.getServerName(), req.getServerPort(), secure);
937     }
938 
939     public static String getPortalURL(
940         String serverName, int serverPort, boolean secure) {
941 
942         StringMaker sm = new StringMaker();
943 
944         if (secure || Http.HTTPS.equals(PropsValues.WEB_SERVER_PROTOCOL)) {
945             sm.append(Http.HTTPS_WITH_SLASH);
946         }
947         else {
948             sm.append(Http.HTTP_WITH_SLASH);
949         }
950 
951         if (Validator.isNull(PropsValues.WEB_SERVER_HOST)) {
952             sm.append(serverName);
953         }
954         else {
955             sm.append(PropsValues.WEB_SERVER_HOST);
956         }
957 
958         if (!secure) {
959             if (PropsValues.WEB_SERVER_HTTP_PORT == -1) {
960                 if ((serverPort != Http.HTTP_PORT) &&
961                     (serverPort != Http.HTTPS_PORT)) {
962 
963                     sm.append(StringPool.COLON);
964                     sm.append(serverPort);
965                 }
966             }
967             else {
968                 if ((PropsValues.WEB_SERVER_HTTP_PORT != serverPort) ||
969                     (PropsValues.WEB_SERVER_HTTP_PORT != Http.HTTP_PORT)) {
970 
971                     sm.append(StringPool.COLON);
972                     sm.append(PropsValues.WEB_SERVER_PROTOCOL);
973                 }
974             }
975         }
976 
977         if (secure) {
978             if (PropsValues.WEB_SERVER_HTTPS_PORT == -1) {
979                 if ((serverPort != Http.HTTP_PORT) &&
980                     (serverPort != Http.HTTPS_PORT)) {
981 
982                     sm.append(StringPool.COLON);
983                     sm.append(serverPort);
984                 }
985             }
986             else {
987                 if ((PropsValues.WEB_SERVER_HTTPS_PORT != serverPort) ||
988                     (PropsValues.WEB_SERVER_HTTPS_PORT != Http.HTTPS_PORT)) {
989 
990                     sm.append(StringPool.COLON);
991                     sm.append(PropsValues.WEB_SERVER_HTTPS_PORT);
992                 }
993             }
994         }
995 
996         return sm.toString();
997     }
998 
999     public static Object[] getPortletFriendlyURLMapper(
1000            long groupId, boolean privateLayout, String url)
1001        throws PortalException, SystemException {
1002
1003        return getPortletFriendlyURLMapper(groupId, privateLayout, url, null);
1004    }
1005
1006    public static Object[] getPortletFriendlyURLMapper(
1007            long groupId, boolean privateLayout, String url, Map params)
1008        throws PortalException, SystemException {
1009
1010        String friendlyURL = url;
1011        String queryString = StringPool.BLANK;
1012
1013        List friendlyURLMappers =
1014            PortletLocalServiceUtil.getFriendlyURLMappers();
1015
1016        Iterator itr = friendlyURLMappers.iterator();
1017
1018        while (itr.hasNext()) {
1019            FriendlyURLMapper friendlyURLMapper = (FriendlyURLMapper)itr.next();
1020
1021            if (url.endsWith(
1022                    StringPool.SLASH + friendlyURLMapper.getMapping())) {
1023
1024                url += StringPool.SLASH;
1025            }
1026
1027            int pos = url.indexOf(
1028                StringPool.SLASH + friendlyURLMapper.getMapping() +
1029                    StringPool.SLASH);
1030
1031            if (pos != -1) {
1032                friendlyURL = url.substring(0, pos);
1033
1034                Map actualParams = null;
1035
1036                if (params != null) {
1037                    actualParams = new HashMap(params);
1038                }
1039                else {
1040                    actualParams = new HashMap();
1041                }
1042
1043                /*Object action = actualParams.get("p_p_action");
1044
1045                if ((action == null) || (((String[])action).length == 0)) {
1046                    actualParams.put("p_p_action", "0");
1047                }
1048
1049                Object state = actualParams.get("p_p_state");
1050
1051                if ((state == null) || (((String[])state).length == 0)) {
1052                    actualParams.put(
1053                        "p_p_state", WindowState.MAXIMIZED.toString());
1054                }*/
1055
1056                friendlyURLMapper.populateParams(
1057                    url.substring(pos), actualParams);
1058
1059                queryString =
1060                    StringPool.AMPERSAND +
1061                        HttpUtil.parameterMapToString(actualParams, false);
1062
1063                break;
1064            }
1065        }
1066
1067        friendlyURL = StringUtil.replace(
1068            friendlyURL, StringPool.DOUBLE_SLASH, StringPool.SLASH);
1069
1070        if (friendlyURL.endsWith(StringPool.SLASH)) {
1071            friendlyURL = friendlyURL.substring(0, friendlyURL.length() - 1);
1072        }
1073
1074        Layout layout = null;
1075
1076        try {
1077            layout = LayoutLocalServiceUtil.getFriendlyURLLayout(
1078                groupId, privateLayout, friendlyURL);
1079        }
1080        catch(NoSuchLayoutException nsle) {
1081            long layoutId = GetterUtil.getLong(friendlyURL.substring(1));
1082
1083            layout = LayoutLocalServiceUtil.getLayout(
1084                groupId, privateLayout, layoutId);
1085        }
1086
1087        return new Object[] {layout, queryString};
1088    }
1089
1090    public static long getPortletGroupId(long plid) {
1091        Layout layout = null;
1092
1093        try {
1094            layout = LayoutLocalServiceUtil.getLayout(plid);
1095        }
1096        catch (Exception e) {
1097        }
1098
1099        return getPortletGroupId(layout);
1100    }
1101
1102    public static long getPortletGroupId(Layout layout) {
1103        if (layout == null) {
1104            return 0;
1105        }
1106        else {
1107            return layout.getGroupId();
1108        }
1109    }
1110
1111    public static long getPortletGroupId(HttpServletRequest req) {
1112        Layout layout = (Layout)req.getAttribute(WebKeys.LAYOUT);
1113
1114        return getPortletGroupId(layout);
1115    }
1116
1117    public static long getPortletGroupId(ActionRequest req) {
1118        return getPortletGroupId(getHttpServletRequest(req));
1119    }
1120
1121    public static long getPortletGroupId(RenderRequest req) {
1122        return getPortletGroupId(getHttpServletRequest(req));
1123    }
1124
1125    public static String getPortletNamespace(String portletId) {
1126        StringMaker sm = new StringMaker();
1127
1128        sm.append(StringPool.UNDERLINE);
1129        sm.append(portletId);
1130        sm.append(StringPool.UNDERLINE);
1131
1132        return sm.toString();
1133    }
1134
1135    public static String getPortletXmlFileName()
1136        throws PortalException, SystemException {
1137
1138        if (PrefsPropsUtil.getBoolean(
1139                PropsUtil.AUTO_DEPLOY_CUSTOM_PORTLET_XML,
1140                PropsValues.AUTO_DEPLOY_CUSTOM_PORTLET_XML)) {
1141
1142            return PORTLET_XML_FILE_NAME_CUSTOM;
1143        }
1144        else {
1145            return PORTLET_XML_FILE_NAME_STANDARD;
1146        }
1147    }
1148
1149    public static String getPortletTitle(
1150        String portletId, long companyId, String languageId) {
1151
1152        Locale locale = LocaleUtil.fromLanguageId(languageId);
1153
1154        StringMaker sm = new StringMaker();
1155
1156        sm.append(JavaConstants.JAVAX_PORTLET_TITLE);
1157        sm.append(StringPool.PERIOD);
1158        sm.append(portletId);
1159
1160        return LanguageUtil.get(companyId, locale, sm.toString());
1161    }
1162
1163    public static String getPortletTitle(String portletId, User user) {
1164        StringMaker sm = new StringMaker();
1165
1166        sm.append(JavaConstants.JAVAX_PORTLET_TITLE);
1167        sm.append(StringPool.PERIOD);
1168        sm.append(portletId);
1169
1170        return LanguageUtil.get(
1171            user.getCompanyId(), user.getLocale(), sm.toString());
1172    }
1173
1174    public static String getPortletTitle(
1175        Portlet portlet, ServletContext ctx, Locale locale) {
1176
1177        PortletConfig portletConfig = PortletConfigFactory.create(portlet, ctx);
1178
1179        ResourceBundle resourceBundle = portletConfig.getResourceBundle(locale);
1180
1181        return resourceBundle.getString(JavaConstants.JAVAX_PORTLET_TITLE);
1182    }
1183
1184    public static PortletPreferences getPreferences(HttpServletRequest req) {
1185        RenderRequest renderRequest = (RenderRequest)req.getAttribute(
1186            JavaConstants.JAVAX_PORTLET_REQUEST);
1187
1188        PortletPreferences prefs = null;
1189
1190        if (renderRequest != null) {
1191            PortletPreferencesWrapper prefsWrapper =
1192                (PortletPreferencesWrapper)renderRequest.getPreferences();
1193
1194            prefs = prefsWrapper.getPreferencesImpl();
1195        }
1196
1197        return prefs;
1198    }
1199
1200    public static PreferencesValidator getPreferencesValidator(
1201        Portlet portlet) {
1202
1203        if (portlet.isWARFile()) {
1204            PortletContextWrapper pcw =
1205                PortletContextPool.get(portlet.getRootPortletId());
1206
1207            return pcw.getPreferencesValidatorInstance();
1208        }
1209        else {
1210            PreferencesValidator prefsValidator = null;
1211
1212            if (Validator.isNotNull(portlet.getPreferencesValidator())) {
1213                prefsValidator =
1214                    (PreferencesValidator)InstancePool.get(
1215                        portlet.getPreferencesValidator());
1216            }
1217
1218            return prefsValidator;
1219        }
1220    }
1221
1222    public static RenderResponseImpl getRenderResponseImpl(RenderResponse res) {
1223        RenderResponseImpl resImpl = null;
1224
1225        if (res instanceof RenderResponseImpl) {
1226            resImpl = (RenderResponseImpl)res;
1227        }
1228        else {
1229
1230            // LEP-4033
1231
1232            try {
1233                Method method = MethodCache.get(
1234                    res.getClass().getName(), "getResponse");
1235
1236                Object obj = method.invoke(res, null);
1237
1238                resImpl = getRenderResponseImpl((RenderResponse)obj);
1239            }
1240            catch (Exception e) {
1241                throw new RuntimeException(e);
1242            }
1243        }
1244
1245        return resImpl;
1246    }
1247
1248    public static User getSelectedUser(HttpServletRequest req)
1249        throws PortalException, RemoteException, SystemException {
1250
1251        return getSelectedUser(req, true);
1252    }
1253
1254    public static User getSelectedUser(
1255            HttpServletRequest req, boolean checkPermission)
1256        throws PortalException, RemoteException, SystemException {
1257
1258        long userId = ParamUtil.getLong(req, "p_u_i_d");
1259
1260        User user = null;
1261
1262        try {
1263            if (checkPermission) {
1264                user = UserServiceUtil.getUserById(userId);
1265            }
1266            else {
1267                user = UserLocalServiceUtil.getUserById(userId);
1268            }
1269        }
1270        catch (NoSuchUserException nsue) {
1271        }
1272
1273        return user;
1274    }
1275
1276    public static User getSelectedUser(ActionRequest req)
1277        throws PortalException, RemoteException, SystemException {
1278
1279        return getSelectedUser(req, true);
1280    }
1281
1282    public static User getSelectedUser(
1283            ActionRequest req, boolean checkPermission)
1284        throws PortalException, RemoteException, SystemException {
1285
1286        return getSelectedUser(getHttpServletRequest(req), checkPermission);
1287    }
1288
1289    public static User getSelectedUser(RenderRequest req)
1290        throws PortalException, RemoteException, SystemException {
1291
1292        return getSelectedUser(req, true);
1293    }
1294
1295    public static User getSelectedUser(
1296            RenderRequest req, boolean checkPermission)
1297        throws PortalException, RemoteException, SystemException {
1298
1299        return getSelectedUser(getHttpServletRequest(req), checkPermission);
1300    }
1301
1302    public static String getStrutsAction(HttpServletRequest req) {
1303        String strutsAction = ParamUtil.getString(req, "struts_action");
1304
1305        if (Validator.isNotNull(strutsAction)) {
1306
1307            // This method should only return a Struts action if you're dealing
1308            // with a regular HTTP servlet request, not a portlet HTTP servlet
1309            // request.
1310
1311            return StringPool.BLANK;
1312        }
1313
1314        int strutsActionCount = 0;
1315
1316        Enumeration enu = req.getParameterNames();
1317
1318        while (enu.hasMoreElements()) {
1319            String name = (String)enu.nextElement();
1320
1321            int pos = name.indexOf("_struts_action");
1322
1323            if (pos != -1) {
1324                strutsActionCount++;
1325
1326                // There should never be more than one Struts action
1327
1328                if (strutsActionCount > 1) {
1329                    return StringPool.BLANK;
1330                }
1331
1332                String curStrutsAction = ParamUtil.getString(req, name);
1333
1334                if (Validator.isNotNull(curStrutsAction)) {
1335
1336                    // The Struts action must be for the correct portlet
1337
1338                    String portletId1 = name.substring(1, pos);
1339                    String portletId2 = ParamUtil.getString(req, "p_p_id");
1340
1341                    if (portletId1.equals(portletId2)) {
1342                        strutsAction = curStrutsAction;
1343                    }
1344                }
1345            }
1346        }
1347
1348        return strutsAction;
1349    }
1350
1351    public static String[] getSystemCommunityRoles() {
1352        return _instance._getSystemCommunityRoles();
1353    }
1354
1355    public static String[] getSystemGroups() {
1356        return _instance._getSystemGroups();
1357    }
1358
1359    public static String[] getSystemOrganizationRoles() {
1360        return _instance._getSystemOrganizationRoles();
1361    }
1362
1363    public static String[] getSystemRoles() {
1364        return _instance._getSystemRoles();
1365    }
1366
1367    public static UploadPortletRequest getUploadPortletRequest(
1368        ActionRequest req) {
1369
1370        ActionRequestImpl actionReq = (ActionRequestImpl)req;
1371
1372        DynamicServletRequest dynamicReq =
1373            (DynamicServletRequest)actionReq.getHttpServletRequest();
1374
1375        HttpServletRequestWrapper reqWrapper =
1376            (HttpServletRequestWrapper)dynamicReq.getRequest();
1377
1378        UploadServletRequest uploadReq = getUploadServletRequest(reqWrapper);
1379
1380        return new UploadPortletRequest(
1381            uploadReq, getPortletNamespace(actionReq.getPortletName()));
1382    }
1383
1384    public static UploadServletRequest getUploadServletRequest(
1385        HttpServletRequest httpReq) {
1386
1387        HttpServletRequestWrapper httpReqWrapper = null;
1388
1389        if (httpReq instanceof HttpServletRequestWrapper) {
1390            httpReqWrapper = (HttpServletRequestWrapper)httpReq;
1391        }
1392
1393        UploadServletRequest uploadReq = null;
1394
1395        while (uploadReq == null) {
1396
1397            // Find the underlying UploadServletRequest wrapper. For example,
1398            // WebSphere wraps all requests with ProtectedServletRequest.
1399
1400            if (httpReqWrapper instanceof UploadServletRequest) {
1401                uploadReq = (UploadServletRequest)httpReqWrapper;
1402            }
1403            else {
1404                ServletRequest req = httpReqWrapper.getRequest();
1405
1406                if (!(req instanceof HttpServletRequestWrapper)) {
1407                    break;
1408                }
1409                else {
1410                    httpReqWrapper =
1411                        (HttpServletRequestWrapper)httpReqWrapper.getRequest();
1412                }
1413            }
1414        }
1415
1416        return uploadReq;
1417    }
1418
1419    public static Date getUptime() {
1420        return UP_TIME;
1421    }
1422
1423    public static 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 static 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 static User getUser(ActionRequest req)
1502        throws PortalException, SystemException {
1503
1504        return getUser(getHttpServletRequest(req));
1505    }
1506
1507    public static User getUser(RenderRequest req)
1508        throws PortalException, SystemException {
1509
1510        return getUser(getHttpServletRequest(req));
1511    }
1512
1513    public static 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 static long getUserId(ActionRequest req) {
1556        return getUserId(getHttpServletRequest(req));
1557    }
1558
1559    public static long getUserId(RenderRequest req) {
1560        return getUserId(getHttpServletRequest(req));
1561    }
1562
1563    public static String getUserName(long userId, String defaultUserName) {
1564        return getUserName(
1565            userId, defaultUserName, UserAttributes.USER_NAME_FULL);
1566    }
1567
1568    public static String getUserName(
1569        long userId, String defaultUserName, String userAttribute) {
1570
1571        return getUserName(userId, defaultUserName, userAttribute, null);
1572    }
1573
1574    public static 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 static 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(), false);
1602
1603                portletURL.setWindowState(WindowState.MAXIMIZED);
1604                portletURL.setPortletMode(PortletMode.VIEW);
1605
1606                portletURL.setParameter(
1607                    "struts_action", "/directory/edit_user");
1608                portletURL.setParameter(
1609                    "p_u_i_d", String.valueOf(user.getUserId()));
1610
1611                userName =
1612                    "<a href=\"" + portletURL.toString() + "\">" + userName +
1613                        "</a>";
1614            }
1615        }
1616        catch (Exception e) {
1617        }
1618
1619        return userName;
1620    }
1621
1622    public static String getUserPassword(HttpSession ses) {
1623        return (String)ses.getAttribute(WebKeys.USER_PASSWORD);
1624    }
1625
1626    public static String getUserPassword(HttpServletRequest req) {
1627        return getUserPassword(req.getSession());
1628    }
1629
1630    public static String getUserPassword(ActionRequest req) {
1631        return getUserPassword(getHttpServletRequest(req));
1632    }
1633
1634    public static String getUserPassword(RenderRequest req) {
1635        return getUserPassword(getHttpServletRequest(req));
1636    }
1637
1638    public static String getUserValue(
1639            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 static 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 static 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 static boolean isLayoutFriendliable(Layout layout) {
1684        return PropsUtil.getComponentProperties().getBoolean(
1685            PropsUtil.LAYOUT_URL_FRIENDLIABLE,
1686            Filter.by(layout.getType()), true);
1687    }
1688
1689    public static boolean isLayoutParentable(Layout layout) {
1690        return isLayoutParentable(layout.getType());
1691    }
1692
1693    public static boolean isLayoutParentable(String type) {
1694        return PropsUtil.getComponentProperties().getBoolean(
1695            PropsUtil.LAYOUT_PARENTABLE, Filter.by(type), true);
1696    }
1697
1698    public static 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 static boolean isReservedParameter(String name) {
1708        return _instance._reservedParams.contains(name);
1709    }
1710
1711    public static boolean isSystemGroup(String groupName) {
1712        return _instance._isSystemGroup(groupName);
1713    }
1714
1715    public static boolean isSystemRole(String roleName) {
1716        return _instance._isSystemRole(roleName);
1717    }
1718
1719    public static boolean isUpdateAvailable()
1720        throws PortalException, SystemException {
1721
1722        return PluginPackageUtil.isUpdateAvailable();
1723    }
1724
1725    public static Document readDocumentFromFile(File file)
1726        throws DocumentException {
1727
1728        return readDocumentFromFile(file, false);
1729    }
1730
1731    public static Document readDocumentFromFile(File file, boolean validate)
1732        throws DocumentException {
1733
1734        SAXReader reader = SAXReaderFactory.getInstance(validate);
1735
1736        return reader.read(file);
1737    }
1738
1739    public static Document readDocumentFromStream(InputStream is)
1740        throws DocumentException {
1741
1742        return readDocumentFromStream(is, false);
1743    }
1744
1745    public static Document readDocumentFromStream(
1746            InputStream is, boolean validate)
1747        throws DocumentException {
1748
1749        SAXReader reader = SAXReaderFactory.getInstance(validate);
1750
1751        return reader.read(is);
1752    }
1753
1754    public static Document readDocumentFromURL(String url)
1755        throws DocumentException, IOException {
1756
1757        return readDocumentFromURL(url, false);
1758    }
1759
1760    public static Document readDocumentFromURL(String url, boolean validate)
1761        throws DocumentException, IOException {
1762
1763        SAXReader reader = SAXReaderFactory.getInstance(validate);
1764
1765        return reader.read(new URL(url));
1766    }
1767
1768    public static Document readDocumentFromXML(String xml)
1769        throws DocumentException {
1770
1771        return readDocumentFromXML(xml, false);
1772    }
1773
1774    public static Document readDocumentFromXML(String xml, boolean validate)
1775        throws DocumentException {
1776
1777        SAXReader reader = SAXReaderFactory.getInstance(validate);
1778
1779        return reader.read(new XMLSafeReader(xml));
1780    }
1781
1782    public static void renderPage(
1783            StringMaker sm, ServletContext ctx, HttpServletRequest req,
1784            HttpServletResponse res, String path)
1785        throws IOException, ServletException {
1786
1787        RequestDispatcher rd = ctx.getRequestDispatcher(path);
1788
1789        StringServletResponse stringServletRes =
1790            new StringServletResponse(res);
1791
1792        rd.include(req, stringServletRes);
1793
1794        sm.append(stringServletRes.getString());
1795    }
1796
1797    public static void renderPortlet(
1798            StringMaker sm, ServletContext ctx, HttpServletRequest req,
1799            HttpServletResponse res, Portlet portlet, String queryString)
1800        throws IOException, ServletException {
1801
1802        renderPortlet(
1803            sm, ctx, req, res, portlet, queryString, null, null, null);
1804    }
1805
1806    public static void renderPortlet(
1807            StringMaker sm, ServletContext ctx, HttpServletRequest req,
1808            HttpServletResponse res, Portlet portlet, String queryString,
1809            String columnId, Integer columnPos, Integer columnCount)
1810        throws IOException, ServletException {
1811
1812        renderPortlet(
1813            sm, ctx, req, res, portlet, queryString, columnId, columnPos,
1814            columnCount, null);
1815    }
1816
1817    public static void renderPortlet(
1818            StringMaker sm, ServletContext ctx, HttpServletRequest req,
1819            HttpServletResponse res, Portlet portlet, String queryString,
1820            String columnId, Integer columnPos, Integer columnCount,
1821            String path)
1822        throws IOException, ServletException {
1823
1824        queryString = GetterUtil.getString(queryString);
1825        columnId = GetterUtil.getString(columnId);
1826
1827        if (columnPos == null) {
1828            columnPos = new Integer(0);
1829        }
1830
1831        if (columnCount == null) {
1832            columnCount = new Integer(0);
1833        }
1834
1835        req.setAttribute(WebKeys.RENDER_PORTLET, portlet);
1836        req.setAttribute(WebKeys.RENDER_PORTLET_QUERY_STRING, queryString);
1837        req.setAttribute(WebKeys.RENDER_PORTLET_COLUMN_ID, columnId);
1838        req.setAttribute(WebKeys.RENDER_PORTLET_COLUMN_POS, columnPos);
1839        req.setAttribute(WebKeys.RENDER_PORTLET_COLUMN_COUNT, columnCount);
1840
1841        if (path == null) {
1842            path = "/html/portal/render_portlet.jsp";
1843        }
1844
1845        RequestDispatcher rd = ctx.getRequestDispatcher(path);
1846
1847        if (sm != null) {
1848            StringServletResponse stringServletRes =
1849                new StringServletResponse(res);
1850
1851            rd.include(req, stringServletRes);
1852
1853            sm.append(stringServletRes.getString());
1854        }
1855        else {
1856
1857            // LEP-766
1858
1859            res.setContentType(ContentTypes.TEXT_HTML_UTF8);
1860
1861            rd.include(req, res);
1862        }
1863    }
1864
1865    public static void sendError(
1866            int status, Exception e, HttpServletRequest req,
1867            HttpServletResponse res)
1868        throws IOException, ServletException {
1869
1870        ServletContext ctx = req.getSession().getServletContext();
1871
1872        String mainPath = PortalUtil.PATH_MAIN;
1873
1874        String redirect = mainPath + "/portal/status";
1875
1876        if (e instanceof NoSuchLayoutException &&
1877            Validator.isNotNull(
1878                PropsValues.LAYOUT_FRIENDLY_URL_PAGE_NOT_FOUND)) {
1879
1880            res.setStatus(status);
1881
1882            redirect = PropsValues.LAYOUT_FRIENDLY_URL_PAGE_NOT_FOUND;
1883
1884            RequestDispatcher rd = ctx.getRequestDispatcher(redirect);
1885
1886            if (rd != null) {
1887                rd.forward(req, res);
1888            }
1889        }
1890        else if (PropsValues.LAYOUT_SHOW_HTTP_STATUS) {
1891            res.setStatus(status);
1892
1893            SessionErrors.add(req, e.getClass().getName(), e);
1894
1895            RequestDispatcher rd = ctx.getRequestDispatcher(redirect);
1896
1897            if (rd != null) {
1898                rd.forward(req, res);
1899            }
1900        }
1901        else {
1902            if (e != null) {
1903                res.sendError(status, e.getMessage());
1904            }
1905            else {
1906                res.sendError(status);
1907            }
1908        }
1909    }
1910
1911    /**
1912     * Sets the subtitle for a page. This is just a hint and can be overridden
1913     * by subsequent calls. The last call to this method wins.
1914     *
1915     * @param       subtitle the subtitle for a page
1916     * @param       req the HTTP servlet request
1917     */
1918    public static void setPageSubtitle(
1919        String subtitle, HttpServletRequest req) {
1920
1921        req.setAttribute(WebKeys.PAGE_SUBTITLE, subtitle);
1922    }
1923
1924    /**
1925     * Sets the whole title for a page. This is just a hint and can be
1926     * overridden by subsequent calls. The last call to this method wins.
1927     *
1928     * @param       title the whole title for a page
1929     * @param       req the HTTP servlet request
1930     */
1931    public static void setPageTitle(String title, HttpServletRequest req) {
1932        req.setAttribute(WebKeys.PAGE_TITLE, title);
1933    }
1934
1935    public static void storePreferences(PortletPreferences prefs)
1936        throws IOException, ValidatorException {
1937
1938        PortletPreferencesWrapper prefsWrapper =
1939            (PortletPreferencesWrapper)prefs;
1940
1941        PortletPreferencesImpl prefsImpl =
1942            (PortletPreferencesImpl)prefsWrapper.getPreferencesImpl();
1943
1944        prefsImpl.store();
1945    }
1946
1947    public static PortletMode updatePortletMode(
1948            String portletId, User user, Layout layout, PortletMode portletMode,
1949            HttpServletRequest req)
1950        throws PortalException, RemoteException, SystemException {
1951
1952        LayoutTypePortlet layoutType =
1953            (LayoutTypePortlet)layout.getLayoutType();
1954
1955        if (portletMode == null || Validator.isNull(portletMode.toString())) {
1956            if (layoutType.hasModeAboutPortletId(portletId)) {
1957                return LiferayPortletMode.ABOUT;
1958            }
1959            else if (layoutType.hasModeConfigPortletId(portletId)) {
1960                return LiferayPortletMode.CONFIG;
1961            }
1962            else if (layoutType.hasModeEditPortletId(portletId)) {
1963                return PortletMode.EDIT;
1964            }
1965            else if (layoutType.hasModeEditDefaultsPortletId(portletId)) {
1966                return LiferayPortletMode.EDIT_DEFAULTS;
1967            }
1968            else if (layoutType.hasModeEditGuestPortletId(portletId)) {
1969                return LiferayPortletMode.EDIT_GUEST;
1970            }
1971            else if (layoutType.hasModeHelpPortletId(portletId)) {
1972                return PortletMode.HELP;
1973            }
1974            else if (layoutType.hasModePreviewPortletId(portletId)) {
1975                return LiferayPortletMode.PREVIEW;
1976            }
1977            else if (layoutType.hasModePrintPortletId(portletId)) {
1978                return LiferayPortletMode.PRINT;
1979            }
1980            else {
1981                return PortletMode.VIEW;
1982            }
1983        }
1984        else {
1985            boolean updateLayout = false;
1986
1987            if (portletMode.equals(LiferayPortletMode.ABOUT) &&
1988                !layoutType.hasModeAboutPortletId(portletId)) {
1989
1990                layoutType.addModeAboutPortletId(portletId);
1991
1992                updateLayout = true;
1993            }
1994            else if (portletMode.equals(LiferayPortletMode.CONFIG) &&
1995                     !layoutType.hasModeConfigPortletId(portletId)) {
1996
1997                layoutType.addModeConfigPortletId(portletId);
1998
1999                updateLayout = true;
2000            }
2001            else if (portletMode.equals(PortletMode.EDIT) &&
2002                     !layoutType.hasModeEditPortletId(portletId)) {
2003
2004                layoutType.addModeEditPortletId(portletId);
2005
2006                updateLayout = true;
2007            }
2008            else if (portletMode.equals(LiferayPortletMode.EDIT_DEFAULTS) &&
2009                     !layoutType.hasModeEditDefaultsPortletId(portletId)) {
2010
2011                layoutType.addModeEditDefaultsPortletId(portletId);
2012
2013                updateLayout = true;
2014            }
2015            else if (portletMode.equals(LiferayPortletMode.EDIT_GUEST) &&
2016                     !layoutType.hasModeEditGuestPortletId(portletId)) {
2017
2018                layoutType.addModeEditGuestPortletId(portletId);
2019
2020                updateLayout = true;
2021            }
2022            else if (portletMode.equals(PortletMode.HELP) &&
2023                     !layoutType.hasModeHelpPortletId(portletId)) {
2024
2025                layoutType.addModeHelpPortletId(portletId);
2026
2027                updateLayout = true;
2028            }
2029            else if (portletMode.equals(LiferayPortletMode.PREVIEW) &&
2030                     !layoutType.hasModePreviewPortletId(portletId)) {
2031
2032                layoutType.addModePreviewPortletId(portletId);
2033
2034                updateLayout = true;
2035            }
2036            else if (portletMode.equals(LiferayPortletMode.PRINT) &&
2037                     !layoutType.hasModePrintPortletId(portletId)) {
2038
2039                layoutType.addModePrintPortletId(portletId);
2040
2041                updateLayout = true;
2042            }
2043            else if (portletMode.equals(PortletMode.VIEW) &&
2044                     !layoutType.hasModeViewPortletId(portletId)) {
2045
2046                layoutType.removeModesPortletId(portletId);
2047
2048                updateLayout = true;
2049            }
2050
2051            if (updateLayout) {
2052                LayoutClone layoutClone = LayoutCloneFactory.getInstance();
2053
2054                if (layoutClone != null) {
2055                    layoutClone.update(
2056                        req, layout.getPlid(), layout.getTypeSettings());
2057                }
2058            }
2059
2060            return portletMode;
2061        }
2062    }
2063
2064    public static WindowState updateWindowState(
2065            String portletId, User user, Layout layout, WindowState windowState,
2066            HttpServletRequest req)
2067        throws PortalException, RemoteException, SystemException {
2068
2069        LayoutTypePortlet layoutType =
2070            (LayoutTypePortlet)layout.getLayoutType();
2071
2072        if ((windowState == null) ||
2073            (Validator.isNull(windowState.toString()))) {
2074
2075            if (layoutType.hasStateMaxPortletId(portletId)) {
2076                return WindowState.MAXIMIZED;
2077            }
2078            else if (layoutType.hasStateMinPortletId(portletId)) {
2079                return WindowState.MINIMIZED;
2080            }
2081            else {
2082                return WindowState.NORMAL;
2083            }
2084        }
2085        else {
2086            boolean updateLayout = false;
2087
2088            if ((windowState.equals(WindowState.MAXIMIZED)) ||
2089                (windowState.equals(LiferayWindowState.EXCLUSIVE)) ||
2090                (windowState.equals(LiferayWindowState.POP_UP))) {
2091
2092                if (layoutType.hasStateMax()) {
2093                    String curMaxPortletId =
2094                        StringUtil.split(layoutType.getStateMax())[0];
2095
2096                    // Clear cache and render parameters for the previous
2097                    // portlet that had a maximum window state
2098
2099                    CachePortlet.clearResponse(
2100                        req.getSession(), layout.getPlid(), curMaxPortletId,
2101                        LanguageUtil.getLanguageId(req));
2102
2103                    /*RenderParametersPool.clear(
2104                        req, layout.getPlid(), curMaxPortletId);*/
2105
2106                    if ((windowState.equals(LiferayWindowState.EXCLUSIVE)) ||
2107                        (windowState.equals(LiferayWindowState.POP_UP))) {
2108
2109                        String stateMaxPrevious =
2110                            layoutType.getStateMaxPrevious();
2111
2112                        if (stateMaxPrevious == null) {
2113                            layoutType.setStateMaxPrevious(curMaxPortletId);
2114
2115                            updateLayout = true;
2116                        }
2117                    }
2118                }
2119                else {
2120                    if ((windowState.equals(LiferayWindowState.EXCLUSIVE)) ||
2121                        (windowState.equals(LiferayWindowState.POP_UP))) {
2122
2123                        String stateMaxPrevious =
2124                            layoutType.getStateMaxPrevious();
2125
2126                        if (stateMaxPrevious == null) {
2127                            layoutType.setStateMaxPrevious(StringPool.BLANK);
2128
2129                            updateLayout = true;
2130                        }
2131                    }
2132                }
2133
2134                if (!layoutType.hasStateMaxPortletId(portletId)) {
2135                    layoutType.addStateMaxPortletId(portletId);
2136
2137                    updateLayout = true;
2138                }
2139            }
2140            else if (windowState.equals(WindowState.MINIMIZED) &&
2141                     !layoutType.hasStateMinPortletId(portletId)) {
2142
2143                layoutType.addStateMinPortletId(portletId);
2144
2145                updateLayout = true;
2146            }
2147            else if (windowState.equals(WindowState.NORMAL) &&
2148                     !layoutType.hasStateNormalPortletId(portletId)) {
2149
2150                layoutType.removeStatesPortletId(portletId);
2151
2152                updateLayout = true;
2153            }
2154
2155            if (updateLayout) {
2156                LayoutClone layoutClone = LayoutCloneFactory.getInstance();
2157
2158                if (layoutClone != null) {
2159                    layoutClone.update(
2160                        req, layout.getPlid(), layout.getTypeSettings());
2161                }
2162            }
2163
2164            return windowState;
2165        }
2166    }
2167
2168    private static long _getDoAsUserId(
2169            HttpServletRequest req, String doAsUserIdString)
2170        throws Exception {
2171
2172        if (Validator.isNull(doAsUserIdString)) {
2173            return 0;
2174        }
2175
2176        long doAsUserId = 0;
2177
2178        try {
2179            Company company = getCompany(req);
2180
2181            doAsUserId = GetterUtil.getLong(
2182                Encryptor.decrypt(company.getKeyObj(), doAsUserIdString));
2183        }
2184        catch (Exception e) {
2185            if (_log.isWarnEnabled()) {
2186                _log.warn(
2187                    "Unable to impersonate " + doAsUserIdString +
2188                        " because the string cannot be decrypted",
2189                    e);
2190            }
2191
2192            return 0;
2193        }
2194
2195        String path = GetterUtil.getString(req.getPathInfo());
2196
2197        if (_log.isDebugEnabled()) {
2198            _log.debug("doAsUserId path " + path);
2199        }
2200
2201        String strutsAction = getStrutsAction(req);
2202
2203        if (_log.isDebugEnabled()) {
2204            _log.debug("Struts action " + strutsAction);
2205        }
2206
2207        boolean alwaysAllowDoAsUser = false;
2208
2209        if (path.equals("/portal/fckeditor") ||
2210            strutsAction.equals("/document_library/edit_file_entry") ||
2211            strutsAction.equals("/image_gallery/edit_image")) {
2212
2213            alwaysAllowDoAsUser = true;
2214        }
2215
2216        if (_log.isDebugEnabled()) {
2217            if (alwaysAllowDoAsUser) {
2218                _log.debug(
2219                    "doAsUserId path or Struts action is always allowed");
2220            }
2221            else {
2222                _log.debug(
2223                    "doAsUserId path is Struts action not always allowed");
2224            }
2225        }
2226
2227        if (alwaysAllowDoAsUser) {
2228            req.setAttribute(WebKeys.USER_ID, new Long(doAsUserId));
2229
2230            return doAsUserId;
2231        }
2232
2233        HttpSession ses = req.getSession();
2234
2235        Long realUserIdObj = (Long)ses.getAttribute(WebKeys.USER_ID);
2236
2237        if (realUserIdObj == null) {
2238            return 0;
2239        }
2240
2241        User doAsUser = UserLocalServiceUtil.getUserById(doAsUserId);
2242
2243        long[] organizationIds = doAsUser.getOrganizationIds();
2244
2245        User realUser = UserLocalServiceUtil.getUserById(
2246            realUserIdObj.longValue());
2247        boolean checkGuest = true;
2248
2249        PermissionCheckerImpl permissionChecker = null;
2250
2251        try {
2252            permissionChecker = PermissionCheckerFactory.create(
2253                realUser, checkGuest);
2254
2255            if (doAsUser.isDefaultUser() ||
2256                UserPermissionUtil.contains(
2257                    permissionChecker, doAsUserId, organizationIds,
2258                    ActionKeys.IMPERSONATE)) {
2259
2260                req.setAttribute(WebKeys.USER_ID, new Long(doAsUserId));
2261
2262                return doAsUserId;
2263            }
2264            else {
2265                _log.error(
2266                    "User " + realUserIdObj + " does not have the permission " +
2267                        "to impersonate " + doAsUserId);
2268
2269                return 0;
2270            }
2271        }
2272        finally {
2273            try {
2274                PermissionCheckerFactory.recycle(permissionChecker);
2275            }
2276            catch (Exception e) {
2277            }
2278        }
2279    }
2280
2281    private PortalUtil() {
2282
2283        // Computer name
2284
2285        _computerName = System.getProperty("env.COMPUTERNAME");
2286
2287        if (Validator.isNull(_computerName)) {
2288            _computerName = System.getProperty("env.HOST");
2289        }
2290
2291        if (Validator.isNull(_computerName)) {
2292            _computerName = System.getProperty("env.HOSTNAME");
2293        }
2294
2295        // Portal lib directory
2296
2297        ClassLoader classLoader = getClass().getClassLoader();
2298
2299        URL url = classLoader.getResource(
2300            "com/liferay/portal/util/PortalUtil.class");
2301
2302        String file = url.getFile();
2303
2304        if (_log.isInfoEnabled()) {
2305            _log.info("Portal lib url " + file);
2306        }
2307
2308        int pos = file.indexOf("/com/liferay/portal/util/");
2309
2310        _portalLibDir = file.substring(0, pos + 1);
2311
2312        if (_portalLibDir.endsWith("/WEB-INF/classes/")) {
2313            _portalLibDir = _portalLibDir.substring(
2314                0, _portalLibDir.length() - 8) + "lib/";
2315        }
2316        else {
2317            pos = _portalLibDir.indexOf("/WEB-INF/lib/");
2318
2319            if (pos != -1) {
2320                _portalLibDir =
2321                    _portalLibDir.substring(0, pos) + "/WEB-INF/lib/";
2322            }
2323        }
2324
2325        if (_portalLibDir.startsWith("file:/")) {
2326            _portalLibDir = _portalLibDir.substring(5, _portalLibDir.length());
2327        }
2328
2329        if (_log.isInfoEnabled()) {
2330            _log.info("Portal lib directory " + _portalLibDir);
2331        }
2332
2333        // CDN host
2334
2335        _cdnHost = PropsUtil.get(PropsUtil.CDN_HOST);
2336
2337        // Paths
2338
2339        _pathContext = PropsUtil.get(PropsUtil.PORTAL_CTX);
2340
2341        if (_pathContext.equals(StringPool.SLASH)) {
2342            _pathContext = StringPool.BLANK;
2343        }
2344
2345        _pathFriendlyURLPrivateGroup =
2346            _pathContext +
2347                PropsValues.LAYOUT_FRIENDLY_URL_PRIVATE_GROUP_SERVLET_MAPPING;
2348        _pathFriendlyURLPrivateUser =
2349            _pathContext +
2350                PropsValues.LAYOUT_FRIENDLY_URL_PRIVATE_USER_SERVLET_MAPPING;
2351        _pathFriendlyURLPublic =
2352            _pathContext +
2353                PropsValues.LAYOUT_FRIENDLY_URL_PUBLIC_SERVLET_MAPPING;
2354        _pathImage = _cdnHost + _pathContext + PATH_IMAGE;
2355        _pathMain = _pathContext + PATH_MAIN;
2356
2357        // Groups
2358
2359        String customSystemGroups[] =
2360            PropsUtil.getArray(PropsUtil.SYSTEM_GROUPS);
2361
2362        if ((customSystemGroups == null) || (customSystemGroups.length == 0)) {
2363            _allSystemGroups = GroupImpl.SYSTEM_GROUPS;
2364        }
2365        else {
2366            _allSystemGroups = ArrayUtil.append(
2367                GroupImpl.SYSTEM_GROUPS, customSystemGroups);
2368        }
2369
2370        _sortedSystemGroups = new String[_allSystemGroups.length];
2371
2372        System.arraycopy(
2373            _allSystemGroups, 0, _sortedSystemGroups, 0,
2374            _allSystemGroups.length);
2375
2376        Arrays.sort(_sortedSystemGroups, new StringComparator());
2377
2378        // Regular roles
2379
2380        String customSystemRoles[] = PropsUtil.getArray(PropsUtil.SYSTEM_ROLES);
2381
2382        if ((customSystemRoles == null) || (customSystemRoles.length == 0)) {
2383            _allSystemRoles = RoleImpl.SYSTEM_ROLES;
2384        }
2385        else {
2386            _allSystemRoles = ArrayUtil.append(
2387                RoleImpl.SYSTEM_ROLES, customSystemRoles);
2388        }
2389
2390        _sortedSystemRoles = new String[_allSystemRoles.length];
2391
2392        System.arraycopy(
2393            _allSystemRoles, 0, _sortedSystemRoles, 0, _allSystemRoles.length);
2394
2395        Arrays.sort(_sortedSystemRoles, new StringComparator());
2396
2397        // Community roles
2398
2399        String customSystemCommunityRoles[] =
2400            PropsUtil.getArray(PropsUtil.SYSTEM_COMMUNITY_ROLES);
2401
2402        if ((customSystemCommunityRoles == null) ||
2403            (customSystemCommunityRoles.length == 0)) {
2404
2405            _allSystemCommunityRoles = RoleImpl.SYSTEM_COMMUNITY_ROLES;
2406        }
2407        else {
2408            _allSystemCommunityRoles = ArrayUtil.append(
2409                RoleImpl.SYSTEM_COMMUNITY_ROLES, customSystemCommunityRoles);
2410        }
2411
2412        _sortedSystemCommunityRoles =
2413            new String[_allSystemCommunityRoles.length];
2414
2415        System.arraycopy(
2416            _allSystemCommunityRoles, 0, _sortedSystemCommunityRoles, 0,
2417                _allSystemCommunityRoles.length);
2418
2419        Arrays.sort(_sortedSystemCommunityRoles, new StringComparator());
2420
2421        // Organization Roles
2422
2423        String customSystemOrganizationRoles[] =
2424            PropsUtil.getArray(PropsUtil.SYSTEM_ORGANIZATION_ROLES);
2425
2426        if ((customSystemOrganizationRoles == null) ||
2427            (customSystemOrganizationRoles.length == 0)) {
2428
2429            _allSystemOrganizationRoles = RoleImpl.SYSTEM_ORGANIZATION_ROLES;
2430        }
2431        else {
2432            _allSystemOrganizationRoles = ArrayUtil.append(
2433                RoleImpl.SYSTEM_ORGANIZATION_ROLES,
2434                customSystemOrganizationRoles);
2435        }
2436
2437        _sortedSystemOrganizationRoles =
2438            new String[_allSystemOrganizationRoles.length];
2439
2440        System.arraycopy(
2441            _allSystemOrganizationRoles, 0, _sortedSystemOrganizationRoles, 0,
2442                _allSystemOrganizationRoles.length);
2443
2444        Arrays.sort(_sortedSystemOrganizationRoles, new StringComparator());
2445
2446        // Reserved parameter names
2447
2448        _reservedParams = CollectionFactory.getHashSet();
2449
2450        _reservedParams.add("p_l_id");
2451        _reservedParams.add("p_l_reset");
2452        _reservedParams.add("p_p_id");
2453        _reservedParams.add("p_p_action");
2454        _reservedParams.add("p_p_state");
2455        _reservedParams.add("p_p_mode");
2456        _reservedParams.add("p_p_width");
2457        _reservedParams.add("p_p_col_id");
2458        _reservedParams.add("p_p_col_pos");
2459        _reservedParams.add("p_p_col_count");
2460        _reservedParams.add("p_p_static");
2461    }
2462
2463    private String _getCDNHost() {
2464        return _cdnHost;
2465    }
2466
2467    private static String _getCurrentURL(HttpServletRequest req) {
2468        StringMaker sm = new StringMaker();
2469
2470        StringBuffer requestURL = req.getRequestURL();
2471
2472        if (requestURL != null) {
2473            sm.append(requestURL.toString());
2474        }
2475
2476        String queryString = req.getQueryString();
2477
2478        if (Validator.isNull(queryString)) {
2479            return sm.toString();
2480        }
2481
2482        String portletId = req.getParameter("p_p_id");
2483
2484        String redirectParam = "redirect";
2485
2486        if (Validator.isNotNull(portletId)) {
2487            redirectParam = getPortletNamespace(portletId) + redirectParam;
2488        }
2489
2490        Map parameterMap = HttpUtil.parameterMapFromString(queryString);
2491
2492        String[] redirectValues = (String[])parameterMap.get(redirectParam);
2493
2494        if ((redirectValues != null) && (redirectValues.length > 0)) {
2495
2496            // Prevent the redirect for GET requests from growing indefinitely
2497            // and using up all the available space by remembering only the
2498            // first redirect.
2499
2500            String redirect = HttpUtil.decodeURL(
2501                GetterUtil.getString(redirectValues[0]));
2502
2503            int pos = redirect.indexOf(StringPool.QUESTION);
2504
2505            if (pos != -1) {
2506                String subqueryString = redirect.substring(
2507                    pos + 1, redirect.length());
2508
2509                Map subparameterMap = HttpUtil.parameterMapFromString(
2510                    subqueryString);
2511
2512                String[] subredirectValues = (String[])subparameterMap.get(
2513                    redirectParam);
2514
2515                if ((subredirectValues != null) &&
2516                    (subredirectValues.length > 0)) {
2517
2518                    String subredirect = HttpUtil.decodeURL(
2519                        GetterUtil.getString(subredirectValues[0]));
2520
2521                    parameterMap.put(redirectParam, new String[] {subredirect});
2522
2523                    queryString = HttpUtil.parameterMapToString(
2524                        parameterMap, false);
2525                }
2526            }
2527        }
2528
2529        sm.append(StringPool.QUESTION);
2530        sm.append(queryString);
2531
2532        return sm.toString();
2533    }
2534
2535    private String _getPathContext() {
2536        return _pathContext;
2537    }
2538
2539    private String _getPathFriendlyURLPrivateGroup() {
2540        return _pathFriendlyURLPrivateGroup;
2541    }
2542
2543    private String _getPathFriendlyURLPrivateUser() {
2544        return _pathFriendlyURLPrivateUser;
2545    }
2546
2547    private String _getPathFriendlyURLPublic() {
2548        return _pathFriendlyURLPublic;
2549    }
2550
2551    private String _getPathImage() {
2552        return _pathImage;
2553    }
2554
2555    private String _getPathMain() {
2556        return _pathMain;
2557    }
2558
2559    private String[] _getSystemCommunityRoles() {
2560        return _allSystemCommunityRoles;
2561    }
2562
2563    private String[] _getSystemOrganizationRoles() {
2564        return _allSystemOrganizationRoles;
2565    }
2566
2567    private String[] _getSystemGroups() {
2568        return _allSystemGroups;
2569    }
2570
2571    private String[] _getSystemRoles() {
2572        return _allSystemRoles;
2573    }
2574
2575    private boolean _isSystemGroup(String groupName) {
2576        if (groupName == null) {
2577            return false;
2578        }
2579
2580        groupName = groupName.trim();
2581
2582        int pos = Arrays.binarySearch(
2583            _sortedSystemGroups, groupName, new StringComparator());
2584
2585        if (pos >= 0) {
2586            return true;
2587        }
2588        else {
2589            return false;
2590        }
2591    }
2592
2593    private boolean _isSystemRole(String roleName) {
2594        if (roleName == null) {
2595            return false;
2596        }
2597
2598        roleName = roleName.trim();
2599
2600        int pos = Arrays.binarySearch(
2601            _sortedSystemRoles, roleName, new StringComparator());
2602
2603        if (pos >= 0) {
2604            return true;
2605        }
2606        else {
2607            pos = Arrays.binarySearch(
2608                _sortedSystemCommunityRoles, roleName, new StringComparator());
2609
2610            if (pos >= 0) {
2611                return true;
2612            }
2613            else {
2614                pos = Arrays.binarySearch(
2615                    _sortedSystemOrganizationRoles, roleName,
2616                    new StringComparator());
2617
2618                if (pos >= 0) {
2619                    return true;
2620                }
2621            }
2622        }
2623
2624        return false;
2625    }
2626
2627    private static final String _JSESSIONID = ";jsessionid=";
2628
2629    private static final String _METHOD_GET = "get";
2630
2631    private static final String _METHOD_POST = "post";
2632
2633    private static Log _log = LogFactory.getLog(PortalUtil.class);
2634
2635    private static PortalUtil _instance = new PortalUtil();
2636
2637    private String _computerName;
2638    private String _portalLibDir;
2639    private String _cdnHost;
2640    private String _pathContext;
2641    private String _pathFriendlyURLPrivateGroup;
2642    private String _pathFriendlyURLPrivateUser;
2643    private String _pathFriendlyURLPublic;
2644    private String _pathImage;
2645    private String _pathMain;
2646    private String[] _allSystemCommunityRoles;
2647    private String[] _allSystemGroups;
2648    private String[] _allSystemOrganizationRoles;
2649    private String[] _allSystemRoles;
2650    private String[] _sortedSystemCommunityRoles;
2651    private String[] _sortedSystemGroups;
2652    private String[] _sortedSystemOrganizationRoles;
2653    private String[] _sortedSystemRoles;
2654    private Set _reservedParams;
2655
2656}