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