1   /**
2    * Copyright (c) 2000-2010 Liferay, Inc. All rights reserved.
3    *
4    * This library is free software; you can redistribute it and/or modify it under
5    * the terms of the GNU Lesser General Public License as published by the Free
6    * Software Foundation; either version 2.1 of the License, or (at your option)
7    * any later version.
8    *
9    * This library is distributed in the hope that it will be useful, but WITHOUT
10   * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
11   * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
12   * details.
13   */
14  
15  package com.liferay.portal.util;
16  
17  import com.liferay.portal.NoSuchCompanyException;
18  import com.liferay.portal.NoSuchLayoutException;
19  import com.liferay.portal.NoSuchUserException;
20  import com.liferay.portal.kernel.bean.BeanPropertiesUtil;
21  import com.liferay.portal.kernel.configuration.Filter;
22  import com.liferay.portal.kernel.dao.db.DB;
23  import com.liferay.portal.kernel.dao.db.DBFactoryUtil;
24  import com.liferay.portal.kernel.exception.PortalException;
25  import com.liferay.portal.kernel.exception.SystemException;
26  import com.liferay.portal.kernel.language.LanguageUtil;
27  import com.liferay.portal.kernel.log.Log;
28  import com.liferay.portal.kernel.log.LogFactoryUtil;
29  import com.liferay.portal.kernel.portlet.FriendlyURLMapper;
30  import com.liferay.portal.kernel.portlet.FriendlyURLMapperThreadLocal;
31  import com.liferay.portal.kernel.portlet.LiferayPortletMode;
32  import com.liferay.portal.kernel.portlet.PortletBag;
33  import com.liferay.portal.kernel.portlet.PortletBagPool;
34  import com.liferay.portal.kernel.servlet.BrowserSnifferUtil;
35  import com.liferay.portal.kernel.servlet.HttpHeaders;
36  import com.liferay.portal.kernel.servlet.HttpMethods;
37  import com.liferay.portal.kernel.servlet.ServletContextUtil;
38  import com.liferay.portal.kernel.servlet.SessionErrors;
39  import com.liferay.portal.kernel.servlet.StringServletResponse;
40  import com.liferay.portal.kernel.servlet.WebDirDetector;
41  import com.liferay.portal.kernel.upload.UploadPortletRequest;
42  import com.liferay.portal.kernel.upload.UploadServletRequest;
43  import com.liferay.portal.kernel.util.ArrayUtil;
44  import com.liferay.portal.kernel.util.Base64;
45  import com.liferay.portal.kernel.util.CalendarFactoryUtil;
46  import com.liferay.portal.kernel.util.CharPool;
47  import com.liferay.portal.kernel.util.ClassUtil;
48  import com.liferay.portal.kernel.util.ContentTypes;
49  import com.liferay.portal.kernel.util.GetterUtil;
50  import com.liferay.portal.kernel.util.Http;
51  import com.liferay.portal.kernel.util.HttpUtil;
52  import com.liferay.portal.kernel.util.InstancePool;
53  import com.liferay.portal.kernel.util.JavaConstants;
54  import com.liferay.portal.kernel.util.KeyValuePair;
55  import com.liferay.portal.kernel.util.LocaleUtil;
56  import com.liferay.portal.kernel.util.ParamUtil;
57  import com.liferay.portal.kernel.util.PropsKeys;
58  import com.liferay.portal.kernel.util.ReleaseInfo;
59  import com.liferay.portal.kernel.util.StringBundler;
60  import com.liferay.portal.kernel.util.StringComparator;
61  import com.liferay.portal.kernel.util.StringPool;
62  import com.liferay.portal.kernel.util.StringUtil;
63  import com.liferay.portal.kernel.util.UnicodeProperties;
64  import com.liferay.portal.kernel.util.Validator;
65  import com.liferay.portal.kernel.xml.QName;
66  import com.liferay.portal.model.BaseModel;
67  import com.liferay.portal.model.ClassName;
68  import com.liferay.portal.model.ColorScheme;
69  import com.liferay.portal.model.Company;
70  import com.liferay.portal.model.CompanyConstants;
71  import com.liferay.portal.model.Group;
72  import com.liferay.portal.model.GroupConstants;
73  import com.liferay.portal.model.Layout;
74  import com.liferay.portal.model.LayoutConstants;
75  import com.liferay.portal.model.LayoutSet;
76  import com.liferay.portal.model.LayoutTypePortlet;
77  import com.liferay.portal.model.Organization;
78  import com.liferay.portal.model.Portlet;
79  import com.liferay.portal.model.PortletApp;
80  import com.liferay.portal.model.PublicRenderParameter;
81  import com.liferay.portal.model.Resource;
82  import com.liferay.portal.model.ResourceCode;
83  import com.liferay.portal.model.ResourcePermission;
84  import com.liferay.portal.model.Role;
85  import com.liferay.portal.model.RoleConstants;
86  import com.liferay.portal.model.Theme;
87  import com.liferay.portal.model.User;
88  import com.liferay.portal.model.UserGroup;
89  import com.liferay.portal.plugin.PluginPackageUtil;
90  import com.liferay.portal.security.auth.PrincipalException;
91  import com.liferay.portal.security.permission.ActionKeys;
92  import com.liferay.portal.security.permission.PermissionChecker;
93  import com.liferay.portal.security.permission.PermissionCheckerFactoryUtil;
94  import com.liferay.portal.service.ClassNameLocalServiceUtil;
95  import com.liferay.portal.service.CompanyLocalServiceUtil;
96  import com.liferay.portal.service.GroupLocalServiceUtil;
97  import com.liferay.portal.service.LayoutLocalServiceUtil;
98  import com.liferay.portal.service.PortletLocalServiceUtil;
99  import com.liferay.portal.service.ResourceCodeLocalServiceUtil;
100 import com.liferay.portal.service.UserLocalServiceUtil;
101 import com.liferay.portal.service.UserServiceUtil;
102 import com.liferay.portal.service.permission.PortletPermissionUtil;
103 import com.liferay.portal.service.permission.UserPermissionUtil;
104 import com.liferay.portal.servlet.filters.i18n.I18nFilter;
105 import com.liferay.portal.struts.StrutsUtil;
106 import com.liferay.portal.theme.ThemeDisplay;
107 import com.liferay.portal.upload.UploadPortletRequestImpl;
108 import com.liferay.portal.upload.UploadServletRequestImpl;
109 import com.liferay.portal.util.comparator.PortletControlPanelWeightComparator;
110 import com.liferay.portlet.ActionResponseImpl;
111 import com.liferay.portlet.ControlPanelEntry;
112 import com.liferay.portlet.DefaultControlPanelEntryFactory;
113 import com.liferay.portlet.PortletConfigFactory;
114 import com.liferay.portlet.PortletConfigImpl;
115 import com.liferay.portlet.PortletPreferencesFactoryUtil;
116 import com.liferay.portlet.PortletPreferencesImpl;
117 import com.liferay.portlet.PortletPreferencesWrapper;
118 import com.liferay.portlet.PortletQNameUtil;
119 import com.liferay.portlet.PortletRequestImpl;
120 import com.liferay.portlet.PortletResponseImpl;
121 import com.liferay.portlet.PortletURLImpl;
122 import com.liferay.portlet.RenderRequestImpl;
123 import com.liferay.portlet.RenderResponseImpl;
124 import com.liferay.portlet.UserAttributes;
125 import com.liferay.portlet.blogs.model.BlogsEntry;
126 import com.liferay.portlet.bookmarks.model.BookmarksEntry;
127 import com.liferay.portlet.calendar.model.CalEvent;
128 import com.liferay.portlet.documentlibrary.model.DLFileEntry;
129 import com.liferay.portlet.expando.action.EditExpandoAction;
130 import com.liferay.portlet.expando.model.ExpandoBridge;
131 import com.liferay.portlet.imagegallery.model.IGImage;
132 import com.liferay.portlet.messageboards.model.MBMessage;
133 import com.liferay.portlet.social.util.FacebookUtil;
134 import com.liferay.portlet.wiki.model.WikiPage;
135 import com.liferay.util.Encryptor;
136 import com.liferay.util.JS;
137 import com.liferay.util.UniqueList;
138 import com.liferay.util.servlet.DynamicServletRequest;
139 
140 import java.io.File;
141 import java.io.IOException;
142 import java.io.Serializable;
143 
144 import java.lang.reflect.Method;
145 
146 import java.net.InetAddress;
147 import java.net.UnknownHostException;
148 
149 import java.util.ArrayList;
150 import java.util.Arrays;
151 import java.util.Calendar;
152 import java.util.Date;
153 import java.util.Enumeration;
154 import java.util.HashMap;
155 import java.util.HashSet;
156 import java.util.Iterator;
157 import java.util.List;
158 import java.util.Locale;
159 import java.util.Map;
160 import java.util.Properties;
161 import java.util.ResourceBundle;
162 import java.util.Set;
163 import java.util.TimeZone;
164 import java.util.TreeSet;
165 import java.util.concurrent.ConcurrentHashMap;
166 
167 import javax.portlet.ActionRequest;
168 import javax.portlet.ActionResponse;
169 import javax.portlet.PortletConfig;
170 import javax.portlet.PortletMode;
171 import javax.portlet.PortletPreferences;
172 import javax.portlet.PortletRequest;
173 import javax.portlet.PortletResponse;
174 import javax.portlet.PortletURL;
175 import javax.portlet.PreferencesValidator;
176 import javax.portlet.RenderRequest;
177 import javax.portlet.ValidatorException;
178 import javax.portlet.WindowState;
179 import javax.portlet.filter.PortletRequestWrapper;
180 import javax.portlet.filter.PortletResponseWrapper;
181 
182 import javax.servlet.RequestDispatcher;
183 import javax.servlet.ServletContext;
184 import javax.servlet.ServletException;
185 import javax.servlet.http.HttpServletRequest;
186 import javax.servlet.http.HttpServletRequestWrapper;
187 import javax.servlet.http.HttpServletResponse;
188 import javax.servlet.http.HttpSession;
189 import javax.servlet.jsp.PageContext;
190 
191 import org.apache.struts.Globals;
192 
193 /**
194  * <a href="PortalImpl.java.html"><b><i>View Source</i></b></a>
195  *
196  * @author Brian Wing Shun Chan
197  * @author Brian Myunghun Kim
198  * @author Jorge Ferrer
199  * @author Raymond Augé
200  * @author Eduardo Lundgren
201  * @author Wesley Gong
202  */
203 public class PortalImpl implements Portal {
204 
205     public PortalImpl() {
206 
207         // Computer name
208 
209         _computerName = System.getProperty("env.COMPUTERNAME");
210 
211         if (Validator.isNull(_computerName)) {
212             _computerName = System.getProperty("env.HOST");
213         }
214 
215         if (Validator.isNull(_computerName)) {
216             _computerName = System.getProperty("env.HOSTNAME");
217         }
218 
219         if (Validator.isNull(_computerName)) {
220             try {
221                 _computerName = InetAddress.getLocalHost().getHostName();
222             }
223             catch (UnknownHostException uhe) {
224             }
225         }
226 
227         try {
228             _computerAddress = InetAddress.getByName(
229                 _computerName).getHostAddress();
230         }
231         catch (UnknownHostException uhe) {
232         }
233 
234         if (Validator.isNull(_computerAddress)) {
235             try {
236                 _computerAddress = InetAddress.getLocalHost().getHostAddress();
237             }
238             catch (UnknownHostException uhe) {
239             }
240         }
241 
242         // Global lib directory
243 
244         _globalLibDir = ClassUtil.getParentPath(
245             ReleaseInfo.class.getClassLoader(), ReleaseInfo.class.getName());
246 
247         int pos = _globalLibDir.lastIndexOf(".jar!");
248 
249         pos = _globalLibDir.lastIndexOf(StringPool.SLASH, pos);
250 
251         _globalLibDir = _globalLibDir.substring(0, pos + 1);
252 
253         if (_log.isInfoEnabled()) {
254             _log.info("Global lib directory " + _globalLibDir);
255         }
256 
257         // Portal lib directory
258 
259         ClassLoader classLoader = getClass().getClassLoader();
260 
261         _portalLibDir = WebDirDetector.getLibDir(classLoader);
262 
263         String portalLibDir = System.getProperty("liferay.lib.portal.dir");
264 
265         if (portalLibDir != null) {
266             if (!portalLibDir.endsWith(StringPool.SLASH)) {
267                 portalLibDir += StringPool.SLASH;
268             }
269 
270             _portalLibDir = portalLibDir;
271         }
272 
273         if (_log.isInfoEnabled()) {
274             _log.info("Portal lib directory " + _portalLibDir);
275         }
276 
277         _portalWebDir = WebDirDetector.getRootDir(_portalLibDir);
278 
279         if (_log.isDebugEnabled()) {
280             _log.debug("Portal web directory " + _portalWebDir);
281         }
282 
283         // CDN host
284 
285         _cdnHostHttp = PropsValues.CDN_HOST_HTTP;
286 
287         if (_cdnHostHttp.startsWith("${")) {
288             _cdnHostHttp = StringPool.BLANK;
289         }
290 
291         _cdnHostHttps = PropsValues.CDN_HOST_HTTPS;
292 
293         if (_cdnHostHttps.startsWith("${")) {
294             _cdnHostHttps = StringPool.BLANK;
295         }
296 
297         // Paths
298 
299         _pathContext = PropsUtil.get(PropsKeys.PORTAL_CTX);
300 
301         if (_pathContext.equals(StringPool.SLASH)) {
302             _pathContext = StringPool.BLANK;
303         }
304 
305         _pathFriendlyURLPrivateGroup =
306             _pathContext + _PRIVATE_GROUP_SERVLET_MAPPING;
307         _pathFriendlyURLPrivateUser =
308             _pathContext + _PRIVATE_USER_SERVLET_MAPPING;
309         _pathFriendlyURLPublic = _pathContext + _PUBLIC_GROUP_SERVLET_MAPPING;
310         _pathImage = _pathContext + PATH_IMAGE;
311         _pathMain = _pathContext + PATH_MAIN;
312 
313         // Groups
314 
315         String customSystemGroups[] =
316             PropsUtil.getArray(PropsKeys.SYSTEM_GROUPS);
317 
318         if ((customSystemGroups == null) || (customSystemGroups.length == 0)) {
319             _allSystemGroups = GroupConstants.SYSTEM_GROUPS;
320         }
321         else {
322             _allSystemGroups = ArrayUtil.append(
323                 GroupConstants.SYSTEM_GROUPS, customSystemGroups);
324         }
325 
326         _sortedSystemGroups = new String[_allSystemGroups.length];
327 
328         System.arraycopy(
329             _allSystemGroups, 0, _sortedSystemGroups, 0,
330             _allSystemGroups.length);
331 
332         Arrays.sort(_sortedSystemGroups, new StringComparator());
333 
334         // Regular roles
335 
336         String customSystemRoles[] = PropsUtil.getArray(PropsKeys.SYSTEM_ROLES);
337 
338         if ((customSystemRoles == null) || (customSystemRoles.length == 0)) {
339             _allSystemRoles = RoleConstants.SYSTEM_ROLES;
340         }
341         else {
342             _allSystemRoles = ArrayUtil.append(
343                 RoleConstants.SYSTEM_ROLES, customSystemRoles);
344         }
345 
346         _sortedSystemRoles = new String[_allSystemRoles.length];
347 
348         System.arraycopy(
349             _allSystemRoles, 0, _sortedSystemRoles, 0, _allSystemRoles.length);
350 
351         Arrays.sort(_sortedSystemRoles, new StringComparator());
352 
353         // Community roles
354 
355         String customSystemCommunityRoles[] =
356             PropsUtil.getArray(PropsKeys.SYSTEM_COMMUNITY_ROLES);
357 
358         if ((customSystemCommunityRoles == null) ||
359             (customSystemCommunityRoles.length == 0)) {
360 
361             _allSystemCommunityRoles = RoleConstants.SYSTEM_COMMUNITY_ROLES;
362         }
363         else {
364             _allSystemCommunityRoles = ArrayUtil.append(
365                 RoleConstants.SYSTEM_COMMUNITY_ROLES,
366                 customSystemCommunityRoles);
367         }
368 
369         _sortedSystemCommunityRoles =
370             new String[_allSystemCommunityRoles.length];
371 
372         System.arraycopy(
373             _allSystemCommunityRoles, 0, _sortedSystemCommunityRoles, 0,
374                 _allSystemCommunityRoles.length);
375 
376         Arrays.sort(_sortedSystemCommunityRoles, new StringComparator());
377 
378         // Organization Roles
379 
380         String customSystemOrganizationRoles[] =
381             PropsUtil.getArray(PropsKeys.SYSTEM_ORGANIZATION_ROLES);
382 
383         if ((customSystemOrganizationRoles == null) ||
384             (customSystemOrganizationRoles.length == 0)) {
385 
386             _allSystemOrganizationRoles =
387                 RoleConstants.SYSTEM_ORGANIZATION_ROLES;
388         }
389         else {
390             _allSystemOrganizationRoles = ArrayUtil.append(
391                 RoleConstants.SYSTEM_ORGANIZATION_ROLES,
392                 customSystemOrganizationRoles);
393         }
394 
395         _sortedSystemOrganizationRoles =
396             new String[_allSystemOrganizationRoles.length];
397 
398         System.arraycopy(
399             _allSystemOrganizationRoles, 0, _sortedSystemOrganizationRoles, 0,
400                 _allSystemOrganizationRoles.length);
401 
402         Arrays.sort(_sortedSystemOrganizationRoles, new StringComparator());
403 
404         // Reserved parameter names
405 
406         _reservedParams = new HashSet<String>();
407 
408         _reservedParams.add("p_l_id");
409         _reservedParams.add("p_l_reset");
410         _reservedParams.add("p_p_id");
411         _reservedParams.add("p_p_lifecycle");
412         _reservedParams.add("p_p_url_type");
413         _reservedParams.add("p_p_state");
414         _reservedParams.add("p_p_mode");
415         _reservedParams.add("p_p_resource_id");
416         _reservedParams.add("p_p_cacheability");
417         _reservedParams.add("p_p_width");
418         _reservedParams.add("p_p_col_id");
419         _reservedParams.add("p_p_col_pos");
420         _reservedParams.add("p_p_col_count");
421         _reservedParams.add("p_p_static");
422         _reservedParams.add("p_p_static");
423         _reservedParams.add("p_p_isolated");
424         _reservedParams.add("saveLastPath");
425     }
426 
427     /**
428      * Adds the description for a page. This appends to the existing page
429      * description.
430      */
431     public void addPageDescription(
432         String description, HttpServletRequest request) {
433 
434         String requestDescription = (String)request.getAttribute(
435             WebKeys.PAGE_DESCRIPTION);
436 
437         if (requestDescription != null) {
438             description = requestDescription + StringPool.SPACE + description;
439         }
440 
441         request.setAttribute(WebKeys.PAGE_DESCRIPTION, description);
442     }
443 
444     /**
445      * Adds the keywords for a page. This appends to the existing page keywords.
446      */
447     public void addPageKeywords(String keywords, HttpServletRequest request) {
448         List<String> requestKeywords = (List<String>)request.getAttribute(
449             WebKeys.PAGE_KEYWORDS);
450 
451         if (requestKeywords == null) {
452             requestKeywords = new UniqueList<String>();
453         }
454 
455         String[] keywordsArray = StringUtil.split(keywords);
456 
457         for (String keyword : keywordsArray) {
458             if (!requestKeywords.contains(keyword.toLowerCase())) {
459                 requestKeywords.add(keyword.toLowerCase());
460             }
461         }
462 
463         request.setAttribute(WebKeys.PAGE_KEYWORDS, requestKeywords);
464     }
465 
466     /**
467      * Adds the subtitle for a page. This appends to the existing page subtitle.
468      */
469     public void addPageSubtitle(String subtitle, HttpServletRequest request) {
470         String requestSubtitle = (String)request.getAttribute(
471             WebKeys.PAGE_SUBTITLE);
472 
473         if (requestSubtitle != null) {
474             subtitle = requestSubtitle + StringPool.SPACE + subtitle;
475         }
476 
477         request.setAttribute(WebKeys.PAGE_SUBTITLE, subtitle);
478     }
479 
480     /**
481      * Adds the whole title for a page. This appends to the existing page whole
482      * title.
483      */
484     public void addPageTitle(String title, HttpServletRequest request) {
485         String requestTitle = (String)request.getAttribute(WebKeys.PAGE_TITLE);
486 
487         if (requestTitle != null) {
488             title = requestTitle + StringPool.SPACE + title;
489         }
490 
491         request.setAttribute(WebKeys.PAGE_TITLE, title);
492     }
493 
494     public void addPortletBreadcrumbEntry(
495         HttpServletRequest request, String title, String url) {
496 
497         List<KeyValuePair> portletBreadcrumbList =
498             (List<KeyValuePair>)request.getAttribute(
499                 WebKeys.PORTLET_BREADCRUMB_MAP);
500 
501         if (portletBreadcrumbList == null) {
502             portletBreadcrumbList = new ArrayList<KeyValuePair>();
503 
504             request.setAttribute(
505                 WebKeys.PORTLET_BREADCRUMB_MAP, portletBreadcrumbList);
506         }
507 
508         portletBreadcrumbList.add(new KeyValuePair(title, url));
509     }
510 
511     public void clearRequestParameters(RenderRequest renderRequest) {
512 
513         // Clear the render parameters if they were set during processAction
514 
515         ThemeDisplay themeDisplay = (ThemeDisplay)renderRequest.getAttribute(
516             WebKeys.THEME_DISPLAY);
517 
518         if (themeDisplay.isLifecycleAction()) {
519             ((RenderRequestImpl)renderRequest).getRenderParameters().clear();
520         }
521     }
522 
523     public void copyRequestParameters(
524         ActionRequest actionRequest, ActionResponse actionResponse) {
525 
526         try {
527             ActionResponseImpl actionResponseImpl =
528                 (ActionResponseImpl)actionResponse;
529 
530             Map<String, String[]> renderParameters =
531                 actionResponseImpl.getRenderParameterMap();
532 
533             actionResponse.setRenderParameter("p_p_lifecycle", "1");
534 
535             Enumeration<String> enu = actionRequest.getParameterNames();
536 
537             while (enu.hasMoreElements()) {
538                 String param = enu.nextElement();
539                 String[] values = actionRequest.getParameterValues(param);
540 
541                 if (renderParameters.get(
542                         actionResponseImpl.getNamespace() + param) == null) {
543 
544                     actionResponse.setRenderParameter(param, values);
545                 }
546             }
547         }
548         catch (IllegalStateException ise) {
549 
550             // This should only happen if the developer called
551             // sendRedirect of javax.portlet.ActionResponse
552 
553         }
554     }
555 
556     public String escapeRedirect(String url) {
557         if (Validator.isNull(url) || !HttpUtil.hasDomain(url)) {
558             return url;
559         }
560 
561         try {
562             String securityMode = PropsValues.REDIRECT_URL_SECURITY_MODE;
563 
564             String domain = StringUtil.split(
565                 HttpUtil.getDomain(url), StringPool.COLON)[0];
566 
567             if (securityMode.equals("domain")) {
568                 String[] allowedDomains =
569                     PropsValues.REDIRECT_URL_DOMAINS_ALLOWED;
570 
571                 if ((allowedDomains.length > 0) &&
572                     !ArrayUtil.contains(allowedDomains, domain)) {
573 
574                     url = null;
575                 }
576             }
577             else if (securityMode.equals("ip")) {
578                 String[] allowedIps = PropsValues.REDIRECT_URL_IPS_ALLOWED;
579 
580                 InetAddress inetAddress = InetAddress.getByName(domain);
581 
582                 if ((allowedIps.length > 0) &&
583                     !ArrayUtil.contains(
584                         allowedIps, inetAddress.getHostAddress())) {
585 
586                     String serverIp = getComputerAddress();
587 
588                     if (!serverIp.equals(inetAddress.getHostAddress()) ||
589                         !ArrayUtil.contains(allowedIps, "SERVER_IP")) {
590 
591                         url = null;
592                     }
593                 }
594             }
595         }
596         catch (UnknownHostException uhe) {
597             url = null;
598         }
599 
600         return url;
601     }
602 
603     public BaseModel<?> getBaseModel(Resource resource)
604         throws PortalException, SystemException {
605 
606         ResourceCode resourceCode =
607             ResourceCodeLocalServiceUtil.getResourceCode(resource.getCodeId());
608 
609         String modelName = resourceCode.getName();
610         String primKey = resource.getPrimKey();
611 
612         return getBaseModel(modelName, primKey);
613     }
614 
615     public BaseModel<?> getBaseModel(ResourcePermission resourcePermission)
616         throws PortalException, SystemException {
617 
618         String modelName = resourcePermission.getName();
619         String primKey = resourcePermission.getPrimKey();
620 
621         return getBaseModel(modelName, primKey);
622     }
623 
624     public BaseModel<?> getBaseModel(String modelName, String primKey)
625         throws PortalException, SystemException {
626 
627         if (!modelName.contains(".model.")) {
628             return null;
629         }
630 
631         String[] parts = StringUtil.split(modelName, StringPool.PERIOD);
632 
633         if ((parts.length <= 2) || !parts[parts.length - 2].equals("model")) {
634             return null;
635         }
636 
637         parts[parts.length - 2] = "service";
638 
639         String serviceName =
640             StringUtil.merge(parts, StringPool.PERIOD) + "LocalServiceUtil";
641         String methodName = "get" + parts[parts.length - 1];
642 
643         Method method = null;
644 
645         try {
646             Class<?> serviceUtil = Class.forName(serviceName);
647 
648             if (Validator.isNumber(primKey)) {
649                 method = serviceUtil.getMethod(
650                     methodName, new Class[] {Long.TYPE});
651 
652                 return (BaseModel<?>)method.invoke(null, new Long(primKey));
653             }
654             else {
655                 method = serviceUtil.getMethod(
656                     methodName, new Class[] {String.class});
657 
658                 return (BaseModel<?>)method.invoke(null, primKey);
659             }
660         }
661         catch (Exception e) {
662             Throwable cause = e.getCause();
663 
664             if (cause instanceof PortalException) {
665                 throw (PortalException)cause;
666             }
667             else if (cause instanceof SystemException) {
668                 throw (SystemException)cause;
669             }
670             else {
671                 throw new SystemException(cause);
672             }
673         }
674     }
675 
676     public long getBasicAuthUserId(HttpServletRequest request)
677         throws PortalException, SystemException {
678 
679         long companyId = PortalInstances.getCompanyId(request);
680 
681         return getBasicAuthUserId(request, companyId);
682     }
683 
684     public long getBasicAuthUserId(HttpServletRequest request, long companyId)
685         throws PortalException, SystemException {
686 
687         long userId = 0;
688 
689         String authorizationHeader = request.getHeader(
690             HttpHeaders.AUTHORIZATION);
691 
692         if (Validator.isNull(authorizationHeader)) {
693             return userId;
694         }
695 
696         String[] authorizationArray = authorizationHeader.split("\\s+");
697 
698         String authorization = authorizationArray[0];
699         String credentials = new String(Base64.decode(authorizationArray[1]));
700 
701         if (!authorization.equalsIgnoreCase(HttpServletRequest.BASIC_AUTH)) {
702             return userId;
703         }
704 
705         String[] loginAndPassword = StringUtil.split(
706             credentials, StringPool.COLON);
707 
708         String login = loginAndPassword[0].trim();
709 
710         String password = null;
711 
712         if (loginAndPassword.length > 1) {
713             password = loginAndPassword[1].trim();
714         }
715 
716         // Strip @uid and @sn for backwards compatibility
717 
718         if (login.endsWith("@uid")) {
719             int pos = login.indexOf("@uid");
720 
721             login = login.substring(0, pos);
722         }
723         else if (login.endsWith("@sn")) {
724             int pos = login.indexOf("@sn");
725 
726             login = login.substring(0, pos);
727         }
728 
729         // Try every authentication type
730 
731         userId = UserLocalServiceUtil.authenticateForBasic(
732             companyId, CompanyConstants.AUTH_TYPE_EA, login, password);
733 
734         if (userId > 0) {
735             return userId;
736         }
737 
738         userId = UserLocalServiceUtil.authenticateForBasic(
739             companyId, CompanyConstants.AUTH_TYPE_SN, login, password);
740 
741         if (userId > 0) {
742             return userId;
743         }
744 
745         userId = UserLocalServiceUtil.authenticateForBasic(
746             companyId, CompanyConstants.AUTH_TYPE_ID, login, password);
747 
748         return userId;
749     }
750 
751     /**
752      * @deprecated {@link #getCDNHost(boolean)}
753      */
754     public String getCDNHost() {
755         return getCDNHostHttp();
756     }
757 
758     public String getCDNHost(boolean secure) {
759         if (secure) {
760             return getCDNHostHttps();
761         }
762         else {
763             return getCDNHostHttp();
764         }
765     }
766 
767     public String getCDNHostHttp() {
768         return _cdnHostHttp;
769     }
770 
771     public String getCDNHostHttps() {
772         return _cdnHostHttps;
773     }
774 
775     public String getClassName(long classNameId) {
776         try {
777             ClassName className = ClassNameLocalServiceUtil.getClassName(
778                 classNameId);
779 
780             return className.getValue();
781         }
782         catch (Exception e) {
783             throw new RuntimeException(
784                 "Unable to get class name from id " + classNameId);
785         }
786     }
787 
788     public long getClassNameId(Class<?> classObj) {
789         return ClassNameLocalServiceUtil.getClassNameId(classObj);
790     }
791 
792     public long getClassNameId(String value) {
793         return ClassNameLocalServiceUtil.getClassNameId(value);
794     }
795 
796     public String getClassNamePortletId(String className) {
797         String portletId = StringPool.BLANK;
798 
799         if (className.startsWith("com.liferay.portlet.blogs")) {
800             portletId = PortletKeys.BLOGS;
801         }
802         else if (className.startsWith("com.liferay.portlet.bookmarks")) {
803             portletId = PortletKeys.BOOKMARKS;
804         }
805         else if (className.startsWith("com.liferay.portlet.calendar")) {
806             portletId = PortletKeys.CALENDAR;
807         }
808         else if (className.startsWith("com.liferay.portlet.documentlibrary")) {
809             portletId = PortletKeys.DOCUMENT_LIBRARY;
810         }
811         else if (className.startsWith("com.liferay.portlet.imagegallery")) {
812             portletId = PortletKeys.IMAGE_GALLERY;
813         }
814         else if (className.startsWith("com.liferay.portlet.journal")) {
815             portletId = PortletKeys.JOURNAL;
816         }
817         else if (className.startsWith("com.liferay.portlet.messageboards")) {
818             portletId = PortletKeys.MESSAGE_BOARDS;
819         }
820         else if (className.startsWith("com.liferay.portlet.wiki")) {
821             portletId = PortletKeys.WIKI;
822         }
823 
824         return portletId;
825     }
826 
827     public String getCommunityLoginURL(ThemeDisplay themeDisplay)
828         throws PortalException, SystemException {
829 
830         if (Validator.isNull(PropsValues.AUTH_LOGIN_COMMUNITY_URL)) {
831             return null;
832         }
833 
834         for (Layout layout : themeDisplay.getLayouts()) {
835             if (layout.getFriendlyURL().equals(
836                     PropsValues.AUTH_LOGIN_COMMUNITY_URL)) {
837 
838                 if (themeDisplay.getLayout() != null) {
839                     String layoutSetFriendlyURL = getLayoutSetFriendlyURL(
840                         themeDisplay.getLayout().getLayoutSet(), themeDisplay);
841 
842                     return layoutSetFriendlyURL +
843                         PropsValues.AUTH_LOGIN_COMMUNITY_URL;
844                 }
845 
846                 break;
847             }
848         }
849 
850         return null;
851     }
852 
853     public String[] getCommunityPermissions(HttpServletRequest request) {
854         return request.getParameterValues("communityPermissions");
855     }
856 
857     public String[] getCommunityPermissions(PortletRequest portletRequest) {
858         return portletRequest.getParameterValues("communityPermissions");
859     }
860 
861     public Company getCompany(HttpServletRequest request)
862         throws PortalException, SystemException {
863 
864         long companyId = getCompanyId(request);
865 
866         if (companyId <= 0) {
867             return null;
868         }
869 
870         Company company = (Company)request.getAttribute(WebKeys.COMPANY);
871 
872         if (company == null) {
873 
874             // LEP-5994
875 
876             try {
877                 company = CompanyLocalServiceUtil.getCompanyById(companyId);
878             }
879             catch (NoSuchCompanyException nsce) {
880                 company = CompanyLocalServiceUtil.getCompanyById(
881                     PortalInstances.getDefaultCompanyId());
882             }
883 
884             request.setAttribute(WebKeys.COMPANY, company);
885         }
886 
887         return company;
888     }
889 
890     public Company getCompany(PortletRequest portletRequest)
891         throws PortalException, SystemException {
892 
893         return getCompany(getHttpServletRequest(portletRequest));
894     }
895 
896     public long getCompanyId(HttpServletRequest request) {
897         return PortalInstances.getCompanyId(request);
898     }
899 
900     public long getCompanyId(PortletRequest portletRequest) {
901         return getCompanyId(getHttpServletRequest(portletRequest));
902     }
903 
904     public long[] getCompanyIds() {
905         return PortalInstances.getCompanyIds();
906     }
907 
908     public String getComputerAddress() {
909         return _computerAddress;
910     }
911 
912     public String getComputerName() {
913         return _computerName;
914     }
915 
916     public String getControlPanelCategory(
917             String portletId, ThemeDisplay themeDisplay)
918         throws SystemException {
919 
920         for (String category : PortletCategoryKeys.ALL) {
921             List<Portlet> portlets = getControlPanelPortlets(
922                 category, themeDisplay);
923 
924             for (Portlet portlet : portlets) {
925                 if (portlet.getPortletId().equals(portletId)) {
926                     return category;
927                 }
928             }
929         }
930 
931         return StringPool.BLANK;
932     }
933 
934     public String getControlPanelFullURL(
935             long scopeGroupId, String ppid, Map<String, String[]> params)
936         throws PortalException, SystemException {
937 
938         StringBundler sb = new StringBundler(6);
939 
940         Group group = GroupLocalServiceUtil.getGroup(scopeGroupId);
941 
942         Company company = CompanyLocalServiceUtil.getCompany(
943             group.getCompanyId());
944 
945         sb.append(
946             getPortalURL(company.getVirtualHost(), getPortalPort(), false));
947         sb.append(PortalUtil.getPathFriendlyURLPrivateGroup());
948         sb.append(GroupConstants.CONTROL_PANEL_FRIENDLY_URL);
949         sb.append(PropsValues.CONTROL_PANEL_LAYOUT_FRIENDLY_URL);
950 
951         if (params != null) {
952             params = new HashMap<String, String[]>(params);
953         }
954         else {
955             params = new HashMap<String, String[]>();
956         }
957 
958         params.put("p_p_id", new String[] {ppid});
959         params.put("p_p_lifecycle", new String[] {"0"});
960         params.put(
961             "p_p_state", new String[] {WindowState.MAXIMIZED.toString()});
962         params.put("p_p_mode", new String[] {PortletMode.VIEW.toString()});
963 
964         sb.append(HttpUtil.parameterMapToString(params, true));
965 
966         return sb.toString();
967     }
968 
969     public List<Portlet> getControlPanelPortlets(
970             String category, ThemeDisplay themeDisplay)
971         throws SystemException {
972 
973         Set<Portlet> portletsSet = new TreeSet<Portlet>(
974             new PortletControlPanelWeightComparator());
975 
976         List<Portlet> portletsList = PortletLocalServiceUtil.getPortlets(
977             themeDisplay.getCompanyId());
978 
979         for (Portlet portlet : portletsList) {
980             if (category.equals(portlet.getControlPanelEntryCategory())) {
981                 portletsSet.add(portlet);
982             }
983         }
984 
985         return filterControlPanelPortlets(portletsSet, category, themeDisplay);
986     }
987 
988     public String getCurrentCompleteURL(HttpServletRequest request) {
989         String currentCompleteURL = (String)request.getAttribute(
990             WebKeys.CURRENT_COMPLETE_URL);
991 
992         if (currentCompleteURL == null) {
993             currentCompleteURL = HttpUtil.getCompleteURL(request);
994 
995             request.setAttribute(
996                 WebKeys.CURRENT_COMPLETE_URL, currentCompleteURL);
997         }
998 
999         return currentCompleteURL;
1000    }
1001
1002    public String getCurrentURL(HttpServletRequest request) {
1003        String currentURL = (String)request.getAttribute(WebKeys.CURRENT_URL);
1004
1005        if (currentURL == null) {
1006            currentURL = ParamUtil.getString(request, "currentURL");
1007
1008            if (Validator.isNull(currentURL)) {
1009                currentURL = HttpUtil.getCompleteURL(request);
1010
1011                if ((Validator.isNotNull(currentURL)) &&
1012                    (currentURL.indexOf(_J_SECURITY_CHECK) == -1)) {
1013
1014                    currentURL = currentURL.substring(
1015                        currentURL.indexOf(Http.PROTOCOL_DELIMITER) +
1016                            Http.PROTOCOL_DELIMITER.length());
1017
1018                    currentURL = currentURL.substring(
1019                        currentURL.indexOf(StringPool.SLASH));
1020                }
1021
1022                if (Validator.isNotNull(currentURL) &&
1023                    FacebookUtil.isFacebook(currentURL)) {
1024
1025                    String[] facebookData = FacebookUtil.getFacebookData(
1026                        request);
1027
1028                    currentURL =
1029                        FacebookUtil.FACEBOOK_APPS_URL + facebookData[0] +
1030                            facebookData[2];
1031                }
1032            }
1033
1034            if (Validator.isNull(currentURL)) {
1035                currentURL = getPathMain();
1036            }
1037
1038            request.setAttribute(WebKeys.CURRENT_URL, currentURL);
1039        }
1040
1041        return currentURL;
1042    }
1043
1044    public String getCurrentURL(PortletRequest portletRequest) {
1045        return (String)portletRequest.getAttribute(WebKeys.CURRENT_URL);
1046    }
1047
1048    public String getCustomSQLFunctionIsNotNull() {
1049        return PropsValues.CUSTOM_SQL_FUNCTION_ISNOTNULL;
1050    }
1051
1052    public String getCustomSQLFunctionIsNull() {
1053        return PropsValues.CUSTOM_SQL_FUNCTION_ISNULL;
1054    }
1055
1056    public Date getDate(
1057            int month, int day, int year, int hour, int min, PortalException pe)
1058        throws PortalException {
1059
1060        return getDate(month, day, year, hour, min, null, pe);
1061    }
1062
1063    public Date getDate(
1064            int month, int day, int year, int hour, int min, TimeZone timeZone,
1065            PortalException pe)
1066        throws PortalException {
1067
1068        if (!Validator.isGregorianDate(month, day, year)) {
1069            throw pe;
1070        }
1071        else {
1072            Calendar cal = null;
1073
1074            if (timeZone == null) {
1075                cal = CalendarFactoryUtil.getCalendar();
1076            }
1077            else {
1078                cal = CalendarFactoryUtil.getCalendar(timeZone);
1079            }
1080
1081            if ((hour == -1) || (min == -1)) {
1082                cal.set(year, month, day, 0, 0, 0);
1083            }
1084            else {
1085                cal.set(year, month, day, hour, min, 0);
1086            }
1087
1088            cal.set(Calendar.MILLISECOND, 0);
1089
1090            Date date = cal.getTime();
1091
1092            /*if (timeZone != null &&
1093                cal.before(CalendarFactoryUtil.getCalendar(timeZone))) {
1094
1095                throw pe;
1096            }*/
1097
1098            return date;
1099        }
1100    }
1101
1102    public Date getDate(int month, int day, int year, PortalException pe)
1103        throws PortalException {
1104
1105        return getDate(month, day, year, null, pe);
1106    }
1107
1108    public Date getDate(
1109            int month, int day, int year, TimeZone timeZone, PortalException pe)
1110        throws PortalException {
1111
1112        return getDate(month, day, year, -1, -1, timeZone, pe);
1113    }
1114
1115    public long getDefaultCompanyId() {
1116        return PortalInstances.getDefaultCompanyId();
1117    }
1118
1119    public Map<String, Serializable> getExpandoBridgeAttributes(
1120            ExpandoBridge expandoBridge, PortletRequest portletRequest)
1121        throws PortalException, SystemException {
1122
1123        Map<String, Serializable> attributes =
1124            new HashMap<String, Serializable>();
1125
1126        List<String> names = new ArrayList<String>();
1127
1128        Enumeration<String> enu = portletRequest.getParameterNames();
1129
1130        while (enu.hasMoreElements()) {
1131            String param = enu.nextElement();
1132
1133            if (param.indexOf("ExpandoAttributeName(") != -1) {
1134                String name = ParamUtil.getString(portletRequest, param);
1135
1136                names.add(name);
1137            }
1138        }
1139
1140        for (String name : names) {
1141            int type = expandoBridge.getAttributeType(name);
1142
1143            Serializable value = EditExpandoAction.getValue(
1144                portletRequest, "ExpandoAttribute(" + name + ")", type);
1145
1146            attributes.put(name, value);
1147        }
1148
1149        return attributes;
1150    }
1151
1152    public String getFirstPageLayoutTypes(PageContext pageContext) {
1153        StringBundler sb = new StringBundler();
1154
1155        for (int i = 0; i < PropsValues.LAYOUT_TYPES.length; i++) {
1156            String type = PropsValues.LAYOUT_TYPES[i];
1157
1158            if (isLayoutFirstPageable(type)) {
1159                sb.append(
1160                    LanguageUtil.get(pageContext, "layout.types." + type));
1161                sb.append(StringPool.COMMA);
1162                sb.append(StringPool.SPACE);
1163            }
1164        }
1165
1166        if (sb.index() >= 2) {
1167            sb.setIndex(sb.index() - 2);
1168        }
1169
1170        return sb.toString();
1171    }
1172
1173    public String getGlobalLibDir() {
1174        return _globalLibDir;
1175    }
1176
1177    public String getGoogleGadgetURL(
1178        Portlet portlet, ThemeDisplay themeDisplay) {
1179
1180        return _getServletURL(
1181            portlet, PropsValues.GOOGLE_GADGET_SERVLET_MAPPING, themeDisplay);
1182    }
1183
1184    public String[] getGuestPermissions(HttpServletRequest request) {
1185        String[] guestPermissions = request.getParameterValues(
1186            "guestPermissions");
1187
1188        if (guestPermissions == null) {
1189            return null;
1190        }
1191
1192        boolean inputPermissionsPublic = ParamUtil.getBoolean(
1193            request, "inputPermissionsPublic");
1194        boolean inputPermissionsShowConfigure = ParamUtil.getBoolean(
1195            request, "inputPermissionsShowConfigure");
1196
1197        if (!inputPermissionsShowConfigure) {
1198            if (!inputPermissionsPublic) {
1199                guestPermissions = new String[0];
1200            }
1201            else if ((guestPermissions == null) ||
1202                     (guestPermissions.length == 0)) {
1203
1204                guestPermissions = new String[] {ActionKeys.VIEW};
1205            }
1206        }
1207
1208        return guestPermissions;
1209    }
1210
1211    public String[] getGuestPermissions(PortletRequest portletRequest) {
1212        String[] guestPermissions = portletRequest.getParameterValues(
1213            "guestPermissions");
1214
1215        if (guestPermissions == null) {
1216            return null;
1217        }
1218
1219        boolean inputPermissionsPublic = ParamUtil.getBoolean(
1220            portletRequest, "inputPermissionsPublic");
1221        boolean inputPermissionsShowConfigure = ParamUtil.getBoolean(
1222            portletRequest, "inputPermissionsShowConfigure");
1223
1224        if (!inputPermissionsShowConfigure) {
1225            if (!inputPermissionsPublic) {
1226                guestPermissions = new String[0];
1227            }
1228            else if ((guestPermissions == null) ||
1229                     (guestPermissions.length == 0)) {
1230
1231                guestPermissions = new String[] {ActionKeys.VIEW};
1232            }
1233        }
1234
1235        return guestPermissions;
1236    }
1237
1238    public String getHomeURL(HttpServletRequest request)
1239        throws PortalException, SystemException {
1240
1241        String portalURL = getPortalURL(request);
1242
1243        Company company = getCompany(request);
1244
1245        String homeURL = company.getHomeURL();
1246
1247        if (Validator.isNull(homeURL)) {
1248            homeURL = PropsValues.COMPANY_DEFAULT_HOME_URL;
1249        }
1250
1251        return portalURL + _pathContext + homeURL;
1252    }
1253
1254    public String getHost(HttpServletRequest request) {
1255        request = getOriginalServletRequest(request);
1256
1257        String host = request.getHeader("Host");
1258
1259        if (host != null) {
1260            host = host.trim().toLowerCase();
1261
1262            int pos = host.indexOf(':');
1263
1264            if (pos >= 0) {
1265                host = host.substring(0, pos);
1266            }
1267        }
1268        else {
1269            host = null;
1270        }
1271
1272        return host;
1273    }
1274
1275    public String getHost(PortletRequest portletRequest) {
1276        return getHost(getHttpServletRequest(portletRequest));
1277    }
1278
1279    public HttpServletRequest getHttpServletRequest(
1280        PortletRequest portletRequest) {
1281
1282        if (portletRequest instanceof PortletRequestImpl) {
1283            PortletRequestImpl portletRequestImpl =
1284                (PortletRequestImpl)portletRequest;
1285
1286            return portletRequestImpl.getHttpServletRequest();
1287        }
1288        else if (portletRequest instanceof PortletRequestWrapper) {
1289            PortletRequestWrapper portletRequestWrapper =
1290                (PortletRequestWrapper)portletRequest;
1291
1292            return getHttpServletRequest(portletRequestWrapper.getRequest());
1293        }
1294
1295        throw new RuntimeException(
1296            "Unable to get the HTTP servlet request from " +
1297                portletRequest.getClass().getName());
1298    }
1299
1300    public HttpServletResponse getHttpServletResponse(
1301        PortletResponse portletResponse) {
1302
1303        if (portletResponse instanceof ActionResponseImpl) {
1304            ActionResponseImpl actionResponseImpl =
1305                (ActionResponseImpl)portletResponse;
1306
1307            return actionResponseImpl.getHttpServletResponse();
1308        }
1309        else if (portletResponse instanceof RenderResponseImpl) {
1310            RenderResponseImpl renderResponseImpl =
1311                (RenderResponseImpl)portletResponse;
1312
1313            return renderResponseImpl.getHttpServletResponse();
1314        }
1315        else if (portletResponse instanceof PortletResponseWrapper) {
1316            PortletResponseWrapper portletResponseWrapper =
1317                (PortletResponseWrapper)portletResponse;
1318
1319            return getHttpServletResponse(portletResponseWrapper.getResponse());
1320        }
1321
1322        PortletResponseImpl portletResponseImpl =
1323            PortletResponseImpl.getPortletResponseImpl(portletResponse);
1324
1325        return portletResponseImpl.getHttpServletResponse();
1326    }
1327
1328    public String getJsSafePortletId(String portletId) {
1329        return JS.getSafeName(portletId);
1330    }
1331
1332    public String getLayoutActualURL(Layout layout) {
1333        return getLayoutActualURL(layout, getPathMain());
1334    }
1335
1336    public String getLayoutActualURL(Layout layout, String mainPath) {
1337        Map<String, String> variables = new HashMap<String, String>();
1338
1339        variables.put("liferay:groupId", String.valueOf(layout.getGroupId()));
1340        variables.put("liferay:mainPath", mainPath);
1341        variables.put("liferay:plid", String.valueOf(layout.getPlid()));
1342
1343        UnicodeProperties typeSettingsProperties =
1344            layout.getLayoutType().getTypeSettingsProperties();
1345
1346        Iterator<Map.Entry<String, String>> itr =
1347            typeSettingsProperties.entrySet().iterator();
1348
1349        while (itr.hasNext()) {
1350            Map.Entry<String, String> entry = itr.next();
1351
1352            String key = entry.getKey();
1353            String value = entry.getValue();
1354
1355            variables.put(key, value);
1356        }
1357
1358        String href = PropsUtil.get(
1359            PropsKeys.LAYOUT_URL, new Filter(layout.getType(), variables));
1360
1361        return href;
1362    }
1363
1364    public String getLayoutActualURL(
1365            long groupId, boolean privateLayout, String mainPath,
1366            String friendlyURL)
1367        throws PortalException, SystemException {
1368
1369        return getLayoutActualURL(
1370            groupId, privateLayout, mainPath, friendlyURL, null);
1371    }
1372
1373    public String getLayoutActualURL(
1374            long groupId, boolean privateLayout, String mainPath,
1375            String friendlyURL, Map<String, String[]> params)
1376        throws PortalException, SystemException {
1377
1378        Layout layout = null;
1379        String queryString = StringPool.BLANK;
1380
1381        if (Validator.isNull(friendlyURL)) {
1382            List<Layout> layouts = LayoutLocalServiceUtil.getLayouts(
1383                groupId, privateLayout,
1384                LayoutConstants.DEFAULT_PARENT_LAYOUT_ID);
1385
1386            if (layouts.size() > 0) {
1387                layout = layouts.get(0);
1388            }
1389            else {
1390                throw new NoSuchLayoutException(
1391                    "{groupId=" + groupId + ",privateLayout=" + privateLayout +
1392                        "} does not have any layouts");
1393            }
1394        }
1395        else {
1396            Object[] friendlyURLMapper = getPortletFriendlyURLMapper(
1397                groupId, privateLayout, friendlyURL, params);
1398
1399            layout = (Layout)friendlyURLMapper[0];
1400            queryString = (String)friendlyURLMapper[1];
1401        }
1402
1403        String layoutActualURL = getLayoutActualURL(layout, mainPath);
1404
1405        if (Validator.isNotNull(queryString)) {
1406            layoutActualURL = layoutActualURL + queryString;
1407        }
1408        else if (params.isEmpty()) {
1409            UnicodeProperties typeSettingsProperties =
1410                layout.getLayoutType().getTypeSettingsProperties();
1411
1412            queryString = typeSettingsProperties.getProperty("query-string");
1413
1414            if (Validator.isNotNull(queryString) &&
1415                layoutActualURL.contains(StringPool.QUESTION)) {
1416
1417                layoutActualURL =
1418                    layoutActualURL + StringPool.AMPERSAND + queryString;
1419            }
1420        }
1421
1422        return layoutActualURL;
1423    }
1424
1425    public String getLayoutEditPage(Layout layout) {
1426        return PropsUtil.get(
1427            PropsKeys.LAYOUT_EDIT_PAGE, new Filter(layout.getType()));
1428    }
1429
1430    public String getLayoutFriendlyURL(
1431        Layout layout, ThemeDisplay themeDisplay) {
1432
1433        if (!isLayoutFriendliable(layout)) {
1434            return null;
1435        }
1436
1437        String layoutFriendlyURL = layout.getFriendlyURL();
1438
1439        LayoutSet layoutSet = layout.getLayoutSet();
1440
1441        long curLayoutSetId =
1442            themeDisplay.getLayout().getLayoutSet().getLayoutSetId();
1443
1444        String portalURL = StringPool.BLANK;
1445
1446        if (!themeDisplay.getServerName().equals(_LOCALHOST)) {
1447            String virtualHost = layoutSet.getVirtualHost();
1448
1449            if (Validator.isNull(virtualHost) &&
1450                Validator.isNotNull(
1451                    PropsValues.VIRTUAL_HOSTS_DEFAULT_COMMUNITY_NAME)) {
1452
1453                try {
1454                    Group group = GroupLocalServiceUtil.getGroup(
1455                        themeDisplay.getCompanyId(),
1456                        PropsValues.VIRTUAL_HOSTS_DEFAULT_COMMUNITY_NAME);
1457
1458                    if (layoutSet.getGroupId() == group.getGroupId()) {
1459                        Company company = themeDisplay.getCompany();
1460
1461                        virtualHost = company.getVirtualHost();
1462                    }
1463                }
1464                catch (Exception e) {
1465                    _log.error(e, e);
1466                }
1467            }
1468
1469            if (Validator.isNotNull(virtualHost)) {
1470                virtualHost = getPortalURL(
1471                    virtualHost, themeDisplay.getServerPort(),
1472                    themeDisplay.isSecure());
1473
1474                String portalDomain = HttpUtil.getDomain(
1475                    themeDisplay.getPortalURL());
1476
1477                if ((layoutSet.getLayoutSetId() != curLayoutSetId) ||
1478                    (virtualHost.indexOf(portalDomain) != -1)) {
1479
1480                    if (themeDisplay.isWidget()) {
1481                        layoutFriendlyURL =
1482                            PropsValues.WIDGET_SERVLET_MAPPING +
1483                                layoutFriendlyURL;
1484                    }
1485
1486                    if (themeDisplay.isI18n()) {
1487                        layoutFriendlyURL =
1488                            themeDisplay.getI18nPath() + layoutFriendlyURL;
1489                    }
1490
1491                    return virtualHost + _pathContext + layoutFriendlyURL;
1492                }
1493            }
1494            else {
1495                if ((layoutSet.getLayoutSetId() != curLayoutSetId) &&
1496                    (layout.getGroup().getClassPK() !=
1497                        themeDisplay.getUserId())) {
1498
1499                    virtualHost = themeDisplay.getCompany().getVirtualHost();
1500
1501                    if (!virtualHost.equalsIgnoreCase(_LOCALHOST)) {
1502                        portalURL = getPortalURL(
1503                            virtualHost, themeDisplay.getServerPort(),
1504                            themeDisplay.isSecure());
1505                    }
1506                }
1507            }
1508        }
1509
1510        Group group = layout.getGroup();
1511
1512        String friendlyURL = null;
1513
1514        if (layout.isPrivateLayout()) {
1515            if (group.isUser()) {
1516                friendlyURL = _PRIVATE_USER_SERVLET_MAPPING;
1517            }
1518            else {
1519                friendlyURL = _PRIVATE_GROUP_SERVLET_MAPPING;
1520            }
1521        }
1522        else {
1523            friendlyURL = _PUBLIC_GROUP_SERVLET_MAPPING;
1524        }
1525
1526        if (themeDisplay.isWidget()) {
1527            friendlyURL = PropsValues.WIDGET_SERVLET_MAPPING + friendlyURL;
1528        }
1529
1530        if (themeDisplay.isI18n()) {
1531            friendlyURL = themeDisplay.getI18nPath() + friendlyURL;
1532        }
1533
1534        return portalURL + _pathContext + friendlyURL + group.getFriendlyURL() +
1535            layoutFriendlyURL;
1536    }
1537
1538    public String getLayoutFriendlyURL(
1539        Layout layout, ThemeDisplay themeDisplay, Locale locale) {
1540
1541        String i18nLanguageId = themeDisplay.getI18nLanguageId();
1542        String i18nPath = themeDisplay.getI18nPath();
1543
1544        try {
1545            String tempI18nLanguageId = null;
1546
1547            if ((I18nFilter.getLanguageIds().contains(locale.toString())) &&
1548                ((PropsValues.LOCALE_PREPEND_FRIENDLY_URL_STYLE == 1) &&
1549                 (!locale.equals(LocaleUtil.getDefault()))) ||
1550                (PropsValues.LOCALE_PREPEND_FRIENDLY_URL_STYLE == 2)) {
1551
1552                tempI18nLanguageId = locale.toString();
1553            }
1554
1555            String tempI18nPath = null;
1556
1557            if (Validator.isNotNull(tempI18nLanguageId)) {
1558                tempI18nPath = StringPool.SLASH + tempI18nLanguageId;
1559
1560                if (!LanguageUtil.isDuplicateLanguageCode(
1561                        locale.getLanguage())) {
1562
1563                    tempI18nPath = StringPool.SLASH + locale.getLanguage();
1564                }
1565                else {
1566                    Locale priorityLocale = LanguageUtil.getLocale(
1567                        locale.getLanguage());
1568
1569                    if (locale.equals(priorityLocale)) {
1570                        tempI18nPath = StringPool.SLASH + locale.getLanguage();
1571                    }
1572                }
1573            }
1574
1575            themeDisplay.setI18nLanguageId(tempI18nLanguageId);
1576            themeDisplay.setI18nPath(tempI18nPath);
1577
1578            return getLayoutFriendlyURL(layout, themeDisplay);
1579        }
1580        finally {
1581            themeDisplay.setI18nLanguageId(i18nLanguageId);
1582            themeDisplay.setI18nPath(i18nPath);
1583        }
1584    }
1585
1586    public String getLayoutFullURL(Layout layout, ThemeDisplay themeDisplay) {
1587        return getLayoutFullURL(layout, themeDisplay, true);
1588    }
1589
1590    public String getLayoutFullURL(
1591        Layout layout, ThemeDisplay themeDisplay, boolean doAsUser) {
1592
1593        String layoutURL = getLayoutURL(layout, themeDisplay, doAsUser);
1594        String portalURL = themeDisplay.getPortalURL();
1595
1596        if (StringUtil.startsWith(layoutURL, portalURL)) {
1597            return layoutURL;
1598        }
1599        else {
1600            return portalURL + layoutURL;
1601        }
1602    }
1603
1604    public String getLayoutFullURL(long groupId, String portletId)
1605        throws PortalException, SystemException {
1606
1607        long plid = getPlidFromPortletId(groupId, portletId);
1608
1609        if (plid == LayoutConstants.DEFAULT_PLID) {
1610            return null;
1611        }
1612
1613        StringBundler sb = new StringBundler(4);
1614
1615        Layout layout = LayoutLocalServiceUtil.getLayout(plid);
1616
1617        Company company = CompanyLocalServiceUtil.getCompany(
1618            layout.getCompanyId());
1619
1620        Group group = GroupLocalServiceUtil.getGroup(groupId);
1621
1622        String portalURL = getPortalURL(
1623            company.getVirtualHost(), getPortalPort(), false);
1624
1625        sb.append(portalURL);
1626
1627        if (layout.isPrivateLayout()) {
1628            if (group.isUser()) {
1629                sb.append(PortalUtil.getPathFriendlyURLPrivateUser());
1630            }
1631            else {
1632                sb.append(PortalUtil.getPathFriendlyURLPrivateGroup());
1633            }
1634        }
1635        else {
1636            sb.append(PortalUtil.getPathFriendlyURLPublic());
1637        }
1638
1639        sb.append(group.getFriendlyURL());
1640        sb.append(layout.getFriendlyURL());
1641
1642        return sb.toString();
1643    }
1644
1645    public String getLayoutFullURL(ThemeDisplay themeDisplay) {
1646        return getLayoutFullURL(themeDisplay.getLayout(), themeDisplay);
1647    }
1648
1649    public String getLayoutSetFriendlyURL(
1650            LayoutSet layoutSet, ThemeDisplay themeDisplay)
1651        throws PortalException, SystemException {
1652
1653        String virtualHost = layoutSet.getVirtualHost();
1654
1655        if (Validator.isNull(virtualHost) &&
1656            Validator.isNotNull(
1657                PropsValues.VIRTUAL_HOSTS_DEFAULT_COMMUNITY_NAME)) {
1658
1659            try {
1660                Group group = GroupLocalServiceUtil.getGroup(
1661                    themeDisplay.getCompanyId(),
1662                    PropsValues.VIRTUAL_HOSTS_DEFAULT_COMMUNITY_NAME);
1663
1664                if (layoutSet.getGroupId() == group.getGroupId()) {
1665                    Company company = themeDisplay.getCompany();
1666
1667                    virtualHost = company.getVirtualHost();
1668                }
1669            }
1670            catch (Exception e) {
1671                _log.error(e, e);
1672            }
1673        }
1674
1675        if (Validator.isNotNull(virtualHost)) {
1676            String portalURL = getPortalURL(
1677                virtualHost, themeDisplay.getServerPort(),
1678                themeDisplay.isSecure());
1679
1680            // Use the layout set's virtual host setting only if the layout set
1681            // is already used for the current request
1682
1683            long curLayoutSetId =
1684                themeDisplay.getLayout().getLayoutSet().getLayoutSetId();
1685
1686            if ((layoutSet.getLayoutSetId() != curLayoutSetId) ||
1687                (portalURL.startsWith(themeDisplay.getURLPortal()))) {
1688
1689                String layoutSetFriendlyURL = StringPool.BLANK;
1690
1691                if (themeDisplay.isI18n()) {
1692                    layoutSetFriendlyURL = themeDisplay.getI18nPath();
1693                }
1694
1695                return portalURL + _pathContext + layoutSetFriendlyURL;
1696            }
1697        }
1698
1699        Group group = GroupLocalServiceUtil.getGroup(layoutSet.getGroupId());
1700
1701        String friendlyURL = null;
1702
1703        if (layoutSet.isPrivateLayout()) {
1704            if (group.isUser()) {
1705                friendlyURL = _PRIVATE_USER_SERVLET_MAPPING;
1706            }
1707            else {
1708                friendlyURL = _PRIVATE_GROUP_SERVLET_MAPPING;
1709            }
1710        }
1711        else {
1712            friendlyURL = _PUBLIC_GROUP_SERVLET_MAPPING;
1713        }
1714
1715        if (themeDisplay.isI18n()) {
1716            friendlyURL = themeDisplay.getI18nPath() + friendlyURL;
1717        }
1718
1719        return _pathContext + friendlyURL + group.getFriendlyURL();
1720    }
1721
1722    public String getLayoutTarget(Layout layout) {
1723        UnicodeProperties typeSettingsProps =
1724            layout.getTypeSettingsProperties();
1725
1726        String target = typeSettingsProps.getProperty("target");
1727
1728        if (Validator.isNull(target)) {
1729            target = StringPool.BLANK;
1730        }
1731        else {
1732            target = "target=\"" + target + "\"";
1733        }
1734
1735        return target;
1736    }
1737
1738    public String getLayoutURL(Layout layout, ThemeDisplay themeDisplay) {
1739        return getLayoutURL(layout, themeDisplay, true);
1740    }
1741
1742    public String getLayoutURL(
1743        Layout layout, ThemeDisplay themeDisplay, boolean doAsUser) {
1744
1745        if (layout == null) {
1746            return themeDisplay.getPathMain() + PATH_PORTAL_LAYOUT;
1747        }
1748
1749        if (!layout.getType().equals(LayoutConstants.TYPE_URL)) {
1750            String layoutFriendlyURL = getLayoutFriendlyURL(
1751                layout, themeDisplay);
1752
1753            if (Validator.isNotNull(layoutFriendlyURL)) {
1754                if (doAsUser) {
1755                    if (Validator.isNotNull(themeDisplay.getDoAsUserId())) {
1756                        layoutFriendlyURL = HttpUtil.addParameter(
1757                            layoutFriendlyURL, "doAsUserId",
1758                            themeDisplay.getDoAsUserId());
1759                    }
1760
1761                    if (Validator.isNotNull(
1762                            themeDisplay.getDoAsUserLanguageId())) {
1763
1764                        layoutFriendlyURL = HttpUtil.addParameter(
1765                            layoutFriendlyURL, "doAsUserLanguageId",
1766                            themeDisplay.getDoAsUserLanguageId());
1767                    }
1768                }
1769
1770                return layoutFriendlyURL;
1771            }
1772        }
1773
1774        String layoutURL = getLayoutActualURL(layout);
1775
1776        if (doAsUser) {
1777            if (Validator.isNotNull(themeDisplay.getDoAsUserId())) {
1778                layoutURL = HttpUtil.addParameter(
1779                    layoutURL, "doAsUserId", themeDisplay.getDoAsUserId());
1780            }
1781
1782            if (Validator.isNotNull(themeDisplay.getDoAsUserLanguageId())) {
1783                layoutURL = HttpUtil.addParameter(
1784                    layoutURL, "doAsUserLanguageId",
1785                    themeDisplay.getDoAsUserLanguageId());
1786            }
1787        }
1788
1789        return layoutURL;
1790    }
1791
1792    public String getLayoutURL(ThemeDisplay themeDisplay) {
1793        return getLayoutURL(themeDisplay.getLayout(), themeDisplay);
1794    }
1795
1796    public String getLayoutViewPage(Layout layout) {
1797        return PropsUtil.get(
1798            PropsKeys.LAYOUT_VIEW_PAGE, new Filter(layout.getType()));
1799    }
1800
1801    public Locale getLocale(HttpServletRequest request) {
1802        ThemeDisplay themeDisplay = (ThemeDisplay)request.getAttribute(
1803            WebKeys.THEME_DISPLAY);
1804
1805        if (themeDisplay != null) {
1806            return themeDisplay.getLocale();
1807        }
1808        else {
1809            HttpSession session = request.getSession();
1810
1811            return (Locale)session.getAttribute(Globals.LOCALE_KEY);
1812        }
1813    }
1814
1815    public Locale getLocale(RenderRequest renderRequest) {
1816        return getLocale(getHttpServletRequest(renderRequest));
1817    }
1818
1819    public String getNetvibesURL(
1820        Portlet portlet, ThemeDisplay themeDisplay) {
1821
1822        return _getServletURL(
1823            portlet, PropsValues.NETVIBES_SERVLET_MAPPING, themeDisplay);
1824    }
1825
1826    public HttpServletRequest getOriginalServletRequest(
1827        HttpServletRequest request) {
1828
1829        HttpServletRequest originalRequest = request;
1830
1831        while (originalRequest.getClass().getName().startsWith(
1832                    "com.liferay.")) {
1833
1834            // Get original request so that portlets inside portlets render
1835            // properly
1836
1837            originalRequest = (HttpServletRequest)
1838                ((HttpServletRequestWrapper)originalRequest).getRequest();
1839        }
1840
1841        return originalRequest;
1842    }
1843
1844    public long getParentGroupId(long groupId)
1845        throws PortalException, SystemException {
1846
1847        if (groupId <= 0) {
1848            return 0;
1849        }
1850
1851        Group group = GroupLocalServiceUtil.getGroup(groupId);
1852
1853        long parentGroupId = groupId;
1854
1855        if (group.isLayout()) {
1856            parentGroupId = group.getParentGroupId();
1857        }
1858
1859        return parentGroupId;
1860    }
1861
1862    public String getPathContext() {
1863        return _pathContext;
1864    }
1865
1866    public String getPathFriendlyURLPrivateGroup() {
1867        return _pathFriendlyURLPrivateGroup;
1868    }
1869
1870    public String getPathFriendlyURLPrivateUser() {
1871        return _pathFriendlyURLPrivateUser;
1872    }
1873
1874    public String getPathFriendlyURLPublic() {
1875        return _pathFriendlyURLPublic;
1876    }
1877
1878    public String getPathImage() {
1879        return _pathImage;
1880    }
1881
1882    public String getPathMain() {
1883        return _pathMain;
1884    }
1885
1886    public long getPlidFromFriendlyURL(long companyId, String friendlyURL) {
1887        if (Validator.isNull(friendlyURL)) {
1888            return LayoutConstants.DEFAULT_PLID;
1889        }
1890
1891        String[] urlParts = friendlyURL.split("\\/", 4);
1892
1893        if ((friendlyURL.charAt(0) != CharPool.SLASH) &&
1894            (urlParts.length != 4)) {
1895
1896            return LayoutConstants.DEFAULT_PLID;
1897        }
1898
1899        boolean privateLayout = true;
1900
1901        String urlPrefix = StringPool.SLASH + urlParts[1];
1902
1903        if (_PUBLIC_GROUP_SERVLET_MAPPING.equals(urlPrefix)) {
1904            privateLayout = false;
1905        }
1906        else if (_PRIVATE_GROUP_SERVLET_MAPPING.equals(urlPrefix) ||
1907                 _PRIVATE_USER_SERVLET_MAPPING.equals(urlPrefix)) {
1908
1909            privateLayout = true;
1910        }
1911        else {
1912            return LayoutConstants.DEFAULT_PLID;
1913        }
1914
1915        Group group = null;
1916
1917        try {
1918            group = GroupLocalServiceUtil.getFriendlyURLGroup(
1919                companyId, StringPool.SLASH + urlParts[2]);
1920        }
1921        catch (Exception e) {
1922        }
1923
1924        if (group != null) {
1925            Layout layout = null;
1926
1927            try {
1928                String layoutFriendlyURL = null;
1929
1930                if (urlParts.length == 4) {
1931                    layoutFriendlyURL = StringPool.SLASH + urlParts[3];
1932                }
1933                else {
1934                    layoutFriendlyURL = "/1";
1935                }
1936
1937                layout = LayoutLocalServiceUtil.getFriendlyURLLayout(
1938                    group.getGroupId(), privateLayout, layoutFriendlyURL);
1939
1940                return layout.getPlid();
1941            }
1942            catch (Exception e) {
1943            }
1944        }
1945
1946        return LayoutConstants.DEFAULT_PLID;
1947    }
1948
1949    public long getPlidFromPortletId(
1950        long groupId, boolean privateLayout, String portletId) {
1951
1952        long plid = LayoutConstants.DEFAULT_PLID;
1953
1954        StringBundler sb = new StringBundler(5);
1955
1956        sb.append(groupId);
1957        sb.append(StringPool.SPACE);
1958        sb.append(privateLayout);
1959        sb.append(StringPool.SPACE);
1960        sb.append(portletId);
1961
1962        String key = sb.toString();
1963
1964        Long plidObj = _plidToPortletIdCache.get(key);
1965
1966        if (plidObj == null) {
1967            plid = _getPlidFromPortletId(groupId, privateLayout, portletId);
1968
1969            if (plid != LayoutConstants.DEFAULT_PLID) {
1970                _plidToPortletIdCache.put(key, plid);
1971            }
1972        }
1973        else {
1974            plid = plidObj.longValue();
1975
1976            boolean validPlid = false;
1977
1978            try {
1979                Layout layout = LayoutLocalServiceUtil.getLayout(plid);
1980
1981                LayoutTypePortlet layoutTypePortlet =
1982                    (LayoutTypePortlet)layout.getLayoutType();
1983
1984                if (layoutTypePortlet.hasPortletId(portletId)) {
1985                    validPlid = true;
1986                }
1987            }
1988            catch (Exception e) {
1989            }
1990
1991            if (!validPlid) {
1992                _plidToPortletIdCache.remove(key);
1993
1994                plid = _getPlidFromPortletId(groupId, privateLayout, portletId);
1995
1996                if (plid != LayoutConstants.DEFAULT_PLID) {
1997                    _plidToPortletIdCache.put(key, plid);
1998                }
1999            }
2000        }
2001
2002        return plid;
2003    }
2004
2005    public long getPlidFromPortletId(long groupId, String portletId) {
2006        long plid = getPlidFromPortletId(groupId, false, portletId);
2007
2008        if (plid == LayoutConstants.DEFAULT_PLID) {
2009            plid = getPlidFromPortletId(groupId, true, portletId);
2010        }
2011
2012        if (plid == LayoutConstants.DEFAULT_PLID) {
2013            if (_log.isDebugEnabled()) {
2014                _log.debug(
2015                    "Portlet " + portletId +
2016                        " does not exist on a page in group " + groupId);
2017            }
2018        }
2019
2020        return plid;
2021    }
2022
2023    public String getPortalLibDir() {
2024        return _portalLibDir;
2025    }
2026
2027    public int getPortalPort() {
2028        return _portalPort.intValue();
2029    }
2030
2031    public Properties getPortalProperties() {
2032        return PropsUtil.getProperties();
2033    }
2034
2035    public String getPortalURL(HttpServletRequest request) {
2036        return getPortalURL(request, request.isSecure());
2037    }
2038
2039    public String getPortalURL(HttpServletRequest request, boolean secure) {
2040        return getPortalURL(
2041            request.getServerName(), request.getServerPort(), secure);
2042    }
2043
2044    public String getPortalURL(PortletRequest portletRequest) {
2045        return getPortalURL(portletRequest, portletRequest.isSecure());
2046    }
2047
2048    public String getPortalURL(PortletRequest portletRequest, boolean secure) {
2049        return getPortalURL(
2050            portletRequest.getServerName(), portletRequest.getServerPort(),
2051            secure);
2052    }
2053
2054    public String getPortalURL(
2055        String serverName, int serverPort, boolean secure) {
2056
2057        StringBundler sb = new StringBundler();
2058
2059        if (secure || Http.HTTPS.equals(PropsValues.WEB_SERVER_PROTOCOL)) {
2060            sb.append(Http.HTTPS_WITH_SLASH);
2061        }
2062        else {
2063            sb.append(Http.HTTP_WITH_SLASH);
2064        }
2065
2066        if (Validator.isNull(PropsValues.WEB_SERVER_HOST)) {
2067            sb.append(serverName);
2068        }
2069        else {
2070            sb.append(PropsValues.WEB_SERVER_HOST);
2071        }
2072
2073        if (!secure) {
2074            if (PropsValues.WEB_SERVER_HTTP_PORT == -1) {
2075                if ((serverPort != Http.HTTP_PORT) &&
2076                    (serverPort != Http.HTTPS_PORT)) {
2077
2078                    sb.append(StringPool.COLON);
2079                    sb.append(serverPort);
2080                }
2081            }
2082            else {
2083                if ((PropsValues.WEB_SERVER_HTTP_PORT != serverPort) &&
2084                    (PropsValues.WEB_SERVER_HTTP_PORT != Http.HTTP_PORT)) {
2085
2086                    sb.append(StringPool.COLON);
2087                    sb.append(PropsValues.WEB_SERVER_HTTP_PORT);
2088                }
2089            }
2090        }
2091
2092        if (secure) {
2093            if (PropsValues.WEB_SERVER_HTTPS_PORT == -1) {
2094                if ((serverPort != Http.HTTP_PORT) &&
2095                    (serverPort != Http.HTTPS_PORT)) {
2096
2097                    sb.append(StringPool.COLON);
2098                    sb.append(serverPort);
2099                }
2100            }
2101            else {
2102                if ((PropsValues.WEB_SERVER_HTTPS_PORT != serverPort) &&
2103                    (PropsValues.WEB_SERVER_HTTPS_PORT != Http.HTTPS_PORT)) {
2104
2105                    sb.append(StringPool.COLON);
2106                    sb.append(PropsValues.WEB_SERVER_HTTPS_PORT);
2107                }
2108            }
2109        }
2110
2111        return sb.toString();
2112    }
2113
2114    public String getPortalURL(ThemeDisplay themeDisplay) {
2115        String serverName = themeDisplay.getServerName();
2116
2117        Layout layout = themeDisplay.getLayout();
2118
2119        if (layout != null) {
2120            LayoutSet layoutSet = layout.getLayoutSet();
2121
2122            String virtualHost = layoutSet.getVirtualHost();
2123
2124            if (Validator.isNotNull(virtualHost)) {
2125                serverName = virtualHost;
2126            }
2127        }
2128
2129        return getPortalURL(
2130            serverName, themeDisplay.getServerPort(), themeDisplay.isSecure());
2131    }
2132
2133    public String getPortalWebDir() {
2134        return _portalWebDir;
2135    }
2136
2137    public List<KeyValuePair> getPortletBreadcrumbList(
2138        HttpServletRequest request) {
2139
2140        return (List<KeyValuePair>)request.getAttribute(
2141            WebKeys.PORTLET_BREADCRUMB_MAP);
2142    }
2143
2144    public String getPortletDescription(
2145        Portlet portlet, ServletContext servletContext, Locale locale) {
2146
2147        PortletConfig portletConfig = PortletConfigFactory.create(
2148            portlet, servletContext);
2149
2150        ResourceBundle resourceBundle = portletConfig.getResourceBundle(locale);
2151
2152        return resourceBundle.getString(
2153            JavaConstants.JAVAX_PORTLET_DESCRIPTION);
2154    }
2155
2156    public String getPortletDescription(Portlet portlet, User user) {
2157        return getPortletDescription(portlet.getPortletId(), user);
2158    }
2159
2160    public String getPortletDescription(String portletId, Locale locale) {
2161        return LanguageUtil.get(
2162            locale,
2163            JavaConstants.JAVAX_PORTLET_DESCRIPTION.concat(
2164                StringPool.PERIOD).concat(portletId));
2165    }
2166
2167    public String getPortletDescription(String portletId, String languageId) {
2168        Locale locale = LocaleUtil.fromLanguageId(languageId);
2169
2170        return getPortletDescription(portletId, locale);
2171    }
2172
2173    public String getPortletDescription(String portletId, User user) {
2174        return LanguageUtil.get(
2175            user.getLocale(),
2176            JavaConstants.JAVAX_PORTLET_DESCRIPTION.concat(
2177                StringPool.PERIOD).concat(portletId));
2178    }
2179
2180    public Object[] getPortletFriendlyURLMapper(
2181            long groupId, boolean privateLayout, String url)
2182        throws PortalException, SystemException {
2183
2184        return getPortletFriendlyURLMapper(groupId, privateLayout, url, null);
2185    }
2186
2187    public Object[] getPortletFriendlyURLMapper(
2188            long groupId, boolean privateLayout, String url,
2189            Map<String, String[]> params)
2190        throws PortalException, SystemException {
2191
2192        boolean foundFriendlyURLMapper = false;
2193
2194        String friendlyURL = url;
2195        String queryString = StringPool.BLANK;
2196
2197        List<Portlet> portlets =
2198            PortletLocalServiceUtil.getFriendlyURLMapperPortlets();
2199
2200        Iterator<Portlet> itr = portlets.iterator();
2201
2202        while (itr.hasNext()) {
2203            Portlet portlet = itr.next();
2204
2205            FriendlyURLMapper friendlyURLMapper =
2206                portlet.getFriendlyURLMapperInstance();
2207
2208            if (url.endsWith(
2209                    StringPool.SLASH + friendlyURLMapper.getMapping())) {
2210
2211                url += StringPool.SLASH;
2212            }
2213
2214            int pos = -1;
2215
2216            if (friendlyURLMapper.isCheckMappingWithPrefix()) {
2217                pos = url.indexOf(
2218                    FRIENDLY_URL_SEPARATOR + friendlyURLMapper.getMapping() +
2219                        StringPool.SLASH);
2220            }
2221            else {
2222                pos = url.indexOf(
2223                    StringPool.SLASH + friendlyURLMapper.getMapping() +
2224                        StringPool.SLASH);
2225            }
2226
2227            if (pos != -1) {
2228                foundFriendlyURLMapper = true;
2229
2230                friendlyURL = url.substring(0, pos);
2231
2232                Map<String, String[]> actualParams =
2233                    new HashMap<String, String[]>();
2234
2235                /*Object lifecycle = actualParams.get("p_p_lifecycle");
2236
2237                if ((lifecycle == null) ||
2238                    (((String[])lifecycle).length == 0)) {
2239
2240                    actualParams.put("p_p_lifecycle", "0");
2241                }
2242
2243                Object state = actualParams.get("p_p_state");
2244
2245                if ((state == null) || (((String[])state).length == 0)) {
2246                    actualParams.put(
2247                        "p_p_state", WindowState.MAXIMIZED.toString());
2248                }*/
2249
2250                Map<String, String> prpIdentifiers =
2251                    new HashMap<String, String>();
2252
2253                Set<PublicRenderParameter> publicRenderParameters =
2254                    portlet.getPublicRenderParameters();
2255
2256                for (PublicRenderParameter publicRenderParameter :
2257                        publicRenderParameters) {
2258
2259                    QName qName = publicRenderParameter.getQName();
2260
2261                    String publicRenderParameterIdentifier =
2262                        qName.getLocalPart();
2263                    String publicRenderParameterName =
2264                        PortletQNameUtil.getPublicRenderParameterName(qName);
2265
2266                    prpIdentifiers.put(
2267                        publicRenderParameterIdentifier,
2268                        publicRenderParameterName);
2269                }
2270
2271                FriendlyURLMapperThreadLocal.setPRPIdentifiers(prpIdentifiers);
2272
2273                if (friendlyURLMapper.isCheckMappingWithPrefix()) {
2274                    friendlyURLMapper.populateParams(
2275                        url.substring(pos + 2), actualParams);
2276                }
2277                else {
2278                    friendlyURLMapper.populateParams(
2279                        url.substring(pos), actualParams);
2280                }
2281
2282                queryString =
2283                    StringPool.AMPERSAND +
2284                        HttpUtil.parameterMapToString(actualParams, false);
2285
2286                break;
2287            }
2288        }
2289
2290        if (!foundFriendlyURLMapper) {
2291            int x = url.indexOf(FRIENDLY_URL_SEPARATOR);
2292
2293            if (x != -1) {
2294                int y = url.indexOf(StringPool.SLASH, x + 3);
2295
2296                if (y == -1) {
2297                    y = url.length();
2298                }
2299
2300                String ppid = url.substring(x + 3, y);
2301
2302                if (Validator.isNotNull(ppid)) {
2303                    friendlyURL = url.substring(0, x);
2304
2305                    Map<String, String[]> actualParams = null;
2306
2307                    if (params != null) {
2308                        actualParams = new HashMap<String, String[]>(params);
2309                    }
2310                    else {
2311                        actualParams = new HashMap<String, String[]>();
2312                    }
2313
2314                    actualParams.put("p_p_id", new String[] {ppid});
2315                    actualParams.put("p_p_lifecycle", new String[] {"0"});
2316                    actualParams.put(
2317                        "p_p_state",
2318                        new String[] {WindowState.MAXIMIZED.toString()});
2319                    actualParams.put(
2320                        "p_p_mode", new String[] {PortletMode.VIEW.toString()});
2321
2322                    queryString =
2323                        StringPool.AMPERSAND +
2324                            HttpUtil.parameterMapToString(actualParams, false);
2325                }
2326            }
2327        }
2328
2329        friendlyURL = StringUtil.replace(
2330            friendlyURL, StringPool.DOUBLE_SLASH, StringPool.SLASH);
2331
2332        if (friendlyURL.endsWith(StringPool.SLASH)) {
2333            friendlyURL = friendlyURL.substring(0, friendlyURL.length() - 1);
2334        }
2335
2336        Layout layout = LayoutLocalServiceUtil.getFriendlyURLLayout(
2337            groupId, privateLayout, friendlyURL);
2338
2339        return new Object[] {layout, queryString};
2340    }
2341
2342    /**
2343     * @deprecated Use <code>getScopeGroupId</code>.
2344     */
2345    public long getPortletGroupId(ActionRequest actionRequest) {
2346        return getScopeGroupId(actionRequest);
2347    }
2348
2349    /**
2350     * @deprecated Use <code>getScopeGroupId</code>.
2351     */
2352    public long getPortletGroupId(HttpServletRequest request) {
2353        return getScopeGroupId(request);
2354    }
2355
2356    /**
2357     * @deprecated Use <code>getScopeGroupId</code>.
2358     */
2359    public long getPortletGroupId(Layout layout) {
2360        return getScopeGroupId(layout);
2361    }
2362
2363    /**
2364     * @deprecated Use <code>getScopeGroupId</code>.
2365     */
2366    public long getPortletGroupId(long plid) {
2367        Layout layout = null;
2368
2369        try {
2370            layout = LayoutLocalServiceUtil.getLayout(plid);
2371        }
2372        catch (Exception e) {
2373        }
2374
2375        return getPortletGroupId(layout);
2376    }
2377
2378    /**
2379     * @deprecated Use <code>getScopeGroupId</code>.
2380     */
2381    public long getPortletGroupId(RenderRequest renderRequest) {
2382        return getScopeGroupId(renderRequest);
2383    }
2384
2385    public String getPortletId(HttpServletRequest request) {
2386        PortletConfigImpl portletConfigImpl =
2387            (PortletConfigImpl)request.getAttribute(
2388                JavaConstants.JAVAX_PORTLET_CONFIG);
2389
2390        if (portletConfigImpl != null) {
2391            return portletConfigImpl.getPortletId();
2392        }
2393        else {
2394            return null;
2395        }
2396    }
2397
2398    public String getPortletId(PortletRequest portletRequest) {
2399        PortletConfigImpl portletConfigImpl =
2400            (PortletConfigImpl)portletRequest.getAttribute(
2401                JavaConstants.JAVAX_PORTLET_CONFIG);
2402
2403        if (portletConfigImpl != null) {
2404            return portletConfigImpl.getPortletId();
2405        }
2406        else {
2407            return null;
2408        }
2409    }
2410
2411    public String getPortletNamespace(String portletId) {
2412        return StringPool.UNDERLINE.concat(portletId).concat(
2413            StringPool.UNDERLINE);
2414    }
2415
2416    public String getPortletTitle(Portlet portlet, Locale locale) {
2417        return getPortletTitle(portlet.getPortletId(), locale);
2418    }
2419
2420    public String getPortletTitle(Portlet portlet, String languageId) {
2421        return getPortletTitle(portlet.getPortletId(), languageId);
2422    }
2423
2424    public String getPortletTitle(
2425        Portlet portlet, ServletContext servletContext, Locale locale) {
2426
2427        PortletConfig portletConfig = PortletConfigFactory.create(
2428            portlet, servletContext);
2429
2430        ResourceBundle resourceBundle = portletConfig.getResourceBundle(locale);
2431
2432        return resourceBundle.getString(JavaConstants.JAVAX_PORTLET_TITLE);
2433    }
2434
2435    public String getPortletTitle(Portlet portlet, User user) {
2436        return getPortletTitle(portlet.getPortletId(), user);
2437    }
2438
2439    public String getPortletTitle(String portletId, Locale locale) {
2440        return LanguageUtil.get(
2441            locale,
2442            JavaConstants.JAVAX_PORTLET_TITLE.concat(StringPool.PERIOD).concat(
2443                portletId));
2444    }
2445
2446    public String getPortletTitle(String portletId, String languageId) {
2447        Locale locale = LocaleUtil.fromLanguageId(languageId);
2448
2449        return getPortletTitle(portletId, locale);
2450    }
2451
2452    public String getPortletTitle(String portletId, User user) {
2453        return LanguageUtil.get(
2454            user.getLocale(),
2455            JavaConstants.JAVAX_PORTLET_TITLE.concat(StringPool.PERIOD).concat(
2456                portletId));
2457    }
2458
2459    public String getPortletXmlFileName() throws SystemException {
2460        if (PrefsPropsUtil.getBoolean(
2461                PropsKeys.AUTO_DEPLOY_CUSTOM_PORTLET_XML,
2462                PropsValues.AUTO_DEPLOY_CUSTOM_PORTLET_XML)) {
2463
2464            return PORTLET_XML_FILE_NAME_CUSTOM;
2465        }
2466        else {
2467            return PORTLET_XML_FILE_NAME_STANDARD;
2468        }
2469    }
2470
2471    public PortletPreferences getPreferences(HttpServletRequest request) {
2472        RenderRequest renderRequest = (RenderRequest)request.getAttribute(
2473            JavaConstants.JAVAX_PORTLET_REQUEST);
2474
2475        PortletPreferences preferences = null;
2476
2477        if (renderRequest != null) {
2478            PortletPreferencesWrapper preferencesWrapper =
2479                (PortletPreferencesWrapper)renderRequest.getPreferences();
2480
2481            preferences = preferencesWrapper.getPreferencesImpl();
2482        }
2483
2484        return preferences;
2485    }
2486
2487    public PreferencesValidator getPreferencesValidator(Portlet portlet) {
2488        PortletApp portletApp = portlet.getPortletApp();
2489
2490        if (portletApp.isWARFile()) {
2491            PortletBag portletBag = PortletBagPool.get(
2492                portlet.getRootPortletId());
2493
2494            return portletBag.getPreferencesValidatorInstance();
2495        }
2496        else {
2497            PreferencesValidator preferencesValidator = null;
2498
2499            if (Validator.isNotNull(portlet.getPreferencesValidator())) {
2500                preferencesValidator =
2501                    (PreferencesValidator)InstancePool.get(
2502                        portlet.getPreferencesValidator());
2503            }
2504
2505            return preferencesValidator;
2506        }
2507    }
2508
2509    public long getScopeGroupId(HttpServletRequest request) {
2510        String portletId = getPortletId(request);
2511
2512        return getScopeGroupId(request, portletId);
2513    }
2514
2515    public long getScopeGroupId(HttpServletRequest request, String portletId) {
2516        Layout layout = (Layout)request.getAttribute(WebKeys.LAYOUT);
2517
2518        long scopeGroupId = 0;
2519
2520        if (layout != null) {
2521            Group group = layout.getGroup();
2522
2523            if (group.getName().equals(GroupConstants.CONTROL_PANEL)) {
2524                long doAsGroupId = ParamUtil.getLong(request, "doAsGroupId");
2525
2526                if (doAsGroupId <= 0) {
2527                    try {
2528                        Group guestGroup = GroupLocalServiceUtil.getGroup(
2529                            group.getCompanyId(), GroupConstants.GUEST);
2530
2531                        doAsGroupId = guestGroup.getGroupId();
2532                    }
2533                    catch (Exception e) {
2534                    }
2535                }
2536
2537                if (doAsGroupId > 0) {
2538                    scopeGroupId = doAsGroupId;
2539                }
2540
2541                try {
2542                    group = GroupLocalServiceUtil.getGroup(scopeGroupId);
2543
2544                    if (group.hasStagingGroup()) {
2545                        Group stagingGroup = group.getStagingGroup();
2546
2547                        scopeGroupId = stagingGroup.getGroupId();
2548                    }
2549                }
2550                catch (Exception e) {
2551                }
2552            }
2553        }
2554
2555        if (scopeGroupId <= 0) {
2556            scopeGroupId = getScopeGroupId(layout, portletId);
2557        }
2558
2559        return scopeGroupId;
2560    }
2561
2562    public long getScopeGroupId(Layout layout) {
2563        if (layout == null) {
2564            return 0;
2565        }
2566        else {
2567            return layout.getGroupId();
2568        }
2569    }
2570
2571    public long getScopeGroupId(Layout layout, String portletId) {
2572        if (layout == null) {
2573            return 0;
2574        }
2575        else {
2576            if (Validator.isNotNull(portletId)) {
2577                try {
2578                    PortletPreferences portletSetup =
2579                        PortletPreferencesFactoryUtil.getLayoutPortletSetup(
2580                            layout, portletId);
2581
2582                    long scopeLayoutId = GetterUtil.getLong(
2583                        portletSetup.getValue("lfr-scope-layout-id", null));
2584
2585                    if (scopeLayoutId > 0) {
2586                        Layout scopeLayout = LayoutLocalServiceUtil.getLayout(
2587                            layout.getGroupId(), layout.isPrivateLayout(),
2588                            scopeLayoutId);
2589
2590                        return scopeLayout.getScopeGroup().getGroupId();
2591                    }
2592                }
2593                catch (Exception e) {
2594                }
2595            }
2596
2597            return layout.getGroupId();
2598        }
2599    }
2600
2601    public long getScopeGroupId(long plid) {
2602        Layout layout = null;
2603
2604        try {
2605            layout = LayoutLocalServiceUtil.getLayout(plid);
2606        }
2607        catch (Exception e) {
2608        }
2609
2610        return getScopeGroupId(layout);
2611    }
2612
2613    public long getScopeGroupId(PortletRequest portletRequest) {
2614        return getScopeGroupId(getHttpServletRequest(portletRequest));
2615    }
2616
2617    public User getSelectedUser(HttpServletRequest request)
2618        throws PortalException, SystemException {
2619
2620        return getSelectedUser(request, true);
2621    }
2622
2623    public User getSelectedUser(
2624            HttpServletRequest request, boolean checkPermission)
2625        throws PortalException, SystemException {
2626
2627        long userId = ParamUtil.getLong(request, "p_u_i_d");
2628
2629        User user = null;
2630
2631        try {
2632            if (checkPermission) {
2633                user = UserServiceUtil.getUserById(userId);
2634            }
2635            else {
2636                user = UserLocalServiceUtil.getUserById(userId);
2637            }
2638        }
2639        catch (NoSuchUserException nsue) {
2640        }
2641
2642        return user;
2643    }
2644
2645    public User getSelectedUser(PortletRequest portletRequest)
2646        throws PortalException, SystemException {
2647
2648        return getSelectedUser(portletRequest, true);
2649    }
2650
2651    public User getSelectedUser(
2652            PortletRequest portletRequest, boolean checkPermission)
2653        throws PortalException, SystemException {
2654
2655        return getSelectedUser(
2656            getHttpServletRequest(portletRequest), checkPermission);
2657    }
2658
2659    public String getStaticResourceURL(
2660        HttpServletRequest request, String uri) {
2661
2662        return getStaticResourceURL(request, uri, null, 0);
2663    }
2664
2665    public String getStaticResourceURL(
2666        HttpServletRequest request, String uri, long timestamp) {
2667
2668        return getStaticResourceURL(request, uri, null, timestamp);
2669    }
2670
2671    public String getStaticResourceURL(
2672        HttpServletRequest request, String uri, String queryString) {
2673
2674        return getStaticResourceURL(request, uri, queryString, 0);
2675    }
2676
2677    public String getStaticResourceURL(
2678        HttpServletRequest request, String uri, String queryString,
2679        long timestamp) {
2680
2681        if (uri.contains(StringPool.QUESTION)) {
2682            return uri;
2683        }
2684
2685        ThemeDisplay themeDisplay = (ThemeDisplay)request.getAttribute(
2686            WebKeys.THEME_DISPLAY);
2687
2688        Theme theme = themeDisplay.getTheme();
2689        ColorScheme colorScheme = themeDisplay.getColorScheme();
2690
2691        Map<String, String[]> parameterMap = null;
2692
2693        if (Validator.isNotNull(queryString)) {
2694            parameterMap = HttpUtil.getParameterMap(queryString);
2695        }
2696
2697        StringBundler sb = new StringBundler();
2698
2699        // URI
2700
2701        sb.append(uri);
2702        sb.append(StringPool.QUESTION);
2703
2704        // Browser id
2705
2706        if ((parameterMap == null) ||
2707            (!parameterMap.containsKey("browserId"))) {
2708
2709            sb.append("&browserId=");
2710            sb.append(BrowserSnifferUtil.getBrowserId(request));
2711        }
2712
2713        // Theme and color scheme
2714
2715        if (uri.endsWith(".jsp")) {
2716            if ((parameterMap == null) ||
2717                (!parameterMap.containsKey("themeId"))) {
2718
2719                sb.append("&themeId=");
2720                sb.append(theme.getThemeId());
2721            }
2722
2723            if ((parameterMap == null) ||
2724                (!parameterMap.containsKey("colorSchemeId"))) {
2725
2726                sb.append("&colorSchemeId=");
2727                sb.append(colorScheme.getColorSchemeId());
2728            }
2729        }
2730
2731        // Minifier
2732
2733        if ((parameterMap == null) ||
2734            (!parameterMap.containsKey("minifierType"))) {
2735
2736            String minifierType = StringPool.BLANK;
2737
2738            if (uri.endsWith(".css") || uri.endsWith("css.jsp")) {
2739                if (themeDisplay.isThemeCssFastLoad()) {
2740                    minifierType = "css";
2741                }
2742            }
2743            else if (themeDisplay.isThemeJsFastLoad()) {
2744                minifierType = "js";
2745            }
2746
2747            if (Validator.isNotNull(minifierType)) {
2748                sb.append("&minifierType=");
2749                sb.append(minifierType);
2750            }
2751        }
2752
2753        // Query string
2754
2755        if (Validator.isNotNull(queryString)) {
2756            if (!queryString.startsWith(StringPool.AMPERSAND)) {
2757                sb.append(StringPool.AMPERSAND);
2758            }
2759
2760            sb.append(queryString);
2761        }
2762
2763        // Language id
2764
2765        sb.append("&languageId=");
2766        sb.append(themeDisplay.getLanguageId());
2767
2768        // Timestamp
2769
2770        boolean appendedTimestamp = false;
2771
2772        if (uri.startsWith(StrutsUtil.TEXT_HTML_DIR)) {
2773            ServletContext servletContext =
2774                (ServletContext)request.getAttribute(WebKeys.CTX);
2775
2776            String uriRealPath = ServletContextUtil.getRealPath(
2777                servletContext, uri);
2778
2779            if (uriRealPath != null) {
2780                File uriFile = new File(uriRealPath);
2781
2782                if (uriFile.exists()) {
2783                    sb.append("&t=");
2784                    sb.append(uriFile.lastModified());
2785
2786                    appendedTimestamp = true;
2787                }
2788            }
2789        }
2790
2791        if (!appendedTimestamp &&
2792            ((parameterMap == null) || !parameterMap.containsKey("t"))) {
2793
2794            sb.append("&t=");
2795            sb.append(theme.getTimestamp());
2796        }
2797
2798        String url = sb.toString();
2799
2800        url = StringUtil.replace(url, "?&", StringPool.QUESTION);
2801
2802        return url;
2803    }
2804
2805    public String getStrutsAction(HttpServletRequest request) {
2806        String strutsAction = ParamUtil.getString(request, "struts_action");
2807
2808        if (Validator.isNotNull(strutsAction)) {
2809
2810            // This method should only return a Struts action if you're dealing
2811            // with a regular HTTP servlet request, not a portlet HTTP servlet
2812            // request.
2813
2814            return StringPool.BLANK;
2815        }
2816
2817        return _getPortletParam(request, "struts_action");
2818    }
2819
2820    public String[] getSystemCommunityRoles() {
2821        return _allSystemCommunityRoles;
2822    }
2823
2824    public String[] getSystemGroups() {
2825        return _allSystemGroups;
2826    }
2827
2828    public String[] getSystemOrganizationRoles() {
2829        return _allSystemOrganizationRoles;
2830    }
2831
2832    public String[] getSystemRoles() {
2833        return _allSystemRoles;
2834    }
2835
2836    public UploadServletRequest getUploadServletRequest(
2837        HttpServletRequest request) {
2838
2839        HttpServletRequestWrapper requestWrapper = null;
2840
2841        if (request instanceof HttpServletRequestWrapper) {
2842            requestWrapper = (HttpServletRequestWrapper)request;
2843        }
2844
2845        UploadServletRequest uploadRequest = null;
2846
2847        while (uploadRequest == null) {
2848
2849            // Find the underlying UploadServletRequest wrapper. For example,
2850            // WebSphere wraps all requests with ProtectedServletRequest.
2851
2852            if (requestWrapper instanceof UploadServletRequest) {
2853                uploadRequest = (UploadServletRequest)requestWrapper;
2854            }
2855            else {
2856                HttpServletRequest parentRequest =
2857                    (HttpServletRequest)requestWrapper.getRequest();
2858
2859                if (!(parentRequest instanceof HttpServletRequestWrapper)) {
2860
2861                    // This block should never be reached unless this method is
2862                    // called from a hot deployable portlet. See LayoutAction.
2863
2864                    uploadRequest = new UploadServletRequestImpl(parentRequest);
2865
2866                    break;
2867                }
2868                else {
2869                    requestWrapper = (HttpServletRequestWrapper)parentRequest;
2870                }
2871            }
2872        }
2873
2874        return uploadRequest;
2875    }
2876
2877    public UploadPortletRequest getUploadPortletRequest(
2878        PortletRequest portletRequest) {
2879
2880        PortletRequestImpl portletRequestImpl =
2881            (PortletRequestImpl)portletRequest;
2882
2883        DynamicServletRequest dynamicRequest =
2884            (DynamicServletRequest)portletRequestImpl.getHttpServletRequest();
2885
2886        HttpServletRequestWrapper requestWrapper =
2887            (HttpServletRequestWrapper)dynamicRequest.getRequest();
2888
2889        UploadServletRequest uploadRequest = getUploadServletRequest(
2890            requestWrapper);
2891
2892        return new UploadPortletRequestImpl(
2893            uploadRequest,
2894            PortalUtil.getPortletNamespace(
2895                portletRequestImpl.getPortletName()));
2896    }
2897
2898    public Date getUptime() {
2899        return _UP_TIME;
2900    }
2901
2902    public String getURLWithSessionId(String url, String sessionId) {
2903        if (!PropsValues.SESSION_ENABLE_URL_WITH_SESSION_ID) {
2904            return url;
2905        }
2906
2907        // LEP-4787
2908
2909        int x = url.indexOf(StringPool.SEMICOLON);
2910
2911        if (x != -1) {
2912            return url;
2913        }
2914
2915        x = url.indexOf(StringPool.QUESTION);
2916
2917        if (x != -1) {
2918            StringBundler sb = new StringBundler(4);
2919
2920            sb.append(url.substring(0, x));
2921            sb.append(_JSESSIONID);
2922            sb.append(sessionId);
2923            sb.append(url.substring(x));
2924
2925            return sb.toString();
2926        }
2927
2928        // In IE6, http://www.abc.com;jsessionid=XYZ does not work, but
2929        // http://www.abc.com/;jsessionid=XYZ does work.
2930
2931        x = url.indexOf(StringPool.DOUBLE_SLASH);
2932
2933        StringBundler sb = new StringBundler(4);
2934
2935        sb.append(url);
2936
2937        if (x != -1) {
2938            int y = url.lastIndexOf(StringPool.SLASH);
2939
2940            if (x + 1 == y) {
2941                sb.append(StringPool.SLASH);
2942            }
2943        }
2944
2945        sb.append(_JSESSIONID);
2946        sb.append(sessionId);
2947
2948        return sb.toString();
2949    }
2950
2951    public User getUser(HttpServletRequest request)
2952        throws PortalException, SystemException {
2953
2954        long userId = getUserId(request);
2955
2956        if (userId <= 0) {
2957
2958            // Portlet WARs may have the correct remote user and not have the
2959            // correct user id because the user id is saved in the session
2960            // and may not be accessible by the portlet WAR's session. This
2961            // behavior is inconsistent across different application servers.
2962
2963            String remoteUser = request.getRemoteUser();
2964
2965            if (remoteUser == null) {
2966                return null;
2967            }
2968
2969            userId = GetterUtil.getLong(remoteUser);
2970        }
2971
2972        User user = (User)request.getAttribute(WebKeys.USER);
2973
2974        if (user == null) {
2975            user = UserLocalServiceUtil.getUserById(userId);
2976
2977            request.setAttribute(WebKeys.USER, user);
2978        }
2979
2980        return user;
2981    }
2982
2983    public User getUser(PortletRequest portletRequest)
2984        throws PortalException, SystemException {
2985
2986        return getUser(getHttpServletRequest(portletRequest));
2987    }
2988
2989    public long getUserId(HttpServletRequest request) {
2990        Long userIdObj = (Long)request.getAttribute(WebKeys.USER_ID);
2991
2992        if (userIdObj != null) {
2993            return userIdObj.longValue();
2994        }
2995
2996        String path = GetterUtil.getString(request.getPathInfo());
2997        String strutsAction = getStrutsAction(request);
2998        String actionName = _getPortletParam(request, "actionName");
2999
3000        boolean alwaysAllowDoAsUser = false;
3001
3002        if (path.equals("/portal/fckeditor") ||
3003            strutsAction.equals("/document_library/edit_file_entry") ||
3004            strutsAction.equals("/image_gallery/edit_image") ||
3005            strutsAction.equals("/wiki/edit_page_attachment") ||
3006            actionName.equals("addFile")) {
3007
3008            alwaysAllowDoAsUser = true;
3009        }
3010
3011        if ((!PropsValues.PORTAL_JAAS_ENABLE &&
3012              PropsValues.PORTAL_IMPERSONATION_ENABLE) ||
3013            (alwaysAllowDoAsUser)) {
3014
3015            String doAsUserIdString = ParamUtil.getString(
3016                request, "doAsUserId");
3017
3018            try {
3019                long doAsUserId = getDoAsUserId(
3020                    request, doAsUserIdString, alwaysAllowDoAsUser);
3021
3022                if (doAsUserId > 0) {
3023                    if (_log.isDebugEnabled()) {
3024                        _log.debug("Impersonating user " + doAsUserId);
3025                    }
3026
3027                    return doAsUserId;
3028                }
3029            }
3030            catch (Exception e) {
3031                _log.error("Unable to impersonate user " + doAsUserIdString, e);
3032            }
3033        }
3034
3035        HttpSession session = request.getSession();
3036
3037        userIdObj = (Long)session.getAttribute(WebKeys.USER_ID);
3038
3039        if (userIdObj != null) {
3040            request.setAttribute(WebKeys.USER_ID, userIdObj);
3041
3042            return userIdObj.longValue();
3043        }
3044        else {
3045            return 0;
3046        }
3047    }
3048
3049    public long getUserId(PortletRequest portletRequest) {
3050        return getUserId(getHttpServletRequest(portletRequest));
3051    }
3052
3053    public String getUserName(long userId, String defaultUserName) {
3054        return getUserName(
3055            userId, defaultUserName, UserAttributes.USER_NAME_FULL);
3056    }
3057
3058    public String getUserName(
3059        long userId, String defaultUserName, HttpServletRequest request) {
3060
3061        return getUserName(
3062            userId, defaultUserName, UserAttributes.USER_NAME_FULL, request);
3063    }
3064
3065    public String getUserName(
3066        long userId, String defaultUserName, String userAttribute) {
3067
3068        return getUserName(userId, defaultUserName, userAttribute, null);
3069    }
3070
3071    public String getUserName(
3072        long userId, String defaultUserName, String userAttribute,
3073        HttpServletRequest request) {
3074
3075        String userName = defaultUserName;
3076
3077        try {
3078            User user = UserLocalServiceUtil.getUserById(userId);
3079
3080            if (userAttribute.equals(UserAttributes.USER_NAME_FULL)) {
3081                userName = user.getFullName();
3082            }
3083            else {
3084                userName = user.getScreenName();
3085            }
3086
3087            if (request != null) {
3088                Layout layout = (Layout)request.getAttribute(WebKeys.LAYOUT);
3089
3090                PortletURL portletURL = new PortletURLImpl(
3091                    request, PortletKeys.DIRECTORY, layout.getPlid(),
3092                    PortletRequest.RENDER_PHASE);
3093
3094                portletURL.setWindowState(WindowState.MAXIMIZED);
3095                portletURL.setPortletMode(PortletMode.VIEW);
3096
3097                portletURL.setParameter(
3098                    "struts_action", "/directory/view_user");
3099                portletURL.setParameter(
3100                    "p_u_i_d", String.valueOf(user.getUserId()));
3101
3102                userName =
3103                    "<a href=\"" + portletURL.toString() + "\">" + userName +
3104                        "</a>";
3105            }
3106        }
3107        catch (Exception e) {
3108        }
3109
3110        return userName;
3111    }
3112
3113    public String getUserPassword(HttpServletRequest request) {
3114        HttpSession session = request.getSession();
3115
3116        return getUserPassword(session);
3117    }
3118
3119    public String getUserPassword(HttpSession session) {
3120        return (String)session.getAttribute(WebKeys.USER_PASSWORD);
3121    }
3122
3123    public String getUserPassword(PortletRequest portletRequest) {
3124        return getUserPassword(getHttpServletRequest(portletRequest));
3125    }
3126
3127    public String getUserValue(long userId, String param, String defaultValue)
3128        throws SystemException {
3129
3130        if (Validator.isNotNull(defaultValue)) {
3131            return defaultValue;
3132        }
3133        else {
3134            try {
3135                User user = UserLocalServiceUtil.getUserById(userId);
3136
3137                return BeanPropertiesUtil.getString(user, param, defaultValue);
3138            }
3139            catch (PortalException pe) {
3140                return StringPool.BLANK;
3141            }
3142        }
3143    }
3144
3145    public String getWidgetURL(Portlet portlet, ThemeDisplay themeDisplay) {
3146        return _getServletURL(
3147            portlet, PropsValues.WIDGET_SERVLET_MAPPING, themeDisplay);
3148    }
3149
3150    public boolean isLayoutFirstPageable(String type) {
3151        return GetterUtil.getBoolean(
3152            PropsUtil.get(PropsKeys.LAYOUT_FIRST_PAGEABLE, new Filter(type)),
3153            false);
3154    }
3155
3156    public boolean isLayoutFriendliable(Layout layout) {
3157        return GetterUtil.getBoolean(
3158            PropsUtil.get(
3159                PropsKeys.LAYOUT_URL_FRIENDLIABLE,
3160                new Filter(layout.getType())),
3161            true);
3162    }
3163
3164    public boolean isLayoutParentable(Layout layout) {
3165        return isLayoutParentable(layout.getType());
3166    }
3167
3168    public boolean isLayoutParentable(String type) {
3169        return GetterUtil.getBoolean(
3170            PropsUtil.get(PropsKeys.LAYOUT_PARENTABLE, new Filter(type)), true);
3171    }
3172
3173    public boolean isLayoutSitemapable(Layout layout) {
3174        if (layout.isPrivateLayout()) {
3175            return false;
3176        }
3177
3178        return GetterUtil.getBoolean(PropsUtil.get(
3179            PropsKeys.LAYOUT_SITEMAPABLE, new Filter(layout.getType())), true);
3180    }
3181
3182    public boolean isMethodGet(PortletRequest portletRequest) {
3183        HttpServletRequest request = getHttpServletRequest(portletRequest);
3184
3185        String method = GetterUtil.getString(request.getMethod());
3186
3187        if (method.equalsIgnoreCase(HttpMethods.GET)) {
3188            return true;
3189        }
3190        else {
3191            return false;
3192        }
3193    }
3194
3195    public boolean isMethodPost(PortletRequest portletRequest) {
3196        HttpServletRequest request = getHttpServletRequest(portletRequest);
3197
3198        String method = GetterUtil.getString(request.getMethod());
3199
3200        if (method.equalsIgnoreCase(HttpMethods.POST)) {
3201            return true;
3202        }
3203        else {
3204            return false;
3205        }
3206    }
3207
3208    public boolean isReservedParameter(String name) {
3209        return _reservedParams.contains(name);
3210    }
3211
3212    public boolean isSystemGroup(String groupName) {
3213        if (groupName == null) {
3214            return false;
3215        }
3216
3217        groupName = groupName.trim();
3218
3219        int pos = Arrays.binarySearch(
3220            _sortedSystemGroups, groupName, new StringComparator());
3221
3222        if (pos >= 0) {
3223            return true;
3224        }
3225        else {
3226            return false;
3227        }
3228    }
3229
3230    public boolean isSystemRole(String roleName) {
3231        if (roleName == null) {
3232            return false;
3233        }
3234
3235        roleName = roleName.trim();
3236
3237        int pos = Arrays.binarySearch(
3238            _sortedSystemRoles, roleName, new StringComparator());
3239
3240        if (pos >= 0) {
3241            return true;
3242        }
3243        else {
3244            pos = Arrays.binarySearch(
3245                _sortedSystemCommunityRoles, roleName, new StringComparator());
3246
3247            if (pos >= 0) {
3248                return true;
3249            }
3250            else {
3251                pos = Arrays.binarySearch(
3252                    _sortedSystemOrganizationRoles, roleName,
3253                    new StringComparator());
3254
3255                if (pos >= 0) {
3256                    return true;
3257                }
3258            }
3259        }
3260
3261        return false;
3262    }
3263
3264    public boolean isUpdateAvailable() throws SystemException {
3265        return PluginPackageUtil.isUpdateAvailable();
3266    }
3267
3268    public void renderPage(
3269            StringBuilder sb, ServletContext servletContext,
3270            HttpServletRequest request, HttpServletResponse response,
3271            String path)
3272        throws IOException, ServletException {
3273
3274        RequestDispatcher requestDispatcher =
3275            servletContext.getRequestDispatcher(path);
3276
3277        StringServletResponse stringResponse = new StringServletResponse(
3278            response);
3279
3280        requestDispatcher.include(request, stringResponse);
3281
3282        sb.append(stringResponse.getString());
3283    }
3284
3285    public void renderPortlet(
3286            StringBuilder sb, ServletContext servletContext,
3287            HttpServletRequest request, HttpServletResponse response,
3288            Portlet portlet, String queryString)
3289        throws IOException, ServletException {
3290
3291        renderPortlet(
3292            sb, servletContext, request, response, portlet, queryString, null,
3293            null, null);
3294    }
3295
3296    public void renderPortlet(
3297            StringBuilder sb, ServletContext servletContext,
3298            HttpServletRequest request, HttpServletResponse response,
3299            Portlet portlet, String queryString, String columnId,
3300            Integer columnPos, Integer columnCount)
3301        throws IOException, ServletException {
3302
3303        renderPortlet(
3304            sb, servletContext, request, response, portlet, queryString,
3305            columnId, columnPos, columnCount, null);
3306    }
3307
3308    public void renderPortlet(
3309            StringBuilder sb, ServletContext servletContext,
3310            HttpServletRequest request, HttpServletResponse response,
3311            Portlet portlet, String queryString, String columnId,
3312            Integer columnPos, Integer columnCount, String path)
3313        throws IOException, ServletException {
3314
3315        queryString = GetterUtil.getString(queryString);
3316        columnId = GetterUtil.getString(columnId);
3317
3318        if (columnPos == null) {
3319            columnPos = new Integer(0);
3320        }
3321
3322        if (columnCount == null) {
3323            columnCount = new Integer(0);
3324        }
3325
3326        request.setAttribute(WebKeys.RENDER_PORTLET, portlet);
3327        request.setAttribute(WebKeys.RENDER_PORTLET_QUERY_STRING, queryString);
3328        request.setAttribute(WebKeys.RENDER_PORTLET_COLUMN_ID, columnId);
3329        request.setAttribute(WebKeys.RENDER_PORTLET_COLUMN_POS, columnPos);
3330        request.setAttribute(WebKeys.RENDER_PORTLET_COLUMN_COUNT, columnCount);
3331
3332        if (path == null) {
3333            path = "/html/portal/render_portlet.jsp";
3334        }
3335
3336        RequestDispatcher requestDispatcher =
3337            servletContext.getRequestDispatcher(path);
3338
3339        if (sb != null) {
3340            StringServletResponse stringResponse = new StringServletResponse(
3341                response);
3342
3343            requestDispatcher.include(request, stringResponse);
3344
3345            boolean showPortlet = true;
3346
3347            Boolean portletConfiguratorVisibility =
3348                (Boolean)request.getAttribute(
3349                    WebKeys.PORTLET_CONFIGURATOR_VISIBILITY);
3350
3351            if (portletConfiguratorVisibility != null) {
3352                ThemeDisplay themeDisplay = (ThemeDisplay)request.getAttribute(
3353                    WebKeys.THEME_DISPLAY);
3354
3355                try {
3356                    if (!PortletPermissionUtil.contains(
3357                            themeDisplay.getPermissionChecker(),
3358                            themeDisplay.getPlid(), portlet.getPortletId(),
3359                            ActionKeys.CONFIGURATION)) {
3360
3361                        showPortlet = false;
3362                    }
3363                }
3364                catch (Exception e) {
3365                    throw new ServletException(e);
3366                }
3367
3368                request.removeAttribute(
3369                    WebKeys.PORTLET_CONFIGURATOR_VISIBILITY);
3370            }
3371
3372            if (showPortlet) {
3373                sb.append(stringResponse.getString());
3374            }
3375        }
3376        else {
3377
3378            // LEP-766
3379
3380            response.setContentType(ContentTypes.TEXT_HTML_UTF8);
3381
3382            requestDispatcher.include(request, response);
3383        }
3384    }
3385
3386    public void sendError(
3387            Exception e, ActionRequest actionRequest,
3388            ActionResponse actionResponse)
3389        throws IOException {
3390
3391        sendError(0, e, actionRequest, actionResponse);
3392    }
3393
3394    public void sendError(
3395            Exception e, HttpServletRequest request,
3396            HttpServletResponse response)
3397        throws IOException, ServletException {
3398
3399        sendError(0, e, request, response);
3400    }
3401
3402    public void sendError(
3403            int status, Exception e, ActionRequest actionRequest,
3404            ActionResponse actionResponse)
3405        throws IOException {
3406
3407        StringBundler sb = new StringBundler(7);
3408
3409        sb.append(_pathMain);
3410        sb.append("/portal/status?status=");
3411        sb.append(status);
3412        sb.append("&exception=");
3413        sb.append(e.getClass().getName());
3414        sb.append("&previousURL=");
3415        sb.append(HttpUtil.encodeURL(PortalUtil.getCurrentURL(actionRequest)));
3416
3417        actionResponse.sendRedirect(sb.toString());
3418    }
3419
3420    public void sendError(
3421            int status, Exception e, HttpServletRequest request,
3422            HttpServletResponse response)
3423        throws IOException, ServletException {
3424
3425        if (_log.isInfoEnabled()) {
3426            String currentURL = (String)request.getAttribute(
3427                WebKeys.CURRENT_URL);
3428
3429            _log.info(
3430                "Current URL " + currentURL + " generates exception: " +
3431                    e.getMessage());
3432        }
3433
3434        if (_log.isWarnEnabled()) {
3435            _log.warn(e, e);
3436        }
3437
3438        if (response.isCommitted()) {
3439            return;
3440        }
3441
3442        if (status == 0) {
3443            if (e instanceof PrincipalException) {
3444                status = HttpServletResponse.SC_FORBIDDEN;
3445            }
3446            else {
3447                String name = e.getClass().getName();
3448
3449                name = name.substring(name.lastIndexOf(StringPool.PERIOD) + 1);
3450
3451                if (name.startsWith("NoSuch") && name.endsWith("Exception")) {
3452                    status = HttpServletResponse.SC_NOT_FOUND;
3453                }
3454            }
3455
3456            if (status == 0) {
3457
3458                // LPS-5352
3459
3460                if (PropsValues.TCK_URL) {
3461                    status = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
3462                }
3463                else {
3464                    status = HttpServletResponse.SC_BAD_REQUEST;
3465                }
3466            }
3467        }
3468
3469        HttpSession session = request.getSession();
3470
3471        ServletContext servletContext = session.getServletContext();
3472
3473        String redirect = PATH_MAIN + "/portal/status";
3474
3475        if (e instanceof NoSuchLayoutException &&
3476            Validator.isNotNull(
3477                PropsValues.LAYOUT_FRIENDLY_URL_PAGE_NOT_FOUND)) {
3478
3479            response.setStatus(status);
3480
3481            redirect = PropsValues.LAYOUT_FRIENDLY_URL_PAGE_NOT_FOUND;
3482
3483            RequestDispatcher requestDispatcher =
3484                servletContext.getRequestDispatcher(redirect);
3485
3486            if (requestDispatcher != null) {
3487                requestDispatcher.forward(request, response);
3488            }
3489        }
3490        else if (PropsValues.LAYOUT_SHOW_HTTP_STATUS) {
3491            response.setStatus(status);
3492
3493            SessionErrors.add(request, e.getClass().getName(), e);
3494
3495            RequestDispatcher requestDispatcher =
3496                servletContext.getRequestDispatcher(redirect);
3497
3498            if (requestDispatcher != null) {
3499                requestDispatcher.forward(request, response);
3500            }
3501        }
3502        else {
3503            if (e != null) {
3504                response.sendError(status, e.getMessage());
3505            }
3506            else {
3507                response.sendError(status);
3508            }
3509        }
3510    }
3511
3512    /**
3513     * Sets the description for a page. This overrides the existing page
3514     * description.
3515     */
3516    public void setPageDescription(
3517        String description, HttpServletRequest request) {
3518
3519        request.setAttribute(WebKeys.PAGE_DESCRIPTION, description);
3520    }
3521
3522    /**
3523     * Sets the keywords for a page. This overrides the existing page keywords.
3524     */
3525    public void setPageKeywords(String keywords, HttpServletRequest request) {
3526        request.removeAttribute(WebKeys.PAGE_KEYWORDS);
3527
3528        addPageKeywords(keywords, request);
3529    }
3530
3531    /**
3532     * Sets the subtitle for a page. This overrides the existing page subtitle.
3533     */
3534    public void setPageSubtitle(String subtitle, HttpServletRequest request) {
3535        request.setAttribute(WebKeys.PAGE_SUBTITLE, subtitle);
3536    }
3537
3538    /**
3539     * Sets the whole title for a page. This overrides the existing page whole
3540     * title.
3541     */
3542    public void setPageTitle(String title, HttpServletRequest request) {
3543        request.setAttribute(WebKeys.PAGE_TITLE, title);
3544    }
3545
3546    /**
3547     * Sets the port obtained on the first request to the portal.
3548     */
3549    public void setPortalPort(HttpServletRequest request) {
3550        if (_portalPort.intValue() == -1) {
3551            synchronized (_portalPort) {
3552                _portalPort = new Integer(request.getServerPort());
3553            }
3554        }
3555    }
3556
3557    public void storePreferences(PortletPreferences preferences)
3558        throws IOException, ValidatorException {
3559
3560        PortletPreferencesWrapper preferencesWrapper =
3561            (PortletPreferencesWrapper)preferences;
3562
3563        PortletPreferencesImpl preferencesImpl =
3564            preferencesWrapper.getPreferencesImpl();
3565
3566        preferencesImpl.store();
3567    }
3568
3569    public String transformCustomSQL(String sql) {
3570        if ((_customSqlClassNames == null) ||
3571            (_customSqlClassNameIds == null)) {
3572
3573            _initCustomSQL();
3574        }
3575
3576        return StringUtil.replace(
3577            sql, _customSqlClassNames, _customSqlClassNameIds);
3578    }
3579
3580    public PortletMode updatePortletMode(
3581        String portletId, User user, Layout layout, PortletMode portletMode,
3582        HttpServletRequest request) {
3583
3584        LayoutTypePortlet layoutType =
3585            (LayoutTypePortlet)layout.getLayoutType();
3586
3587        if (portletMode == null || Validator.isNull(portletMode.toString())) {
3588            if (layoutType.hasModeAboutPortletId(portletId)) {
3589                return LiferayPortletMode.ABOUT;
3590            }
3591            else if (layoutType.hasModeConfigPortletId(portletId)) {
3592                return LiferayPortletMode.CONFIG;
3593            }
3594            else if (layoutType.hasModeEditPortletId(portletId)) {
3595                return PortletMode.EDIT;
3596            }
3597            else if (layoutType.hasModeEditDefaultsPortletId(portletId)) {
3598                return LiferayPortletMode.EDIT_DEFAULTS;
3599            }
3600            else if (layoutType.hasModeEditGuestPortletId(portletId)) {
3601                return LiferayPortletMode.EDIT_GUEST;
3602            }
3603            else if (layoutType.hasModeHelpPortletId(portletId)) {
3604                return PortletMode.HELP;
3605            }
3606            else if (layoutType.hasModePreviewPortletId(portletId)) {
3607                return LiferayPortletMode.PREVIEW;
3608            }
3609            else if (layoutType.hasModePrintPortletId(portletId)) {
3610                return LiferayPortletMode.PRINT;
3611            }
3612            else {
3613                return PortletMode.VIEW;
3614            }
3615        }
3616        else {
3617            boolean updateLayout = false;
3618
3619            if (portletMode.equals(LiferayPortletMode.ABOUT) &&
3620                !layoutType.hasModeAboutPortletId(portletId)) {
3621
3622                layoutType.addModeAboutPortletId(portletId);
3623
3624                updateLayout = true;
3625            }
3626            else if (portletMode.equals(LiferayPortletMode.CONFIG) &&
3627                     !layoutType.hasModeConfigPortletId(portletId)) {
3628
3629                layoutType.addModeConfigPortletId(portletId);
3630
3631                updateLayout = true;
3632            }
3633            else if (portletMode.equals(PortletMode.EDIT) &&
3634                     !layoutType.hasModeEditPortletId(portletId)) {
3635
3636                layoutType.addModeEditPortletId(portletId);
3637
3638                updateLayout = true;
3639            }
3640            else if (portletMode.equals(LiferayPortletMode.EDIT_DEFAULTS) &&
3641                     !layoutType.hasModeEditDefaultsPortletId(portletId)) {
3642
3643                layoutType.addModeEditDefaultsPortletId(portletId);
3644
3645                updateLayout = true;
3646            }
3647            else if (portletMode.equals(LiferayPortletMode.EDIT_GUEST) &&
3648                     !layoutType.hasModeEditGuestPortletId(portletId)) {
3649
3650                layoutType.addModeEditGuestPortletId(portletId);
3651
3652                updateLayout = true;
3653            }
3654            else if (portletMode.equals(PortletMode.HELP) &&
3655                     !layoutType.hasModeHelpPortletId(portletId)) {
3656
3657                layoutType.addModeHelpPortletId(portletId);
3658
3659                updateLayout = true;
3660            }
3661            else if (portletMode.equals(LiferayPortletMode.PREVIEW) &&
3662                     !layoutType.hasModePreviewPortletId(portletId)) {
3663
3664                layoutType.addModePreviewPortletId(portletId);
3665
3666                updateLayout = true;
3667            }
3668            else if (portletMode.equals(LiferayPortletMode.PRINT) &&
3669                     !layoutType.hasModePrintPortletId(portletId)) {
3670
3671                layoutType.addModePrintPortletId(portletId);
3672
3673                updateLayout = true;
3674            }
3675            else if (portletMode.equals(PortletMode.VIEW) &&
3676                     !layoutType.hasModeViewPortletId(portletId)) {
3677
3678                layoutType.removeModesPortletId(portletId);
3679
3680                updateLayout = true;
3681            }
3682
3683            if (updateLayout) {
3684                LayoutClone layoutClone = LayoutCloneFactory.getInstance();
3685
3686                if (layoutClone != null) {
3687                    layoutClone.update(
3688                        request, layout.getPlid(), layout.getTypeSettings());
3689                }
3690            }
3691
3692            return portletMode;
3693        }
3694    }
3695
3696    public WindowState updateWindowState(
3697        String portletId, User user, Layout layout, WindowState windowState,
3698        HttpServletRequest request) {
3699
3700        LayoutTypePortlet layoutType =
3701            (LayoutTypePortlet)layout.getLayoutType();
3702
3703        if ((windowState == null) ||
3704            (Validator.isNull(windowState.toString()))) {
3705
3706            if (layoutType.hasStateMaxPortletId(portletId)) {
3707                return WindowState.MAXIMIZED;
3708            }
3709            else if (layoutType.hasStateMinPortletId(portletId)) {
3710                return WindowState.MINIMIZED;
3711            }
3712            else {
3713                return WindowState.NORMAL;
3714            }
3715        }
3716        else {
3717            boolean updateLayout = false;
3718
3719            if (windowState.equals(WindowState.MAXIMIZED) &&
3720                !layoutType.hasStateMaxPortletId(portletId)) {
3721
3722                layoutType.addStateMaxPortletId(portletId);
3723
3724                if (PropsValues.LAYOUT_REMEMBER_MAXIMIZED_WINDOW_STATE) {
3725                    updateLayout = true;
3726                }
3727            }
3728            else if (windowState.equals(WindowState.MINIMIZED) &&
3729                     !layoutType.hasStateMinPortletId(portletId)) {
3730
3731                layoutType.addStateMinPortletId(portletId);
3732
3733                updateLayout = true;
3734            }
3735            else if (windowState.equals(WindowState.NORMAL) &&
3736                     !layoutType.hasStateNormalPortletId(portletId)) {
3737
3738                layoutType.removeStatesPortletId(portletId);
3739
3740                updateLayout = true;
3741            }
3742
3743            if (portletId.equals(PortletKeys.LAYOUT_MANAGEMENT) ||
3744                portletId.equals(PortletKeys.PORTLET_CONFIGURATION)) {
3745
3746                updateLayout = false;
3747            }
3748
3749            if (updateLayout) {
3750                LayoutClone layoutClone = LayoutCloneFactory.getInstance();
3751
3752                if (layoutClone != null) {
3753                    layoutClone.update(
3754                        request, layout.getPlid(), layout.getTypeSettings());
3755                }
3756            }
3757
3758            return windowState;
3759        }
3760    }
3761
3762    protected List<Portlet> filterControlPanelPortlets(
3763        Set<Portlet> portlets, String category, ThemeDisplay themeDisplay) {
3764
3765        Group group = themeDisplay.getScopeGroup();
3766
3767        List<Portlet> filteredPortlets = new ArrayList<Portlet>();
3768
3769        if (category.equals(PortletCategoryKeys.CONTENT) && group.isLayout()) {
3770            for (Portlet portlet : portlets) {
3771                if (portlet.isScopeable()) {
3772                    filteredPortlets.add(portlet);
3773                }
3774            }
3775        }
3776        else {
3777            filteredPortlets.addAll(portlets);
3778        }
3779
3780        Iterator<Portlet> itr = filteredPortlets.iterator();
3781
3782        while (itr.hasNext()) {
3783            Portlet portlet = itr.next();
3784
3785            try {
3786                ControlPanelEntry controlPanelEntry =
3787                    portlet.getControlPanelEntryInstance();
3788
3789                if (controlPanelEntry == null) {
3790                    controlPanelEntry =
3791                        DefaultControlPanelEntryFactory.getInstance();
3792                }
3793
3794                if (!controlPanelEntry.isVisible(
3795                        portlet, category, themeDisplay)) {
3796
3797                    itr.remove();
3798                }
3799            }
3800            catch (Exception e) {
3801                _log.error(e, e);
3802
3803                itr.remove();
3804            }
3805        }
3806
3807        return filteredPortlets;
3808    }
3809
3810    protected long getDoAsUserId(
3811            HttpServletRequest request, String doAsUserIdString,
3812            boolean alwaysAllowDoAsUser)
3813        throws Exception {
3814
3815        if (Validator.isNull(doAsUserIdString)) {
3816            return 0;
3817        }
3818
3819        long doAsUserId = 0;
3820
3821        try {
3822            Company company = getCompany(request);
3823
3824            doAsUserId = GetterUtil.getLong(
3825                Encryptor.decrypt(company.getKeyObj(), doAsUserIdString));
3826        }
3827        catch (Exception e) {
3828            if (_log.isWarnEnabled()) {
3829                _log.warn(
3830                    "Unable to impersonate " + doAsUserIdString +
3831                        " because the string cannot be decrypted",
3832                    e);
3833            }
3834
3835            return 0;
3836        }
3837
3838        if (_log.isDebugEnabled()) {
3839            if (alwaysAllowDoAsUser) {
3840                _log.debug(
3841                    "doAsUserId path or Struts action is always allowed");
3842            }
3843            else {
3844                _log.debug(
3845                    "doAsUserId path is Struts action not always allowed");
3846            }
3847        }
3848
3849        if (alwaysAllowDoAsUser) {
3850            request.setAttribute(WebKeys.USER_ID, new Long(doAsUserId));
3851
3852            return doAsUserId;
3853        }
3854
3855        HttpSession session = request.getSession();
3856
3857        Long realUserIdObj = (Long)session.getAttribute(WebKeys.USER_ID);
3858
3859        if (realUserIdObj == null) {
3860            return 0;
3861        }
3862
3863        User doAsUser = UserLocalServiceUtil.getUserById(doAsUserId);
3864
3865        long[] organizationIds = doAsUser.getOrganizationIds();
3866
3867        User realUser = UserLocalServiceUtil.getUserById(
3868            realUserIdObj.longValue());
3869        boolean checkGuest = true;
3870
3871        PermissionChecker permissionChecker =
3872            PermissionCheckerFactoryUtil.create(realUser, checkGuest);
3873
3874        if (doAsUser.isDefaultUser() ||
3875            UserPermissionUtil.contains(
3876                permissionChecker, doAsUserId, organizationIds,
3877                ActionKeys.IMPERSONATE)) {
3878
3879            request.setAttribute(WebKeys.USER_ID, new Long(doAsUserId));
3880
3881            return doAsUserId;
3882        }
3883        else {
3884            _log.error(
3885                "User " + realUserIdObj + " does not have the permission " +
3886                    "to impersonate " + doAsUserId);
3887
3888            return 0;
3889        }
3890    }
3891
3892    private long _getPlidFromPortletId(
3893        long groupId, boolean privateLayout, String portletId) {
3894
3895        long scopeGroupId = groupId;
3896
3897        try {
3898            Group group = GroupLocalServiceUtil.getGroup(groupId);
3899
3900            if (group.isLayout()) {
3901                Layout scopeLayout = LayoutLocalServiceUtil.getLayout(
3902                    group.getClassPK());
3903
3904                groupId = scopeLayout.getGroupId();
3905            }
3906        }
3907        catch (Exception e) {
3908        }
3909
3910        long plid = LayoutConstants.DEFAULT_PLID;
3911
3912        try {
3913            List<Layout> layouts = LayoutLocalServiceUtil.getLayouts(
3914                groupId, privateLayout, LayoutConstants.TYPE_PORTLET);
3915
3916            for (Layout layout : layouts) {
3917                LayoutTypePortlet layoutTypePortlet =
3918                    (LayoutTypePortlet)layout.getLayoutType();
3919
3920                if (layoutTypePortlet.hasPortletId(portletId)) {
3921                    if (getScopeGroupId(layout, portletId) == scopeGroupId) {
3922                        plid = layout.getPlid();
3923
3924                        break;
3925                    }
3926                }
3927            }
3928        }
3929        catch (SystemException se) {
3930            if (_log.isWarnEnabled()) {
3931                _log.warn(se.getMessage(), se);
3932            }
3933        }
3934
3935        return plid;
3936    }
3937
3938    private String _getPortletParam(HttpServletRequest request, String name) {
3939        String value = null;
3940
3941        int valueCount = 0;
3942
3943        Enumeration<String> enu = request.getParameterNames();
3944
3945        while (enu.hasMoreElements()) {
3946            String curName = enu.nextElement();
3947
3948            int pos = curName.indexOf(StringPool.UNDERLINE + name);
3949
3950            if (pos != -1) {
3951                valueCount++;
3952
3953                // There should never be more than one value
3954
3955                if (valueCount > 1) {
3956                    return StringPool.BLANK;
3957                }
3958
3959                String curValue = ParamUtil.getString(request, curName);
3960
3961                if (Validator.isNotNull(curValue)) {
3962
3963                    // The Struts action must be for the correct portlet
3964
3965                    String portletId1 = curName.substring(1, pos);
3966                    String portletId2 = ParamUtil.getString(request, "p_p_id");
3967
3968                    if (portletId1.equals(portletId2)) {
3969                        value = curValue;
3970                    }
3971                }
3972            }
3973        }
3974
3975        if (value == null) {
3976            value = StringPool.BLANK;
3977        }
3978
3979        return value;
3980    }
3981
3982    private String _getServletURL(
3983        Portlet portlet, String servletPath, ThemeDisplay themeDisplay) {
3984
3985        String layoutURL = getLayoutURL(themeDisplay);
3986
3987        Layout layout = themeDisplay.getLayout();
3988
3989        StringBundler sb = new StringBundler();
3990
3991        if (HttpUtil.hasDomain(layoutURL)) {
3992            String protocol = HttpUtil.getProtocol(layoutURL);
3993            String domain = HttpUtil.getDomain(layoutURL);
3994            HttpUtil.removeDomain(layoutURL);
3995
3996            sb.append(protocol);
3997            sb.append(Http.PROTOCOL_DELIMITER);
3998            sb.append(domain);
3999
4000            if (Validator.isNotNull(_pathContext)) {
4001                sb.append(_pathContext);
4002            }
4003
4004            if (themeDisplay.isI18n()) {
4005                sb.append(themeDisplay.getI18nPath());
4006            }
4007
4008            sb.append(servletPath);
4009            sb.append(layout.getFriendlyURL());
4010        }
4011        else {
4012            sb.append(themeDisplay.getPortalURL());
4013
4014            if (Validator.isNotNull(_pathContext)) {
4015                sb.append(_pathContext);
4016            }
4017
4018            if (themeDisplay.isI18n()) {
4019                sb.append(themeDisplay.getI18nPath());
4020            }
4021
4022            sb.append(servletPath);
4023
4024            Group group = layout.getGroup();
4025
4026            if (layout.isPrivateLayout()) {
4027                if (group.isUser()) {
4028                    sb.append(_PRIVATE_USER_SERVLET_MAPPING);
4029                }
4030                else {
4031                    sb.append(_PRIVATE_GROUP_SERVLET_MAPPING);
4032                }
4033            }
4034            else {
4035                sb.append(_PUBLIC_GROUP_SERVLET_MAPPING);
4036            }
4037
4038            sb.append(group.getFriendlyURL());
4039            sb.append(layout.getFriendlyURL());
4040        }
4041
4042        sb.append(FRIENDLY_URL_SEPARATOR);
4043
4044        FriendlyURLMapper friendlyURLMapper =
4045            portlet.getFriendlyURLMapperInstance();
4046
4047        if ((friendlyURLMapper != null) && !portlet.isInstanceable()) {
4048            sb.append(friendlyURLMapper.getMapping());
4049        }
4050        else {
4051            sb.append(portlet.getPortletId());
4052        }
4053
4054        return sb.toString();
4055    }
4056
4057    private void _initCustomSQL() {
4058        _customSqlClassNames = new String[] {
4059            "[$CLASS_NAME_ID_COM.LIFERAY.PORTAL.MODEL.GROUP$]",
4060            "[$CLASS_NAME_ID_COM.LIFERAY.PORTAL.MODEL.ORGANIZATION$]",
4061            "[$CLASS_NAME_ID_COM.LIFERAY.PORTAL.MODEL.ROLE$]",
4062            "[$CLASS_NAME_ID_COM.LIFERAY.PORTAL.MODEL.USER$]",
4063            "[$CLASS_NAME_ID_COM.LIFERAY.PORTAL.MODEL.USERGROUP$]",
4064            "[$CLASS_NAME_ID_COM.LIFERAY.PORTLET.BLOGS.MODEL.BLOGSENTRY$]",
4065            "[$CLASS_NAME_ID_COM.LIFERAY.PORTLET.BOOKMARKS.MODEL." +
4066                "BOOKMARKSENTRY$]",
4067            "[$CLASS_NAME_ID_COM.LIFERAY.PORTLET.CALENDAR.MODEL.CALEVENT$]",
4068            "[$CLASS_NAME_ID_COM.LIFERAY.PORTLET.DOCUMENTLIBRARY.MODEL." +
4069                "DLFILEENTRY$]",
4070            "[$CLASS_NAME_ID_COM.LIFERAY.PORTLET.IMAGEGALLERY.MODEL.IGIMAGE$]",
4071            "[$CLASS_NAME_ID_COM.LIFERAY.PORTLET.MESSAGEBOARDS.MODEL." +
4072                "MBMESSAGE$]",
4073            "[$CLASS_NAME_ID_COM.LIFERAY.PORTLET.WIKI.MODEL.WIKIPAGE$]",
4074            "[$FALSE$]",
4075            "[$TRUE$]"
4076        };
4077
4078        DB db = DBFactoryUtil.getDB();
4079
4080        _customSqlClassNameIds = new String[] {
4081            String.valueOf(PortalUtil.getClassNameId(Group.class)),
4082            String.valueOf(PortalUtil.getClassNameId(Organization.class)),
4083            String.valueOf(PortalUtil.getClassNameId(Role.class)),
4084            String.valueOf(PortalUtil.getClassNameId(User.class)),
4085            String.valueOf(PortalUtil.getClassNameId(UserGroup.class)),
4086            String.valueOf(PortalUtil.getClassNameId(BlogsEntry.class)),
4087            String.valueOf(PortalUtil.getClassNameId(BookmarksEntry.class)),
4088            String.valueOf(PortalUtil.getClassNameId(CalEvent.class)),
4089            String.valueOf(PortalUtil.getClassNameId(DLFileEntry.class)),
4090            String.valueOf(PortalUtil.getClassNameId(IGImage.class)),
4091            String.valueOf(PortalUtil.getClassNameId(MBMessage.class)),
4092            String.valueOf(PortalUtil.getClassNameId(WikiPage.class)),
4093            db.getTemplateFalse(),
4094            db.getTemplateTrue()
4095        };
4096    }
4097
4098    private static final String _J_SECURITY_CHECK = "j_security_check";
4099
4100    private static final String _JSESSIONID = ";jsessionid=";
4101
4102    private static final String _LOCALHOST = "localhost";
4103
4104    private static final String  _PRIVATE_GROUP_SERVLET_MAPPING =
4105        PropsValues.LAYOUT_FRIENDLY_URL_PRIVATE_GROUP_SERVLET_MAPPING;
4106
4107    private static final String _PRIVATE_USER_SERVLET_MAPPING =
4108        PropsValues.LAYOUT_FRIENDLY_URL_PRIVATE_USER_SERVLET_MAPPING;
4109
4110    private static final String _PUBLIC_GROUP_SERVLET_MAPPING =
4111        PropsValues.LAYOUT_FRIENDLY_URL_PUBLIC_SERVLET_MAPPING;
4112
4113    private static final Date _UP_TIME = new Date();
4114
4115    private static Log _log = LogFactoryUtil.getLog(PortalImpl.class);
4116
4117    private String[] _allSystemCommunityRoles;
4118    private String[] _allSystemGroups;
4119    private String[] _allSystemOrganizationRoles;
4120    private String[] _allSystemRoles;
4121    private String _cdnHostHttp;
4122    private String _cdnHostHttps;
4123    private String _computerAddress;
4124    private String _computerName;
4125    private String[] _customSqlClassNameIds;
4126    private String[] _customSqlClassNames;
4127    private String _globalLibDir;
4128    private String _pathContext;
4129    private String _pathFriendlyURLPrivateGroup;
4130    private String _pathFriendlyURLPrivateUser;
4131    private String _pathFriendlyURLPublic;
4132    private String _pathImage;
4133    private String _pathMain;
4134    private Map<String, Long> _plidToPortletIdCache =
4135        new ConcurrentHashMap<String, Long>();
4136    private String _portalLibDir;
4137    private Integer _portalPort = new Integer(-1);
4138    private String _portalWebDir;
4139    private Set<String> _reservedParams;
4140    private String[] _sortedSystemCommunityRoles;
4141    private String[] _sortedSystemGroups;
4142    private String[] _sortedSystemOrganizationRoles;
4143    private String[] _sortedSystemRoles;
4144
4145}