0001: /**
0002: * Copyright (c) 2000-2008 Liferay, Inc. All rights reserved.
0003: *
0004: * Permission is hereby granted, free of charge, to any person obtaining a copy
0005: * of this software and associated documentation files (the "Software"), to deal
0006: * in the Software without restriction, including without limitation the rights
0007: * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
0008: * copies of the Software, and to permit persons to whom the Software is
0009: * furnished to do so, subject to the following conditions:
0010: *
0011: * The above copyright notice and this permission notice shall be included in
0012: * all copies or substantial portions of the Software.
0013: *
0014: * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
0015: * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
0016: * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
0017: * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
0018: * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
0019: * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
0020: * SOFTWARE.
0021: */package com.liferay.portal.util;
0022:
0023: import com.germinus.easyconf.Filter;
0024:
0025: import com.liferay.portal.NoSuchLayoutException;
0026: import com.liferay.portal.NoSuchUserException;
0027: import com.liferay.portal.PortalException;
0028: import com.liferay.portal.SystemException;
0029: import com.liferay.portal.kernel.language.LanguageUtil;
0030: import com.liferay.portal.kernel.portlet.FriendlyURLMapper;
0031: import com.liferay.portal.kernel.portlet.LiferayPortletMode;
0032: import com.liferay.portal.kernel.portlet.LiferayWindowState;
0033: import com.liferay.portal.kernel.portlet.PortletRequestWrapper;
0034: import com.liferay.portal.kernel.portlet.PortletResponseWrapper;
0035: import com.liferay.portal.kernel.security.permission.ActionKeys;
0036: import com.liferay.portal.kernel.servlet.StringServletResponse;
0037: import com.liferay.portal.kernel.util.ArrayUtil;
0038: import com.liferay.portal.kernel.util.CalendarFactoryUtil;
0039: import com.liferay.portal.kernel.util.CharPool;
0040: import com.liferay.portal.kernel.util.ContentTypes;
0041: import com.liferay.portal.kernel.util.GetterUtil;
0042: import com.liferay.portal.kernel.util.InstancePool;
0043: import com.liferay.portal.kernel.util.JavaConstants;
0044: import com.liferay.portal.kernel.util.LocaleUtil;
0045: import com.liferay.portal.kernel.util.MethodCache;
0046: import com.liferay.portal.kernel.util.ParamUtil;
0047: import com.liferay.portal.kernel.util.StringComparator;
0048: import com.liferay.portal.kernel.util.StringMaker;
0049: import com.liferay.portal.kernel.util.StringPool;
0050: import com.liferay.portal.kernel.util.StringUtil;
0051: import com.liferay.portal.kernel.util.Validator;
0052: import com.liferay.portal.model.ClassName;
0053: import com.liferay.portal.model.Company;
0054: import com.liferay.portal.model.Group;
0055: import com.liferay.portal.model.Layout;
0056: import com.liferay.portal.model.LayoutSet;
0057: import com.liferay.portal.model.LayoutTypePortlet;
0058: import com.liferay.portal.model.Portlet;
0059: import com.liferay.portal.model.User;
0060: import com.liferay.portal.model.impl.GroupImpl;
0061: import com.liferay.portal.model.impl.LayoutImpl;
0062: import com.liferay.portal.model.impl.RoleImpl;
0063: import com.liferay.portal.plugin.PluginPackageUtil;
0064: import com.liferay.portal.security.permission.PermissionCheckerFactory;
0065: import com.liferay.portal.security.permission.PermissionCheckerImpl;
0066: import com.liferay.portal.service.ClassNameServiceUtil;
0067: import com.liferay.portal.service.CompanyLocalServiceUtil;
0068: import com.liferay.portal.service.GroupLocalServiceUtil;
0069: import com.liferay.portal.service.LayoutLocalServiceUtil;
0070: import com.liferay.portal.service.PortletLocalServiceUtil;
0071: import com.liferay.portal.service.UserLocalServiceUtil;
0072: import com.liferay.portal.service.UserServiceUtil;
0073: import com.liferay.portal.service.permission.UserPermissionUtil;
0074: import com.liferay.portal.servlet.PortletContextPool;
0075: import com.liferay.portal.servlet.PortletContextWrapper;
0076: import com.liferay.portal.theme.ThemeDisplay;
0077: import com.liferay.portlet.ActionRequestImpl;
0078: import com.liferay.portlet.ActionResponseImpl;
0079: import com.liferay.portlet.CachePortlet;
0080: import com.liferay.portlet.PortletConfigFactory;
0081: import com.liferay.portlet.PortletPreferencesImpl;
0082: import com.liferay.portlet.PortletPreferencesWrapper;
0083: import com.liferay.portlet.PortletURLImpl;
0084: import com.liferay.portlet.RenderRequestImpl;
0085: import com.liferay.portlet.RenderResponseImpl;
0086: import com.liferay.portlet.UserAttributes;
0087: import com.liferay.portlet.wsrp.URLGeneratorImpl;
0088: import com.liferay.util.BeanUtil;
0089: import com.liferay.util.CollectionFactory;
0090: import com.liferay.util.Encryptor;
0091: import com.liferay.util.Http;
0092: import com.liferay.util.HttpUtil;
0093: import com.liferay.util.JS;
0094: import com.liferay.util.servlet.DynamicServletRequest;
0095: import com.liferay.util.servlet.SessionErrors;
0096: import com.liferay.util.servlet.UploadPortletRequest;
0097: import com.liferay.util.servlet.UploadServletRequest;
0098: import com.liferay.util.xml.XMLSafeReader;
0099:
0100: import java.io.File;
0101: import java.io.IOException;
0102: import java.io.InputStream;
0103:
0104: import java.lang.reflect.Method;
0105:
0106: import java.net.URL;
0107:
0108: import java.rmi.RemoteException;
0109:
0110: import java.security.Key;
0111:
0112: import java.util.Arrays;
0113: import java.util.Calendar;
0114: import java.util.Date;
0115: import java.util.Enumeration;
0116: import java.util.HashMap;
0117: import java.util.Iterator;
0118: import java.util.List;
0119: import java.util.Locale;
0120: import java.util.Map;
0121: import java.util.Properties;
0122: import java.util.ResourceBundle;
0123: import java.util.Set;
0124: import java.util.TimeZone;
0125:
0126: import javax.portlet.ActionRequest;
0127: import javax.portlet.ActionResponse;
0128: import javax.portlet.PortletConfig;
0129: import javax.portlet.PortletMode;
0130: import javax.portlet.PortletPreferences;
0131: import javax.portlet.PortletRequest;
0132: import javax.portlet.PortletResponse;
0133: import javax.portlet.PortletURL;
0134: import javax.portlet.PreferencesValidator;
0135: import javax.portlet.RenderRequest;
0136: import javax.portlet.RenderResponse;
0137: import javax.portlet.ValidatorException;
0138: import javax.portlet.WindowState;
0139:
0140: import javax.servlet.RequestDispatcher;
0141: import javax.servlet.ServletContext;
0142: import javax.servlet.ServletException;
0143: import javax.servlet.ServletRequest;
0144: import javax.servlet.http.HttpServletRequest;
0145: import javax.servlet.http.HttpServletRequestWrapper;
0146: import javax.servlet.http.HttpServletResponse;
0147: import javax.servlet.http.HttpSession;
0148:
0149: import org.apache.commons.logging.Log;
0150: import org.apache.commons.logging.LogFactory;
0151: import org.apache.struts.Globals;
0152:
0153: import org.dom4j.Document;
0154: import org.dom4j.DocumentException;
0155: import org.dom4j.io.SAXReader;
0156:
0157: import org.hibernate.util.FastHashMap;
0158:
0159: /**
0160: * <a href="PortalUtil.java.html"><b><i>View Source</i></b></a>
0161: *
0162: * @author Brian Wing Shun Chan
0163: * @author Brian Myunghun Kim
0164: * @author Jorge Ferrer
0165: *
0166: */
0167: public class PortalUtil {
0168:
0169: public static final String PATH_IMAGE = "/image";
0170:
0171: public static final String PATH_MAIN = "/c";
0172:
0173: public static final String PATH_PORTAL_LAYOUT = "/portal/layout";
0174:
0175: public static final String PORTLET_XML_FILE_NAME_STANDARD = "portlet.xml";
0176:
0177: public static final String PORTLET_XML_FILE_NAME_CUSTOM = "portlet-custom.xml";
0178:
0179: public static final Date UP_TIME = new Date();
0180:
0181: public static void clearRequestParameters(RenderRequest req) {
0182:
0183: // Clear the render parameters if they were set during processAction
0184:
0185: boolean action = ParamUtil.getBoolean(req, "p_p_action");
0186:
0187: if (action) {
0188: ((RenderRequestImpl) req).getRenderParameters().clear();
0189: }
0190: }
0191:
0192: public static void copyRequestParameters(ActionRequest req,
0193: ActionResponse res) {
0194:
0195: try {
0196: ActionResponseImpl resImpl = (ActionResponseImpl) res;
0197:
0198: Map renderParameters = resImpl.getRenderParameters();
0199:
0200: res.setRenderParameter("p_p_action", "1");
0201:
0202: Enumeration enu = req.getParameterNames();
0203:
0204: while (enu.hasMoreElements()) {
0205: String param = (String) enu.nextElement();
0206: String[] values = req.getParameterValues(param);
0207:
0208: if (renderParameters
0209: .get(resImpl.getNamespace() + param) == null) {
0210:
0211: res.setRenderParameter(param, values);
0212: }
0213: }
0214: } catch (IllegalStateException ise) {
0215:
0216: // This should only happen if the developer called
0217: // sendRedirect of javax.portlet.ActionResponse
0218:
0219: }
0220: }
0221:
0222: public static String createSecureProxyURL(String url, Key key,
0223: boolean secure) {
0224:
0225: // Use this method to fetch external content that may not be available
0226: // in secure mode. See how the Weather portlet fetches images.
0227:
0228: if (!secure) {
0229: return url;
0230: } else {
0231: Map params = CollectionFactory.getHashMap();
0232:
0233: params.put(org.apache.wsrp4j.util.Constants.URL, url);
0234:
0235: return URLGeneratorImpl.getResourceProxyURL(params, key);
0236: }
0237: }
0238:
0239: public static String getCDNHost() {
0240: return _instance._getCDNHost();
0241: }
0242:
0243: public static String getClassName(long classNameId) {
0244: try {
0245: ClassName className = ClassNameServiceUtil
0246: .getClassName(classNameId);
0247:
0248: return className.getValue();
0249: } catch (Exception e) {
0250: throw new RuntimeException(
0251: "Unable to get class name from id " + classNameId);
0252: }
0253: }
0254:
0255: public static long getClassNameId(Class classObj) {
0256: return getClassNameId(classObj.getName());
0257: }
0258:
0259: public static long getClassNameId(String value) {
0260: try {
0261: ClassName className = ClassNameServiceUtil
0262: .getClassName(value);
0263:
0264: return className.getClassNameId();
0265: } catch (Exception e) {
0266: throw new RuntimeException(
0267: "Unable to get class name from value " + value);
0268: }
0269: }
0270:
0271: public static String getClassNamePortletId(String className) {
0272: String portletId = StringPool.BLANK;
0273:
0274: if (className.startsWith("com.liferay.portlet.blogs")) {
0275: portletId = PortletKeys.BLOGS;
0276: } else if (className
0277: .startsWith("com.liferay.portlet.bookmarks")) {
0278: portletId = PortletKeys.BOOKMARKS;
0279: } else if (className
0280: .startsWith("com.liferay.portlet.documentlibrary")) {
0281: portletId = PortletKeys.DOCUMENT_LIBRARY;
0282: } else if (className
0283: .startsWith("com.liferay.portlet.imagegallery")) {
0284: portletId = PortletKeys.IMAGE_GALLERY;
0285: } else if (className.startsWith("com.liferay.portlet.journal")) {
0286: portletId = PortletKeys.JOURNAL;
0287: } else if (className
0288: .startsWith("com.liferay.portlet.messageboards")) {
0289: portletId = PortletKeys.MESSAGE_BOARDS;
0290: } else if (className.startsWith("com.liferay.portlet.wiki")) {
0291: portletId = PortletKeys.WIKI;
0292: }
0293:
0294: return portletId;
0295: }
0296:
0297: public static Company getCompany(HttpServletRequest req)
0298: throws PortalException, SystemException {
0299:
0300: long companyId = getCompanyId(req);
0301:
0302: if (companyId <= 0) {
0303: return null;
0304: }
0305:
0306: Company company = (Company) req.getAttribute(WebKeys.COMPANY);
0307:
0308: if (company == null) {
0309: company = CompanyLocalServiceUtil.getCompanyById(companyId);
0310:
0311: req.setAttribute(WebKeys.COMPANY, company);
0312: }
0313:
0314: return company;
0315: }
0316:
0317: public static Company getCompany(ActionRequest req)
0318: throws PortalException, SystemException {
0319:
0320: return getCompany(getHttpServletRequest(req));
0321: }
0322:
0323: public static Company getCompany(RenderRequest req)
0324: throws PortalException, SystemException {
0325:
0326: return getCompany(getHttpServletRequest(req));
0327: }
0328:
0329: public static long getCompanyId(HttpServletRequest req) {
0330: return PortalInstances.getCompanyId(req);
0331: }
0332:
0333: public static long getCompanyId(ActionRequest req) {
0334: return getCompanyId(getHttpServletRequest(req));
0335: }
0336:
0337: public static long getCompanyId(PortletRequest req) {
0338: long companyId = 0;
0339:
0340: if (req instanceof ActionRequest) {
0341: companyId = getCompanyId((ActionRequest) req);
0342: } else {
0343: companyId = getCompanyId((RenderRequest) req);
0344: }
0345:
0346: return companyId;
0347: }
0348:
0349: public static long getCompanyId(RenderRequest req) {
0350: return getCompanyId(getHttpServletRequest(req));
0351: }
0352:
0353: public static long getCompanyIdByWebId(ServletContext ctx) {
0354: String webId = GetterUtil.getString(ctx
0355: .getInitParameter("company_web_id"));
0356:
0357: return getCompanyIdByWebId(webId);
0358: }
0359:
0360: public static long getCompanyIdByWebId(String webId) {
0361: long companyId = 0;
0362:
0363: try {
0364: Company company = CompanyLocalServiceUtil
0365: .getCompanyByWebId(webId);
0366:
0367: companyId = company.getCompanyId();
0368: } catch (Exception e) {
0369: _log.error(e.getMessage());
0370: }
0371:
0372: return companyId;
0373: }
0374:
0375: public static String getComputerName() {
0376: return _instance._computerName;
0377: }
0378:
0379: public static String getCurrentURL(HttpServletRequest req) {
0380: String currentURL = (String) req
0381: .getAttribute(WebKeys.CURRENT_URL);
0382:
0383: if (currentURL == null) {
0384: currentURL = ParamUtil.getString(req, "currentURL");
0385:
0386: if (Validator.isNull(currentURL)) {
0387: if (true) {
0388: currentURL = Http.getCompleteURL(req);
0389: } else {
0390:
0391: // Do we need to trim redirects?
0392:
0393: currentURL = _getCurrentURL(req);
0394: }
0395:
0396: if ((Validator.isNotNull(currentURL))
0397: && (currentURL.indexOf("j_security_check") == -1)) {
0398:
0399: currentURL = currentURL.substring(currentURL
0400: .indexOf("://") + 3, currentURL.length());
0401:
0402: currentURL = currentURL.substring(currentURL
0403: .indexOf("/"), currentURL.length());
0404: }
0405: }
0406:
0407: if (Validator.isNull(currentURL)) {
0408: currentURL = getPathMain();
0409: }
0410:
0411: req.setAttribute(WebKeys.CURRENT_URL, currentURL);
0412: }
0413:
0414: return currentURL;
0415: }
0416:
0417: public static String getCurrentURL(PortletRequest req) {
0418: return (String) req.getAttribute(WebKeys.CURRENT_URL);
0419: }
0420:
0421: public static Date getDate(int month, int day, int year,
0422: PortalException pe) throws PortalException {
0423:
0424: return getDate(month, day, year, null, pe);
0425: }
0426:
0427: public static Date getDate(int month, int day, int year,
0428: TimeZone timeZone, PortalException pe)
0429: throws PortalException {
0430:
0431: return getDate(month, day, year, -1, -1, timeZone, pe);
0432: }
0433:
0434: public static Date getDate(int month, int day, int year, int hour,
0435: int min, PortalException pe) throws PortalException {
0436:
0437: return getDate(month, day, year, hour, min, null, pe);
0438: }
0439:
0440: public static Date getDate(int month, int day, int year, int hour,
0441: int min, TimeZone timeZone, PortalException pe)
0442: throws PortalException {
0443:
0444: if (!Validator.isGregorianDate(month, day, year)) {
0445: throw pe;
0446: } else {
0447: Calendar cal = null;
0448:
0449: if (timeZone == null) {
0450: cal = CalendarFactoryUtil.getCalendar();
0451: } else {
0452: cal = CalendarFactoryUtil.getCalendar(timeZone);
0453: }
0454:
0455: if ((hour == -1) || (min == -1)) {
0456: cal.set(year, month, day);
0457: } else {
0458: cal.set(year, month, day, hour, min, 0);
0459: }
0460:
0461: Date date = cal.getTime();
0462:
0463: /*if (timeZone != null &&
0464: cal.before(CalendarFactoryUtil.getCalendar(timeZone))) {
0465:
0466: throw pe;
0467: }*/
0468:
0469: return date;
0470: }
0471: }
0472:
0473: public static String getHost(HttpServletRequest req) {
0474: String host = req.getHeader("Host");
0475:
0476: if (host != null) {
0477: host = host.trim().toLowerCase();
0478:
0479: int pos = host.indexOf(':');
0480:
0481: if (pos >= 0) {
0482: host = host.substring(0, pos);
0483: }
0484: } else {
0485: host = null;
0486: }
0487:
0488: return host;
0489: }
0490:
0491: public static String getHost(ActionRequest req) {
0492: return getHost(getHttpServletRequest(req));
0493: }
0494:
0495: public static String getHost(RenderRequest req) {
0496: return getHost(getHttpServletRequest(req));
0497: }
0498:
0499: public static HttpServletRequest getHttpServletRequest(
0500: PortletRequest req) {
0501: if (req instanceof ActionRequestImpl) {
0502: ActionRequestImpl reqImpl = (ActionRequestImpl) req;
0503:
0504: return reqImpl.getHttpServletRequest();
0505: } else if (req instanceof RenderRequestImpl) {
0506: RenderRequestImpl reqImpl = (RenderRequestImpl) req;
0507:
0508: return reqImpl.getHttpServletRequest();
0509: } else if (req instanceof PortletRequestWrapper) {
0510: PortletRequestWrapper reqWrapper = (PortletRequestWrapper) req;
0511:
0512: return getHttpServletRequest(reqWrapper.getPortletRequest());
0513: } else {
0514: throw new RuntimeException(
0515: "Unable to get the HTTP servlet request from "
0516: + req.getClass().getName());
0517: }
0518: }
0519:
0520: public static HttpServletResponse getHttpServletResponse(
0521: PortletResponse res) {
0522:
0523: if (res instanceof ActionResponseImpl) {
0524: ActionResponseImpl resImpl = (ActionResponseImpl) res;
0525:
0526: return resImpl.getHttpServletResponse();
0527: } else if (res instanceof RenderResponseImpl) {
0528: RenderResponseImpl resImpl = (RenderResponseImpl) res;
0529:
0530: return resImpl.getHttpServletResponse();
0531: } else if (res instanceof PortletResponseWrapper) {
0532: PortletResponseWrapper resWrapper = (PortletResponseWrapper) res;
0533:
0534: return getHttpServletResponse(resWrapper
0535: .getPortletResponse());
0536: } else if (res instanceof RenderResponse) {
0537: RenderResponseImpl resImpl = getRenderResponseImpl((RenderResponse) res);
0538:
0539: return resImpl.getHttpServletResponse();
0540: } else {
0541: throw new RuntimeException(
0542: "Unable to get the HTTP servlet resuest from "
0543: + res.getClass().getName());
0544: }
0545: }
0546:
0547: public static String getLayoutEditPage(Layout layout) {
0548: return PropsUtil.getComponentProperties()
0549: .getString(PropsUtil.LAYOUT_EDIT_PAGE,
0550: Filter.by(layout.getType()));
0551: }
0552:
0553: public static String getLayoutViewPage(Layout layout) {
0554: return PropsUtil.getComponentProperties()
0555: .getString(PropsUtil.LAYOUT_VIEW_PAGE,
0556: Filter.by(layout.getType()));
0557: }
0558:
0559: public static String getLayoutURL(ThemeDisplay themeDisplay)
0560: throws PortalException, SystemException {
0561:
0562: return getLayoutURL(themeDisplay.getLayout(), themeDisplay);
0563: }
0564:
0565: public static String getLayoutURL(Layout layout,
0566: ThemeDisplay themeDisplay) throws PortalException,
0567: SystemException {
0568:
0569: return getLayoutURL(layout, themeDisplay, true);
0570: }
0571:
0572: public static String getLayoutURL(Layout layout,
0573: ThemeDisplay themeDisplay, boolean doAsUser)
0574: throws PortalException, SystemException {
0575:
0576: if (layout == null) {
0577: return themeDisplay.getPathMain() + PATH_PORTAL_LAYOUT;
0578: }
0579:
0580: if (!layout.getType().equals(LayoutImpl.TYPE_URL)) {
0581: String layoutFriendlyURL = getLayoutFriendlyURL(layout,
0582: themeDisplay);
0583:
0584: if (Validator.isNotNull(layoutFriendlyURL)) {
0585: if (doAsUser
0586: && Validator.isNotNull(themeDisplay
0587: .getDoAsUserId())) {
0588:
0589: layoutFriendlyURL = Http.addParameter(
0590: layoutFriendlyURL, "doAsUserId",
0591: themeDisplay.getDoAsUserId());
0592: }
0593:
0594: return layoutFriendlyURL;
0595: }
0596: }
0597:
0598: String layoutURL = getLayoutActualURL(layout);
0599:
0600: if (doAsUser
0601: && Validator.isNotNull(themeDisplay.getDoAsUserId())) {
0602: layoutURL = Http.addParameter(layoutURL, "doAsUserId",
0603: themeDisplay.getDoAsUserId());
0604: }
0605:
0606: return layoutURL;
0607: }
0608:
0609: public static String getLayoutActualURL(Layout layout)
0610: throws PortalException, SystemException {
0611:
0612: return getLayoutActualURL(layout, getPathMain());
0613: }
0614:
0615: public static String getLayoutActualURL(Layout layout,
0616: String mainPath) throws PortalException, SystemException {
0617:
0618: Map vars = new FastHashMap();
0619:
0620: vars.put("liferay:mainPath", mainPath);
0621: vars.put("liferay:plid", String.valueOf(layout.getPlid()));
0622: vars.putAll(layout.getLayoutType().getTypeSettingsProperties());
0623:
0624: String href = PropsUtil.getComponentProperties().getString(
0625: PropsUtil.LAYOUT_URL,
0626: Filter.by(layout.getType()).setVariables(vars));
0627:
0628: return href;
0629: }
0630:
0631: public static String getLayoutActualURL(long groupId,
0632: boolean privateLayout, String mainPath, String friendlyURL)
0633: throws PortalException, SystemException {
0634:
0635: return getLayoutActualURL(groupId, privateLayout, mainPath,
0636: friendlyURL, null);
0637: }
0638:
0639: public static String getLayoutActualURL(long groupId,
0640: boolean privateLayout, String mainPath, String friendlyURL,
0641: Map params) throws PortalException, SystemException {
0642:
0643: Layout layout = null;
0644: String queryString = StringPool.BLANK;
0645:
0646: if (Validator.isNull(friendlyURL)) {
0647: List layouts = LayoutLocalServiceUtil.getLayouts(groupId,
0648: privateLayout, LayoutImpl.DEFAULT_PARENT_LAYOUT_ID);
0649:
0650: if (layouts.size() > 0) {
0651: layout = (Layout) layouts.get(0);
0652: } else {
0653: throw new NoSuchLayoutException("{groupId=" + groupId
0654: + ",privateLayout=" + privateLayout
0655: + "} does not have any layouts");
0656: }
0657: } else {
0658: Object[] friendlyURLMapper = getPortletFriendlyURLMapper(
0659: groupId, privateLayout, friendlyURL, params);
0660:
0661: layout = (Layout) friendlyURLMapper[0];
0662: queryString = (String) friendlyURLMapper[1];
0663: }
0664:
0665: String layoutActualURL = getLayoutActualURL(layout, mainPath);
0666:
0667: if (Validator.isNotNull(queryString)) {
0668: layoutActualURL = layoutActualURL + queryString;
0669: }
0670:
0671: return layoutActualURL;
0672: }
0673:
0674: public static String getLayoutFriendlyURL(Layout layout,
0675: ThemeDisplay themeDisplay) throws PortalException,
0676: SystemException {
0677:
0678: if (!isLayoutFriendliable(layout)) {
0679: return null;
0680: }
0681:
0682: String layoutFriendlyURL = layout.getFriendlyURL();
0683:
0684: if (Validator.isNull(layoutFriendlyURL)) {
0685: layoutFriendlyURL = layout.getDefaultFriendlyURL();
0686: }
0687:
0688: LayoutSet layoutSet = layout.getLayoutSet();
0689:
0690: if (Validator.isNotNull(layoutSet.getVirtualHost())) {
0691: String portalURL = getPortalURL(layoutSet.getVirtualHost(),
0692: themeDisplay.getServerPort(), themeDisplay
0693: .isSecure());
0694:
0695: // Use the layout set's virtual host setting only if the layout set
0696: // is already used for the current request
0697:
0698: long curLayoutSetId = themeDisplay.getLayout()
0699: .getLayoutSet().getLayoutSetId();
0700:
0701: if ((layoutSet.getLayoutSetId() != curLayoutSetId)
0702: || (portalURL.startsWith(themeDisplay
0703: .getURLPortal()))) {
0704:
0705: return portalURL + getPathContext() + layoutFriendlyURL;
0706: }
0707: }
0708:
0709: Group group = layout.getGroup();
0710:
0711: String parentFriendlyURL = group.getFriendlyURL();
0712:
0713: if (Validator.isNull(parentFriendlyURL)) {
0714: parentFriendlyURL = group.getDefaultFriendlyURL(layout
0715: .isPrivateLayout());
0716: }
0717:
0718: String friendlyURL = null;
0719:
0720: if (layout.isPrivateLayout()) {
0721: if (group.isUser()) {
0722: friendlyURL = getPathFriendlyURLPrivateUser();
0723: } else {
0724: friendlyURL = getPathFriendlyURLPrivateGroup();
0725: }
0726: } else {
0727: friendlyURL = getPathFriendlyURLPublic();
0728: }
0729:
0730: return friendlyURL + parentFriendlyURL + layoutFriendlyURL;
0731: }
0732:
0733: public static String getLayoutTarget(Layout layout) {
0734: Properties typeSettingsProps = layout
0735: .getTypeSettingsProperties();
0736:
0737: String target = typeSettingsProps.getProperty("target");
0738:
0739: if (Validator.isNull(target)) {
0740: target = StringPool.BLANK;
0741: } else {
0742: target = "target=\"" + target + "\"";
0743: }
0744:
0745: return target;
0746: }
0747:
0748: public static String getJsSafePortletId(String portletId) {
0749: return JS.getSafeName(portletId);
0750: }
0751:
0752: /**
0753: * @deprecated Use <code>getJsSafePortletId</code>.
0754: */
0755: public static String getJsSafePortletName(String portletName) {
0756: return JS.getSafeName(portletName);
0757: }
0758:
0759: public static Locale getLocale(HttpServletRequest req) {
0760: return (Locale) req.getSession().getAttribute(
0761: Globals.LOCALE_KEY);
0762: }
0763:
0764: public static Locale getLocale(RenderRequest req) {
0765: return getLocale(getHttpServletRequest(req));
0766: }
0767:
0768: public static HttpServletRequest getOriginalServletRequest(
0769: HttpServletRequest req) {
0770:
0771: HttpServletRequest originalReq = req;
0772:
0773: while (originalReq.getClass().getName().startsWith(
0774: "com.liferay.")) {
0775:
0776: // Get original request so that portlets inside portlets render
0777: // properly
0778:
0779: originalReq = (HttpServletRequest) ((HttpServletRequestWrapper) originalReq)
0780: .getRequest();
0781: }
0782:
0783: return originalReq;
0784: }
0785:
0786: public static String getPathContext() {
0787: return _instance._getPathContext();
0788: }
0789:
0790: public static String getPathFriendlyURLPrivateGroup() {
0791: return _instance._getPathFriendlyURLPrivateGroup();
0792: }
0793:
0794: public static String getPathFriendlyURLPrivateUser() {
0795: return _instance._getPathFriendlyURLPrivateUser();
0796: }
0797:
0798: public static String getPathFriendlyURLPublic() {
0799: return _instance._getPathFriendlyURLPublic();
0800: }
0801:
0802: public static String getPathImage() {
0803: return _instance._getPathImage();
0804: }
0805:
0806: public static String getPathMain() {
0807: return _instance._getPathMain();
0808: }
0809:
0810: public static long getPlidIdFromFriendlyURL(long companyId,
0811: String friendlyURL) {
0812:
0813: String[] urlParts = friendlyURL.split("\\/", 4);
0814:
0815: if ((friendlyURL.charAt(0) != CharPool.SLASH)
0816: && (urlParts.length != 4)) {
0817:
0818: return LayoutImpl.DEFAULT_PLID;
0819: }
0820:
0821: boolean privateLayout = true;
0822:
0823: String urlPrefix = StringPool.SLASH + urlParts[1];
0824:
0825: if (getPathFriendlyURLPublic().equals(urlPrefix)) {
0826: privateLayout = false;
0827: } else if (getPathFriendlyURLPrivateGroup().equals(urlPrefix)
0828: || getPathFriendlyURLPrivateUser().equals(urlPrefix)) {
0829:
0830: privateLayout = true;
0831: } else {
0832: return LayoutImpl.DEFAULT_PLID;
0833: }
0834:
0835: Group group = null;
0836:
0837: try {
0838:
0839: // Start by trying to parse the url part as a group id because it is
0840: // faster to eliminate this possibility first
0841:
0842: long groupId = GetterUtil.getLong(urlParts[2]);
0843:
0844: group = GroupLocalServiceUtil.getGroup(groupId);
0845: } catch (Exception e1) {
0846: try {
0847:
0848: // Now try as a friendly url
0849:
0850: group = GroupLocalServiceUtil.getFriendlyURLGroup(
0851: companyId, StringPool.SLASH + urlParts[2]);
0852: } catch (Exception e2) {
0853: }
0854: }
0855:
0856: if (group != null) {
0857: Layout layout = null;
0858:
0859: try {
0860:
0861: // Start by trying to parse the url part as a layout id because
0862: // it is faster to eliminate this possibility first
0863:
0864: long layoutId = GetterUtil.getLong(urlParts[3]);
0865:
0866: layout = LayoutLocalServiceUtil.getLayout(group
0867: .getGroupId(), privateLayout, layoutId);
0868:
0869: return layout.getPlid();
0870: } catch (Exception e1) {
0871: try {
0872:
0873: // Now try as a friendly url
0874:
0875: layout = LayoutLocalServiceUtil
0876: .getFriendlyURLLayout(group.getGroupId(),
0877: privateLayout, StringPool.SLASH
0878: + urlParts[3]);
0879:
0880: return layout.getPlid();
0881: } catch (Exception e2) {
0882: }
0883: }
0884: }
0885:
0886: return LayoutImpl.DEFAULT_PLID;
0887: }
0888:
0889: public static String getPortalLibDir() {
0890: return _instance._portalLibDir;
0891: }
0892:
0893: public static String getPortalURL(ThemeDisplay themeDisplay) {
0894: String serverName = themeDisplay.getServerName();
0895:
0896: Layout layout = themeDisplay.getLayout();
0897:
0898: if (layout != null) {
0899: LayoutSet layoutSet = layout.getLayoutSet();
0900:
0901: if (Validator.isNotNull(layoutSet.getVirtualHost())) {
0902: serverName = layoutSet.getVirtualHost();
0903: }
0904: }
0905:
0906: return getPortalURL(serverName, themeDisplay.getServerPort(),
0907: themeDisplay.isSecure());
0908: }
0909:
0910: public static String getPortalURL(HttpServletRequest req) {
0911: return getPortalURL(req, req.isSecure());
0912: }
0913:
0914: public static String getPortalURL(HttpServletRequest req,
0915: boolean secure) {
0916: return getPortalURL(req.getServerName(), req.getServerPort(),
0917: secure);
0918: }
0919:
0920: public static String getPortalURL(PortletRequest req) {
0921: return getPortalURL(req, req.isSecure());
0922: }
0923:
0924: public static String getPortalURL(PortletRequest req, boolean secure) {
0925: return getPortalURL(req.getServerName(), req.getServerPort(),
0926: secure);
0927: }
0928:
0929: public static String getPortalURL(String serverName,
0930: int serverPort, boolean secure) {
0931:
0932: StringMaker sm = new StringMaker();
0933:
0934: if (secure
0935: || Http.HTTPS.equals(PropsValues.WEB_SERVER_PROTOCOL)) {
0936: sm.append(Http.HTTPS_WITH_SLASH);
0937: } else {
0938: sm.append(Http.HTTP_WITH_SLASH);
0939: }
0940:
0941: if (Validator.isNull(PropsValues.WEB_SERVER_HOST)) {
0942: sm.append(serverName);
0943: } else {
0944: sm.append(PropsValues.WEB_SERVER_HOST);
0945: }
0946:
0947: if (!secure) {
0948: if (PropsValues.WEB_SERVER_HTTP_PORT == -1) {
0949: if ((serverPort != Http.HTTP_PORT)
0950: && (serverPort != Http.HTTPS_PORT)) {
0951:
0952: sm.append(StringPool.COLON);
0953: sm.append(serverPort);
0954: }
0955: } else {
0956: if ((PropsValues.WEB_SERVER_HTTP_PORT != serverPort)
0957: || (PropsValues.WEB_SERVER_HTTP_PORT != Http.HTTP_PORT)) {
0958:
0959: sm.append(StringPool.COLON);
0960: sm.append(PropsValues.WEB_SERVER_HTTP_PORT);
0961: }
0962: }
0963: }
0964:
0965: if (secure) {
0966: if (PropsValues.WEB_SERVER_HTTPS_PORT == -1) {
0967: if ((serverPort != Http.HTTP_PORT)
0968: && (serverPort != Http.HTTPS_PORT)) {
0969:
0970: sm.append(StringPool.COLON);
0971: sm.append(serverPort);
0972: }
0973: } else {
0974: if ((PropsValues.WEB_SERVER_HTTPS_PORT != serverPort)
0975: || (PropsValues.WEB_SERVER_HTTPS_PORT != Http.HTTPS_PORT)) {
0976:
0977: sm.append(StringPool.COLON);
0978: sm.append(PropsValues.WEB_SERVER_HTTPS_PORT);
0979: }
0980: }
0981: }
0982:
0983: return sm.toString();
0984: }
0985:
0986: public static Object[] getPortletFriendlyURLMapper(long groupId,
0987: boolean privateLayout, String url) throws PortalException,
0988: SystemException {
0989:
0990: return getPortletFriendlyURLMapper(groupId, privateLayout, url,
0991: null);
0992: }
0993:
0994: public static Object[] getPortletFriendlyURLMapper(long groupId,
0995: boolean privateLayout, String url, Map params)
0996: throws PortalException, SystemException {
0997:
0998: String friendlyURL = url;
0999: String queryString = StringPool.BLANK;
1000:
1001: List friendlyURLMappers = PortletLocalServiceUtil
1002: .getFriendlyURLMappers();
1003:
1004: Iterator itr = friendlyURLMappers.iterator();
1005:
1006: while (itr.hasNext()) {
1007: FriendlyURLMapper friendlyURLMapper = (FriendlyURLMapper) itr
1008: .next();
1009:
1010: if (url.endsWith(StringPool.SLASH
1011: + friendlyURLMapper.getMapping())) {
1012:
1013: url += StringPool.SLASH;
1014: }
1015:
1016: int pos = url
1017: .indexOf(StringPool.SLASH
1018: + friendlyURLMapper.getMapping()
1019: + StringPool.SLASH);
1020:
1021: if (pos != -1) {
1022: friendlyURL = url.substring(0, pos);
1023:
1024: Map actualParams = null;
1025:
1026: if (params != null) {
1027: actualParams = new HashMap(params);
1028: } else {
1029: actualParams = new HashMap();
1030: }
1031:
1032: /*Object action = actualParams.get("p_p_action");
1033:
1034: if ((action == null) || (((String[])action).length == 0)) {
1035: actualParams.put("p_p_action", "0");
1036: }
1037:
1038: Object state = actualParams.get("p_p_state");
1039:
1040: if ((state == null) || (((String[])state).length == 0)) {
1041: actualParams.put(
1042: "p_p_state", WindowState.MAXIMIZED.toString());
1043: }*/
1044:
1045: friendlyURLMapper.populateParams(url.substring(pos),
1046: actualParams);
1047:
1048: queryString = StringPool.AMPERSAND
1049: + HttpUtil.parameterMapToString(actualParams,
1050: false);
1051:
1052: break;
1053: }
1054: }
1055:
1056: friendlyURL = StringUtil.replace(friendlyURL,
1057: StringPool.DOUBLE_SLASH, StringPool.SLASH);
1058:
1059: if (friendlyURL.endsWith(StringPool.SLASH)) {
1060: friendlyURL = friendlyURL.substring(0,
1061: friendlyURL.length() - 1);
1062: }
1063:
1064: Layout layout = null;
1065:
1066: try {
1067: layout = LayoutLocalServiceUtil.getFriendlyURLLayout(
1068: groupId, privateLayout, friendlyURL);
1069: } catch (NoSuchLayoutException nsle) {
1070: long layoutId = GetterUtil
1071: .getLong(friendlyURL.substring(1));
1072:
1073: layout = LayoutLocalServiceUtil.getLayout(groupId,
1074: privateLayout, layoutId);
1075: }
1076:
1077: return new Object[] { layout, queryString };
1078: }
1079:
1080: public static long getPortletGroupId(long plid) {
1081: Layout layout = null;
1082:
1083: try {
1084: layout = LayoutLocalServiceUtil.getLayout(plid);
1085: } catch (Exception e) {
1086: }
1087:
1088: return getPortletGroupId(layout);
1089: }
1090:
1091: public static long getPortletGroupId(Layout layout) {
1092: if (layout == null) {
1093: return 0;
1094: } else {
1095: return layout.getGroupId();
1096: }
1097: }
1098:
1099: public static long getPortletGroupId(HttpServletRequest req) {
1100: Layout layout = (Layout) req.getAttribute(WebKeys.LAYOUT);
1101:
1102: return getPortletGroupId(layout);
1103: }
1104:
1105: public static long getPortletGroupId(ActionRequest req) {
1106: return getPortletGroupId(getHttpServletRequest(req));
1107: }
1108:
1109: public static long getPortletGroupId(RenderRequest req) {
1110: return getPortletGroupId(getHttpServletRequest(req));
1111: }
1112:
1113: public static String getPortletNamespace(String portletId) {
1114: StringMaker sm = new StringMaker();
1115:
1116: sm.append(StringPool.UNDERLINE);
1117: sm.append(portletId);
1118: sm.append(StringPool.UNDERLINE);
1119:
1120: return sm.toString();
1121: }
1122:
1123: public static String getPortletXmlFileName()
1124: throws PortalException, SystemException {
1125:
1126: if (PrefsPropsUtil.getBoolean(
1127: PropsUtil.AUTO_DEPLOY_CUSTOM_PORTLET_XML,
1128: PropsValues.AUTO_DEPLOY_CUSTOM_PORTLET_XML)) {
1129:
1130: return PORTLET_XML_FILE_NAME_CUSTOM;
1131: } else {
1132: return PORTLET_XML_FILE_NAME_STANDARD;
1133: }
1134: }
1135:
1136: public static String getPortletTitle(String portletId,
1137: long companyId, String languageId) {
1138:
1139: Locale locale = LocaleUtil.fromLanguageId(languageId);
1140:
1141: StringMaker sm = new StringMaker();
1142:
1143: sm.append(JavaConstants.JAVAX_PORTLET_TITLE);
1144: sm.append(StringPool.PERIOD);
1145: sm.append(portletId);
1146:
1147: return LanguageUtil.get(companyId, locale, sm.toString());
1148: }
1149:
1150: public static String getPortletTitle(String portletId, User user) {
1151: StringMaker sm = new StringMaker();
1152:
1153: sm.append(JavaConstants.JAVAX_PORTLET_TITLE);
1154: sm.append(StringPool.PERIOD);
1155: sm.append(portletId);
1156:
1157: return LanguageUtil.get(user.getCompanyId(), user.getLocale(),
1158: sm.toString());
1159: }
1160:
1161: public static String getPortletTitle(Portlet portlet,
1162: ServletContext ctx, Locale locale) {
1163:
1164: PortletConfig portletConfig = PortletConfigFactory.create(
1165: portlet, ctx);
1166:
1167: ResourceBundle resourceBundle = portletConfig
1168: .getResourceBundle(locale);
1169:
1170: return resourceBundle
1171: .getString(JavaConstants.JAVAX_PORTLET_TITLE);
1172: }
1173:
1174: public static PortletPreferences getPreferences(
1175: HttpServletRequest req) {
1176: RenderRequest renderRequest = (RenderRequest) req
1177: .getAttribute(JavaConstants.JAVAX_PORTLET_REQUEST);
1178:
1179: PortletPreferences prefs = null;
1180:
1181: if (renderRequest != null) {
1182: PortletPreferencesWrapper prefsWrapper = (PortletPreferencesWrapper) renderRequest
1183: .getPreferences();
1184:
1185: prefs = prefsWrapper.getPreferencesImpl();
1186: }
1187:
1188: return prefs;
1189: }
1190:
1191: public static PreferencesValidator getPreferencesValidator(
1192: Portlet portlet) {
1193:
1194: if (portlet.isWARFile()) {
1195: PortletContextWrapper pcw = PortletContextPool.get(portlet
1196: .getRootPortletId());
1197:
1198: return pcw.getPreferencesValidatorInstance();
1199: } else {
1200: PreferencesValidator prefsValidator = null;
1201:
1202: if (Validator.isNotNull(portlet.getPreferencesValidator())) {
1203: prefsValidator = (PreferencesValidator) InstancePool
1204: .get(portlet.getPreferencesValidator());
1205: }
1206:
1207: return prefsValidator;
1208: }
1209: }
1210:
1211: public static RenderResponseImpl getRenderResponseImpl(
1212: RenderResponse res) {
1213: RenderResponseImpl resImpl = null;
1214:
1215: if (res instanceof RenderResponseImpl) {
1216: resImpl = (RenderResponseImpl) res;
1217: } else {
1218:
1219: // LEP-4033
1220:
1221: try {
1222: Method method = MethodCache.get(res.getClass()
1223: .getName(), "getResponse");
1224:
1225: Object obj = method.invoke(res, null);
1226:
1227: resImpl = getRenderResponseImpl((RenderResponse) obj);
1228: } catch (Exception e) {
1229: throw new RuntimeException(e);
1230: }
1231: }
1232:
1233: return resImpl;
1234: }
1235:
1236: public static User getSelectedUser(HttpServletRequest req)
1237: throws PortalException, RemoteException, SystemException {
1238:
1239: return getSelectedUser(req, true);
1240: }
1241:
1242: public static User getSelectedUser(HttpServletRequest req,
1243: boolean checkPermission) throws PortalException,
1244: RemoteException, SystemException {
1245:
1246: long userId = ParamUtil.getLong(req, "p_u_i_d");
1247:
1248: User user = null;
1249:
1250: try {
1251: if (checkPermission) {
1252: user = UserServiceUtil.getUserById(userId);
1253: } else {
1254: user = UserLocalServiceUtil.getUserById(userId);
1255: }
1256: } catch (NoSuchUserException nsue) {
1257: }
1258:
1259: return user;
1260: }
1261:
1262: public static User getSelectedUser(ActionRequest req)
1263: throws PortalException, RemoteException, SystemException {
1264:
1265: return getSelectedUser(req, true);
1266: }
1267:
1268: public static User getSelectedUser(ActionRequest req,
1269: boolean checkPermission) throws PortalException,
1270: RemoteException, SystemException {
1271:
1272: return getSelectedUser(getHttpServletRequest(req),
1273: checkPermission);
1274: }
1275:
1276: public static User getSelectedUser(RenderRequest req)
1277: throws PortalException, RemoteException, SystemException {
1278:
1279: return getSelectedUser(req, true);
1280: }
1281:
1282: public static User getSelectedUser(RenderRequest req,
1283: boolean checkPermission) throws PortalException,
1284: RemoteException, SystemException {
1285:
1286: return getSelectedUser(getHttpServletRequest(req),
1287: checkPermission);
1288: }
1289:
1290: public static String getStrutsAction(HttpServletRequest req) {
1291: String strutsAction = ParamUtil.getString(req, "struts_action");
1292:
1293: if (Validator.isNotNull(strutsAction)) {
1294:
1295: // This method should only return a Struts action if you're dealing
1296: // with a regular HTTP servlet request, not a portlet HTTP servlet
1297: // request.
1298:
1299: return StringPool.BLANK;
1300: }
1301:
1302: int strutsActionCount = 0;
1303:
1304: Enumeration enu = req.getParameterNames();
1305:
1306: while (enu.hasMoreElements()) {
1307: String name = (String) enu.nextElement();
1308:
1309: int pos = name.indexOf("_struts_action");
1310:
1311: if (pos != -1) {
1312: strutsActionCount++;
1313:
1314: // There should never be more than one Struts action
1315:
1316: if (strutsActionCount > 1) {
1317: return StringPool.BLANK;
1318: }
1319:
1320: String curStrutsAction = ParamUtil.getString(req, name);
1321:
1322: if (Validator.isNotNull(curStrutsAction)) {
1323:
1324: // The Struts action must be for the correct portlet
1325:
1326: String portletId1 = name.substring(1, pos);
1327: String portletId2 = ParamUtil.getString(req,
1328: "p_p_id");
1329:
1330: if (portletId1.equals(portletId2)) {
1331: strutsAction = curStrutsAction;
1332: }
1333: }
1334: }
1335: }
1336:
1337: return strutsAction;
1338: }
1339:
1340: public static String[] getSystemCommunityRoles() {
1341: return _instance._getSystemCommunityRoles();
1342: }
1343:
1344: public static String[] getSystemGroups() {
1345: return _instance._getSystemGroups();
1346: }
1347:
1348: public static String[] getSystemOrganizationRoles() {
1349: return _instance._getSystemOrganizationRoles();
1350: }
1351:
1352: public static String[] getSystemRoles() {
1353: return _instance._getSystemRoles();
1354: }
1355:
1356: public static UploadPortletRequest getUploadPortletRequest(
1357: ActionRequest req) {
1358:
1359: ActionRequestImpl actionReq = (ActionRequestImpl) req;
1360:
1361: DynamicServletRequest dynamicReq = (DynamicServletRequest) actionReq
1362: .getHttpServletRequest();
1363:
1364: HttpServletRequestWrapper reqWrapper = (HttpServletRequestWrapper) dynamicReq
1365: .getRequest();
1366:
1367: UploadServletRequest uploadReq = getUploadServletRequest(reqWrapper);
1368:
1369: return new UploadPortletRequest(uploadReq,
1370: getPortletNamespace(actionReq.getPortletName()));
1371: }
1372:
1373: public static UploadServletRequest getUploadServletRequest(
1374: HttpServletRequest httpReq) {
1375:
1376: HttpServletRequestWrapper httpReqWrapper = null;
1377:
1378: if (httpReq instanceof HttpServletRequestWrapper) {
1379: httpReqWrapper = (HttpServletRequestWrapper) httpReq;
1380: }
1381:
1382: UploadServletRequest uploadReq = null;
1383:
1384: while (uploadReq == null) {
1385:
1386: // Find the underlying UploadServletRequest wrapper. For example,
1387: // WebSphere wraps all requests with ProtectedServletRequest.
1388:
1389: if (httpReqWrapper instanceof UploadServletRequest) {
1390: uploadReq = (UploadServletRequest) httpReqWrapper;
1391: } else {
1392: ServletRequest req = httpReqWrapper.getRequest();
1393:
1394: if (!(req instanceof HttpServletRequestWrapper)) {
1395: break;
1396: } else {
1397: httpReqWrapper = (HttpServletRequestWrapper) httpReqWrapper
1398: .getRequest();
1399: }
1400: }
1401: }
1402:
1403: return uploadReq;
1404: }
1405:
1406: public static Date getUptime() {
1407: return UP_TIME;
1408: }
1409:
1410: public static String getURLWithSessionId(String url,
1411: String sessionId) {
1412:
1413: // LEP-4787
1414:
1415: int x = url.indexOf(StringPool.SEMICOLON);
1416:
1417: if (x != -1) {
1418: return url;
1419: }
1420:
1421: x = url.indexOf(StringPool.QUESTION);
1422:
1423: if (x != -1) {
1424: StringMaker sm = new StringMaker();
1425:
1426: sm.append(url.substring(0, x));
1427: sm.append(_JSESSIONID);
1428: sm.append(sessionId);
1429: sm.append(url.substring(x));
1430:
1431: return sm.toString();
1432: }
1433:
1434: // In IE6, http://www.abc.com;jsessionid=XYZ does not work,
1435: // but http://www.abc.com/;jsessionid=XYZ does work.
1436:
1437: x = url.indexOf(StringPool.DOUBLE_SLASH);
1438:
1439: StringMaker sm = new StringMaker();
1440:
1441: sm.append(url);
1442:
1443: if (x != -1) {
1444: int y = url.lastIndexOf(StringPool.SLASH);
1445:
1446: if (x + 1 == y) {
1447: sm.append(StringPool.SLASH);
1448: }
1449: }
1450:
1451: sm.append(_JSESSIONID);
1452: sm.append(sessionId);
1453:
1454: return sm.toString();
1455: }
1456:
1457: public static User getUser(HttpServletRequest req)
1458: throws PortalException, SystemException {
1459:
1460: long userId = getUserId(req);
1461:
1462: if (userId <= 0) {
1463:
1464: // Portlet WARs may have the correct remote user and not have the
1465: // correct user id because the user id is saved in the session
1466: // and may not be accessible by the portlet WAR's session. This
1467: // behavior is inconsistent across different application servers.
1468:
1469: String remoteUser = req.getRemoteUser();
1470:
1471: if (remoteUser == null) {
1472: return null;
1473: }
1474:
1475: userId = GetterUtil.getLong(remoteUser);
1476: }
1477:
1478: User user = (User) req.getAttribute(WebKeys.USER);
1479:
1480: if (user == null) {
1481: user = UserLocalServiceUtil.getUserById(userId);
1482:
1483: req.setAttribute(WebKeys.USER, user);
1484: }
1485:
1486: return user;
1487: }
1488:
1489: public static User getUser(ActionRequest req)
1490: throws PortalException, SystemException {
1491:
1492: return getUser(getHttpServletRequest(req));
1493: }
1494:
1495: public static User getUser(RenderRequest req)
1496: throws PortalException, SystemException {
1497:
1498: return getUser(getHttpServletRequest(req));
1499: }
1500:
1501: public static long getUserId(HttpServletRequest req) {
1502: Long userIdObj = (Long) req.getAttribute(WebKeys.USER_ID);
1503:
1504: if (userIdObj != null) {
1505: return userIdObj.longValue();
1506: }
1507:
1508: if (!PropsValues.PORTAL_JAAS_ENABLE
1509: && PropsValues.PORTAL_IMPERSONATION_ENABLE) {
1510:
1511: String doAsUserIdString = ParamUtil.getString(req,
1512: "doAsUserId");
1513:
1514: try {
1515: long doAsUserId = _getDoAsUserId(req, doAsUserIdString);
1516:
1517: if (doAsUserId > 0) {
1518: if (_log.isDebugEnabled()) {
1519: _log.debug("Impersonating user " + doAsUserId);
1520: }
1521:
1522: return doAsUserId;
1523: }
1524: } catch (Exception e) {
1525: _log.error("Unable to impersonate user "
1526: + doAsUserIdString, e);
1527: }
1528: }
1529:
1530: HttpSession ses = req.getSession();
1531:
1532: userIdObj = (Long) ses.getAttribute(WebKeys.USER_ID);
1533:
1534: if (userIdObj != null) {
1535: req.setAttribute(WebKeys.USER_ID, userIdObj);
1536:
1537: return userIdObj.longValue();
1538: } else {
1539: return 0;
1540: }
1541: }
1542:
1543: public static long getUserId(ActionRequest req) {
1544: return getUserId(getHttpServletRequest(req));
1545: }
1546:
1547: public static long getUserId(RenderRequest req) {
1548: return getUserId(getHttpServletRequest(req));
1549: }
1550:
1551: public static String getUserName(long userId, String defaultUserName) {
1552: return getUserName(userId, defaultUserName,
1553: UserAttributes.USER_NAME_FULL);
1554: }
1555:
1556: public static String getUserName(long userId,
1557: String defaultUserName, String userAttribute) {
1558:
1559: return getUserName(userId, defaultUserName, userAttribute, null);
1560: }
1561:
1562: public static String getUserName(long userId,
1563: String defaultUserName, HttpServletRequest req) {
1564:
1565: return getUserName(userId, defaultUserName,
1566: UserAttributes.USER_NAME_FULL, req);
1567: }
1568:
1569: public static String getUserName(long userId,
1570: String defaultUserName, String userAttribute,
1571: HttpServletRequest req) {
1572:
1573: String userName = defaultUserName;
1574:
1575: try {
1576: User user = UserLocalServiceUtil.getUserById(userId);
1577:
1578: if (userAttribute.equals(UserAttributes.USER_NAME_FULL)) {
1579: userName = user.getFullName();
1580: } else {
1581: userName = user.getScreenName();
1582: }
1583:
1584: if (req != null) {
1585: Layout layout = (Layout) req
1586: .getAttribute(WebKeys.LAYOUT);
1587:
1588: PortletURL portletURL = new PortletURLImpl(req,
1589: PortletKeys.DIRECTORY, layout.getPlid(), false);
1590:
1591: portletURL.setWindowState(WindowState.MAXIMIZED);
1592: portletURL.setPortletMode(PortletMode.VIEW);
1593:
1594: portletURL.setParameter("struts_action",
1595: "/directory/edit_user");
1596: portletURL.setParameter("p_u_i_d", String.valueOf(user
1597: .getUserId()));
1598:
1599: userName = "<a href=\"" + portletURL.toString() + "\">"
1600: + userName + "</a>";
1601: }
1602: } catch (Exception e) {
1603: }
1604:
1605: return userName;
1606: }
1607:
1608: public static String getUserPassword(HttpSession ses) {
1609: return (String) ses.getAttribute(WebKeys.USER_PASSWORD);
1610: }
1611:
1612: public static String getUserPassword(HttpServletRequest req) {
1613: return getUserPassword(req.getSession());
1614: }
1615:
1616: public static String getUserPassword(ActionRequest req) {
1617: return getUserPassword(getHttpServletRequest(req));
1618: }
1619:
1620: public static String getUserPassword(RenderRequest req) {
1621: return getUserPassword(getHttpServletRequest(req));
1622: }
1623:
1624: public static String getUserValue(long userId, String param,
1625: String defaultValue) throws SystemException {
1626:
1627: if (Validator.isNotNull(defaultValue)) {
1628: return defaultValue;
1629: } else {
1630: try {
1631: User user = UserLocalServiceUtil.getUserById(userId);
1632:
1633: return BeanUtil.getString(user, param, defaultValue);
1634: } catch (PortalException pe) {
1635: return StringPool.BLANK;
1636: }
1637: }
1638: }
1639:
1640: public static boolean isMethodGet(PortletRequest req) {
1641: HttpServletRequest httpReq = getHttpServletRequest(req);
1642:
1643: String method = GetterUtil.getString(httpReq.getMethod());
1644:
1645: if (method.equalsIgnoreCase(_METHOD_GET)) {
1646: return true;
1647: } else {
1648: return false;
1649: }
1650: }
1651:
1652: public static boolean isMethodPost(PortletRequest req) {
1653: HttpServletRequest httpReq = getHttpServletRequest(req);
1654:
1655: String method = GetterUtil.getString(httpReq.getMethod());
1656:
1657: if (method.equalsIgnoreCase(_METHOD_POST)) {
1658: return true;
1659: } else {
1660: return false;
1661: }
1662: }
1663:
1664: public static boolean isLayoutFriendliable(Layout layout) {
1665: return PropsUtil.getComponentProperties().getBoolean(
1666: PropsUtil.LAYOUT_URL_FRIENDLIABLE,
1667: Filter.by(layout.getType()), true);
1668: }
1669:
1670: public static boolean isLayoutParentable(Layout layout) {
1671: return isLayoutParentable(layout.getType());
1672: }
1673:
1674: public static boolean isLayoutParentable(String type) {
1675: return PropsUtil.getComponentProperties().getBoolean(
1676: PropsUtil.LAYOUT_PARENTABLE, Filter.by(type), true);
1677: }
1678:
1679: public static boolean isLayoutSitemapable(Layout layout) {
1680: if (layout.isPrivateLayout()) {
1681: return false;
1682: }
1683:
1684: return PropsUtil.getComponentProperties().getBoolean(
1685: PropsUtil.LAYOUT_SITEMAPABLE,
1686: Filter.by(layout.getType()), true);
1687: }
1688:
1689: public static boolean isReservedParameter(String name) {
1690: return _instance._reservedParams.contains(name);
1691: }
1692:
1693: public static boolean isSystemGroup(String groupName) {
1694: return _instance._isSystemGroup(groupName);
1695: }
1696:
1697: public static boolean isSystemRole(String roleName) {
1698: return _instance._isSystemRole(roleName);
1699: }
1700:
1701: public static boolean isUpdateAvailable() throws PortalException,
1702: SystemException {
1703:
1704: return PluginPackageUtil.isUpdateAvailable();
1705: }
1706:
1707: public static Document readDocumentFromFile(File file)
1708: throws DocumentException {
1709:
1710: return readDocumentFromFile(file, false);
1711: }
1712:
1713: public static Document readDocumentFromFile(File file,
1714: boolean validate) throws DocumentException {
1715:
1716: SAXReader reader = SAXReaderFactory.getInstance(validate);
1717:
1718: return reader.read(file);
1719: }
1720:
1721: public static Document readDocumentFromStream(InputStream is)
1722: throws DocumentException {
1723:
1724: return readDocumentFromStream(is, false);
1725: }
1726:
1727: public static Document readDocumentFromStream(InputStream is,
1728: boolean validate) throws DocumentException {
1729:
1730: SAXReader reader = SAXReaderFactory.getInstance(validate);
1731:
1732: return reader.read(is);
1733: }
1734:
1735: public static Document readDocumentFromURL(String url)
1736: throws DocumentException, IOException {
1737:
1738: return readDocumentFromURL(url, false);
1739: }
1740:
1741: public static Document readDocumentFromURL(String url,
1742: boolean validate) throws DocumentException, IOException {
1743:
1744: SAXReader reader = SAXReaderFactory.getInstance(validate);
1745:
1746: return reader.read(new URL(url));
1747: }
1748:
1749: public static Document readDocumentFromXML(String xml)
1750: throws DocumentException {
1751:
1752: return readDocumentFromXML(xml, false);
1753: }
1754:
1755: public static Document readDocumentFromXML(String xml,
1756: boolean validate) throws DocumentException {
1757:
1758: SAXReader reader = SAXReaderFactory.getInstance(validate);
1759:
1760: return reader.read(new XMLSafeReader(xml));
1761: }
1762:
1763: public static void renderPage(StringMaker sm, ServletContext ctx,
1764: HttpServletRequest req, HttpServletResponse res, String path)
1765: throws IOException, ServletException {
1766:
1767: RequestDispatcher rd = ctx.getRequestDispatcher(path);
1768:
1769: StringServletResponse stringServletRes = new StringServletResponse(
1770: res);
1771:
1772: rd.include(req, stringServletRes);
1773:
1774: sm.append(stringServletRes.getString());
1775: }
1776:
1777: public static void renderPortlet(StringMaker sm,
1778: ServletContext ctx, HttpServletRequest req,
1779: HttpServletResponse res, Portlet portlet, String queryString)
1780: throws IOException, ServletException {
1781:
1782: renderPortlet(sm, ctx, req, res, portlet, queryString, null,
1783: null, null);
1784: }
1785:
1786: public static void renderPortlet(StringMaker sm,
1787: ServletContext ctx, HttpServletRequest req,
1788: HttpServletResponse res, Portlet portlet,
1789: String queryString, String columnId, Integer columnPos,
1790: Integer columnCount) throws IOException, ServletException {
1791:
1792: renderPortlet(sm, ctx, req, res, portlet, queryString,
1793: columnId, columnPos, columnCount, null);
1794: }
1795:
1796: public static void renderPortlet(StringMaker sm,
1797: ServletContext ctx, HttpServletRequest req,
1798: HttpServletResponse res, Portlet portlet,
1799: String queryString, String columnId, Integer columnPos,
1800: Integer columnCount, String path) throws IOException,
1801: ServletException {
1802:
1803: queryString = GetterUtil.getString(queryString);
1804: columnId = GetterUtil.getString(columnId);
1805:
1806: if (columnPos == null) {
1807: columnPos = new Integer(0);
1808: }
1809:
1810: if (columnCount == null) {
1811: columnCount = new Integer(0);
1812: }
1813:
1814: req.setAttribute(WebKeys.RENDER_PORTLET, portlet);
1815: req.setAttribute(WebKeys.RENDER_PORTLET_QUERY_STRING,
1816: queryString);
1817: req.setAttribute(WebKeys.RENDER_PORTLET_COLUMN_ID, columnId);
1818: req.setAttribute(WebKeys.RENDER_PORTLET_COLUMN_POS, columnPos);
1819: req.setAttribute(WebKeys.RENDER_PORTLET_COLUMN_COUNT,
1820: columnCount);
1821:
1822: if (path == null) {
1823: path = "/html/portal/render_portlet.jsp";
1824: }
1825:
1826: RequestDispatcher rd = ctx.getRequestDispatcher(path);
1827:
1828: if (sm != null) {
1829: StringServletResponse stringServletRes = new StringServletResponse(
1830: res);
1831:
1832: rd.include(req, stringServletRes);
1833:
1834: sm.append(stringServletRes.getString());
1835: } else {
1836:
1837: // LEP-766
1838:
1839: res.setContentType(ContentTypes.TEXT_HTML_UTF8);
1840:
1841: rd.include(req, res);
1842: }
1843: }
1844:
1845: public static void sendError(int status, Exception e,
1846: HttpServletRequest req, HttpServletResponse res)
1847: throws IOException, ServletException {
1848:
1849: ServletContext ctx = req.getSession().getServletContext();
1850:
1851: String mainPath = PortalUtil.PATH_MAIN;
1852:
1853: String redirect = mainPath + "/portal/status";
1854:
1855: if (e instanceof NoSuchLayoutException
1856: && Validator
1857: .isNotNull(PropsValues.LAYOUT_FRIENDLY_URL_PAGE_NOT_FOUND)) {
1858:
1859: res.setStatus(status);
1860:
1861: redirect = PropsValues.LAYOUT_FRIENDLY_URL_PAGE_NOT_FOUND;
1862:
1863: RequestDispatcher rd = ctx.getRequestDispatcher(redirect);
1864:
1865: if (rd != null) {
1866: rd.forward(req, res);
1867: }
1868: } else if (PropsValues.LAYOUT_SHOW_HTTP_STATUS) {
1869: res.setStatus(status);
1870:
1871: SessionErrors.add(req, e.getClass().getName(), e);
1872:
1873: RequestDispatcher rd = ctx.getRequestDispatcher(redirect);
1874:
1875: if (rd != null) {
1876: rd.forward(req, res);
1877: }
1878: } else {
1879: if (e != null) {
1880: res.sendError(status, e.getMessage());
1881: } else {
1882: res.sendError(status);
1883: }
1884: }
1885: }
1886:
1887: /**
1888: * Sets the subtitle for a page. This is just a hint and can be overridden
1889: * by subsequent calls. The last call to this method wins.
1890: *
1891: * @param subtitle the subtitle for a page
1892: * @param req the HTTP servlet request
1893: */
1894: public static void setPageSubtitle(String subtitle,
1895: HttpServletRequest req) {
1896:
1897: req.setAttribute(WebKeys.PAGE_SUBTITLE, subtitle);
1898: }
1899:
1900: /**
1901: * Sets the whole title for a page. This is just a hint and can be
1902: * overridden by subsequent calls. The last call to this method wins.
1903: *
1904: * @param title the whole title for a page
1905: * @param req the HTTP servlet request
1906: */
1907: public static void setPageTitle(String title, HttpServletRequest req) {
1908: req.setAttribute(WebKeys.PAGE_TITLE, title);
1909: }
1910:
1911: public static void storePreferences(PortletPreferences prefs)
1912: throws IOException, ValidatorException {
1913:
1914: PortletPreferencesWrapper prefsWrapper = (PortletPreferencesWrapper) prefs;
1915:
1916: PortletPreferencesImpl prefsImpl = (PortletPreferencesImpl) prefsWrapper
1917: .getPreferencesImpl();
1918:
1919: prefsImpl.store();
1920: }
1921:
1922: public static PortletMode updatePortletMode(String portletId,
1923: User user, Layout layout, PortletMode portletMode,
1924: HttpServletRequest req) throws PortalException,
1925: RemoteException, SystemException {
1926:
1927: LayoutTypePortlet layoutType = (LayoutTypePortlet) layout
1928: .getLayoutType();
1929:
1930: if (portletMode == null
1931: || Validator.isNull(portletMode.toString())) {
1932: if (layoutType.hasModeAboutPortletId(portletId)) {
1933: return LiferayPortletMode.ABOUT;
1934: } else if (layoutType.hasModeConfigPortletId(portletId)) {
1935: return LiferayPortletMode.CONFIG;
1936: } else if (layoutType.hasModeEditPortletId(portletId)) {
1937: return PortletMode.EDIT;
1938: } else if (layoutType
1939: .hasModeEditDefaultsPortletId(portletId)) {
1940: return LiferayPortletMode.EDIT_DEFAULTS;
1941: } else if (layoutType.hasModeEditGuestPortletId(portletId)) {
1942: return LiferayPortletMode.EDIT_GUEST;
1943: } else if (layoutType.hasModeHelpPortletId(portletId)) {
1944: return PortletMode.HELP;
1945: } else if (layoutType.hasModePreviewPortletId(portletId)) {
1946: return LiferayPortletMode.PREVIEW;
1947: } else if (layoutType.hasModePrintPortletId(portletId)) {
1948: return LiferayPortletMode.PRINT;
1949: } else {
1950: return PortletMode.VIEW;
1951: }
1952: } else {
1953: boolean updateLayout = false;
1954:
1955: if (portletMode.equals(LiferayPortletMode.ABOUT)
1956: && !layoutType.hasModeAboutPortletId(portletId)) {
1957:
1958: layoutType.addModeAboutPortletId(portletId);
1959:
1960: updateLayout = true;
1961: } else if (portletMode.equals(LiferayPortletMode.CONFIG)
1962: && !layoutType.hasModeConfigPortletId(portletId)) {
1963:
1964: layoutType.addModeConfigPortletId(portletId);
1965:
1966: updateLayout = true;
1967: } else if (portletMode.equals(PortletMode.EDIT)
1968: && !layoutType.hasModeEditPortletId(portletId)) {
1969:
1970: layoutType.addModeEditPortletId(portletId);
1971:
1972: updateLayout = true;
1973: } else if (portletMode
1974: .equals(LiferayPortletMode.EDIT_DEFAULTS)
1975: && !layoutType
1976: .hasModeEditDefaultsPortletId(portletId)) {
1977:
1978: layoutType.addModeEditDefaultsPortletId(portletId);
1979:
1980: updateLayout = true;
1981: } else if (portletMode
1982: .equals(LiferayPortletMode.EDIT_GUEST)
1983: && !layoutType.hasModeEditGuestPortletId(portletId)) {
1984:
1985: layoutType.addModeEditGuestPortletId(portletId);
1986:
1987: updateLayout = true;
1988: } else if (portletMode.equals(PortletMode.HELP)
1989: && !layoutType.hasModeHelpPortletId(portletId)) {
1990:
1991: layoutType.addModeHelpPortletId(portletId);
1992:
1993: updateLayout = true;
1994: } else if (portletMode.equals(LiferayPortletMode.PREVIEW)
1995: && !layoutType.hasModePreviewPortletId(portletId)) {
1996:
1997: layoutType.addModePreviewPortletId(portletId);
1998:
1999: updateLayout = true;
2000: } else if (portletMode.equals(LiferayPortletMode.PRINT)
2001: && !layoutType.hasModePrintPortletId(portletId)) {
2002:
2003: layoutType.addModePrintPortletId(portletId);
2004:
2005: updateLayout = true;
2006: } else if (portletMode.equals(PortletMode.VIEW)
2007: && !layoutType.hasModeViewPortletId(portletId)) {
2008:
2009: layoutType.removeModesPortletId(portletId);
2010:
2011: updateLayout = true;
2012: }
2013:
2014: if (updateLayout) {
2015: LayoutClone layoutClone = LayoutCloneFactory
2016: .getInstance();
2017:
2018: if (layoutClone != null) {
2019: layoutClone.update(req, layout.getPlid(), layout
2020: .getTypeSettings());
2021: }
2022: }
2023:
2024: return portletMode;
2025: }
2026: }
2027:
2028: public static WindowState updateWindowState(String portletId,
2029: User user, Layout layout, WindowState windowState,
2030: HttpServletRequest req) throws PortalException,
2031: RemoteException, SystemException {
2032:
2033: LayoutTypePortlet layoutType = (LayoutTypePortlet) layout
2034: .getLayoutType();
2035:
2036: if ((windowState == null)
2037: || (Validator.isNull(windowState.toString()))) {
2038:
2039: if (layoutType.hasStateMaxPortletId(portletId)) {
2040: return WindowState.MAXIMIZED;
2041: } else if (layoutType.hasStateMinPortletId(portletId)) {
2042: return WindowState.MINIMIZED;
2043: } else {
2044: return WindowState.NORMAL;
2045: }
2046: } else {
2047: boolean updateLayout = false;
2048:
2049: if ((windowState.equals(WindowState.MAXIMIZED))
2050: || (windowState
2051: .equals(LiferayWindowState.EXCLUSIVE))
2052: || (windowState.equals(LiferayWindowState.POP_UP))) {
2053:
2054: if (layoutType.hasStateMax()) {
2055: String curMaxPortletId = StringUtil
2056: .split(layoutType.getStateMax())[0];
2057:
2058: // Clear cache and render parameters for the previous
2059: // portlet that had a maximum window state
2060:
2061: CachePortlet.clearResponse(req.getSession(), layout
2062: .getPlid(), curMaxPortletId, LanguageUtil
2063: .getLanguageId(req));
2064:
2065: /*RenderParametersPool.clear(
2066: req, layout.getPlid(), curMaxPortletId);*/
2067:
2068: if ((windowState
2069: .equals(LiferayWindowState.EXCLUSIVE))
2070: || (windowState
2071: .equals(LiferayWindowState.POP_UP))) {
2072:
2073: String stateMaxPrevious = layoutType
2074: .getStateMaxPrevious();
2075:
2076: if (stateMaxPrevious == null) {
2077: layoutType
2078: .setStateMaxPrevious(curMaxPortletId);
2079:
2080: updateLayout = true;
2081: }
2082: }
2083: } else {
2084: if ((windowState
2085: .equals(LiferayWindowState.EXCLUSIVE))
2086: || (windowState
2087: .equals(LiferayWindowState.POP_UP))) {
2088:
2089: String stateMaxPrevious = layoutType
2090: .getStateMaxPrevious();
2091:
2092: if (stateMaxPrevious == null) {
2093: layoutType
2094: .setStateMaxPrevious(StringPool.BLANK);
2095:
2096: updateLayout = true;
2097: }
2098: }
2099: }
2100:
2101: if (!layoutType.hasStateMaxPortletId(portletId)) {
2102: layoutType.addStateMaxPortletId(portletId);
2103:
2104: updateLayout = true;
2105: }
2106: } else if (windowState.equals(WindowState.MINIMIZED)
2107: && !layoutType.hasStateMinPortletId(portletId)) {
2108:
2109: layoutType.addStateMinPortletId(portletId);
2110:
2111: updateLayout = true;
2112: } else if (windowState.equals(WindowState.NORMAL)
2113: && !layoutType.hasStateNormalPortletId(portletId)) {
2114:
2115: layoutType.removeStatesPortletId(portletId);
2116:
2117: updateLayout = true;
2118: }
2119:
2120: if (updateLayout) {
2121: LayoutClone layoutClone = LayoutCloneFactory
2122: .getInstance();
2123:
2124: if (layoutClone != null) {
2125: layoutClone.update(req, layout.getPlid(), layout
2126: .getTypeSettings());
2127: }
2128: }
2129:
2130: return windowState;
2131: }
2132: }
2133:
2134: private static long _getDoAsUserId(HttpServletRequest req,
2135: String doAsUserIdString) throws Exception {
2136:
2137: if (Validator.isNull(doAsUserIdString)) {
2138: return 0;
2139: }
2140:
2141: long doAsUserId = 0;
2142:
2143: try {
2144: Company company = getCompany(req);
2145:
2146: doAsUserId = GetterUtil.getLong(Encryptor.decrypt(company
2147: .getKeyObj(), doAsUserIdString));
2148: } catch (Exception e) {
2149: if (_log.isWarnEnabled()) {
2150: _log.warn("Unable to impersonate " + doAsUserIdString
2151: + " because the string cannot be decrypted", e);
2152: }
2153:
2154: return 0;
2155: }
2156:
2157: String path = GetterUtil.getString(req.getPathInfo());
2158:
2159: if (_log.isDebugEnabled()) {
2160: _log.debug("doAsUserId path " + path);
2161: }
2162:
2163: String strutsAction = getStrutsAction(req);
2164:
2165: if (_log.isDebugEnabled()) {
2166: _log.debug("Struts action " + strutsAction);
2167: }
2168:
2169: boolean alwaysAllowDoAsUser = false;
2170:
2171: if (path.equals("/portal/fckeditor")
2172: || strutsAction
2173: .equals("/document_library/edit_file_entry")
2174: || strutsAction.equals("/image_gallery/edit_image")) {
2175:
2176: alwaysAllowDoAsUser = true;
2177: }
2178:
2179: if (_log.isDebugEnabled()) {
2180: if (alwaysAllowDoAsUser) {
2181: _log
2182: .debug("doAsUserId path or Struts action is always allowed");
2183: } else {
2184: _log
2185: .debug("doAsUserId path is Struts action not always allowed");
2186: }
2187: }
2188:
2189: if (alwaysAllowDoAsUser) {
2190: req.setAttribute(WebKeys.USER_ID, new Long(doAsUserId));
2191:
2192: return doAsUserId;
2193: }
2194:
2195: HttpSession ses = req.getSession();
2196:
2197: Long realUserIdObj = (Long) ses.getAttribute(WebKeys.USER_ID);
2198:
2199: if (realUserIdObj == null) {
2200: return 0;
2201: }
2202:
2203: User doAsUser = UserLocalServiceUtil.getUserById(doAsUserId);
2204:
2205: long[] organizationIds = doAsUser.getOrganizationIds();
2206:
2207: User realUser = UserLocalServiceUtil.getUserById(realUserIdObj
2208: .longValue());
2209: boolean checkGuest = true;
2210:
2211: PermissionCheckerImpl permissionChecker = null;
2212:
2213: try {
2214: permissionChecker = PermissionCheckerFactory.create(
2215: realUser, checkGuest);
2216:
2217: if (doAsUser.isDefaultUser()
2218: || UserPermissionUtil.contains(permissionChecker,
2219: doAsUserId, organizationIds,
2220: ActionKeys.IMPERSONATE)) {
2221:
2222: req.setAttribute(WebKeys.USER_ID, new Long(doAsUserId));
2223:
2224: return doAsUserId;
2225: } else {
2226: _log.error("User " + realUserIdObj
2227: + " does not have the permission "
2228: + "to impersonate " + doAsUserId);
2229:
2230: return 0;
2231: }
2232: } finally {
2233: try {
2234: PermissionCheckerFactory.recycle(permissionChecker);
2235: } catch (Exception e) {
2236: }
2237: }
2238: }
2239:
2240: private PortalUtil() {
2241:
2242: // Computer name
2243:
2244: _computerName = System.getProperty("env.COMPUTERNAME");
2245:
2246: if (Validator.isNull(_computerName)) {
2247: _computerName = System.getProperty("env.HOST");
2248: }
2249:
2250: if (Validator.isNull(_computerName)) {
2251: _computerName = System.getProperty("env.HOSTNAME");
2252: }
2253:
2254: // Portal lib directory
2255:
2256: ClassLoader classLoader = getClass().getClassLoader();
2257:
2258: URL url = classLoader
2259: .getResource("com/liferay/portal/util/PortalUtil.class");
2260:
2261: String file = url.getFile();
2262:
2263: if (_log.isInfoEnabled()) {
2264: _log.info("Portal lib url " + file);
2265: }
2266:
2267: int pos = file.indexOf("/com/liferay/portal/util/");
2268:
2269: _portalLibDir = file.substring(0, pos + 1);
2270:
2271: if (_portalLibDir.endsWith("/WEB-INF/classes/")) {
2272: _portalLibDir = _portalLibDir.substring(0, _portalLibDir
2273: .length() - 8)
2274: + "lib/";
2275: } else {
2276: pos = _portalLibDir.indexOf("/WEB-INF/lib/");
2277:
2278: if (pos != -1) {
2279: _portalLibDir = _portalLibDir.substring(0, pos)
2280: + "/WEB-INF/lib/";
2281: }
2282: }
2283:
2284: if (_portalLibDir.startsWith("file:/")) {
2285: _portalLibDir = _portalLibDir.substring(5, _portalLibDir
2286: .length());
2287: }
2288:
2289: if (_log.isInfoEnabled()) {
2290: _log.info("Portal lib directory " + _portalLibDir);
2291: }
2292:
2293: // CDN host
2294:
2295: _cdnHost = PropsUtil.get(PropsUtil.CDN_HOST);
2296:
2297: // Paths
2298:
2299: _pathContext = PropsUtil.get(PropsUtil.PORTAL_CTX);
2300:
2301: if (_pathContext.equals(StringPool.SLASH)) {
2302: _pathContext = StringPool.BLANK;
2303: }
2304:
2305: _pathFriendlyURLPrivateGroup = _pathContext
2306: + PropsValues.LAYOUT_FRIENDLY_URL_PRIVATE_GROUP_SERVLET_MAPPING;
2307: _pathFriendlyURLPrivateUser = _pathContext
2308: + PropsValues.LAYOUT_FRIENDLY_URL_PRIVATE_USER_SERVLET_MAPPING;
2309: _pathFriendlyURLPublic = _pathContext
2310: + PropsValues.LAYOUT_FRIENDLY_URL_PUBLIC_SERVLET_MAPPING;
2311: _pathImage = _cdnHost + _pathContext + PATH_IMAGE;
2312: _pathMain = _pathContext + PATH_MAIN;
2313:
2314: // Groups
2315:
2316: String customSystemGroups[] = PropsUtil
2317: .getArray(PropsUtil.SYSTEM_GROUPS);
2318:
2319: if ((customSystemGroups == null)
2320: || (customSystemGroups.length == 0)) {
2321: _allSystemGroups = GroupImpl.SYSTEM_GROUPS;
2322: } else {
2323: _allSystemGroups = ArrayUtil.append(
2324: GroupImpl.SYSTEM_GROUPS, customSystemGroups);
2325: }
2326:
2327: _sortedSystemGroups = new String[_allSystemGroups.length];
2328:
2329: System.arraycopy(_allSystemGroups, 0, _sortedSystemGroups, 0,
2330: _allSystemGroups.length);
2331:
2332: Arrays.sort(_sortedSystemGroups, new StringComparator());
2333:
2334: // Regular roles
2335:
2336: String customSystemRoles[] = PropsUtil
2337: .getArray(PropsUtil.SYSTEM_ROLES);
2338:
2339: if ((customSystemRoles == null)
2340: || (customSystemRoles.length == 0)) {
2341: _allSystemRoles = RoleImpl.SYSTEM_ROLES;
2342: } else {
2343: _allSystemRoles = ArrayUtil.append(RoleImpl.SYSTEM_ROLES,
2344: customSystemRoles);
2345: }
2346:
2347: _sortedSystemRoles = new String[_allSystemRoles.length];
2348:
2349: System.arraycopy(_allSystemRoles, 0, _sortedSystemRoles, 0,
2350: _allSystemRoles.length);
2351:
2352: Arrays.sort(_sortedSystemRoles, new StringComparator());
2353:
2354: // Community roles
2355:
2356: String customSystemCommunityRoles[] = PropsUtil
2357: .getArray(PropsUtil.SYSTEM_COMMUNITY_ROLES);
2358:
2359: if ((customSystemCommunityRoles == null)
2360: || (customSystemCommunityRoles.length == 0)) {
2361:
2362: _allSystemCommunityRoles = RoleImpl.SYSTEM_COMMUNITY_ROLES;
2363: } else {
2364: _allSystemCommunityRoles = ArrayUtil.append(
2365: RoleImpl.SYSTEM_COMMUNITY_ROLES,
2366: customSystemCommunityRoles);
2367: }
2368:
2369: _sortedSystemCommunityRoles = new String[_allSystemCommunityRoles.length];
2370:
2371: System.arraycopy(_allSystemCommunityRoles, 0,
2372: _sortedSystemCommunityRoles, 0,
2373: _allSystemCommunityRoles.length);
2374:
2375: Arrays
2376: .sort(_sortedSystemCommunityRoles,
2377: new StringComparator());
2378:
2379: // Organization Roles
2380:
2381: String customSystemOrganizationRoles[] = PropsUtil
2382: .getArray(PropsUtil.SYSTEM_ORGANIZATION_ROLES);
2383:
2384: if ((customSystemOrganizationRoles == null)
2385: || (customSystemOrganizationRoles.length == 0)) {
2386:
2387: _allSystemOrganizationRoles = RoleImpl.SYSTEM_ORGANIZATION_ROLES;
2388: } else {
2389: _allSystemOrganizationRoles = ArrayUtil.append(
2390: RoleImpl.SYSTEM_ORGANIZATION_ROLES,
2391: customSystemOrganizationRoles);
2392: }
2393:
2394: _sortedSystemOrganizationRoles = new String[_allSystemOrganizationRoles.length];
2395:
2396: System.arraycopy(_allSystemOrganizationRoles, 0,
2397: _sortedSystemOrganizationRoles, 0,
2398: _allSystemOrganizationRoles.length);
2399:
2400: Arrays.sort(_sortedSystemOrganizationRoles,
2401: new StringComparator());
2402:
2403: // Reserved parameter names
2404:
2405: _reservedParams = CollectionFactory.getHashSet();
2406:
2407: _reservedParams.add("p_l_id");
2408: _reservedParams.add("p_l_reset");
2409: _reservedParams.add("p_p_id");
2410: _reservedParams.add("p_p_action");
2411: _reservedParams.add("p_p_state");
2412: _reservedParams.add("p_p_mode");
2413: _reservedParams.add("p_p_width");
2414: _reservedParams.add("p_p_col_id");
2415: _reservedParams.add("p_p_col_pos");
2416: _reservedParams.add("p_p_col_count");
2417: _reservedParams.add("p_p_static");
2418: }
2419:
2420: private String _getCDNHost() {
2421: return _cdnHost;
2422: }
2423:
2424: private static String _getCurrentURL(HttpServletRequest req) {
2425: StringMaker sm = new StringMaker();
2426:
2427: StringBuffer requestURL = req.getRequestURL();
2428:
2429: if (requestURL != null) {
2430: sm.append(requestURL.toString());
2431: }
2432:
2433: String queryString = req.getQueryString();
2434:
2435: if (Validator.isNull(queryString)) {
2436: return sm.toString();
2437: }
2438:
2439: String portletId = req.getParameter("p_p_id");
2440:
2441: String redirectParam = "redirect";
2442:
2443: if (Validator.isNotNull(portletId)) {
2444: redirectParam = getPortletNamespace(portletId)
2445: + redirectParam;
2446: }
2447:
2448: Map parameterMap = HttpUtil.parameterMapFromString(queryString);
2449:
2450: String[] redirectValues = (String[]) parameterMap
2451: .get(redirectParam);
2452:
2453: if ((redirectValues != null) && (redirectValues.length > 0)) {
2454:
2455: // Prevent the redirect for GET requests from growing indefinitely
2456: // and using up all the available space by remembering only the
2457: // first redirect.
2458:
2459: String redirect = HttpUtil.decodeURL(GetterUtil
2460: .getString(redirectValues[0]));
2461:
2462: int pos = redirect.indexOf(StringPool.QUESTION);
2463:
2464: if (pos != -1) {
2465: String subqueryString = redirect.substring(pos + 1,
2466: redirect.length());
2467:
2468: Map subparameterMap = HttpUtil
2469: .parameterMapFromString(subqueryString);
2470:
2471: String[] subredirectValues = (String[]) subparameterMap
2472: .get(redirectParam);
2473:
2474: if ((subredirectValues != null)
2475: && (subredirectValues.length > 0)) {
2476:
2477: String subredirect = HttpUtil.decodeURL(GetterUtil
2478: .getString(subredirectValues[0]));
2479:
2480: parameterMap.put(redirectParam,
2481: new String[] { subredirect });
2482:
2483: queryString = HttpUtil.parameterMapToString(
2484: parameterMap, false);
2485: }
2486: }
2487: }
2488:
2489: sm.append(StringPool.QUESTION);
2490: sm.append(queryString);
2491:
2492: return sm.toString();
2493: }
2494:
2495: private String _getPathContext() {
2496: return _pathContext;
2497: }
2498:
2499: private String _getPathFriendlyURLPrivateGroup() {
2500: return _pathFriendlyURLPrivateGroup;
2501: }
2502:
2503: private String _getPathFriendlyURLPrivateUser() {
2504: return _pathFriendlyURLPrivateUser;
2505: }
2506:
2507: private String _getPathFriendlyURLPublic() {
2508: return _pathFriendlyURLPublic;
2509: }
2510:
2511: private String _getPathImage() {
2512: return _pathImage;
2513: }
2514:
2515: private String _getPathMain() {
2516: return _pathMain;
2517: }
2518:
2519: private String[] _getSystemCommunityRoles() {
2520: return _allSystemCommunityRoles;
2521: }
2522:
2523: private String[] _getSystemOrganizationRoles() {
2524: return _allSystemOrganizationRoles;
2525: }
2526:
2527: private String[] _getSystemGroups() {
2528: return _allSystemGroups;
2529: }
2530:
2531: private String[] _getSystemRoles() {
2532: return _allSystemRoles;
2533: }
2534:
2535: private boolean _isSystemGroup(String groupName) {
2536: if (groupName == null) {
2537: return false;
2538: }
2539:
2540: groupName = groupName.trim();
2541:
2542: int pos = Arrays.binarySearch(_sortedSystemGroups, groupName,
2543: new StringComparator());
2544:
2545: if (pos >= 0) {
2546: return true;
2547: } else {
2548: return false;
2549: }
2550: }
2551:
2552: private boolean _isSystemRole(String roleName) {
2553: if (roleName == null) {
2554: return false;
2555: }
2556:
2557: roleName = roleName.trim();
2558:
2559: int pos = Arrays.binarySearch(_sortedSystemRoles, roleName,
2560: new StringComparator());
2561:
2562: if (pos >= 0) {
2563: return true;
2564: } else {
2565: pos = Arrays.binarySearch(_sortedSystemCommunityRoles,
2566: roleName, new StringComparator());
2567:
2568: if (pos >= 0) {
2569: return true;
2570: } else {
2571: pos = Arrays.binarySearch(
2572: _sortedSystemOrganizationRoles, roleName,
2573: new StringComparator());
2574:
2575: if (pos >= 0) {
2576: return true;
2577: }
2578: }
2579: }
2580:
2581: return false;
2582: }
2583:
2584: private static final String _JSESSIONID = ";jsessionid=";
2585:
2586: private static final String _METHOD_GET = "get";
2587:
2588: private static final String _METHOD_POST = "post";
2589:
2590: private static Log _log = LogFactory.getLog(PortalUtil.class);
2591:
2592: private static PortalUtil _instance = new PortalUtil();
2593:
2594: private String _computerName;
2595: private String _portalLibDir;
2596: private String _cdnHost;
2597: private String _pathContext;
2598: private String _pathFriendlyURLPrivateGroup;
2599: private String _pathFriendlyURLPrivateUser;
2600: private String _pathFriendlyURLPublic;
2601: private String _pathImage;
2602: private String _pathMain;
2603: private String[] _allSystemCommunityRoles;
2604: private String[] _allSystemGroups;
2605: private String[] _allSystemOrganizationRoles;
2606: private String[] _allSystemRoles;
2607: private String[] _sortedSystemCommunityRoles;
2608: private String[] _sortedSystemGroups;
2609: private String[] _sortedSystemOrganizationRoles;
2610: private String[] _sortedSystemRoles;
2611: private Set _reservedParams;
2612:
2613: }
|