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