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