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 
861             // Start by trying to parse the url part as a group id because it is
862             // faster to eliminate this possibility first
863 
864             long groupId = GetterUtil.getLong(urlParts[2]);
865 
866             group = GroupLocalServiceUtil.getGroup(groupId);
867         }
868         catch (Exception e1) {
869             try {
870 
871                 // Now try as a friendly url
872 
873                 group = GroupLocalServiceUtil.getFriendlyURLGroup(
874                     companyId, StringPool.SLASH + urlParts[2]);
875             }
876             catch (Exception e2) {
877             }
878         }
879 
880         if (group != null) {
881             Layout layout = null;
882 
883             try {
884 
885                 // Start by trying to parse the url part as a layout id because
886                 // it is faster to eliminate this possibility first
887 
888                 long layoutId = GetterUtil.getLong(urlParts[3]);
889 
890                 layout = LayoutLocalServiceUtil.getLayout(
891                     group.getGroupId(), privateLayout, layoutId);
892 
893                 return layout.getPlid();
894             }
895             catch (Exception e1) {
896                 try {
897 
898                     // Now try as a friendly url
899 
900                     layout = LayoutLocalServiceUtil.getFriendlyURLLayout(
901                         group.getGroupId(), privateLayout,
902                         StringPool.SLASH + urlParts[3]);
903 
904                     return layout.getPlid();
905                 }
906                 catch (Exception e2) {
907                 }
908             }
909         }
910 
911         return LayoutImpl.DEFAULT_PLID;
912     }
913 
914     public static String getPortalLibDir() {
915         return _instance._portalLibDir;
916     }
917 
918     public static String getPortalURL(ThemeDisplay themeDisplay) {
919         String serverName = themeDisplay.getServerName();
920 
921         Layout layout = themeDisplay.getLayout();
922 
923         if (layout != null) {
924             LayoutSet layoutSet = layout.getLayoutSet();
925 
926             if (Validator.isNotNull(layoutSet.getVirtualHost())) {
927                 serverName = layoutSet.getVirtualHost();
928             }
929         }
930 
931         return getPortalURL(
932             serverName, themeDisplay.getServerPort(), themeDisplay.isSecure());
933     }
934 
935     public static String getPortalURL(HttpServletRequest req) {
936         return getPortalURL(req, req.isSecure());
937     }
938 
939     public static String getPortalURL(HttpServletRequest req, boolean secure) {
940         return getPortalURL(req.getServerName(), req.getServerPort(), secure);
941     }
942 
943     public static String getPortalURL(PortletRequest req) {
944         return getPortalURL(req, req.isSecure());
945     }
946 
947     public static String getPortalURL(PortletRequest req, boolean secure) {
948         return getPortalURL(req.getServerName(), req.getServerPort(), secure);
949     }
950 
951     public static String getPortalURL(
952         String serverName, int serverPort, boolean secure) {
953 
954         StringMaker sm = new StringMaker();
955 
956         if (secure || Http.HTTPS.equals(PropsValues.WEB_SERVER_PROTOCOL)) {
957             sm.append(Http.HTTPS_WITH_SLASH);
958         }
959         else {
960             sm.append(Http.HTTP_WITH_SLASH);
961         }
962 
963         if (Validator.isNull(PropsValues.WEB_SERVER_HOST)) {
964             sm.append(serverName);
965         }
966         else {
967             sm.append(PropsValues.WEB_SERVER_HOST);
968         }
969 
970         if (!secure) {
971             if (PropsValues.WEB_SERVER_HTTP_PORT == -1) {
972                 if ((serverPort != Http.HTTP_PORT) &&
973                     (serverPort != Http.HTTPS_PORT)) {
974 
975                     sm.append(StringPool.COLON);
976                     sm.append(serverPort);
977                 }
978             }
979             else {
980                 if ((PropsValues.WEB_SERVER_HTTP_PORT != serverPort) ||
981                     (PropsValues.WEB_SERVER_HTTP_PORT != Http.HTTP_PORT)) {
982 
983                     sm.append(StringPool.COLON);
984                     sm.append(PropsValues.WEB_SERVER_PROTOCOL);
985                 }
986             }
987         }
988 
989         if (secure) {
990             if (PropsValues.WEB_SERVER_HTTPS_PORT == -1) {
991                 if ((serverPort != Http.HTTP_PORT) &&
992                     (serverPort != Http.HTTPS_PORT)) {
993 
994                     sm.append(StringPool.COLON);
995                     sm.append(serverPort);
996                 }
997             }
998             else {
999                 if ((PropsValues.WEB_SERVER_HTTPS_PORT != serverPort) ||
1000                    (PropsValues.WEB_SERVER_HTTPS_PORT != Http.HTTPS_PORT)) {
1001
1002                    sm.append(StringPool.COLON);
1003                    sm.append(PropsValues.WEB_SERVER_HTTPS_PORT);
1004                }
1005            }
1006        }
1007
1008        return sm.toString();
1009    }
1010
1011    public static Object[] getPortletFriendlyURLMapper(
1012            long groupId, boolean privateLayout, String url)
1013        throws PortalException, SystemException {
1014
1015        return getPortletFriendlyURLMapper(groupId, privateLayout, url, null);
1016    }
1017
1018    public static Object[] getPortletFriendlyURLMapper(
1019            long groupId, boolean privateLayout, String url, Map params)
1020        throws PortalException, SystemException {
1021
1022        String friendlyURL = url;
1023        String queryString = StringPool.BLANK;
1024
1025        List friendlyURLMappers =
1026            PortletLocalServiceUtil.getFriendlyURLMappers();
1027
1028        Iterator itr = friendlyURLMappers.iterator();
1029
1030        while (itr.hasNext()) {
1031            FriendlyURLMapper friendlyURLMapper = (FriendlyURLMapper)itr.next();
1032
1033            if (url.endsWith(
1034                    StringPool.SLASH + friendlyURLMapper.getMapping())) {
1035
1036                url += StringPool.SLASH;
1037            }
1038
1039            int pos = url.indexOf(
1040                StringPool.SLASH + friendlyURLMapper.getMapping() +
1041                    StringPool.SLASH);
1042
1043            if (pos != -1) {
1044                friendlyURL = url.substring(0, pos);
1045
1046                Map actualParams = null;
1047
1048                if (params != null) {
1049                    actualParams = new HashMap(params);
1050                }
1051                else {
1052                    actualParams = new HashMap();
1053                }
1054
1055                /*Object action = actualParams.get("p_p_action");
1056
1057                if ((action == null) || (((String[])action).length == 0)) {
1058                    actualParams.put("p_p_action", "0");
1059                }
1060
1061                Object state = actualParams.get("p_p_state");
1062
1063                if ((state == null) || (((String[])state).length == 0)) {
1064                    actualParams.put(
1065                        "p_p_state", WindowState.MAXIMIZED.toString());
1066                }*/
1067
1068                friendlyURLMapper.populateParams(
1069                    url.substring(pos), actualParams);
1070
1071                queryString =
1072                    StringPool.AMPERSAND +
1073                        HttpUtil.parameterMapToString(actualParams, false);
1074
1075                break;
1076            }
1077        }
1078
1079        friendlyURL = StringUtil.replace(
1080            friendlyURL, StringPool.DOUBLE_SLASH, StringPool.SLASH);
1081
1082        if (friendlyURL.endsWith(StringPool.SLASH)) {
1083            friendlyURL = friendlyURL.substring(0, friendlyURL.length() - 1);
1084        }
1085
1086        Layout layout = null;
1087
1088        try {
1089            layout = LayoutLocalServiceUtil.getFriendlyURLLayout(
1090                groupId, privateLayout, friendlyURL);
1091        }
1092        catch(NoSuchLayoutException nsle) {
1093            long layoutId = GetterUtil.getLong(friendlyURL.substring(1));
1094
1095            layout = LayoutLocalServiceUtil.getLayout(
1096                groupId, privateLayout, layoutId);
1097        }
1098
1099        return new Object[] {layout, queryString};
1100    }
1101
1102    public static long getPortletGroupId(long plid) {
1103        Layout layout = null;
1104
1105        try {
1106            layout = LayoutLocalServiceUtil.getLayout(plid);
1107        }
1108        catch (Exception e) {
1109        }
1110
1111        return getPortletGroupId(layout);
1112    }
1113
1114    public static long getPortletGroupId(Layout layout) {
1115        if (layout == null) {
1116            return 0;
1117        }
1118        else {
1119            return layout.getGroupId();
1120        }
1121    }
1122
1123    public static long getPortletGroupId(HttpServletRequest req) {
1124        Layout layout = (Layout)req.getAttribute(WebKeys.LAYOUT);
1125
1126        return getPortletGroupId(layout);
1127    }
1128
1129    public static long getPortletGroupId(ActionRequest req) {
1130        return getPortletGroupId(getHttpServletRequest(req));
1131    }
1132
1133    public static long getPortletGroupId(RenderRequest req) {
1134        return getPortletGroupId(getHttpServletRequest(req));
1135    }
1136
1137    public static String getPortletNamespace(String portletId) {
1138        StringMaker sm = new StringMaker();
1139
1140        sm.append(StringPool.UNDERLINE);
1141        sm.append(portletId);
1142        sm.append(StringPool.UNDERLINE);
1143
1144        return sm.toString();
1145    }
1146
1147    public static String getPortletXmlFileName()
1148        throws PortalException, SystemException {
1149
1150        if (PrefsPropsUtil.getBoolean(
1151                PropsUtil.AUTO_DEPLOY_CUSTOM_PORTLET_XML,
1152                PropsValues.AUTO_DEPLOY_CUSTOM_PORTLET_XML)) {
1153
1154            return PORTLET_XML_FILE_NAME_CUSTOM;
1155        }
1156        else {
1157            return PORTLET_XML_FILE_NAME_STANDARD;
1158        }
1159    }
1160
1161    public static String getPortletTitle(
1162        String portletId, long companyId, String languageId) {
1163
1164        Locale locale = LocaleUtil.fromLanguageId(languageId);
1165
1166        StringMaker sm = new StringMaker();
1167
1168        sm.append(JavaConstants.JAVAX_PORTLET_TITLE);
1169        sm.append(StringPool.PERIOD);
1170        sm.append(portletId);
1171
1172        return LanguageUtil.get(companyId, locale, sm.toString());
1173    }
1174
1175    public static String getPortletTitle(String portletId, User user) {
1176        StringMaker sm = new StringMaker();
1177
1178        sm.append(JavaConstants.JAVAX_PORTLET_TITLE);
1179        sm.append(StringPool.PERIOD);
1180        sm.append(portletId);
1181
1182        return LanguageUtil.get(
1183            user.getCompanyId(), user.getLocale(), sm.toString());
1184    }
1185
1186    public static String getPortletTitle(
1187        Portlet portlet, ServletContext ctx, Locale locale) {
1188
1189        PortletConfig portletConfig = PortletConfigFactory.create(portlet, ctx);
1190
1191        ResourceBundle resourceBundle = portletConfig.getResourceBundle(locale);
1192
1193        return resourceBundle.getString(JavaConstants.JAVAX_PORTLET_TITLE);
1194    }
1195
1196    public static PortletPreferences getPreferences(HttpServletRequest req) {
1197        RenderRequest renderRequest = (RenderRequest)req.getAttribute(
1198            JavaConstants.JAVAX_PORTLET_REQUEST);
1199
1200        PortletPreferences prefs = null;
1201
1202        if (renderRequest != null) {
1203            PortletPreferencesWrapper prefsWrapper =
1204                (PortletPreferencesWrapper)renderRequest.getPreferences();
1205
1206            prefs = prefsWrapper.getPreferencesImpl();
1207        }
1208
1209        return prefs;
1210    }
1211
1212    public static PreferencesValidator getPreferencesValidator(
1213        Portlet portlet) {
1214
1215        if (portlet.isWARFile()) {
1216            PortletContextWrapper pcw =
1217                PortletContextPool.get(portlet.getRootPortletId());
1218
1219            return pcw.getPreferencesValidatorInstance();
1220        }
1221        else {
1222            PreferencesValidator prefsValidator = null;
1223
1224            if (Validator.isNotNull(portlet.getPreferencesValidator())) {
1225                prefsValidator =
1226                    (PreferencesValidator)InstancePool.get(
1227                        portlet.getPreferencesValidator());
1228            }
1229
1230            return prefsValidator;
1231        }
1232    }
1233
1234    public static RenderResponseImpl getRenderResponseImpl(RenderResponse res) {
1235        RenderResponseImpl resImpl = null;
1236
1237        if (res instanceof RenderResponseImpl) {
1238            resImpl = (RenderResponseImpl)res;
1239        }
1240        else {
1241
1242            // LEP-4033
1243
1244            try {
1245                Method method = MethodCache.get(
1246                    res.getClass().getName(), "getResponse");
1247
1248                Object obj = method.invoke(res, null);
1249
1250                resImpl = getRenderResponseImpl((RenderResponse)obj);
1251            }
1252            catch (Exception e) {
1253                throw new RuntimeException(e);
1254            }
1255        }
1256
1257        return resImpl;
1258    }
1259
1260    public static User getSelectedUser(HttpServletRequest req)
1261        throws PortalException, RemoteException, SystemException {
1262
1263        return getSelectedUser(req, true);
1264    }
1265
1266    public static User getSelectedUser(
1267            HttpServletRequest req, boolean checkPermission)
1268        throws PortalException, RemoteException, SystemException {
1269
1270        long userId = ParamUtil.getLong(req, "p_u_i_d");
1271
1272        User user = null;
1273
1274        try {
1275            if (checkPermission) {
1276                user = UserServiceUtil.getUserById(userId);
1277            }
1278            else {
1279                user = UserLocalServiceUtil.getUserById(userId);
1280            }
1281        }
1282        catch (NoSuchUserException nsue) {
1283        }
1284
1285        return user;
1286    }
1287
1288    public static User getSelectedUser(ActionRequest req)
1289        throws PortalException, RemoteException, SystemException {
1290
1291        return getSelectedUser(req, true);
1292    }
1293
1294    public static User getSelectedUser(
1295            ActionRequest req, boolean checkPermission)
1296        throws PortalException, RemoteException, SystemException {
1297
1298        return getSelectedUser(getHttpServletRequest(req), checkPermission);
1299    }
1300
1301    public static User getSelectedUser(RenderRequest req)
1302        throws PortalException, RemoteException, SystemException {
1303
1304        return getSelectedUser(req, true);
1305    }
1306
1307    public static User getSelectedUser(
1308            RenderRequest req, boolean checkPermission)
1309        throws PortalException, RemoteException, SystemException {
1310
1311        return getSelectedUser(getHttpServletRequest(req), checkPermission);
1312    }
1313
1314    public static String getStrutsAction(HttpServletRequest req) {
1315        String strutsAction = ParamUtil.getString(req, "struts_action");
1316
1317        if (Validator.isNotNull(strutsAction)) {
1318
1319            // This method should only return a Struts action if you're dealing
1320            // with a regular HTTP servlet request, not a portlet HTTP servlet
1321            // request.
1322
1323            return StringPool.BLANK;
1324        }
1325
1326        int strutsActionCount = 0;
1327
1328        Enumeration enu = req.getParameterNames();
1329
1330        while (enu.hasMoreElements()) {
1331            String name = (String)enu.nextElement();
1332
1333            int pos = name.indexOf("_struts_action");
1334
1335            if (pos != -1) {
1336                strutsActionCount++;
1337
1338                // There should never be more than one Struts action
1339
1340                if (strutsActionCount > 1) {
1341                    return StringPool.BLANK;
1342                }
1343
1344                String curStrutsAction = ParamUtil.getString(req, name);
1345
1346                if (Validator.isNotNull(curStrutsAction)) {
1347
1348                    // The Struts action must be for the correct portlet
1349
1350                    String portletId1 = name.substring(1, pos);
1351                    String portletId2 = ParamUtil.getString(req, "p_p_id");
1352
1353                    if (portletId1.equals(portletId2)) {
1354                        strutsAction = curStrutsAction;
1355                    }
1356                }
1357            }
1358        }
1359
1360        return strutsAction;
1361    }
1362
1363    public static String[] getSystemCommunityRoles() {
1364        return _instance._getSystemCommunityRoles();
1365    }
1366
1367    public static String[] getSystemGroups() {
1368        return _instance._getSystemGroups();
1369    }
1370
1371    public static String[] getSystemOrganizationRoles() {
1372        return _instance._getSystemOrganizationRoles();
1373    }
1374
1375    public static String[] getSystemRoles() {
1376        return _instance._getSystemRoles();
1377    }
1378
1379    public static UploadPortletRequest getUploadPortletRequest(
1380        ActionRequest req) {
1381
1382        ActionRequestImpl actionReq = (ActionRequestImpl)req;
1383
1384        DynamicServletRequest dynamicReq =
1385            (DynamicServletRequest)actionReq.getHttpServletRequest();
1386
1387        HttpServletRequestWrapper reqWrapper =
1388            (HttpServletRequestWrapper)dynamicReq.getRequest();
1389
1390        UploadServletRequest uploadReq = getUploadServletRequest(reqWrapper);
1391
1392        return new UploadPortletRequest(
1393            uploadReq, getPortletNamespace(actionReq.getPortletName()));
1394    }
1395
1396    public static UploadServletRequest getUploadServletRequest(
1397        HttpServletRequest httpReq) {
1398
1399        HttpServletRequestWrapper httpReqWrapper = null;
1400
1401        if (httpReq instanceof HttpServletRequestWrapper) {
1402            httpReqWrapper = (HttpServletRequestWrapper)httpReq;
1403        }
1404
1405        UploadServletRequest uploadReq = null;
1406
1407        while (uploadReq == null) {
1408
1409            // Find the underlying UploadServletRequest wrapper. For example,
1410            // WebSphere wraps all requests with ProtectedServletRequest.
1411
1412            if (httpReqWrapper instanceof UploadServletRequest) {
1413                uploadReq = (UploadServletRequest)httpReqWrapper;
1414            }
1415            else {
1416                ServletRequest req = httpReqWrapper.getRequest();
1417
1418                if (!(req instanceof HttpServletRequestWrapper)) {
1419                    break;
1420                }
1421                else {
1422                    httpReqWrapper =
1423                        (HttpServletRequestWrapper)httpReqWrapper.getRequest();
1424                }
1425            }
1426        }
1427
1428        return uploadReq;
1429    }
1430
1431    public static Date getUptime() {
1432        return UP_TIME;
1433    }
1434
1435    public static String getURLWithSessionId(String url, String sessionId) {
1436
1437        // LEP-4787
1438
1439        int x = url.indexOf(StringPool.SEMICOLON);
1440
1441        if (x != -1) {
1442            return url;
1443        }
1444
1445        x = url.indexOf(StringPool.QUESTION);
1446
1447        if (x != -1) {
1448            StringMaker sm = new StringMaker();
1449
1450            sm.append(url.substring(0, x));
1451            sm.append(_JSESSIONID);
1452            sm.append(sessionId);
1453            sm.append(url.substring(x));
1454
1455            return sm.toString();
1456        }
1457
1458        // In IE6, http://www.abc.com;jsessionid=XYZ does not work,
1459        // but http://www.abc.com/;jsessionid=XYZ does work.
1460
1461        x = url.indexOf(StringPool.DOUBLE_SLASH);
1462
1463        StringMaker sm = new StringMaker();
1464
1465        sm.append(url);
1466
1467        if (x != -1) {
1468            int y = url.lastIndexOf(StringPool.SLASH);
1469
1470            if (x + 1 == y) {
1471                sm.append(StringPool.SLASH);
1472            }
1473        }
1474
1475        sm.append(_JSESSIONID);
1476        sm.append(sessionId);
1477
1478        return sm.toString();
1479    }
1480
1481    public static User getUser(HttpServletRequest req)
1482        throws PortalException, SystemException {
1483
1484        long userId = getUserId(req);
1485
1486        if (userId <= 0) {
1487
1488            // Portlet WARs may have the correct remote user and not have the
1489            // correct user id because the user id is saved in the session
1490            // and may not be accessible by the portlet WAR's session. This
1491            // behavior is inconsistent across different application servers.
1492
1493            String remoteUser = req.getRemoteUser();
1494
1495            if (remoteUser == null) {
1496                return null;
1497            }
1498
1499            userId = GetterUtil.getLong(remoteUser);
1500        }
1501
1502        User user = (User)req.getAttribute(WebKeys.USER);
1503
1504        if (user == null) {
1505            user = UserLocalServiceUtil.getUserById(userId);
1506
1507            req.setAttribute(WebKeys.USER, user);
1508        }
1509
1510        return user;
1511    }
1512
1513    public static User getUser(ActionRequest req)
1514        throws PortalException, SystemException {
1515
1516        return getUser(getHttpServletRequest(req));
1517    }
1518
1519    public static User getUser(RenderRequest req)
1520        throws PortalException, SystemException {
1521
1522        return getUser(getHttpServletRequest(req));
1523    }
1524
1525    public static long getUserId(HttpServletRequest req) {
1526        Long userIdObj = (Long)req.getAttribute(WebKeys.USER_ID);
1527
1528        if (userIdObj != null) {
1529            return userIdObj.longValue();
1530        }
1531
1532        if (!PropsValues.PORTAL_JAAS_ENABLE &&
1533            PropsValues.PORTAL_IMPERSONATION_ENABLE) {
1534
1535            String doAsUserIdString = ParamUtil.getString(req, "doAsUserId");
1536
1537            try {
1538                long doAsUserId = _getDoAsUserId(req, doAsUserIdString);
1539
1540                if (doAsUserId > 0) {
1541                    if (_log.isDebugEnabled()) {
1542                        _log.debug("Impersonating user " + doAsUserId);
1543                    }
1544
1545                    return doAsUserId;
1546                }
1547            }
1548            catch (Exception e) {
1549                _log.error("Unable to impersonate user " + doAsUserIdString, e);
1550            }
1551        }
1552
1553        HttpSession ses = req.getSession();
1554
1555        userIdObj = (Long)ses.getAttribute(WebKeys.USER_ID);
1556
1557        if (userIdObj != null) {
1558            req.setAttribute(WebKeys.USER_ID, userIdObj);
1559
1560            return userIdObj.longValue();
1561        }
1562        else {
1563            return 0;
1564        }
1565    }
1566
1567    public static long getUserId(ActionRequest req) {
1568        return getUserId(getHttpServletRequest(req));
1569    }
1570
1571    public static long getUserId(RenderRequest req) {
1572        return getUserId(getHttpServletRequest(req));
1573    }
1574
1575    public static String getUserName(long userId, String defaultUserName) {
1576        return getUserName(
1577            userId, defaultUserName, UserAttributes.USER_NAME_FULL);
1578    }
1579
1580    public static String getUserName(
1581        long userId, String defaultUserName, String userAttribute) {
1582
1583        return getUserName(userId, defaultUserName, userAttribute, null);
1584    }
1585
1586    public static String getUserName(
1587        long userId, String defaultUserName, HttpServletRequest req) {
1588
1589        return getUserName(
1590            userId, defaultUserName, UserAttributes.USER_NAME_FULL, req);
1591    }
1592
1593    public static String getUserName(
1594        long userId, String defaultUserName, String userAttribute,
1595        HttpServletRequest req) {
1596
1597        String userName = defaultUserName;
1598
1599        try {
1600            User user = UserLocalServiceUtil.getUserById(userId);
1601
1602            if (userAttribute.equals(UserAttributes.USER_NAME_FULL)) {
1603                userName = user.getFullName();
1604            }
1605            else {
1606                userName = user.getScreenName();
1607            }
1608
1609            if (req != null) {
1610                Layout layout = (Layout)req.getAttribute(WebKeys.LAYOUT);
1611
1612                PortletURL portletURL = new PortletURLImpl(
1613                    req, PortletKeys.DIRECTORY, layout.getPlid(), false);
1614
1615                portletURL.setWindowState(WindowState.MAXIMIZED);
1616                portletURL.setPortletMode(PortletMode.VIEW);
1617
1618                portletURL.setParameter(
1619                    "struts_action", "/directory/edit_user");
1620                portletURL.setParameter(
1621                    "p_u_i_d", String.valueOf(user.getUserId()));
1622
1623                userName =
1624                    "<a href=\"" + portletURL.toString() + "\">" + userName +
1625                        "</a>";
1626            }
1627        }
1628        catch (Exception e) {
1629        }
1630
1631        return userName;
1632    }
1633
1634    public static String getUserPassword(HttpSession ses) {
1635        return (String)ses.getAttribute(WebKeys.USER_PASSWORD);
1636    }
1637
1638    public static String getUserPassword(HttpServletRequest req) {
1639        return getUserPassword(req.getSession());
1640    }
1641
1642    public static String getUserPassword(ActionRequest req) {
1643        return getUserPassword(getHttpServletRequest(req));
1644    }
1645
1646    public static String getUserPassword(RenderRequest req) {
1647        return getUserPassword(getHttpServletRequest(req));
1648    }
1649
1650    public static String getUserValue(
1651            long userId, String param, String defaultValue)
1652        throws SystemException {
1653
1654        if (Validator.isNotNull(defaultValue)) {
1655            return defaultValue;
1656        }
1657        else {
1658            try {
1659                User user = UserLocalServiceUtil.getUserById(userId);
1660
1661                return BeanUtil.getString(user, param, defaultValue);
1662            }
1663            catch (PortalException pe) {
1664                return StringPool.BLANK;
1665            }
1666        }
1667    }
1668
1669    public static boolean isMethodGet(PortletRequest req) {
1670        HttpServletRequest httpReq = getHttpServletRequest(req);
1671
1672        String method = GetterUtil.getString(httpReq.getMethod());
1673
1674        if (method.equalsIgnoreCase(_METHOD_GET)) {
1675            return true;
1676        }
1677        else {
1678            return false;
1679        }
1680    }
1681
1682    public static boolean isMethodPost(PortletRequest req) {
1683        HttpServletRequest httpReq = getHttpServletRequest(req);
1684
1685        String method = GetterUtil.getString(httpReq.getMethod());
1686
1687        if (method.equalsIgnoreCase(_METHOD_POST)) {
1688            return true;
1689        }
1690        else {
1691            return false;
1692        }
1693    }
1694
1695    public static boolean isLayoutFriendliable(Layout layout) {
1696        return PropsUtil.getComponentProperties().getBoolean(
1697            PropsUtil.LAYOUT_URL_FRIENDLIABLE,
1698            Filter.by(layout.getType()), true);
1699    }
1700
1701    public static boolean isLayoutParentable(Layout layout) {
1702        return isLayoutParentable(layout.getType());
1703    }
1704
1705    public static boolean isLayoutParentable(String type) {
1706        return PropsUtil.getComponentProperties().getBoolean(
1707            PropsUtil.LAYOUT_PARENTABLE, Filter.by(type), true);
1708    }
1709
1710    public static boolean isLayoutSitemapable(Layout layout) {
1711        if (layout.isPrivateLayout()) {
1712            return false;
1713        }
1714
1715        return PropsUtil.getComponentProperties().getBoolean(
1716            PropsUtil.LAYOUT_SITEMAPABLE, Filter.by(layout.getType()), true);
1717    }
1718
1719    public static boolean isReservedParameter(String name) {
1720        return _instance._reservedParams.contains(name);
1721    }
1722
1723    public static boolean isSystemGroup(String groupName) {
1724        return _instance._isSystemGroup(groupName);
1725    }
1726
1727    public static boolean isSystemRole(String roleName) {
1728        return _instance._isSystemRole(roleName);
1729    }
1730
1731    public static boolean isUpdateAvailable()
1732        throws PortalException, SystemException {
1733
1734        return PluginPackageUtil.isUpdateAvailable();
1735    }
1736
1737    public static Document readDocumentFromFile(File file)
1738        throws DocumentException {
1739
1740        return readDocumentFromFile(file, false);
1741    }
1742
1743    public static Document readDocumentFromFile(File file, boolean validate)
1744        throws DocumentException {
1745
1746        SAXReader reader = SAXReaderFactory.getInstance(validate);
1747
1748        return reader.read(file);
1749    }
1750
1751    public static Document readDocumentFromStream(InputStream is)
1752        throws DocumentException {
1753
1754        return readDocumentFromStream(is, false);
1755    }
1756
1757    public static Document readDocumentFromStream(
1758            InputStream is, boolean validate)
1759        throws DocumentException {
1760
1761        SAXReader reader = SAXReaderFactory.getInstance(validate);
1762
1763        return reader.read(is);
1764    }
1765
1766    public static Document readDocumentFromURL(String url)
1767        throws DocumentException, IOException {
1768
1769        return readDocumentFromURL(url, false);
1770    }
1771
1772    public static Document readDocumentFromURL(String url, boolean validate)
1773        throws DocumentException, IOException {
1774
1775        SAXReader reader = SAXReaderFactory.getInstance(validate);
1776
1777        return reader.read(new URL(url));
1778    }
1779
1780    public static Document readDocumentFromXML(String xml)
1781        throws DocumentException {
1782
1783        return readDocumentFromXML(xml, false);
1784    }
1785
1786    public static Document readDocumentFromXML(String xml, boolean validate)
1787        throws DocumentException {
1788
1789        SAXReader reader = SAXReaderFactory.getInstance(validate);
1790
1791        return reader.read(new XMLSafeReader(xml));
1792    }
1793
1794    public static void renderPage(
1795            StringMaker sm, ServletContext ctx, HttpServletRequest req,
1796            HttpServletResponse res, String path)
1797        throws IOException, ServletException {
1798
1799        RequestDispatcher rd = ctx.getRequestDispatcher(path);
1800
1801        StringServletResponse stringServletRes =
1802            new StringServletResponse(res);
1803
1804        rd.include(req, stringServletRes);
1805
1806        sm.append(stringServletRes.getString());
1807    }
1808
1809    public static void renderPortlet(
1810            StringMaker sm, ServletContext ctx, HttpServletRequest req,
1811            HttpServletResponse res, Portlet portlet, String queryString)
1812        throws IOException, ServletException {
1813
1814        renderPortlet(
1815            sm, ctx, req, res, portlet, queryString, null, null, null);
1816    }
1817
1818    public static void renderPortlet(
1819            StringMaker sm, ServletContext ctx, HttpServletRequest req,
1820            HttpServletResponse res, Portlet portlet, String queryString,
1821            String columnId, Integer columnPos, Integer columnCount)
1822        throws IOException, ServletException {
1823
1824        renderPortlet(
1825            sm, ctx, req, res, portlet, queryString, columnId, columnPos,
1826            columnCount, null);
1827    }
1828
1829    public static void renderPortlet(
1830            StringMaker sm, ServletContext ctx, HttpServletRequest req,
1831            HttpServletResponse res, Portlet portlet, String queryString,
1832            String columnId, Integer columnPos, Integer columnCount,
1833            String path)
1834        throws IOException, ServletException {
1835
1836        queryString = GetterUtil.getString(queryString);
1837        columnId = GetterUtil.getString(columnId);
1838
1839        if (columnPos == null) {
1840            columnPos = new Integer(0);
1841        }
1842
1843        if (columnCount == null) {
1844            columnCount = new Integer(0);
1845        }
1846
1847        req.setAttribute(WebKeys.RENDER_PORTLET, portlet);
1848        req.setAttribute(WebKeys.RENDER_PORTLET_QUERY_STRING, queryString);
1849        req.setAttribute(WebKeys.RENDER_PORTLET_COLUMN_ID, columnId);
1850        req.setAttribute(WebKeys.RENDER_PORTLET_COLUMN_POS, columnPos);
1851        req.setAttribute(WebKeys.RENDER_PORTLET_COLUMN_COUNT, columnCount);
1852
1853        if (path == null) {
1854            path = "/html/portal/render_portlet.jsp";
1855        }
1856
1857        RequestDispatcher rd = ctx.getRequestDispatcher(path);
1858
1859        if (sm != null) {
1860            StringServletResponse stringServletRes =
1861                new StringServletResponse(res);
1862
1863            rd.include(req, stringServletRes);
1864
1865            sm.append(stringServletRes.getString());
1866        }
1867        else {
1868
1869            // LEP-766
1870
1871            res.setContentType(ContentTypes.TEXT_HTML_UTF8);
1872
1873            rd.include(req, res);
1874        }
1875    }
1876
1877    public static void sendError(
1878            int status, Exception e, HttpServletRequest req,
1879            HttpServletResponse res)
1880        throws IOException, ServletException {
1881
1882        ServletContext ctx = req.getSession().getServletContext();
1883
1884        String mainPath = PortalUtil.PATH_MAIN;
1885
1886        String redirect = mainPath + "/portal/status";
1887
1888        if (e instanceof NoSuchLayoutException &&
1889            Validator.isNotNull(
1890                PropsValues.LAYOUT_FRIENDLY_URL_PAGE_NOT_FOUND)) {
1891
1892            res.setStatus(status);
1893
1894            redirect = PropsValues.LAYOUT_FRIENDLY_URL_PAGE_NOT_FOUND;
1895
1896            RequestDispatcher rd = ctx.getRequestDispatcher(redirect);
1897
1898            if (rd != null) {
1899                rd.forward(req, res);
1900            }
1901        }
1902        else if (PropsValues.LAYOUT_SHOW_HTTP_STATUS) {
1903            res.setStatus(status);
1904
1905            SessionErrors.add(req, e.getClass().getName(), e);
1906
1907            RequestDispatcher rd = ctx.getRequestDispatcher(redirect);
1908
1909            if (rd != null) {
1910                rd.forward(req, res);
1911            }
1912        }
1913        else {
1914            if (e != null) {
1915                res.sendError(status, e.getMessage());
1916            }
1917            else {
1918                res.sendError(status);
1919            }
1920        }
1921    }
1922
1923    /**
1924     * Sets the subtitle for a page. This is just a hint and can be overridden
1925     * by subsequent calls. The last call to this method wins.
1926     *
1927     * @param       subtitle the subtitle for a page
1928     * @param       req the HTTP servlet request
1929     */
1930    public static void setPageSubtitle(
1931        String subtitle, HttpServletRequest req) {
1932
1933        req.setAttribute(WebKeys.PAGE_SUBTITLE, subtitle);
1934    }
1935
1936    /**
1937     * Sets the whole title for a page. This is just a hint and can be
1938     * overridden by subsequent calls. The last call to this method wins.
1939     *
1940     * @param       title the whole title for a page
1941     * @param       req the HTTP servlet request
1942     */
1943    public static void setPageTitle(String title, HttpServletRequest req) {
1944        req.setAttribute(WebKeys.PAGE_TITLE, title);
1945    }
1946
1947    public static void storePreferences(PortletPreferences prefs)
1948        throws IOException, ValidatorException {
1949
1950        PortletPreferencesWrapper prefsWrapper =
1951            (PortletPreferencesWrapper)prefs;
1952
1953        PortletPreferencesImpl prefsImpl =
1954            (PortletPreferencesImpl)prefsWrapper.getPreferencesImpl();
1955
1956        prefsImpl.store();
1957    }
1958
1959    public static PortletMode updatePortletMode(
1960            String portletId, User user, Layout layout, PortletMode portletMode,
1961            HttpServletRequest req)
1962        throws PortalException, RemoteException, SystemException {
1963
1964        LayoutTypePortlet layoutType =
1965            (LayoutTypePortlet)layout.getLayoutType();
1966
1967        if (portletMode == null || Validator.isNull(portletMode.toString())) {
1968            if (layoutType.hasModeAboutPortletId(portletId)) {
1969                return LiferayPortletMode.ABOUT;
1970            }
1971            else if (layoutType.hasModeConfigPortletId(portletId)) {
1972                return LiferayPortletMode.CONFIG;
1973            }
1974            else if (layoutType.hasModeEditPortletId(portletId)) {
1975                return PortletMode.EDIT;
1976            }
1977            else if (layoutType.hasModeEditDefaultsPortletId(portletId)) {
1978                return LiferayPortletMode.EDIT_DEFAULTS;
1979            }
1980            else if (layoutType.hasModeEditGuestPortletId(portletId)) {
1981                return LiferayPortletMode.EDIT_GUEST;
1982            }
1983            else if (layoutType.hasModeHelpPortletId(portletId)) {
1984                return PortletMode.HELP;
1985            }
1986            else if (layoutType.hasModePreviewPortletId(portletId)) {
1987                return LiferayPortletMode.PREVIEW;
1988            }
1989            else if (layoutType.hasModePrintPortletId(portletId)) {
1990                return LiferayPortletMode.PRINT;
1991            }
1992            else {
1993                return PortletMode.VIEW;
1994            }
1995        }
1996        else {
1997            boolean updateLayout = false;
1998
1999            if (portletMode.equals(LiferayPortletMode.ABOUT) &&
2000                !layoutType.hasModeAboutPortletId(portletId)) {
2001
2002                layoutType.addModeAboutPortletId(portletId);
2003
2004                updateLayout = true;
2005            }
2006            else if (portletMode.equals(LiferayPortletMode.CONFIG) &&
2007                     !layoutType.hasModeConfigPortletId(portletId)) {
2008
2009                layoutType.addModeConfigPortletId(portletId);
2010
2011                updateLayout = true;
2012            }
2013            else if (portletMode.equals(PortletMode.EDIT) &&
2014                     !layoutType.hasModeEditPortletId(portletId)) {
2015
2016                layoutType.addModeEditPortletId(portletId);
2017
2018                updateLayout = true;
2019            }
2020            else if (portletMode.equals(LiferayPortletMode.EDIT_DEFAULTS) &&
2021                     !layoutType.hasModeEditDefaultsPortletId(portletId)) {
2022
2023                layoutType.addModeEditDefaultsPortletId(portletId);
2024
2025                updateLayout = true;
2026            }
2027            else if (portletMode.equals(LiferayPortletMode.EDIT_GUEST) &&
2028                     !layoutType.hasModeEditGuestPortletId(portletId)) {
2029
2030                layoutType.addModeEditGuestPortletId(portletId);
2031
2032                updateLayout = true;
2033            }
2034            else if (portletMode.equals(PortletMode.HELP) &&
2035                     !layoutType.hasModeHelpPortletId(portletId)) {
2036
2037                layoutType.addModeHelpPortletId(portletId);
2038
2039                updateLayout = true;
2040            }
2041            else if (portletMode.equals(LiferayPortletMode.PREVIEW) &&
2042                     !layoutType.hasModePreviewPortletId(portletId)) {
2043
2044                layoutType.addModePreviewPortletId(portletId);
2045
2046                updateLayout = true;
2047            }
2048            else if (portletMode.equals(LiferayPortletMode.PRINT) &&
2049                     !layoutType.hasModePrintPortletId(portletId)) {
2050
2051                layoutType.addModePrintPortletId(portletId);
2052
2053                updateLayout = true;
2054            }
2055            else if (portletMode.equals(PortletMode.VIEW) &&
2056                     !layoutType.hasModeViewPortletId(portletId)) {
2057
2058                layoutType.removeModesPortletId(portletId);
2059
2060                updateLayout = true;
2061            }
2062
2063            if (updateLayout) {
2064                LayoutClone layoutClone = LayoutCloneFactory.getInstance();
2065
2066                if (layoutClone != null) {
2067                    layoutClone.update(
2068                        req, layout.getPlid(), layout.getTypeSettings());
2069                }
2070            }
2071
2072            return portletMode;
2073        }
2074    }
2075
2076    public static WindowState updateWindowState(
2077            String portletId, User user, Layout layout, WindowState windowState,
2078            HttpServletRequest req)
2079        throws PortalException, RemoteException, SystemException {
2080
2081        LayoutTypePortlet layoutType =
2082            (LayoutTypePortlet)layout.getLayoutType();
2083
2084        if ((windowState == null) ||
2085            (Validator.isNull(windowState.toString()))) {
2086
2087            if (layoutType.hasStateMaxPortletId(portletId)) {
2088                return WindowState.MAXIMIZED;
2089            }
2090            else if (layoutType.hasStateMinPortletId(portletId)) {
2091                return WindowState.MINIMIZED;
2092            }
2093            else {
2094                return WindowState.NORMAL;
2095            }
2096        }
2097        else {
2098            boolean updateLayout = false;
2099
2100            if ((windowState.equals(WindowState.MAXIMIZED)) ||
2101                (windowState.equals(LiferayWindowState.EXCLUSIVE)) ||
2102                (windowState.equals(LiferayWindowState.POP_UP))) {
2103
2104                if (layoutType.hasStateMax()) {
2105                    String curMaxPortletId =
2106                        StringUtil.split(layoutType.getStateMax())[0];
2107
2108                    // Clear cache and render parameters for the previous
2109                    // portlet that had a maximum window state
2110
2111                    CachePortlet.clearResponse(
2112                        req.getSession(), layout.getPlid(), curMaxPortletId,
2113                        LanguageUtil.getLanguageId(req));
2114
2115                    /*RenderParametersPool.clear(
2116                        req, layout.getPlid(), curMaxPortletId);*/
2117
2118                    if ((windowState.equals(LiferayWindowState.EXCLUSIVE)) ||
2119                        (windowState.equals(LiferayWindowState.POP_UP))) {
2120
2121                        String stateMaxPrevious =
2122                            layoutType.getStateMaxPrevious();
2123
2124                        if (stateMaxPrevious == null) {
2125                            layoutType.setStateMaxPrevious(curMaxPortletId);
2126
2127                            updateLayout = true;
2128                        }
2129                    }
2130                }
2131                else {
2132                    if ((windowState.equals(LiferayWindowState.EXCLUSIVE)) ||
2133                        (windowState.equals(LiferayWindowState.POP_UP))) {
2134
2135                        String stateMaxPrevious =
2136                            layoutType.getStateMaxPrevious();
2137
2138                        if (stateMaxPrevious == null) {
2139                            layoutType.setStateMaxPrevious(StringPool.BLANK);
2140
2141                            updateLayout = true;
2142                        }
2143                    }
2144                }
2145
2146                if (!layoutType.hasStateMaxPortletId(portletId)) {
2147                    layoutType.addStateMaxPortletId(portletId);
2148
2149                    updateLayout = true;
2150                }
2151            }
2152            else if (windowState.equals(WindowState.MINIMIZED) &&
2153                     !layoutType.hasStateMinPortletId(portletId)) {
2154
2155                layoutType.addStateMinPortletId(portletId);
2156
2157                updateLayout = true;
2158            }
2159            else if (windowState.equals(WindowState.NORMAL) &&
2160                     !layoutType.hasStateNormalPortletId(portletId)) {
2161
2162                layoutType.removeStatesPortletId(portletId);
2163
2164                updateLayout = true;
2165            }
2166
2167            if (updateLayout) {
2168                LayoutClone layoutClone = LayoutCloneFactory.getInstance();
2169
2170                if (layoutClone != null) {
2171                    layoutClone.update(
2172                        req, layout.getPlid(), layout.getTypeSettings());
2173                }
2174            }
2175
2176            return windowState;
2177        }
2178    }
2179
2180    private static long _getDoAsUserId(
2181            HttpServletRequest req, String doAsUserIdString)
2182        throws Exception {
2183
2184        if (Validator.isNull(doAsUserIdString)) {
2185            return 0;
2186        }
2187
2188        long doAsUserId = 0;
2189
2190        try {
2191            Company company = getCompany(req);
2192
2193            doAsUserId = GetterUtil.getLong(
2194                Encryptor.decrypt(company.getKeyObj(), doAsUserIdString));
2195        }
2196        catch (Exception e) {
2197            if (_log.isWarnEnabled()) {
2198                _log.warn(
2199                    "Unable to impersonate " + doAsUserIdString +
2200                        " because the string cannot be decrypted",
2201                    e);
2202            }
2203
2204            return 0;
2205        }
2206
2207        String path = GetterUtil.getString(req.getPathInfo());
2208
2209        if (_log.isDebugEnabled()) {
2210            _log.debug("doAsUserId path " + path);
2211        }
2212
2213        String strutsAction = getStrutsAction(req);
2214
2215        if (_log.isDebugEnabled()) {
2216            _log.debug("Struts action " + strutsAction);
2217        }
2218
2219        boolean alwaysAllowDoAsUser = false;
2220
2221        if (path.equals("/portal/fckeditor") ||
2222            strutsAction.equals("/document_library/edit_file_entry") ||
2223            strutsAction.equals("/image_gallery/edit_image")) {
2224
2225            alwaysAllowDoAsUser = true;
2226        }
2227
2228        if (_log.isDebugEnabled()) {
2229            if (alwaysAllowDoAsUser) {
2230                _log.debug(
2231                    "doAsUserId path or Struts action is always allowed");
2232            }
2233            else {
2234                _log.debug(
2235                    "doAsUserId path is Struts action not always allowed");
2236            }
2237        }
2238
2239        if (alwaysAllowDoAsUser) {
2240            req.setAttribute(WebKeys.USER_ID, new Long(doAsUserId));
2241
2242            return doAsUserId;
2243        }
2244
2245        HttpSession ses = req.getSession();
2246
2247        Long realUserIdObj = (Long)ses.getAttribute(WebKeys.USER_ID);
2248
2249        if (realUserIdObj == null) {
2250            return 0;
2251        }
2252
2253        User doAsUser = UserLocalServiceUtil.getUserById(doAsUserId);
2254
2255        long[] organizationIds = doAsUser.getOrganizationIds();
2256
2257        User realUser = UserLocalServiceUtil.getUserById(
2258            realUserIdObj.longValue());
2259        boolean checkGuest = true;
2260
2261        PermissionCheckerImpl permissionChecker = null;
2262
2263        try {
2264            permissionChecker = PermissionCheckerFactory.create(
2265                realUser, checkGuest);
2266
2267            if (doAsUser.isDefaultUser() ||
2268                UserPermissionUtil.contains(
2269                    permissionChecker, doAsUserId, organizationIds,
2270                    ActionKeys.IMPERSONATE)) {
2271
2272                req.setAttribute(WebKeys.USER_ID, new Long(doAsUserId));
2273
2274                return doAsUserId;
2275            }
2276            else {
2277                _log.error(
2278                    "User " + realUserIdObj + " does not have the permission " +
2279                        "to impersonate " + doAsUserId);
2280
2281                return 0;
2282            }
2283        }
2284        finally {
2285            try {
2286                PermissionCheckerFactory.recycle(permissionChecker);
2287            }
2288            catch (Exception e) {
2289            }
2290        }
2291    }
2292
2293    private PortalUtil() {
2294
2295        // Computer name
2296
2297        _computerName = System.getProperty("env.COMPUTERNAME");
2298
2299        if (Validator.isNull(_computerName)) {
2300            _computerName = System.getProperty("env.HOST");
2301        }
2302
2303        if (Validator.isNull(_computerName)) {
2304            _computerName = System.getProperty("env.HOSTNAME");
2305        }
2306
2307        // Portal lib directory
2308
2309        ClassLoader classLoader = getClass().getClassLoader();
2310
2311        URL url = classLoader.getResource(
2312            "com/liferay/portal/util/PortalUtil.class");
2313
2314        String file = url.getFile();
2315
2316        if (_log.isInfoEnabled()) {
2317            _log.info("Portal lib url " + file);
2318        }
2319
2320        int pos = file.indexOf("/com/liferay/portal/util/");
2321
2322        _portalLibDir = file.substring(0, pos + 1);
2323
2324        if (_portalLibDir.endsWith("/WEB-INF/classes/")) {
2325            _portalLibDir = _portalLibDir.substring(
2326                0, _portalLibDir.length() - 8) + "lib/";
2327        }
2328        else {
2329            pos = _portalLibDir.indexOf("/WEB-INF/lib/");
2330
2331            if (pos != -1) {
2332                _portalLibDir =
2333                    _portalLibDir.substring(0, pos) + "/WEB-INF/lib/";
2334            }
2335        }
2336
2337        if (_portalLibDir.startsWith("file:/")) {
2338            _portalLibDir = _portalLibDir.substring(5, _portalLibDir.length());
2339        }
2340
2341        if (_log.isInfoEnabled()) {
2342            _log.info("Portal lib directory " + _portalLibDir);
2343        }
2344
2345        // CDN host
2346
2347        _cdnHost = PropsUtil.get(PropsUtil.CDN_HOST);
2348
2349        // Paths
2350
2351        _pathContext = PropsUtil.get(PropsUtil.PORTAL_CTX);
2352
2353        if (_pathContext.equals(StringPool.SLASH)) {
2354            _pathContext = StringPool.BLANK;
2355        }
2356
2357        _pathFriendlyURLPrivateGroup =
2358            _pathContext +
2359                PropsValues.LAYOUT_FRIENDLY_URL_PRIVATE_GROUP_SERVLET_MAPPING;
2360        _pathFriendlyURLPrivateUser =
2361            _pathContext +
2362                PropsValues.LAYOUT_FRIENDLY_URL_PRIVATE_USER_SERVLET_MAPPING;
2363        _pathFriendlyURLPublic =
2364            _pathContext +
2365                PropsValues.LAYOUT_FRIENDLY_URL_PUBLIC_SERVLET_MAPPING;
2366        _pathImage = _cdnHost + _pathContext + PATH_IMAGE;
2367        _pathMain = _pathContext + PATH_MAIN;
2368
2369        // Groups
2370
2371        String customSystemGroups[] =
2372            PropsUtil.getArray(PropsUtil.SYSTEM_GROUPS);
2373
2374        if ((customSystemGroups == null) || (customSystemGroups.length == 0)) {
2375            _allSystemGroups = GroupImpl.SYSTEM_GROUPS;
2376        }
2377        else {
2378            _allSystemGroups = ArrayUtil.append(
2379                GroupImpl.SYSTEM_GROUPS, customSystemGroups);
2380        }
2381
2382        _sortedSystemGroups = new String[_allSystemGroups.length];
2383
2384        System.arraycopy(
2385            _allSystemGroups, 0, _sortedSystemGroups, 0,
2386            _allSystemGroups.length);
2387
2388        Arrays.sort(_sortedSystemGroups, new StringComparator());
2389
2390        // Regular roles
2391
2392        String customSystemRoles[] = PropsUtil.getArray(PropsUtil.SYSTEM_ROLES);
2393
2394        if ((customSystemRoles == null) || (customSystemRoles.length == 0)) {
2395            _allSystemRoles = RoleImpl.SYSTEM_ROLES;
2396        }
2397        else {
2398            _allSystemRoles = ArrayUtil.append(
2399                RoleImpl.SYSTEM_ROLES, customSystemRoles);
2400        }
2401
2402        _sortedSystemRoles = new String[_allSystemRoles.length];
2403
2404        System.arraycopy(
2405            _allSystemRoles, 0, _sortedSystemRoles, 0, _allSystemRoles.length);
2406
2407        Arrays.sort(_sortedSystemRoles, new StringComparator());
2408
2409        // Community roles
2410
2411        String customSystemCommunityRoles[] =
2412            PropsUtil.getArray(PropsUtil.SYSTEM_COMMUNITY_ROLES);
2413
2414        if ((customSystemCommunityRoles == null) ||
2415            (customSystemCommunityRoles.length == 0)) {
2416
2417            _allSystemCommunityRoles = RoleImpl.SYSTEM_COMMUNITY_ROLES;
2418        }
2419        else {
2420            _allSystemCommunityRoles = ArrayUtil.append(
2421                RoleImpl.SYSTEM_COMMUNITY_ROLES, customSystemCommunityRoles);
2422        }
2423
2424        _sortedSystemCommunityRoles =
2425            new String[_allSystemCommunityRoles.length];
2426
2427        System.arraycopy(
2428            _allSystemCommunityRoles, 0, _sortedSystemCommunityRoles, 0,
2429                _allSystemCommunityRoles.length);
2430
2431        Arrays.sort(_sortedSystemCommunityRoles, new StringComparator());
2432
2433        // Organization Roles
2434
2435        String customSystemOrganizationRoles[] =
2436            PropsUtil.getArray(PropsUtil.SYSTEM_ORGANIZATION_ROLES);
2437
2438        if ((customSystemOrganizationRoles == null) ||
2439            (customSystemOrganizationRoles.length == 0)) {
2440
2441            _allSystemOrganizationRoles = RoleImpl.SYSTEM_ORGANIZATION_ROLES;
2442        }
2443        else {
2444            _allSystemOrganizationRoles = ArrayUtil.append(
2445                RoleImpl.SYSTEM_ORGANIZATION_ROLES,
2446                customSystemOrganizationRoles);
2447        }
2448
2449        _sortedSystemOrganizationRoles =
2450            new String[_allSystemOrganizationRoles.length];
2451
2452        System.arraycopy(
2453            _allSystemOrganizationRoles, 0, _sortedSystemOrganizationRoles, 0,
2454                _allSystemOrganizationRoles.length);
2455
2456        Arrays.sort(_sortedSystemOrganizationRoles, new StringComparator());
2457
2458        // Reserved parameter names
2459
2460        _reservedParams = CollectionFactory.getHashSet();
2461
2462        _reservedParams.add("p_l_id");
2463        _reservedParams.add("p_l_reset");
2464        _reservedParams.add("p_p_id");
2465        _reservedParams.add("p_p_action");
2466        _reservedParams.add("p_p_state");
2467        _reservedParams.add("p_p_mode");
2468        _reservedParams.add("p_p_width");
2469        _reservedParams.add("p_p_col_id");
2470        _reservedParams.add("p_p_col_pos");
2471        _reservedParams.add("p_p_col_count");
2472        _reservedParams.add("p_p_static");
2473    }
2474
2475    private String _getCDNHost() {
2476        return _cdnHost;
2477    }
2478
2479    private static String _getCurrentURL(HttpServletRequest req) {
2480        StringMaker sm = new StringMaker();
2481
2482        StringBuffer requestURL = req.getRequestURL();
2483
2484        if (requestURL != null) {
2485            sm.append(requestURL.toString());
2486        }
2487
2488        String queryString = req.getQueryString();
2489
2490        if (Validator.isNull(queryString)) {
2491            return sm.toString();
2492        }
2493
2494        String portletId = req.getParameter("p_p_id");
2495
2496        String redirectParam = "redirect";
2497
2498        if (Validator.isNotNull(portletId)) {
2499            redirectParam = getPortletNamespace(portletId) + redirectParam;
2500        }
2501
2502        Map parameterMap = HttpUtil.parameterMapFromString(queryString);
2503
2504        String[] redirectValues = (String[])parameterMap.get(redirectParam);
2505
2506        if ((redirectValues != null) && (redirectValues.length > 0)) {
2507
2508            // Prevent the redirect for GET requests from growing indefinitely
2509            // and using up all the available space by remembering only the
2510            // first redirect.
2511
2512            String redirect = HttpUtil.decodeURL(
2513                GetterUtil.getString(redirectValues[0]));
2514
2515            int pos = redirect.indexOf(StringPool.QUESTION);
2516
2517            if (pos != -1) {
2518                String subqueryString = redirect.substring(
2519                    pos + 1, redirect.length());
2520
2521                Map subparameterMap = HttpUtil.parameterMapFromString(
2522                    subqueryString);
2523
2524                String[] subredirectValues = (String[])subparameterMap.get(
2525                    redirectParam);
2526
2527                if ((subredirectValues != null) &&
2528                    (subredirectValues.length > 0)) {
2529
2530                    String subredirect = HttpUtil.decodeURL(
2531                        GetterUtil.getString(subredirectValues[0]));
2532
2533                    parameterMap.put(redirectParam, new String[] {subredirect});
2534
2535                    queryString = HttpUtil.parameterMapToString(
2536                        parameterMap, false);
2537                }
2538            }
2539        }
2540
2541        sm.append(StringPool.QUESTION);
2542        sm.append(queryString);
2543
2544        return sm.toString();
2545    }
2546
2547    private String _getPathContext() {
2548        return _pathContext;
2549    }
2550
2551    private String _getPathFriendlyURLPrivateGroup() {
2552        return _pathFriendlyURLPrivateGroup;
2553    }
2554
2555    private String _getPathFriendlyURLPrivateUser() {
2556        return _pathFriendlyURLPrivateUser;
2557    }
2558
2559    private String _getPathFriendlyURLPublic() {
2560        return _pathFriendlyURLPublic;
2561    }
2562
2563    private String _getPathImage() {
2564        return _pathImage;
2565    }
2566
2567    private String _getPathMain() {
2568        return _pathMain;
2569    }
2570
2571    private String[] _getSystemCommunityRoles() {
2572        return _allSystemCommunityRoles;
2573    }
2574
2575    private String[] _getSystemOrganizationRoles() {
2576        return _allSystemOrganizationRoles;
2577    }
2578
2579    private String[] _getSystemGroups() {
2580        return _allSystemGroups;
2581    }
2582
2583    private String[] _getSystemRoles() {
2584        return _allSystemRoles;
2585    }
2586
2587    private boolean _isSystemGroup(String groupName) {
2588        if (groupName == null) {
2589            return false;
2590        }
2591
2592        groupName = groupName.trim();
2593
2594        int pos = Arrays.binarySearch(
2595            _sortedSystemGroups, groupName, new StringComparator());
2596
2597        if (pos >= 0) {
2598            return true;
2599        }
2600        else {
2601            return false;
2602        }
2603    }
2604
2605    private boolean _isSystemRole(String roleName) {
2606        if (roleName == null) {
2607            return false;
2608        }
2609
2610        roleName = roleName.trim();
2611
2612        int pos = Arrays.binarySearch(
2613            _sortedSystemRoles, roleName, new StringComparator());
2614
2615        if (pos >= 0) {
2616            return true;
2617        }
2618        else {
2619            pos = Arrays.binarySearch(
2620                _sortedSystemCommunityRoles, roleName, new StringComparator());
2621
2622            if (pos >= 0) {
2623                return true;
2624            }
2625            else {
2626                pos = Arrays.binarySearch(
2627                    _sortedSystemOrganizationRoles, roleName,
2628                    new StringComparator());
2629
2630                if (pos >= 0) {
2631                    return true;
2632                }
2633            }
2634        }
2635
2636        return false;
2637    }
2638
2639    private static final String _JSESSIONID = ";jsessionid=";
2640
2641    private static final String _METHOD_GET = "get";
2642
2643    private static final String _METHOD_POST = "post";
2644
2645    private static Log _log = LogFactory.getLog(PortalUtil.class);
2646
2647    private static PortalUtil _instance = new PortalUtil();
2648
2649    private String _computerName;
2650    private String _portalLibDir;
2651    private String _cdnHost;
2652    private String _pathContext;
2653    private String _pathFriendlyURLPrivateGroup;
2654    private String _pathFriendlyURLPrivateUser;
2655    private String _pathFriendlyURLPublic;
2656    private String _pathImage;
2657    private String _pathMain;
2658    private String[] _allSystemCommunityRoles;
2659    private String[] _allSystemGroups;
2660    private String[] _allSystemOrganizationRoles;
2661    private String[] _allSystemRoles;
2662    private String[] _sortedSystemCommunityRoles;
2663    private String[] _sortedSystemGroups;
2664    private String[] _sortedSystemOrganizationRoles;
2665    private String[] _sortedSystemRoles;
2666    private Set _reservedParams;
2667
2668}