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