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