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