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