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