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