001    /**
002     * Copyright (c) 2000-2013 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.events;
016    
017    import com.liferay.portal.LayoutPermissionException;
018    import com.liferay.portal.NoSuchGroupException;
019    import com.liferay.portal.NoSuchLayoutException;
020    import com.liferay.portal.NoSuchUserException;
021    import com.liferay.portal.kernel.dao.orm.QueryUtil;
022    import com.liferay.portal.kernel.events.Action;
023    import com.liferay.portal.kernel.events.ActionException;
024    import com.liferay.portal.kernel.exception.PortalException;
025    import com.liferay.portal.kernel.exception.SystemException;
026    import com.liferay.portal.kernel.image.ImageToolUtil;
027    import com.liferay.portal.kernel.lar.PortletDataHandlerKeys;
028    import com.liferay.portal.kernel.log.Log;
029    import com.liferay.portal.kernel.log.LogFactoryUtil;
030    import com.liferay.portal.kernel.portlet.LiferayPortletURL;
031    import com.liferay.portal.kernel.portlet.LiferayWindowState;
032    import com.liferay.portal.kernel.servlet.BrowserSnifferUtil;
033    import com.liferay.portal.kernel.servlet.HttpHeaders;
034    import com.liferay.portal.kernel.servlet.SessionErrors;
035    import com.liferay.portal.kernel.util.ColorSchemeFactoryUtil;
036    import com.liferay.portal.kernel.util.CookieKeys;
037    import com.liferay.portal.kernel.util.FriendlyURLNormalizerUtil;
038    import com.liferay.portal.kernel.util.GetterUtil;
039    import com.liferay.portal.kernel.util.HttpUtil;
040    import com.liferay.portal.kernel.util.LocaleUtil;
041    import com.liferay.portal.kernel.util.ParamUtil;
042    import com.liferay.portal.kernel.util.PropsKeys;
043    import com.liferay.portal.kernel.util.ServerDetector;
044    import com.liferay.portal.kernel.util.SessionParamUtil;
045    import com.liferay.portal.kernel.util.StringBundler;
046    import com.liferay.portal.kernel.util.StringPool;
047    import com.liferay.portal.kernel.util.StringUtil;
048    import com.liferay.portal.kernel.util.UnicodeProperties;
049    import com.liferay.portal.kernel.util.Validator;
050    import com.liferay.portal.model.ColorScheme;
051    import com.liferay.portal.model.Company;
052    import com.liferay.portal.model.Group;
053    import com.liferay.portal.model.GroupConstants;
054    import com.liferay.portal.model.Image;
055    import com.liferay.portal.model.Layout;
056    import com.liferay.portal.model.LayoutConstants;
057    import com.liferay.portal.model.LayoutSet;
058    import com.liferay.portal.model.LayoutTemplate;
059    import com.liferay.portal.model.LayoutTypePortlet;
060    import com.liferay.portal.model.LayoutTypePortletConstants;
061    import com.liferay.portal.model.Portlet;
062    import com.liferay.portal.model.RoleConstants;
063    import com.liferay.portal.model.Theme;
064    import com.liferay.portal.model.User;
065    import com.liferay.portal.model.impl.VirtualLayout;
066    import com.liferay.portal.security.auth.PrincipalException;
067    import com.liferay.portal.security.permission.ActionKeys;
068    import com.liferay.portal.security.permission.PermissionChecker;
069    import com.liferay.portal.security.permission.PermissionCheckerFactoryUtil;
070    import com.liferay.portal.security.permission.PermissionThreadLocal;
071    import com.liferay.portal.service.GroupLocalServiceUtil;
072    import com.liferay.portal.service.ImageLocalServiceUtil;
073    import com.liferay.portal.service.LayoutLocalServiceUtil;
074    import com.liferay.portal.service.LayoutSetLocalServiceUtil;
075    import com.liferay.portal.service.PortletLocalServiceUtil;
076    import com.liferay.portal.service.RoleLocalServiceUtil;
077    import com.liferay.portal.service.ServiceContext;
078    import com.liferay.portal.service.ServiceContextFactory;
079    import com.liferay.portal.service.ServiceContextThreadLocal;
080    import com.liferay.portal.service.ThemeLocalServiceUtil;
081    import com.liferay.portal.service.UserLocalServiceUtil;
082    import com.liferay.portal.service.permission.GroupPermissionUtil;
083    import com.liferay.portal.service.permission.LayoutPermissionUtil;
084    import com.liferay.portal.service.permission.PortalPermissionUtil;
085    import com.liferay.portal.service.permission.PortletPermissionUtil;
086    import com.liferay.portal.theme.ThemeDisplay;
087    import com.liferay.portal.theme.ThemeDisplayFactory;
088    import com.liferay.portal.util.LayoutClone;
089    import com.liferay.portal.util.LayoutCloneFactory;
090    import com.liferay.portal.util.PortalUtil;
091    import com.liferay.portal.util.PortletCategoryKeys;
092    import com.liferay.portal.util.PortletKeys;
093    import com.liferay.portal.util.PrefsPropsUtil;
094    import com.liferay.portal.util.PropsUtil;
095    import com.liferay.portal.util.PropsValues;
096    import com.liferay.portal.util.WebKeys;
097    import com.liferay.portal.webserver.WebServerServletTokenUtil;
098    import com.liferay.portlet.PortalPreferences;
099    import com.liferay.portlet.PortletPreferencesFactoryUtil;
100    import com.liferay.portlet.PortletURLImpl;
101    import com.liferay.portlet.asset.model.AssetEntry;
102    import com.liferay.portlet.asset.service.AssetEntryLocalServiceUtil;
103    import com.liferay.portlet.journal.NoSuchArticleException;
104    import com.liferay.portlet.journal.model.JournalArticle;
105    import com.liferay.portlet.journal.service.JournalArticleServiceUtil;
106    import com.liferay.portlet.sites.util.SitesUtil;
107    
108    import java.io.File;
109    
110    import java.util.ArrayList;
111    import java.util.HashMap;
112    import java.util.LinkedHashMap;
113    import java.util.List;
114    import java.util.Locale;
115    import java.util.Map;
116    import java.util.TimeZone;
117    
118    import javax.portlet.PortletMode;
119    import javax.portlet.PortletRequest;
120    import javax.portlet.PortletURL;
121    import javax.portlet.WindowState;
122    
123    import javax.servlet.http.HttpServletRequest;
124    import javax.servlet.http.HttpServletResponse;
125    import javax.servlet.http.HttpSession;
126    
127    import org.apache.commons.lang.time.StopWatch;
128    
129    /**
130     * @author Brian Wing Shun Chan
131     * @author Felix Ventero
132     * @author Jorge Ferrer
133     */
134    public class ServicePreAction extends Action {
135    
136            public ServicePreAction() {
137                    initImportLARFiles();
138            }
139    
140            public ThemeDisplay initThemeDisplay(
141                            HttpServletRequest request, HttpServletResponse response)
142                    throws Exception {
143    
144                    HttpSession session = request.getSession();
145    
146                    // Company
147    
148                    Company company = PortalUtil.getCompany(request);
149    
150                    long companyId = company.getCompanyId();
151    
152                    // CDN host
153    
154                    String cdnHost = PortalUtil.getCDNHost(request);
155    
156                    String dynamicResourcesCDNHost = StringPool.BLANK;
157    
158                    boolean cdnDynamicResourceEnabled =
159                            PortalUtil.isCDNDynamicResourcesEnabled(request);
160    
161                    if (cdnDynamicResourceEnabled) {
162                            dynamicResourcesCDNHost = cdnHost;
163                    }
164    
165                    // Portal URL
166    
167                    String portalURL = PortalUtil.getPortalURL(request);
168    
169                    // Paths
170    
171                    String contextPath = PortalUtil.getPathContext();
172                    String friendlyURLPrivateGroupPath =
173                            PortalUtil.getPathFriendlyURLPrivateGroup();
174                    String friendlyURLPrivateUserPath =
175                            PortalUtil.getPathFriendlyURLPrivateUser();
176                    String friendlyURLPublicPath = PortalUtil.getPathFriendlyURLPublic();
177                    String imagePath = dynamicResourcesCDNHost.concat(
178                            PortalUtil.getPathImage());
179                    String mainPath = PortalUtil.getPathMain();
180    
181                    String i18nPath = (String)request.getAttribute(WebKeys.I18N_PATH);
182    
183                    if (Validator.isNotNull(i18nPath)) {
184                            if (Validator.isNotNull(contextPath)) {
185                                    String i18nContextPath = contextPath.concat(i18nPath);
186    
187                                    friendlyURLPrivateGroupPath = StringUtil.replaceFirst(
188                                            friendlyURLPrivateGroupPath, contextPath, i18nContextPath);
189                                    friendlyURLPrivateUserPath = StringUtil.replaceFirst(
190                                            friendlyURLPrivateUserPath, contextPath, i18nContextPath);
191                                    friendlyURLPublicPath = StringUtil.replaceFirst(
192                                            friendlyURLPublicPath, contextPath, i18nContextPath);
193                                    mainPath = StringUtil.replaceFirst(
194                                            mainPath, contextPath, i18nContextPath);
195                            }
196                            else {
197                                    friendlyURLPrivateGroupPath = i18nPath.concat(
198                                            friendlyURLPrivateGroupPath);
199                                    friendlyURLPrivateUserPath = i18nPath.concat(
200                                            friendlyURLPrivateUserPath);
201                                    friendlyURLPublicPath = i18nPath.concat(friendlyURLPublicPath);
202                                    mainPath = i18nPath.concat(mainPath);
203                            }
204                    }
205    
206                    // Company logo
207    
208                    StringBundler sb = new StringBundler(5);
209    
210                    sb.append(imagePath);
211                    sb.append("/company_logo?img_id=");
212                    sb.append(company.getLogoId());
213                    sb.append("&t=");
214                    sb.append(WebServerServletTokenUtil.getToken(company.getLogoId()));
215    
216                    String companyLogo = sb.toString();
217    
218                    int companyLogoHeight = 0;
219                    int companyLogoWidth = 0;
220    
221                    Image companyLogoImage = null;
222    
223                    if (company.getLogoId() > 0) {
224                            companyLogoImage = ImageLocalServiceUtil.getCompanyLogo(
225                                    company.getLogoId());
226                    }
227                    else {
228                            companyLogoImage = ImageToolUtil.getDefaultCompanyLogo();
229                    }
230    
231                    if (companyLogoImage != null) {
232                            companyLogoHeight = companyLogoImage.getHeight();
233                            companyLogoWidth = companyLogoImage.getWidth();
234                    }
235    
236                    String realCompanyLogo = companyLogo;
237                    int realCompanyLogoHeight = companyLogoHeight;
238                    int realCompanyLogoWidth = companyLogoWidth;
239    
240                    // User
241    
242                    User user = null;
243    
244                    try {
245                            user = PortalUtil.initUser(request);
246                    }
247                    catch (NoSuchUserException nsue) {
248                            return null;
249                    }
250    
251                    boolean signedIn = !user.isDefaultUser();
252    
253                    if (PropsValues.BROWSER_CACHE_DISABLED ||
254                            (PropsValues.BROWSER_CACHE_SIGNED_IN_DISABLED && signedIn)) {
255    
256                            response.setDateHeader(HttpHeaders.EXPIRES, 0);
257                            response.setHeader(
258                                    HttpHeaders.CACHE_CONTROL,
259                                    HttpHeaders.CACHE_CONTROL_NO_CACHE_VALUE);
260                            response.setHeader(
261                                    HttpHeaders.PRAGMA, HttpHeaders.PRAGMA_NO_CACHE_VALUE);
262                    }
263    
264                    User realUser = user;
265    
266                    Long realUserId = (Long)session.getAttribute(WebKeys.USER_ID);
267    
268                    if (realUserId != null) {
269                            if (user.getUserId() != realUserId.longValue()) {
270                                    realUser = UserLocalServiceUtil.getUserById(
271                                            realUserId.longValue());
272                            }
273                    }
274    
275                    String doAsUserId = ParamUtil.getString(request, "doAsUserId");
276                    String doAsUserLanguageId = ParamUtil.getString(
277                            request, "doAsUserLanguageId");
278                    long doAsGroupId = ParamUtil.getLong(request, "doAsGroupId");
279    
280                    long refererGroupId = ParamUtil.getLong(request, "refererGroupId");
281    
282                    long refererPlid = ParamUtil.getLong(request, "refererPlid");
283    
284                    if (LayoutLocalServiceUtil.fetchLayout(refererPlid) == null) {
285                            refererPlid = 0;
286                    }
287    
288                    String controlPanelCategory = ParamUtil.getString(
289                            request, "controlPanelCategory");
290    
291                    // Permission checker
292    
293                    PermissionChecker permissionChecker =
294                            PermissionCheckerFactoryUtil.create(user);
295    
296                    PermissionThreadLocal.setPermissionChecker(permissionChecker);
297    
298                    // Cookie support
299    
300                    try {
301    
302                            // LEP-4069
303    
304                            CookieKeys.validateSupportCookie(request);
305                    }
306                    catch (Exception e) {
307                            CookieKeys.addSupportCookie(request, response);
308                    }
309    
310                    // Time zone
311    
312                    TimeZone timeZone = user.getTimeZone();
313    
314                    if (timeZone == null) {
315                            timeZone = company.getTimeZone();
316                    }
317    
318                    // Layouts
319    
320                    if (signedIn) {
321                            updateUserLayouts(user);
322                    }
323    
324                    Layout layout = null;
325                    List<Layout> layouts = null;
326    
327                    long plid = ParamUtil.getLong(request, "p_l_id");
328    
329                    boolean viewableSourceGroup = true;
330    
331                    if (plid > 0) {
332                            layout = LayoutLocalServiceUtil.getLayout(plid);
333    
334                            long sourceGroupId = ParamUtil.getLong(request, "p_v_l_s_g_id");
335    
336                            if ((sourceGroupId > 0) && (sourceGroupId != layout.getGroupId())) {
337                                    Group sourceGroup = GroupLocalServiceUtil.getGroup(
338                                            sourceGroupId);
339    
340                                    if (layout.isPublicLayout() ||
341                                            SitesUtil.isUserGroupLayoutSetViewable(
342                                                    permissionChecker, layout.getGroup())) {
343    
344                                            layout = new VirtualLayout(layout, sourceGroup);
345                                    }
346                                    else {
347                                            viewableSourceGroup = false;
348                                    }
349                            }
350                    }
351                    else {
352                            long groupId = ParamUtil.getLong(request, "groupId");
353                            boolean privateLayout = ParamUtil.getBoolean(
354                                    request, "privateLayout");
355                            long layoutId = ParamUtil.getLong(request, "layoutId");
356    
357                            if ((groupId > 0) && (layoutId > 0)) {
358                                    layout = LayoutLocalServiceUtil.getLayout(
359                                            groupId, privateLayout, layoutId);
360                            }
361                    }
362    
363                    String ppid = ParamUtil.getString(request, "p_p_id");
364    
365                    Boolean redirectToDefaultLayout = (Boolean)request.getAttribute(
366                            WebKeys.REDIRECT_TO_DEFAULT_LAYOUT);
367    
368                    if (redirectToDefaultLayout == null) {
369                            redirectToDefaultLayout = Boolean.FALSE;
370                    }
371    
372                    if (layout != null) {
373                            Group group = layout.getGroup();
374    
375                            if (!signedIn && PropsValues.AUTH_FORWARD_BY_REDIRECT) {
376                                    request.setAttribute(WebKeys.REQUESTED_LAYOUT, layout);
377                            }
378    
379                            if (Validator.isNull(controlPanelCategory) &&
380                                    Validator.isNotNull(ppid) &&
381                                    (LiferayWindowState.isPopUp(request) ||
382                                     LiferayWindowState.isExclusive(request))) {
383    
384                                    controlPanelCategory = PortletCategoryKeys.PORTLET;
385                            }
386                            else if (Validator.isNotNull(ppid)) {
387                                    Portlet portlet = PortletLocalServiceUtil.getPortletById(
388                                            companyId, ppid);
389    
390                                    String portletControlPanelEntryCategory =
391                                            portlet.getControlPanelEntryCategory();
392    
393                                    if (!controlPanelCategory.startsWith(
394                                                    PortletCategoryKeys.CURRENT_SITE) &&
395                                            portletControlPanelEntryCategory.startsWith(
396                                                    PortletCategoryKeys.SITE_ADMINISTRATION)) {
397    
398                                            portletControlPanelEntryCategory =
399                                                    PortletCategoryKeys.SITES;
400                                    }
401    
402                                    if (!controlPanelCategory.startsWith(
403                                                    PortletCategoryKeys.CURRENT_SITE) &&
404                                            Validator.isNotNull(portletControlPanelEntryCategory)) {
405    
406                                            controlPanelCategory = portletControlPanelEntryCategory;
407                                    }
408                            }
409    
410                            boolean viewableGroup = hasAccessPermission(
411                                    permissionChecker, layout, doAsGroupId, controlPanelCategory,
412                                    true);
413                            boolean viewableStaging =
414                                    !group.isControlPanel() &&
415                                    GroupPermissionUtil.contains(
416                                            permissionChecker, group.getGroupId(),
417                                            ActionKeys.VIEW_STAGING);
418    
419                            if (viewableStaging) {
420                                    layouts = LayoutLocalServiceUtil.getLayouts(
421                                            layout.getGroupId(), layout.isPrivateLayout(),
422                                            LayoutConstants.DEFAULT_PARENT_LAYOUT_ID);
423                            }
424                            else if ((!viewableGroup || !viewableSourceGroup) &&
425                                             group.isStagingGroup()) {
426    
427                                    layout = null;
428                            }
429                            else if (!isLoginRequest(request) &&
430                                             ((!viewableGroup || !viewableSourceGroup) ||
431                                              (!redirectToDefaultLayout &&
432                                               !hasAccessPermission(
433                                                       permissionChecker, layout, doAsGroupId,
434                                                       controlPanelCategory, false)))) {
435    
436                                    if (user.isDefaultUser() &&
437                                            PropsValues.AUTH_LOGIN_PROMPT_ENABLED) {
438    
439                                            throw new PrincipalException("User is not authenticated");
440                                    }
441    
442                                    sb = new StringBundler(6);
443    
444                                    sb.append("User ");
445                                    sb.append(user.getUserId());
446                                    sb.append(" is not allowed to access the ");
447                                    sb.append(layout.isPrivateLayout() ? "private": "public");
448                                    sb.append(" pages of group ");
449                                    sb.append(layout.getGroupId());
450    
451                                    if (_log.isWarnEnabled()) {
452                                            _log.warn(sb.toString());
453                                    }
454    
455                                    throw new NoSuchLayoutException(sb.toString());
456                            }
457                            else if (isLoginRequest(request) && !viewableGroup) {
458                                    layout = null;
459                            }
460                            else if (group.isLayoutPrototype()) {
461                                    layouts = new ArrayList<Layout>();
462                            }
463                            else {
464                                    layouts = LayoutLocalServiceUtil.getLayouts(
465                                            layout.getGroupId(), layout.isPrivateLayout(),
466                                            LayoutConstants.DEFAULT_PARENT_LAYOUT_ID);
467    
468                                    if (!group.isControlPanel()) {
469                                            doAsGroupId = 0;
470                                    }
471                            }
472                    }
473    
474                    List<Layout> unfilteredLayouts = layouts;
475    
476                    if (layout == null) {
477                            Object[] defaultLayout = getDefaultLayout(request, user, signedIn);
478    
479                            layout = (Layout)defaultLayout[0];
480                            layouts = (List<Layout>)defaultLayout[1];
481    
482                            request.setAttribute(WebKeys.LAYOUT_DEFAULT, Boolean.TRUE);
483                    }
484    
485                    Object[] viewableLayouts = getViewableLayouts(
486                            request, user, permissionChecker, layout, layouts, doAsGroupId,
487                            controlPanelCategory);
488    
489                    String layoutSetLogo = null;
490    
491                    layout = (Layout)viewableLayouts[0];
492                    layouts = (List<Layout>)viewableLayouts[1];
493    
494                    Group group = null;
495    
496                    if (layout != null) {
497                            group = layout.getGroup();
498    
499                            if (!group.isControlPanel()) {
500                                    rememberVisitedGroupIds(request, group.getGroupId());
501                            }
502                    }
503    
504                    LayoutTypePortlet layoutTypePortlet = null;
505    
506                    layouts = mergeAdditionalLayouts(
507                            request, user, permissionChecker, layout, layouts, doAsGroupId,
508                            controlPanelCategory);
509    
510                    LayoutSet layoutSet = null;
511    
512                    boolean hasCustomizeLayoutPermission = false;
513                    boolean hasDeleteLayoutPermission = false;
514                    boolean hasUpdateLayoutPermission = false;
515    
516                    boolean customizedView = SessionParamUtil.getBoolean(
517                            request, "customized_view", true);
518    
519                    if (layout != null) {
520                            if (!layout.isTypeControlPanel()) {
521                                    hasCustomizeLayoutPermission = LayoutPermissionUtil.contains(
522                                            permissionChecker, layout, ActionKeys.CUSTOMIZE);
523                                    hasDeleteLayoutPermission = LayoutPermissionUtil.contains(
524                                            permissionChecker, layout, ActionKeys.DELETE);
525                                    hasUpdateLayoutPermission = LayoutPermissionUtil.contains(
526                                            permissionChecker, layout, ActionKeys.UPDATE);
527                            }
528    
529                            layoutSet = layout.getLayoutSet();
530    
531                            if (company.isSiteLogo()) {
532                                    long logoId = 0;
533    
534                                    if (layoutSet.isLogo()) {
535                                            logoId = layoutSet.getLogoId();
536    
537                                            if (logoId == 0) {
538                                                    logoId = layoutSet.getLiveLogoId();
539                                            }
540                                    }
541                                    else {
542                                            LayoutSet siblingLayoutSet =
543                                                    LayoutSetLocalServiceUtil.getLayoutSet(
544                                                            layout.getGroupId(), !layout.isPrivateLayout());
545    
546                                            if (siblingLayoutSet.isLogo()) {
547                                                    logoId = siblingLayoutSet.getLogoId();
548                                            }
549                                    }
550    
551                                    if (logoId > 0) {
552                                            sb = new StringBundler(5);
553    
554                                            sb.append(imagePath);
555                                            sb.append("/layout_set_logo?img_id=");
556                                            sb.append(logoId);
557                                            sb.append("&t=");
558                                            sb.append(WebServerServletTokenUtil.getToken(logoId));
559    
560                                            layoutSetLogo = sb.toString();
561    
562                                            Image layoutSetLogoImage =
563                                                    ImageLocalServiceUtil.getCompanyLogo(logoId);
564    
565                                            companyLogo = layoutSetLogo;
566                                            companyLogoHeight = layoutSetLogoImage.getHeight();
567                                            companyLogoWidth = layoutSetLogoImage.getWidth();
568                                    }
569                            }
570    
571                            plid = layout.getPlid();
572    
573                            // Updates to shared layouts are not reflected until the next time
574                            // the user logs in because group layouts are cached in the session
575    
576                            layout = (Layout)layout.clone();
577    
578                            layoutTypePortlet = (LayoutTypePortlet)layout.getLayoutType();
579    
580                            boolean customizable = layoutTypePortlet.isCustomizable();
581    
582                            if (!customizable ||
583                                    (group.isLayoutPrototype() || group.isLayoutSetPrototype())) {
584    
585                                    customizedView = false;
586                            }
587    
588                            layoutTypePortlet.setCustomizedView(customizedView);
589                            layoutTypePortlet.setUpdatePermission(hasUpdateLayoutPermission);
590    
591                            if (signedIn && customizable && customizedView &&
592                                    hasCustomizeLayoutPermission) {
593    
594                                    PortalPreferences portalPreferences =
595                                            PortletPreferencesFactoryUtil.getPortalPreferences(
596                                                    user.getUserId(), true);
597    
598                                    layoutTypePortlet.setPortalPreferences(portalPreferences);
599                            }
600    
601                            LayoutClone layoutClone = LayoutCloneFactory.getInstance();
602    
603                            if (layoutClone != null) {
604                                    String typeSettings = layoutClone.get(request, plid);
605    
606                                    if (typeSettings != null) {
607                                            UnicodeProperties typeSettingsProperties =
608                                                    new UnicodeProperties(true);
609    
610                                            typeSettingsProperties.load(typeSettings);
611    
612                                            String stateMax = typeSettingsProperties.getProperty(
613                                                    LayoutTypePortletConstants.STATE_MAX);
614                                            String stateMin = typeSettingsProperties.getProperty(
615                                                    LayoutTypePortletConstants.STATE_MIN);
616                                            String modeAbout = typeSettingsProperties.getProperty(
617                                                    LayoutTypePortletConstants.MODE_ABOUT);
618                                            String modeConfig = typeSettingsProperties.getProperty(
619                                                    LayoutTypePortletConstants.MODE_CONFIG);
620                                            String modeEdit = typeSettingsProperties.getProperty(
621                                                    LayoutTypePortletConstants.MODE_EDIT);
622                                            String modeEditDefaults =
623                                                    typeSettingsProperties.getProperty(
624                                                            LayoutTypePortletConstants.MODE_EDIT_DEFAULTS);
625                                            String modeEditGuest = typeSettingsProperties.getProperty(
626                                                    LayoutTypePortletConstants.MODE_EDIT_GUEST);
627                                            String modeHelp = typeSettingsProperties.getProperty(
628                                                    LayoutTypePortletConstants.MODE_HELP);
629                                            String modePreview = typeSettingsProperties.getProperty(
630                                                    LayoutTypePortletConstants.MODE_PREVIEW);
631                                            String modePrint = typeSettingsProperties.getProperty(
632                                                    LayoutTypePortletConstants.MODE_PRINT);
633    
634                                            layoutTypePortlet.setStateMax(stateMax);
635                                            layoutTypePortlet.setStateMin(stateMin);
636                                            layoutTypePortlet.setModeAbout(modeAbout);
637                                            layoutTypePortlet.setModeConfig(modeConfig);
638                                            layoutTypePortlet.setModeEdit(modeEdit);
639                                            layoutTypePortlet.setModeEditDefaults(modeEditDefaults);
640                                            layoutTypePortlet.setModeEditGuest(modeEditGuest);
641                                            layoutTypePortlet.setModeHelp(modeHelp);
642                                            layoutTypePortlet.setModePreview(modePreview);
643                                            layoutTypePortlet.setModePrint(modePrint);
644                                    }
645                            }
646    
647                            request.setAttribute(WebKeys.LAYOUT, layout);
648                            request.setAttribute(WebKeys.LAYOUTS, layouts);
649                    }
650    
651                    // Locale
652    
653                    String i18nLanguageId = (String)request.getAttribute(
654                            WebKeys.I18N_LANGUAGE_ID);
655    
656                    Locale locale = PortalUtil.getLocale(request, response, true);
657    
658                    // Scope
659    
660                    long scopeGroupId = PortalUtil.getScopeGroupId(request);
661    
662                    if ((scopeGroupId <= 0) && (doAsGroupId > 0)) {
663                            scopeGroupId = doAsGroupId;
664                    }
665    
666                    long siteGroupId = PortalUtil.getSiteGroupId(scopeGroupId);
667    
668                    // Theme and color scheme
669    
670                    Theme theme = null;
671                    ColorScheme colorScheme = null;
672    
673                    boolean wapTheme = BrowserSnifferUtil.isWap(request);
674    
675                    if ((layout != null) && group.isControlPanel()) {
676                            String themeId = PrefsPropsUtil.getString(
677                                    companyId, PropsKeys.CONTROL_PANEL_LAYOUT_REGULAR_THEME_ID);
678                            String colorSchemeId =
679                                    ColorSchemeFactoryUtil.getDefaultRegularColorSchemeId();
680    
681                            theme = ThemeLocalServiceUtil.getTheme(
682                                    companyId, themeId, wapTheme);
683                            colorScheme = ThemeLocalServiceUtil.getColorScheme(
684                                    companyId, theme.getThemeId(), colorSchemeId, wapTheme);
685    
686                            if (!wapTheme && theme.isWapTheme()) {
687                                    theme = ThemeLocalServiceUtil.getTheme(
688                                            companyId,
689                                            PropsValues.CONTROL_PANEL_LAYOUT_REGULAR_THEME_ID, false);
690                                    colorScheme = ThemeLocalServiceUtil.getColorScheme(
691                                            companyId, theme.getThemeId(), colorSchemeId, false);
692                            }
693    
694                            request.setAttribute(WebKeys.THEME, theme);
695                            request.setAttribute(WebKeys.COLOR_SCHEME, colorScheme);
696                    }
697    
698                    boolean themeCssFastLoad = SessionParamUtil.getBoolean(
699                            request, "css_fast_load", PropsValues.THEME_CSS_FAST_LOAD);
700                    boolean themeImagesFastLoad = SessionParamUtil.getBoolean(
701                            request, "images_fast_load", PropsValues.THEME_IMAGES_FAST_LOAD);
702    
703                    boolean themeJsBarebone = PropsValues.JAVASCRIPT_BAREBONE_ENABLED;
704    
705                    if (themeJsBarebone) {
706                            if (signedIn) {
707                                    themeJsBarebone = false;
708                            }
709                    }
710    
711                    boolean themeJsFastLoad = SessionParamUtil.getBoolean(
712                            request, "js_fast_load", PropsValues.JAVASCRIPT_FAST_LOAD);
713    
714                    String lifecycle = ParamUtil.getString(request, "p_p_lifecycle", "0");
715    
716                    lifecycle = ParamUtil.getString(request, "p_t_lifecycle", lifecycle);
717    
718                    boolean isolated = ParamUtil.getBoolean(request, "p_p_isolated");
719    
720                    String facebookCanvasPageURL = (String)request.getAttribute(
721                            WebKeys.FACEBOOK_CANVAS_PAGE_URL);
722    
723                    boolean widget = false;
724    
725                    Boolean widgetObj = (Boolean)request.getAttribute(WebKeys.WIDGET);
726    
727                    if (widgetObj != null) {
728                            widget = widgetObj.booleanValue();
729                    }
730    
731                    // Theme display
732    
733                    ThemeDisplay themeDisplay = ThemeDisplayFactory.create();
734    
735                    themeDisplay.setRequest(request);
736    
737                    // Set the CDN host, portal URL, and Facebook application ID first
738                    // because other methods (setLookAndFeel) depend on them being set
739    
740                    themeDisplay.setCDNHost(cdnHost);
741                    themeDisplay.setCDNDynamicResourcesHost(dynamicResourcesCDNHost);
742                    themeDisplay.setPortalURL(portalURL);
743                    themeDisplay.setFacebookCanvasPageURL(facebookCanvasPageURL);
744                    themeDisplay.setWidget(widget);
745    
746                    themeDisplay.setCompany(company);
747                    themeDisplay.setCompanyLogo(companyLogo);
748                    themeDisplay.setCompanyLogoHeight(companyLogoHeight);
749                    themeDisplay.setCompanyLogoWidth(companyLogoWidth);
750                    themeDisplay.setControlPanelCategory(controlPanelCategory);
751                    themeDisplay.setDoAsGroupId(doAsGroupId);
752                    themeDisplay.setDoAsUserId(doAsUserId);
753                    themeDisplay.setDoAsUserLanguageId(doAsUserLanguageId);
754                    themeDisplay.setI18nLanguageId(i18nLanguageId);
755                    themeDisplay.setI18nPath(i18nPath);
756                    themeDisplay.setIsolated(isolated);
757                    themeDisplay.setLanguageId(LocaleUtil.toLanguageId(locale));
758                    themeDisplay.setLayout(layout);
759                    themeDisplay.setLayouts(layouts);
760                    themeDisplay.setLayoutSet(layoutSet);
761                    themeDisplay.setLayoutSetLogo(layoutSetLogo);
762                    themeDisplay.setLayoutTypePortlet(layoutTypePortlet);
763                    themeDisplay.setLifecycle(lifecycle);
764                    themeDisplay.setLifecycleAction(lifecycle.equals("1"));
765                    themeDisplay.setLifecycleEvent(lifecycle.equals("3"));
766                    themeDisplay.setLifecycleRender(lifecycle.equals("0"));
767                    themeDisplay.setLifecycleResource(lifecycle.equals("2"));
768                    themeDisplay.setLocale(locale);
769                    themeDisplay.setLookAndFeel(theme, colorScheme);
770                    themeDisplay.setPathApplet(contextPath.concat("/applets"));
771                    themeDisplay.setPathCms(contextPath.concat("/cms"));
772                    themeDisplay.setPathContext(contextPath);
773                    themeDisplay.setPathFlash(contextPath.concat("/flash"));
774                    themeDisplay.setPathFriendlyURLPrivateGroup(
775                            friendlyURLPrivateGroupPath);
776                    themeDisplay.setPathFriendlyURLPrivateUser(friendlyURLPrivateUserPath);
777                    themeDisplay.setPathFriendlyURLPublic(friendlyURLPublicPath);
778                    themeDisplay.setPathImage(imagePath);
779                    themeDisplay.setPathJavaScript(contextPath.concat("/html/js"));
780                    themeDisplay.setPathMain(mainPath);
781                    themeDisplay.setPathSound(contextPath.concat("/html/sound"));
782                    themeDisplay.setPermissionChecker(permissionChecker);
783                    themeDisplay.setPlid(plid);
784                    themeDisplay.setPpid(ppid);
785                    themeDisplay.setRealCompanyLogo(realCompanyLogo);
786                    themeDisplay.setRealCompanyLogoHeight(realCompanyLogoHeight);
787                    themeDisplay.setRealCompanyLogoWidth(realCompanyLogoWidth);
788                    themeDisplay.setRealUser(realUser);
789                    themeDisplay.setRefererGroupId(refererGroupId);
790                    themeDisplay.setRefererPlid(refererPlid);
791                    themeDisplay.setScopeGroupId(scopeGroupId);
792                    themeDisplay.setSecure(request.isSecure());
793                    themeDisplay.setServerName(request.getServerName());
794                    themeDisplay.setServerPort(request.getServerPort());
795                    themeDisplay.setSignedIn(signedIn);
796                    themeDisplay.setSiteDefaultLocale(
797                            PortalUtil.getSiteDefaultLocale(siteGroupId));
798                    themeDisplay.setSiteGroupId(siteGroupId);
799                    themeDisplay.setStateExclusive(LiferayWindowState.isExclusive(request));
800                    themeDisplay.setStateMaximized(LiferayWindowState.isMaximized(request));
801                    themeDisplay.setStatePopUp(LiferayWindowState.isPopUp(request));
802                    themeDisplay.setThemeCssFastLoad(themeCssFastLoad);
803                    themeDisplay.setThemeImagesFastLoad(themeImagesFastLoad);
804                    themeDisplay.setThemeJsBarebone(themeJsBarebone);
805                    themeDisplay.setThemeJsFastLoad(themeJsFastLoad);
806                    themeDisplay.setTimeZone(timeZone);
807                    themeDisplay.setUnfilteredLayouts(unfilteredLayouts);
808                    themeDisplay.setUser(user);
809    
810                    // Icons
811    
812                    themeDisplay.setShowAddContentIcon(false);
813    
814                    boolean showControlPanelIcon = false;
815    
816                    if (signedIn &&
817                            PortalPermissionUtil.contains(
818                                    permissionChecker, ActionKeys.VIEW_CONTROL_PANEL)) {
819    
820                            showControlPanelIcon = true;
821                    }
822    
823                    themeDisplay.setShowControlPanelIcon(showControlPanelIcon);
824    
825                    themeDisplay.setShowHomeIcon(true);
826                    themeDisplay.setShowMyAccountIcon(signedIn);
827                    themeDisplay.setShowPageSettingsIcon(hasDeleteLayoutPermission);
828                    themeDisplay.setShowPortalIcon(true);
829                    themeDisplay.setShowSignInIcon(!signedIn);
830    
831                    boolean showSignOutIcon = signedIn;
832    
833                    if (themeDisplay.isImpersonated()) {
834                            showSignOutIcon = false;
835                    }
836    
837                    themeDisplay.setShowSignOutIcon(showSignOutIcon);
838    
839                    themeDisplay.setShowStagingIcon(false);
840    
841                    boolean showSiteAdministrationIcon = false;
842    
843                    if (signedIn &&
844                            GroupPermissionUtil.contains(
845                                    permissionChecker, group,
846                                    ActionKeys.VIEW_SITE_ADMINISTRATION)) {
847    
848                            showSiteAdministrationIcon = true;
849                    }
850    
851                    themeDisplay.setShowSiteAdministrationIcon(showSiteAdministrationIcon);
852    
853                    // Session
854    
855                    if (PropsValues.SESSION_ENABLE_URL_WITH_SESSION_ID &&
856                            !CookieKeys.hasSessionId(request)) {
857    
858                            themeDisplay.setAddSessionIdToURL(true);
859                            themeDisplay.setSessionId(session.getId());
860                    }
861    
862                    // URLs
863    
864                    String urlControlPanel = friendlyURLPrivateGroupPath.concat(
865                            GroupConstants.CONTROL_PANEL_FRIENDLY_URL);
866    
867                    if (Validator.isNotNull(doAsUserId)) {
868                            urlControlPanel = HttpUtil.addParameter(
869                                    urlControlPanel, "doAsUserId", doAsUserId);
870                    }
871    
872                    if (refererGroupId > 0) {
873                            urlControlPanel = HttpUtil.addParameter(
874                                    urlControlPanel, "refererGroupId", refererGroupId);
875                    }
876                    else if (scopeGroupId > 0) {
877                            Layout refererLayout = LayoutLocalServiceUtil.fetchLayout(plid);
878    
879                            if (refererLayout != null) {
880                                    Group refererLayoutGroup = refererLayout.getGroup();
881    
882                                    if (refererLayoutGroup.isUserGroup()) {
883                                            urlControlPanel = HttpUtil.addParameter(
884                                                    urlControlPanel, "refererGroupId", scopeGroupId);
885                                    }
886                            }
887                    }
888    
889                    if (refererPlid > 0) {
890                            urlControlPanel = HttpUtil.addParameter(
891                                    urlControlPanel, "refererPlid", refererPlid);
892                    }
893                    else if (plid > 0) {
894                            urlControlPanel = HttpUtil.addParameter(
895                                    urlControlPanel, "refererPlid", plid);
896                    }
897    
898                    if (themeDisplay.isAddSessionIdToURL()) {
899                            urlControlPanel = PortalUtil.getURLWithSessionId(
900                                    urlControlPanel, session.getId());
901                    }
902    
903                    themeDisplay.setURLControlPanel(urlControlPanel);
904    
905                    String currentURL = PortalUtil.getCurrentURL(request);
906    
907                    themeDisplay.setURLCurrent(currentURL);
908    
909                    String urlHome = PortalUtil.getHomeURL(request);
910    
911                    themeDisplay.setURLHome(urlHome);
912    
913                    String siteAdministrationURL = urlControlPanel;
914    
915                    siteAdministrationURL = HttpUtil.addParameter(
916                            siteAdministrationURL, "controlPanelCategory",
917                            PortletCategoryKeys.CURRENT_SITE);
918                    siteAdministrationURL = HttpUtil.addParameter(
919                            siteAdministrationURL, "doAsGroupId", siteGroupId);
920    
921                    themeDisplay.setURLSiteAdministration(siteAdministrationURL);
922    
923                    long controlPanelPlid = PortalUtil.getControlPanelPlid(companyId);
924    
925                    if (layout != null) {
926                            if (layout.isTypePortlet()) {
927                                    boolean freeformLayout =
928                                            layoutTypePortlet.getLayoutTemplateId().equals("freeform");
929    
930                                    themeDisplay.setFreeformLayout(freeformLayout);
931    
932                                    if (hasUpdateLayoutPermission) {
933                                            themeDisplay.setShowAddContentIconPermission(true);
934    
935                                            if (!LiferayWindowState.isMaximized(request)) {
936                                                    themeDisplay.setShowAddContentIcon(true);
937                                            }
938    
939                                            themeDisplay.setShowLayoutTemplatesIcon(true);
940    
941                                            if (!group.isUser()) {
942                                                    themeDisplay.setShowPageCustomizationIcon(true);
943                                            }
944    
945                                            themeDisplay.setURLAddContent(
946                                                    "Liferay.Dockbar.loadAddPanel();");
947                                    }
948    
949                                    if (hasCustomizeLayoutPermission && customizedView) {
950                                            themeDisplay.setShowAddContentIconPermission(true);
951    
952                                            if (!LiferayWindowState.isMaximized(request)) {
953                                                    themeDisplay.setShowAddContentIcon(true);
954                                            }
955    
956                                            themeDisplay.setURLAddContent(
957                                                    "Liferay.Dockbar.loadAddPanel();");
958                                    }
959                            }
960    
961                            if (hasUpdateLayoutPermission) {
962                                    themeDisplay.setShowPageSettingsIcon(true);
963    
964                                    LiferayPortletURL pageSettingsURL = new PortletURLImpl(
965                                            request, PortletKeys.LAYOUTS_ADMIN, controlPanelPlid,
966                                            PortletRequest.RENDER_PHASE);
967    
968                                    pageSettingsURL.setDoAsGroupId(scopeGroupId);
969                                    pageSettingsURL.setParameter(
970                                            "struts_action", "/layouts_admin/edit_layouts");
971    
972                                    if (layout.isPrivateLayout()) {
973                                            pageSettingsURL.setParameter("tabs1", "private-pages");
974                                    }
975                                    else {
976                                            pageSettingsURL.setParameter("tabs1", "public-pages");
977                                    }
978    
979                                    pageSettingsURL.setParameter(
980                                            "groupId", String.valueOf(scopeGroupId));
981                                    pageSettingsURL.setParameter("selPlid", String.valueOf(plid));
982                                    pageSettingsURL.setPortletMode(PortletMode.VIEW);
983    
984                                    if (PropsValues.DOCKBAR_ADMINISTRATIVE_LINKS_SHOW_IN_POP_UP) {
985                                            pageSettingsURL.setControlPanelCategory(
986                                                    PortletCategoryKeys.PORTLET);
987                                            pageSettingsURL.setParameter("closeRedirect", currentURL);
988                                            pageSettingsURL.setWindowState(LiferayWindowState.POP_UP);
989                                    }
990                                    else {
991                                            pageSettingsURL.setParameter(
992                                                    "redirect", themeDisplay.getURLHome());
993                                            pageSettingsURL.setPlid(plid);
994                                            pageSettingsURL.setWindowState(WindowState.MAXIMIZED);
995                                    }
996    
997                                    themeDisplay.setURLPageSettings(pageSettingsURL);
998    
999                                    boolean site = group.isSite();
1000    
1001                                    if (!site && group.isStagingGroup()) {
1002                                            Group liveGroup = group.getLiveGroup();
1003    
1004                                            site = liveGroup.isSite();
1005                                    }
1006    
1007                                    if (site &&
1008                                            GroupPermissionUtil.contains(
1009                                                    permissionChecker, scopeGroupId,
1010                                                    ActionKeys.ASSIGN_MEMBERS)) {
1011    
1012                                            themeDisplay.setShowManageSiteMembershipsIcon(true);
1013    
1014                                            LiferayPortletURL manageSiteMembershipsURL =
1015                                                    new PortletURLImpl(
1016                                                            request, PortletKeys.SITE_MEMBERSHIPS_ADMIN,
1017                                                            controlPanelPlid, PortletRequest.RENDER_PHASE);
1018    
1019                                            manageSiteMembershipsURL.setDoAsGroupId(scopeGroupId);
1020                                            manageSiteMembershipsURL.setParameter(
1021                                                    "struts_action", "/sites_admin/edit_site_assignments");
1022                                            manageSiteMembershipsURL.setParameter(
1023                                                    "groupId", String.valueOf(scopeGroupId));
1024                                            manageSiteMembershipsURL.setParameter(
1025                                                    "selPlid", String.valueOf(plid));
1026                                            manageSiteMembershipsURL.setPortletMode(PortletMode.VIEW);
1027    
1028                                            if (PropsValues.
1029                                                            DOCKBAR_ADMINISTRATIVE_LINKS_SHOW_IN_POP_UP) {
1030    
1031                                                    manageSiteMembershipsURL.setControlPanelCategory(
1032                                                            PortletCategoryKeys.PORTLET);
1033                                                    manageSiteMembershipsURL.setWindowState(
1034                                                            LiferayWindowState.POP_UP);
1035                                            }
1036                                            else {
1037                                                    manageSiteMembershipsURL.setParameter(
1038                                                            "redirect", themeDisplay.getURLHome());
1039                                                    manageSiteMembershipsURL.setParameter(
1040                                                            "showBackURL", Boolean.FALSE.toString());
1041                                                    manageSiteMembershipsURL.setPlid(plid);
1042                                                    manageSiteMembershipsURL.setWindowState(
1043                                                            WindowState.MAXIMIZED);
1044                                            }
1045    
1046                                            themeDisplay.setURLManageSiteMemberships(
1047                                                    manageSiteMembershipsURL);
1048                                    }
1049                                    else {
1050                                            themeDisplay.setShowManageSiteMembershipsIcon(false);
1051                                    }
1052                            }
1053    
1054                            boolean hasAddLayoutGroupPermission = GroupPermissionUtil.contains(
1055                                    permissionChecker, scopeGroupId, ActionKeys.ADD_LAYOUT);
1056                            boolean hasAddLayoutLayoutPermission =
1057                                    !layout.isTypeControlPanel() &&
1058                                    LayoutPermissionUtil.contains(
1059                                            permissionChecker, layout, ActionKeys.ADD_LAYOUT);
1060                            boolean hasManageLayoutsGroupPermission =
1061                                    GroupPermissionUtil.contains(
1062                                            permissionChecker, scopeGroupId, ActionKeys.MANAGE_LAYOUTS);
1063                            boolean hasManageStagingPermission = GroupPermissionUtil.contains(
1064                                    permissionChecker, scopeGroupId, ActionKeys.MANAGE_STAGING);
1065                            boolean hasPublishStagingPermission = GroupPermissionUtil.contains(
1066                                    permissionChecker, scopeGroupId, ActionKeys.PUBLISH_STAGING);
1067                            boolean hasUpdateGroupPermission = GroupPermissionUtil.contains(
1068                                    permissionChecker, scopeGroupId, ActionKeys.UPDATE);
1069                            boolean hasViewStagingPermission = GroupPermissionUtil.contains(
1070                                    permissionChecker, scopeGroupId, ActionKeys.VIEW_STAGING);
1071    
1072                            if (!group.isControlPanel() && !group.isUser() &&
1073                                    !group.isUserGroup() && hasUpdateGroupPermission) {
1074    
1075                                    themeDisplay.setShowSiteSettingsIcon(true);
1076    
1077                                    LiferayPortletURL siteSettingsURL = new PortletURLImpl(
1078                                            request, PortletKeys.SITE_SETTINGS, controlPanelPlid,
1079                                            PortletRequest.RENDER_PHASE);
1080    
1081                                    siteSettingsURL.setDoAsGroupId(scopeGroupId);
1082                                    siteSettingsURL.setParameter(
1083                                            "struts_action", "/sites_admin/edit_site");
1084                                    siteSettingsURL.setParameter(
1085                                            "groupId", String.valueOf(scopeGroupId));
1086                                    siteSettingsURL.setParameter(
1087                                            "showBackURL", Boolean.FALSE.toString());
1088                                    siteSettingsURL.setPortletMode(PortletMode.VIEW);
1089    
1090                                    if (PropsValues.DOCKBAR_ADMINISTRATIVE_LINKS_SHOW_IN_POP_UP) {
1091                                            siteSettingsURL.setControlPanelCategory(
1092                                                    PortletCategoryKeys.PORTLET);
1093                                            siteSettingsURL.setParameter("closeRedirect", currentURL);
1094                                            siteSettingsURL.setWindowState(LiferayWindowState.POP_UP);
1095                                    }
1096                                    else {
1097                                            siteSettingsURL.setParameter(
1098                                                    "redirect", themeDisplay.getURLHome());
1099                                            siteSettingsURL.setPlid(plid);
1100                                            siteSettingsURL.setWindowState(
1101                                                    LiferayWindowState.MAXIMIZED);
1102                                    }
1103    
1104                                    themeDisplay.setURLSiteSettings(siteSettingsURL);
1105                            }
1106    
1107                            if (!group.isLayoutPrototype() &&
1108                                    (hasAddLayoutGroupPermission || hasAddLayoutLayoutPermission ||
1109                                     hasManageLayoutsGroupPermission || hasUpdateGroupPermission)) {
1110    
1111                                    themeDisplay.setShowSiteMapSettingsIcon(true);
1112    
1113                                    LiferayPortletURL siteMapSettingsURL = new PortletURLImpl(
1114                                            request, PortletKeys.LAYOUTS_ADMIN, controlPanelPlid,
1115                                            PortletRequest.RENDER_PHASE);
1116    
1117                                    siteMapSettingsURL.setDoAsGroupId(scopeGroupId);
1118                                    siteMapSettingsURL.setParameter(
1119                                            "struts_action", "/layouts_admin/edit_layouts");
1120    
1121                                    if (layout.isPrivateLayout()) {
1122                                            siteMapSettingsURL.setParameter("tabs1", "private-pages");
1123                                    }
1124                                    else {
1125                                            siteMapSettingsURL.setParameter("tabs1", "public-pages");
1126                                    }
1127    
1128                                    siteMapSettingsURL.setParameter(
1129                                            "groupId", String.valueOf(scopeGroupId));
1130                                    siteMapSettingsURL.setPortletMode(PortletMode.VIEW);
1131    
1132                                    if (PropsValues.DOCKBAR_ADMINISTRATIVE_LINKS_SHOW_IN_POP_UP) {
1133                                            siteMapSettingsURL.setControlPanelCategory(
1134                                                    PortletCategoryKeys.PORTLET);
1135                                            siteMapSettingsURL.setParameter(
1136                                                    "closeRedirect", currentURL);
1137                                            siteMapSettingsURL.setWindowState(
1138                                                    LiferayWindowState.POP_UP);
1139                                    }
1140                                    else {
1141                                            siteMapSettingsURL.setParameter(
1142                                                    "redirect", themeDisplay.getURLHome());
1143                                            siteMapSettingsURL.setPlid(plid);
1144                                            siteMapSettingsURL.setWindowState(
1145                                                    LiferayWindowState.MAXIMIZED);
1146                                    }
1147    
1148                                    themeDisplay.setURLSiteMapSettings(siteMapSettingsURL);
1149                            }
1150    
1151                            if (group.hasStagingGroup() && !group.isStagingGroup()) {
1152                                    themeDisplay.setShowAddContentIcon(false);
1153                                    themeDisplay.setShowLayoutTemplatesIcon(false);
1154                                    themeDisplay.setURLPublishToLive(null);
1155                            }
1156    
1157                            if (group.isControlPanel()) {
1158                                    themeDisplay.setShowPageSettingsIcon(false);
1159                                    themeDisplay.setURLPublishToLive(null);
1160                            }
1161    
1162                            // LEP-4987
1163    
1164                            if (group.isStaged() || group.isStagingGroup()) {
1165                                    if (hasManageStagingPermission || hasPublishStagingPermission ||
1166                                            hasUpdateLayoutPermission || hasViewStagingPermission) {
1167    
1168                                            themeDisplay.setShowStagingIcon(true);
1169                                    }
1170    
1171                                    if (hasPublishStagingPermission) {
1172                                            PortletURL publishToLiveURL = new PortletURLImpl(
1173                                                    request, PortletKeys.LAYOUTS_ADMIN, plid,
1174                                                    PortletRequest.RENDER_PHASE);
1175    
1176                                            publishToLiveURL.setParameter(
1177                                                    "struts_action", "/layouts_admin/publish_layouts");
1178    
1179                                            if (layout.isPrivateLayout()) {
1180                                                    publishToLiveURL.setParameter("tabs1", "private-pages");
1181                                            }
1182                                            else {
1183                                                    publishToLiveURL.setParameter("tabs1", "public-pages");
1184                                            }
1185    
1186                                            publishToLiveURL.setParameter("pagesRedirect", currentURL);
1187                                            publishToLiveURL.setParameter(
1188                                                    "groupId", String.valueOf(scopeGroupId));
1189                                            publishToLiveURL.setParameter(
1190                                                    "selPlid", String.valueOf(plid));
1191                                            publishToLiveURL.setPortletMode(PortletMode.VIEW);
1192                                            publishToLiveURL.setWindowState(
1193                                                    LiferayWindowState.EXCLUSIVE);
1194    
1195                                            themeDisplay.setURLPublishToLive(publishToLiveURL);
1196                                    }
1197                            }
1198    
1199                            Portlet myAccountPortlet = PortalUtil.getFirstMyAccountPortlet(
1200                                    themeDisplay);
1201    
1202                            if (myAccountPortlet != null) {
1203                                    PortletURLImpl myAccountURL = new PortletURLImpl(
1204                                            request, myAccountPortlet.getPortletName(),
1205                                            controlPanelPlid, PortletRequest.RENDER_PHASE);
1206    
1207                                    if (scopeGroupId > 0) {
1208                                            myAccountURL.setDoAsGroupId(scopeGroupId);
1209                                    }
1210    
1211                                    if (refererPlid > 0) {
1212                                            myAccountURL.setRefererPlid(refererPlid);
1213                                    }
1214                                    else {
1215                                            myAccountURL.setRefererPlid(plid);
1216                                    }
1217    
1218                                    myAccountURL.setWindowState(WindowState.MAXIMIZED);
1219    
1220                                    themeDisplay.setURLMyAccount(myAccountURL);
1221                            }
1222                    }
1223    
1224                    if (!user.isActive() ||
1225                            (PrefsPropsUtil.getBoolean(
1226                                    companyId, PropsKeys.TERMS_OF_USE_REQUIRED) &&
1227                             !user.isAgreedToTermsOfUse())) {
1228    
1229                            themeDisplay.setShowAddContentIcon(false);
1230                            themeDisplay.setShowMyAccountIcon(false);
1231                            themeDisplay.setShowPageSettingsIcon(false);
1232                    }
1233    
1234                    if (layout.isLayoutPrototypeLinkActive()) {
1235                            themeDisplay.setShowPageCustomizationIcon(false);
1236                    }
1237    
1238                    if (group.isLayoutPrototype()) {
1239                            themeDisplay.setShowHomeIcon(false);
1240                            themeDisplay.setShowManageSiteMembershipsIcon(false);
1241                            themeDisplay.setShowMyAccountIcon(false);
1242                            themeDisplay.setShowPageCustomizationIcon(false);
1243                            themeDisplay.setShowPageSettingsIcon(true);
1244                            themeDisplay.setShowPortalIcon(false);
1245                            themeDisplay.setShowSignInIcon(false);
1246                            themeDisplay.setShowSignOutIcon(false);
1247                            themeDisplay.setShowSiteAdministrationIcon(false);
1248                            themeDisplay.setShowSiteSettingsIcon(false);
1249                            themeDisplay.setShowStagingIcon(false);
1250                    }
1251    
1252                    if (group.isLayoutSetPrototype()) {
1253                            themeDisplay.setShowPageCustomizationIcon(false);
1254                            themeDisplay.setShowSiteSettingsIcon(false);
1255                    }
1256    
1257                    if (group.hasStagingGroup() && !group.isStagingGroup()) {
1258                            themeDisplay.setShowLayoutTemplatesIcon(false);
1259                            themeDisplay.setShowPageCustomizationIcon(false);
1260                            themeDisplay.setShowSiteMapSettingsIcon(false);
1261                            themeDisplay.setShowSiteSettingsIcon(false);
1262                    }
1263    
1264                    themeDisplay.setURLPortal(portalURL.concat(contextPath));
1265    
1266                    boolean secure = false;
1267    
1268                    if (PropsValues.COMPANY_SECURITY_AUTH_REQUIRES_HTTPS ||
1269                            request.isSecure()) {
1270    
1271                            secure = true;
1272                    }
1273    
1274                    String securePortalURL = PortalUtil.getPortalURL(request, secure);
1275    
1276                    String urlSignIn = securePortalURL.concat(mainPath).concat(
1277                            _PATH_PORTAL_LOGIN);
1278    
1279                    if (layout != null) {
1280                            urlSignIn = HttpUtil.addParameter(
1281                                    urlSignIn, "p_l_id", layout.getPlid());
1282                    }
1283    
1284                    themeDisplay.setURLSignIn(urlSignIn);
1285    
1286                    themeDisplay.setURLSignOut(mainPath.concat(_PATH_PORTAL_LOGOUT));
1287    
1288                    PortletURL updateManagerURL = new PortletURLImpl(
1289                            request, PortletKeys.MARKETPLACE_STORE, controlPanelPlid,
1290                            PortletRequest.RENDER_PHASE);
1291    
1292                    themeDisplay.setURLUpdateManager(updateManagerURL);
1293    
1294                    // Control Panel redirects
1295    
1296                    if (group.isControlPanel() && Validator.isNotNull(ppid)) {
1297                            if (!PortletPermissionUtil.hasControlPanelAccessPermission(
1298                                            permissionChecker, scopeGroupId, ppid)) {
1299    
1300                                    String redirect = HttpUtil.removeParameter(
1301                                            currentURL, "p_p_id");
1302    
1303                                    response.sendRedirect(redirect);
1304                            }
1305                    }
1306                    else if (group.isControlPanel() && Validator.isNull(ppid)) {
1307                            if (controlPanelCategory.startsWith(
1308                                            PortletCategoryKeys.CURRENT_SITE)) {
1309    
1310                                    if (controlPanelCategory.indexOf(StringPool.PERIOD) == -1) {
1311                                            controlPanelCategory = StringUtil.replace(
1312                                                    controlPanelCategory, PortletCategoryKeys.CURRENT_SITE,
1313                                                    PortletCategoryKeys.SITE_ADMINISTRATION);
1314                                    }
1315                                    else {
1316                                            controlPanelCategory = StringUtil.replace(
1317                                                    controlPanelCategory,
1318                                                    PortletCategoryKeys.CURRENT_SITE + StringPool.PERIOD,
1319                                                    PortletCategoryKeys.SITE_ADMINISTRATION);
1320                                    }
1321                            }
1322    
1323                            if (controlPanelCategory.equals(
1324                                            PortletCategoryKeys.SITE_ADMINISTRATION)) {
1325    
1326                                    Portlet firstPortlet =
1327                                            PortalUtil.getFirstSiteAdministrationPortlet(themeDisplay);
1328    
1329                                    String redirect = HttpUtil.setParameter(
1330                                            currentURL, "p_p_id", firstPortlet.getPortletId());
1331    
1332                                    response.sendRedirect(
1333                                            PortalUtil.getAbsoluteURL(request, redirect));
1334                            }
1335                            else {
1336                                    List<Portlet> portlets = PortalUtil.getControlPanelPortlets(
1337                                            controlPanelCategory, themeDisplay);
1338    
1339                                    for (Portlet portlet : portlets) {
1340                                            if (PortletPermissionUtil.hasControlPanelAccessPermission(
1341                                                            permissionChecker, scopeGroupId, portlet)) {
1342    
1343                                                    String redirect = HttpUtil.setParameter(
1344                                                            currentURL, "p_p_id", portlet.getPortletId());
1345    
1346                                                    response.sendRedirect(
1347                                                            PortalUtil.getAbsoluteURL(request, redirect));
1348    
1349                                                    break;
1350                                            }
1351                                    }
1352                            }
1353                    }
1354    
1355                    return themeDisplay;
1356            }
1357    
1358            @Override
1359            public void run(HttpServletRequest request, HttpServletResponse response)
1360                    throws ActionException {
1361    
1362                    StopWatch stopWatch = null;
1363    
1364                    if (_log.isDebugEnabled()) {
1365                            stopWatch = new StopWatch();
1366    
1367                            stopWatch.start();
1368                    }
1369    
1370                    try {
1371                            servicePre(request, response);
1372                    }
1373                    catch (Exception e) {
1374                            throw new ActionException(e);
1375                    }
1376    
1377                    if (_log.isDebugEnabled()) {
1378                            _log.debug("Running takes " + stopWatch.getTime() + " ms");
1379                    }
1380            }
1381    
1382            protected void addDefaultLayoutsByLAR(
1383                            long userId, long groupId, boolean privateLayout, File larFile)
1384                    throws PortalException, SystemException {
1385    
1386                    Map<String, String[]> parameterMap = new HashMap<String, String[]>();
1387    
1388                    parameterMap.put(
1389                            PortletDataHandlerKeys.PERMISSIONS,
1390                            new String[] {Boolean.TRUE.toString()});
1391                    parameterMap.put(
1392                            PortletDataHandlerKeys.PORTLET_CONFIGURATION,
1393                            new String[] {Boolean.TRUE.toString()});
1394                    parameterMap.put(
1395                            PortletDataHandlerKeys.PORTLET_DATA,
1396                            new String[] {Boolean.TRUE.toString()});
1397                    parameterMap.put(
1398                            PortletDataHandlerKeys.PORTLET_DATA_CONTROL_DEFAULT,
1399                            new String[] {Boolean.TRUE.toString()});
1400                    parameterMap.put(
1401                            PortletDataHandlerKeys.THEME_REFERENCE,
1402                            new String[] {Boolean.TRUE.toString()});
1403    
1404                    LayoutLocalServiceUtil.importLayouts(
1405                            userId, groupId, privateLayout, parameterMap, larFile);
1406            }
1407    
1408            protected void addDefaultUserPrivateLayoutByProperties(
1409                            long userId, long groupId)
1410                    throws PortalException, SystemException {
1411    
1412                    String friendlyURL = getFriendlyURL(
1413                            PropsValues.DEFAULT_USER_PRIVATE_LAYOUT_FRIENDLY_URL);
1414    
1415                    ServiceContext serviceContext = new ServiceContext();
1416    
1417                    Layout layout = LayoutLocalServiceUtil.addLayout(
1418                            userId, groupId, true, LayoutConstants.DEFAULT_PARENT_LAYOUT_ID,
1419                            PropsValues.DEFAULT_USER_PRIVATE_LAYOUT_NAME, StringPool.BLANK,
1420                            StringPool.BLANK, LayoutConstants.TYPE_PORTLET, false, friendlyURL,
1421                            serviceContext);
1422    
1423                    LayoutTypePortlet layoutTypePortlet =
1424                            (LayoutTypePortlet)layout.getLayoutType();
1425    
1426                    layoutTypePortlet.setLayoutTemplateId(
1427                            0, PropsValues.DEFAULT_USER_PRIVATE_LAYOUT_TEMPLATE_ID, false);
1428    
1429                    LayoutTemplate layoutTemplate = layoutTypePortlet.getLayoutTemplate();
1430    
1431                    for (String columnId : layoutTemplate.getColumns()) {
1432                            String keyPrefix = PropsKeys.DEFAULT_USER_PRIVATE_LAYOUT_PREFIX;
1433    
1434                            String portletIds = PropsUtil.get(keyPrefix.concat(columnId));
1435    
1436                            layoutTypePortlet.addPortletIds(
1437                                    0, StringUtil.split(portletIds), columnId, false);
1438                    }
1439    
1440                    LayoutLocalServiceUtil.updateLayout(
1441                            layout.getGroupId(), layout.isPrivateLayout(), layout.getLayoutId(),
1442                            layout.getTypeSettings());
1443    
1444                    boolean updateLayoutSet = false;
1445    
1446                    LayoutSet layoutSet = layout.getLayoutSet();
1447    
1448                    if (Validator.isNotNull(
1449                                    PropsValues.DEFAULT_USER_PRIVATE_LAYOUT_REGULAR_THEME_ID)) {
1450    
1451                            layoutSet.setThemeId(
1452                                    PropsValues.DEFAULT_USER_PRIVATE_LAYOUT_REGULAR_THEME_ID);
1453    
1454                            updateLayoutSet = true;
1455                    }
1456    
1457                    if (Validator.isNotNull(
1458                                    PropsValues.
1459                                            DEFAULT_USER_PRIVATE_LAYOUT_REGULAR_COLOR_SCHEME_ID)) {
1460    
1461                            layoutSet.setColorSchemeId(
1462                                    PropsValues.
1463                                            DEFAULT_USER_PRIVATE_LAYOUT_REGULAR_COLOR_SCHEME_ID);
1464    
1465                            updateLayoutSet = true;
1466                    }
1467    
1468                    if (Validator.isNotNull(
1469                                    PropsValues.DEFAULT_USER_PRIVATE_LAYOUT_WAP_THEME_ID)) {
1470    
1471                            layoutSet.setWapThemeId(
1472                                    PropsValues.DEFAULT_USER_PRIVATE_LAYOUT_WAP_THEME_ID);
1473    
1474                            updateLayoutSet = true;
1475                    }
1476    
1477                    if (Validator.isNotNull(
1478                                    PropsValues.DEFAULT_USER_PRIVATE_LAYOUT_WAP_COLOR_SCHEME_ID)) {
1479    
1480                            layoutSet.setWapColorSchemeId(
1481                                    PropsValues.DEFAULT_USER_PRIVATE_LAYOUT_WAP_COLOR_SCHEME_ID);
1482    
1483                            updateLayoutSet = true;
1484                    }
1485    
1486                    if (updateLayoutSet) {
1487                            LayoutSetLocalServiceUtil.updateLayoutSet(layoutSet);
1488                    }
1489            }
1490    
1491            protected void addDefaultUserPrivateLayouts(User user)
1492                    throws PortalException, SystemException {
1493    
1494                    Group userGroup = user.getGroup();
1495    
1496                    if (privateLARFile != null) {
1497                            addDefaultLayoutsByLAR(
1498                                    user.getUserId(), userGroup.getGroupId(), true, privateLARFile);
1499                    }
1500                    else {
1501                            addDefaultUserPrivateLayoutByProperties(
1502                                    user.getUserId(), userGroup.getGroupId());
1503                    }
1504            }
1505    
1506            protected void addDefaultUserPublicLayoutByProperties(
1507                            long userId, long groupId)
1508                    throws PortalException, SystemException {
1509    
1510                    String friendlyURL = getFriendlyURL(
1511                            PropsValues.DEFAULT_USER_PUBLIC_LAYOUT_FRIENDLY_URL);
1512    
1513                    ServiceContext serviceContext = new ServiceContext();
1514    
1515                    Layout layout = LayoutLocalServiceUtil.addLayout(
1516                            userId, groupId, false, LayoutConstants.DEFAULT_PARENT_LAYOUT_ID,
1517                            PropsValues.DEFAULT_USER_PUBLIC_LAYOUT_NAME, StringPool.BLANK,
1518                            StringPool.BLANK, LayoutConstants.TYPE_PORTLET, false, friendlyURL,
1519                            serviceContext);
1520    
1521                    LayoutTypePortlet layoutTypePortlet =
1522                            (LayoutTypePortlet)layout.getLayoutType();
1523    
1524                    layoutTypePortlet.setLayoutTemplateId(
1525                            0, PropsValues.DEFAULT_USER_PUBLIC_LAYOUT_TEMPLATE_ID, false);
1526    
1527                    LayoutTemplate layoutTemplate = layoutTypePortlet.getLayoutTemplate();
1528    
1529                    for (String columnId : layoutTemplate.getColumns()) {
1530                            String keyPrefix = PropsKeys.DEFAULT_USER_PUBLIC_LAYOUT_PREFIX;
1531    
1532                            String portletIds = PropsUtil.get(keyPrefix.concat(columnId));
1533    
1534                            layoutTypePortlet.addPortletIds(
1535                                    0, StringUtil.split(portletIds), columnId, false);
1536                    }
1537    
1538                    LayoutLocalServiceUtil.updateLayout(
1539                            layout.getGroupId(), layout.isPrivateLayout(), layout.getLayoutId(),
1540                            layout.getTypeSettings());
1541    
1542                    boolean updateLayoutSet = false;
1543    
1544                    LayoutSet layoutSet = layout.getLayoutSet();
1545    
1546                    if (Validator.isNotNull(
1547                                    PropsValues.DEFAULT_USER_PUBLIC_LAYOUT_REGULAR_THEME_ID)) {
1548    
1549                            layoutSet.setThemeId(
1550                                    PropsValues.DEFAULT_USER_PUBLIC_LAYOUT_REGULAR_THEME_ID);
1551    
1552                            updateLayoutSet = true;
1553                    }
1554    
1555                    if (Validator.isNotNull(
1556                                    PropsValues.
1557                                            DEFAULT_USER_PUBLIC_LAYOUT_REGULAR_COLOR_SCHEME_ID)) {
1558    
1559                            layoutSet.setColorSchemeId(
1560                                    PropsValues.DEFAULT_USER_PUBLIC_LAYOUT_REGULAR_COLOR_SCHEME_ID);
1561    
1562                            updateLayoutSet = true;
1563                    }
1564    
1565                    if (Validator.isNotNull(
1566                                    PropsValues.DEFAULT_USER_PUBLIC_LAYOUT_WAP_THEME_ID)) {
1567    
1568                            layoutSet.setWapThemeId(
1569                                    PropsValues.DEFAULT_USER_PUBLIC_LAYOUT_WAP_THEME_ID);
1570    
1571                            updateLayoutSet = true;
1572                    }
1573    
1574                    if (Validator.isNotNull(
1575                                    PropsValues.DEFAULT_USER_PUBLIC_LAYOUT_WAP_COLOR_SCHEME_ID)) {
1576    
1577                            layoutSet.setWapColorSchemeId(
1578                                    PropsValues.DEFAULT_USER_PUBLIC_LAYOUT_WAP_COLOR_SCHEME_ID);
1579    
1580                            updateLayoutSet = true;
1581                    }
1582    
1583                    if (updateLayoutSet) {
1584                            LayoutSetLocalServiceUtil.updateLayoutSet(layoutSet);
1585                    }
1586            }
1587    
1588            protected void addDefaultUserPublicLayouts(User user)
1589                    throws PortalException, SystemException {
1590    
1591                    Group userGroup = user.getGroup();
1592    
1593                    if (publicLARFile != null) {
1594                            addDefaultLayoutsByLAR(
1595                                    user.getUserId(), userGroup.getGroupId(), false, publicLARFile);
1596                    }
1597                    else {
1598                            addDefaultUserPublicLayoutByProperties(
1599                                    user.getUserId(), userGroup.getGroupId());
1600                    }
1601            }
1602    
1603            protected void deleteDefaultUserPrivateLayouts(User user)
1604                    throws PortalException, SystemException {
1605    
1606                    Group userGroup = user.getGroup();
1607    
1608                    ServiceContext serviceContext = new ServiceContext();
1609    
1610                    LayoutLocalServiceUtil.deleteLayouts(
1611                            userGroup.getGroupId(), true, serviceContext);
1612            }
1613    
1614            protected void deleteDefaultUserPublicLayouts(User user)
1615                    throws PortalException, SystemException {
1616    
1617                    Group userGroup = user.getGroup();
1618    
1619                    ServiceContext serviceContext = new ServiceContext();
1620    
1621                    LayoutLocalServiceUtil.deleteLayouts(
1622                            userGroup.getGroupId(), false, serviceContext);
1623            }
1624    
1625            protected Object[] getDefaultLayout(
1626                            HttpServletRequest request, User user, boolean signedIn)
1627                    throws PortalException, SystemException {
1628    
1629                    Layout layout = null;
1630                    List<Layout> layouts = null;
1631    
1632                    if (signedIn) {
1633    
1634                            // Check the user's personal layouts
1635    
1636                            Group userGroup = user.getGroup();
1637    
1638                            layouts = LayoutLocalServiceUtil.getLayouts(
1639                                    userGroup.getGroupId(), true,
1640                                    LayoutConstants.DEFAULT_PARENT_LAYOUT_ID);
1641    
1642                            if (layouts.size() == 0) {
1643                                    layouts = LayoutLocalServiceUtil.getLayouts(
1644                                            userGroup.getGroupId(), false,
1645                                            LayoutConstants.DEFAULT_PARENT_LAYOUT_ID);
1646                            }
1647    
1648                            if (layouts.size() > 0) {
1649                                    layout = layouts.get(0);
1650                            }
1651    
1652                            // Check the user's sites
1653    
1654                            if (layout == null) {
1655                                    LinkedHashMap<String, Object> groupParams =
1656                                            new LinkedHashMap<String, Object>();
1657    
1658                                    groupParams.put("usersGroups", new Long(user.getUserId()));
1659    
1660                                    List<Group> groups = GroupLocalServiceUtil.search(
1661                                            user.getCompanyId(), null, null, groupParams,
1662                                            QueryUtil.ALL_POS, QueryUtil.ALL_POS);
1663    
1664                                    for (Group group : groups) {
1665                                            layouts = LayoutLocalServiceUtil.getLayouts(
1666                                                    group.getGroupId(), true,
1667                                                    LayoutConstants.DEFAULT_PARENT_LAYOUT_ID);
1668    
1669                                            if (layouts.size() == 0) {
1670                                                    layouts = LayoutLocalServiceUtil.getLayouts(
1671                                                            group.getGroupId(), false,
1672                                                            LayoutConstants.DEFAULT_PARENT_LAYOUT_ID);
1673                                            }
1674    
1675                                            if (layouts.size() > 0) {
1676                                                    layout = layouts.get(0);
1677    
1678                                                    break;
1679                                            }
1680                                    }
1681                            }
1682                    }
1683                    else {
1684    
1685                            // Check the virtual host
1686    
1687                            LayoutSet layoutSet = (LayoutSet)request.getAttribute(
1688                                    WebKeys.VIRTUAL_HOST_LAYOUT_SET);
1689    
1690                            if (layoutSet != null) {
1691                                    layouts = LayoutLocalServiceUtil.getLayouts(
1692                                            layoutSet.getGroupId(), layoutSet.isPrivateLayout(),
1693                                            LayoutConstants.DEFAULT_PARENT_LAYOUT_ID);
1694    
1695                                    Group group = null;
1696    
1697                                    if (!layouts.isEmpty()) {
1698                                            layout = layouts.get(0);
1699    
1700                                            group = layout.getGroup();
1701                                    }
1702    
1703                                    if ((layout != null) && layout.isPrivateLayout()) {
1704                                            layouts = LayoutLocalServiceUtil.getLayouts(
1705                                                    group.getGroupId(), false,
1706                                                    LayoutConstants.DEFAULT_PARENT_LAYOUT_ID);
1707    
1708                                            if (!layouts.isEmpty()) {
1709                                                    layout = layouts.get(0);
1710                                            }
1711                                            else {
1712                                                    group = null;
1713                                                    layout = null;
1714                                            }
1715                                    }
1716    
1717                                    if ((group != null) && group.isStagingGroup()) {
1718                                            Group liveGroup = group.getLiveGroup();
1719    
1720                                            layouts = LayoutLocalServiceUtil.getLayouts(
1721                                                    liveGroup.getGroupId(), false,
1722                                                    LayoutConstants.DEFAULT_PARENT_LAYOUT_ID);
1723    
1724                                            if (!layouts.isEmpty()) {
1725                                                    layout = layouts.get(0);
1726                                            }
1727                                            else {
1728                                                    layout = null;
1729                                            }
1730                                    }
1731                            }
1732                    }
1733    
1734                    if (layout == null) {
1735    
1736                            // Check the Guest site
1737    
1738                            Group guestGroup = GroupLocalServiceUtil.getGroup(
1739                                    user.getCompanyId(), GroupConstants.GUEST);
1740    
1741                            layouts = LayoutLocalServiceUtil.getLayouts(
1742                                    guestGroup.getGroupId(), false,
1743                                    LayoutConstants.DEFAULT_PARENT_LAYOUT_ID);
1744    
1745                            if (layouts.size() > 0) {
1746                                    layout = layouts.get(0);
1747                            }
1748                    }
1749    
1750                    return new Object[] {layout, layouts};
1751            }
1752    
1753            protected String getFriendlyURL(String friendlyURL) {
1754                    friendlyURL = GetterUtil.getString(friendlyURL);
1755    
1756                    return FriendlyURLNormalizerUtil.normalize(friendlyURL);
1757            }
1758    
1759            protected Object[] getViewableLayouts(
1760                            HttpServletRequest request, User user,
1761                            PermissionChecker permissionChecker, Layout layout,
1762                            List<Layout> layouts, long doAsGroupId, String controlPanelCategory)
1763                    throws PortalException, SystemException {
1764    
1765                    if ((layouts == null) || layouts.isEmpty()) {
1766                            return new Object[] {layout, layouts};
1767                    }
1768    
1769                    Group group = layout.getGroup();
1770    
1771                    boolean hasViewLayoutPermission = false;
1772                    boolean hasViewStagingPermission =
1773                            (group.isStagingGroup() || group.isStagedRemotely()) &&
1774                             !group.isControlPanel() &&
1775                             GroupPermissionUtil.contains(
1776                                     permissionChecker, group.getGroupId(),
1777                                     ActionKeys.VIEW_STAGING);
1778    
1779                    if (hasAccessPermission(
1780                                    permissionChecker, layout, doAsGroupId, controlPanelCategory,
1781                                    false) ||
1782                            hasViewStagingPermission) {
1783    
1784                            hasViewLayoutPermission = true;
1785                    }
1786    
1787                    List<Layout> accessibleLayouts = new ArrayList<Layout>();
1788    
1789                    for (int i = 0; i < layouts.size(); i++) {
1790                            Layout curLayout = layouts.get(i);
1791    
1792                            if (!curLayout.isHidden() &&
1793                                    (hasAccessPermission(
1794                                            permissionChecker, curLayout, doAsGroupId,
1795                                            controlPanelCategory, false) ||
1796                                     hasViewStagingPermission)) {
1797    
1798                                    if (accessibleLayouts.isEmpty() && !hasViewLayoutPermission) {
1799                                            layout = curLayout;
1800                                    }
1801    
1802                                    accessibleLayouts.add(curLayout);
1803                            }
1804                    }
1805    
1806                    if (accessibleLayouts.isEmpty()) {
1807                            layouts = null;
1808    
1809                            if (!isLoginRequest(request) && !hasViewLayoutPermission) {
1810                                    if (user.isDefaultUser() &&
1811                                            PropsValues.AUTH_LOGIN_PROMPT_ENABLED) {
1812    
1813                                            throw new PrincipalException("User is not authenticated");
1814                                    }
1815    
1816                                    SessionErrors.add(
1817                                            request, LayoutPermissionException.class.getName());
1818                            }
1819                    }
1820                    else {
1821                            layouts = accessibleLayouts;
1822                    }
1823    
1824                    return new Object[] {layout, layouts};
1825            }
1826    
1827            protected boolean hasAccessPermission(
1828                            PermissionChecker permissionChecker, Layout layout,
1829                            long doAsGroupId, String controlPanelCategory,
1830                            boolean checkViewableGroup)
1831                    throws PortalException, SystemException {
1832    
1833                    if (layout.isTypeControlPanel()) {
1834                            if (!permissionChecker.isSignedIn()) {
1835                                    return false;
1836                            }
1837    
1838                            if (controlPanelCategory.startsWith(
1839                                            PortletCategoryKeys.CURRENT_SITE)) {
1840    
1841                                    if (doAsGroupId <= 0) {
1842                                            return false;
1843                                    }
1844    
1845                                    Group group = GroupLocalServiceUtil.getGroup(doAsGroupId);
1846    
1847                                    if (group.isLayout()) {
1848                                            group = group.getParentGroup();
1849                                    }
1850    
1851                                    if (GroupPermissionUtil.contains(
1852                                                    permissionChecker, group.getGroupId(),
1853                                                    ActionKeys.VIEW_SITE_ADMINISTRATION)) {
1854    
1855                                            return true;
1856                                    }
1857                            }
1858                            else if (controlPanelCategory.equals(PortletCategoryKeys.MY) ||
1859                                             controlPanelCategory.equals(PortletCategoryKeys.PORTLET)) {
1860    
1861                                    return true;
1862                            }
1863    
1864                            return PortalPermissionUtil.contains(
1865                                    permissionChecker, ActionKeys.VIEW_CONTROL_PANEL);
1866                    }
1867    
1868                    return LayoutPermissionUtil.contains(
1869                            permissionChecker, layout, checkViewableGroup, ActionKeys.VIEW);
1870            }
1871    
1872            protected Boolean hasPowerUserRole(User user) throws Exception {
1873                    return RoleLocalServiceUtil.hasUserRole(
1874                            user.getUserId(), user.getCompanyId(), RoleConstants.POWER_USER,
1875                            true);
1876            }
1877    
1878            protected void initImportLARFiles() {
1879                    String privateLARFileName =
1880                            PropsValues.DEFAULT_USER_PRIVATE_LAYOUTS_LAR;
1881    
1882                    if (_log.isDebugEnabled()) {
1883                            _log.debug("Reading private LAR file " + privateLARFileName);
1884                    }
1885    
1886                    if (Validator.isNotNull(privateLARFileName)) {
1887                            privateLARFile = new File(privateLARFileName);
1888    
1889                            if (!privateLARFile.exists()) {
1890                                    _log.error(
1891                                            "Private LAR file " + privateLARFile + " does not exist");
1892    
1893                                    privateLARFile = null;
1894                            }
1895                            else {
1896                                    if (_log.isDebugEnabled()) {
1897                                            _log.debug("Using private LAR file " + privateLARFileName);
1898                                    }
1899                            }
1900                    }
1901    
1902                    String publicLARFileName = PropsValues.DEFAULT_USER_PUBLIC_LAYOUTS_LAR;
1903    
1904                    if (_log.isDebugEnabled()) {
1905                            _log.debug("Reading public LAR file " + publicLARFileName);
1906                    }
1907    
1908                    if (Validator.isNotNull(publicLARFileName)) {
1909                            publicLARFile = new File(publicLARFileName);
1910    
1911                            if (!publicLARFile.exists()) {
1912                                    _log.error(
1913                                            "Public LAR file " + publicLARFile + " does not exist");
1914    
1915                                    publicLARFile = null;
1916                            }
1917                            else {
1918                                    if (_log.isDebugEnabled()) {
1919                                            _log.debug("Using public LAR file " + publicLARFileName);
1920                                    }
1921                            }
1922                    }
1923            }
1924    
1925            protected boolean isLoginRequest(HttpServletRequest request) {
1926                    String requestURI = request.getRequestURI();
1927    
1928                    String mainPath = PortalUtil.getPathMain();
1929    
1930                    if (requestURI.startsWith(mainPath.concat(_PATH_PORTAL_LOGIN))) {
1931                            return true;
1932                    }
1933                    else {
1934                            return false;
1935                    }
1936            }
1937    
1938            /**
1939             * @deprecated As of 6.1.0
1940             */
1941            protected boolean isViewableCommunity(
1942                            User user, long groupId, boolean privateLayout,
1943                            PermissionChecker permissionChecker)
1944                    throws PortalException, SystemException {
1945    
1946                    return LayoutPermissionUtil.contains(
1947                            permissionChecker, groupId, privateLayout, 0, ActionKeys.VIEW);
1948            }
1949    
1950            /**
1951             * @deprecated As of 6.1.0
1952             */
1953            protected boolean isViewableGroup(
1954                            User user, long groupId, boolean privateLayout, long layoutId,
1955                            String controlPanelCategory, PermissionChecker permissionChecker)
1956                    throws PortalException, SystemException {
1957    
1958                    return LayoutPermissionUtil.contains(
1959                            permissionChecker, groupId, privateLayout, layoutId,
1960                            ActionKeys.VIEW);
1961            }
1962    
1963            protected List<Layout> mergeAdditionalLayouts(
1964                            HttpServletRequest request, User user,
1965                            PermissionChecker permissionChecker, Layout layout,
1966                            List<Layout> layouts, long doAsGroupId, String controlPanelCategory)
1967                    throws PortalException, SystemException {
1968    
1969                    if ((layout == null) || layout.isPrivateLayout()) {
1970                            return layouts;
1971                    }
1972    
1973                    long layoutGroupId = layout.getGroupId();
1974    
1975                    Group guestGroup = GroupLocalServiceUtil.getGroup(
1976                            user.getCompanyId(), GroupConstants.GUEST);
1977    
1978                    if (layoutGroupId != guestGroup.getGroupId()) {
1979                            Group layoutGroup = GroupLocalServiceUtil.getGroup(layoutGroupId);
1980    
1981                            UnicodeProperties typeSettingsProperties =
1982                                    layoutGroup.getTypeSettingsProperties();
1983    
1984                            boolean mergeGuestPublicPages = GetterUtil.getBoolean(
1985                                    typeSettingsProperties.getProperty("mergeGuestPublicPages"));
1986    
1987                            if (!mergeGuestPublicPages) {
1988                                    return layouts;
1989                            }
1990    
1991                            List<Layout> guestLayouts = LayoutLocalServiceUtil.getLayouts(
1992                                    guestGroup.getGroupId(), false,
1993                                    LayoutConstants.DEFAULT_PARENT_LAYOUT_ID);
1994    
1995                            Object[] viewableLayouts = getViewableLayouts(
1996                                    request, user, permissionChecker, layout, guestLayouts,
1997                                    doAsGroupId, controlPanelCategory);
1998    
1999                            guestLayouts = (List<Layout>)viewableLayouts[1];
2000    
2001                            if (layouts == null) {
2002                                    return guestLayouts;
2003                            }
2004    
2005                            layouts.addAll(0, guestLayouts);
2006                    }
2007                    else {
2008                            HttpSession session = request.getSession();
2009    
2010                            Long previousGroupId = (Long)session.getAttribute(
2011                                    WebKeys.VISITED_GROUP_ID_PREVIOUS);
2012    
2013                            if ((previousGroupId != null) &&
2014                                    (previousGroupId.longValue() != layoutGroupId)) {
2015    
2016                                    Group previousGroup = null;
2017    
2018                                    try {
2019                                            previousGroup = GroupLocalServiceUtil.getGroup(
2020                                                    previousGroupId.longValue());
2021                                    }
2022                                    catch (NoSuchGroupException nsge) {
2023                                            if (_log.isWarnEnabled()) {
2024                                                    _log.warn(nsge);
2025                                            }
2026    
2027                                            return layouts;
2028                                    }
2029    
2030                                    UnicodeProperties typeSettingsProperties =
2031                                            previousGroup.getTypeSettingsProperties();
2032    
2033                                    boolean mergeGuestPublicPages = GetterUtil.getBoolean(
2034                                            typeSettingsProperties.getProperty(
2035                                                    "mergeGuestPublicPages"));
2036    
2037                                    if (!mergeGuestPublicPages) {
2038                                            return layouts;
2039                                    }
2040    
2041                                    List<Layout> previousLayouts =
2042                                            LayoutLocalServiceUtil.getLayouts(
2043                                                    previousGroupId.longValue(), false,
2044                                                    LayoutConstants.DEFAULT_PARENT_LAYOUT_ID);
2045    
2046                                    Object[] viewableLayouts = getViewableLayouts(
2047                                            request, user, permissionChecker, layout, previousLayouts,
2048                                            doAsGroupId, controlPanelCategory);
2049    
2050                                    previousLayouts = (List<Layout>)viewableLayouts[1];
2051    
2052                                    if (previousLayouts != null) {
2053                                            layouts.addAll(previousLayouts);
2054                                    }
2055                            }
2056                    }
2057    
2058                    return layouts;
2059            }
2060    
2061            protected void rememberVisitedGroupIds(
2062                    HttpServletRequest request, long currentGroupId) {
2063    
2064                    String requestURI = GetterUtil.getString(request.getRequestURI());
2065    
2066                    if (!requestURI.endsWith(_PATH_PORTAL_LAYOUT)) {
2067                            return;
2068                    }
2069    
2070                    HttpSession session = request.getSession();
2071    
2072                    Long recentGroupId = (Long)session.getAttribute(
2073                            WebKeys.VISITED_GROUP_ID_RECENT);
2074    
2075                    Long previousGroupId = (Long)session.getAttribute(
2076                            WebKeys.VISITED_GROUP_ID_PREVIOUS);
2077    
2078                    if (recentGroupId == null) {
2079                            recentGroupId = new Long(currentGroupId);
2080    
2081                            session.setAttribute(
2082                                    WebKeys.VISITED_GROUP_ID_RECENT, recentGroupId);
2083                    }
2084                    else if (recentGroupId.longValue() != currentGroupId) {
2085                            previousGroupId = new Long(recentGroupId.longValue());
2086    
2087                            recentGroupId = new Long(currentGroupId);
2088    
2089                            session.setAttribute(
2090                                    WebKeys.VISITED_GROUP_ID_RECENT, recentGroupId);
2091    
2092                            session.setAttribute(
2093                                    WebKeys.VISITED_GROUP_ID_PREVIOUS, previousGroupId);
2094                    }
2095    
2096                    if (_log.isDebugEnabled()) {
2097                            _log.debug("Current group id " + currentGroupId);
2098                            _log.debug("Recent group id " + recentGroupId);
2099                            _log.debug("Previous group id " + previousGroupId);
2100                    }
2101            }
2102    
2103            protected void servicePre(
2104                            HttpServletRequest request, HttpServletResponse response)
2105                    throws Exception {
2106    
2107                    ThemeDisplay themeDisplay = initThemeDisplay(request, response);
2108    
2109                    if (themeDisplay == null) {
2110                            return;
2111                    }
2112    
2113                    request.setAttribute(WebKeys.THEME_DISPLAY, themeDisplay);
2114    
2115                    // Service context
2116    
2117                    ServiceContext serviceContext = ServiceContextFactory.getInstance(
2118                            request);
2119    
2120                    ServiceContextThreadLocal.pushServiceContext(serviceContext);
2121    
2122                    // Ajaxable render
2123    
2124                    if (PropsValues.LAYOUT_AJAX_RENDER_ENABLE) {
2125                            boolean portletAjaxRender = ParamUtil.getBoolean(
2126                                    request, "p_p_ajax", true);
2127    
2128                            request.setAttribute(
2129                                    WebKeys.PORTLET_AJAX_RENDER, portletAjaxRender);
2130                    }
2131    
2132                    // Parallel render
2133    
2134                    if (PropsValues.LAYOUT_PARALLEL_RENDER_ENABLE &&
2135                            ServerDetector.isTomcat()) {
2136    
2137                            boolean portletParallelRender = ParamUtil.getBoolean(
2138                                    request, "p_p_parallel", true);
2139    
2140                            request.setAttribute(
2141                                    WebKeys.PORTLET_PARALLEL_RENDER, portletParallelRender);
2142                    }
2143    
2144                    // Main Journal article
2145    
2146                    long mainJournalArticleId = ParamUtil.getLong(request, "p_j_a_id");
2147    
2148                    if (mainJournalArticleId > 0) {
2149                            try {
2150                                    JournalArticle mainJournalArticle =
2151                                            JournalArticleServiceUtil.getArticle(mainJournalArticleId);
2152    
2153                                    AssetEntry layoutAssetEntry =
2154                                            AssetEntryLocalServiceUtil.getEntry(
2155                                                    JournalArticle.class.getName(),
2156                                                    mainJournalArticle.getResourcePrimKey());
2157    
2158                                    request.setAttribute(
2159                                            WebKeys.LAYOUT_ASSET_ENTRY, layoutAssetEntry);
2160                            }
2161                            catch (NoSuchArticleException nsae) {
2162                                    if (_log.isWarnEnabled()) {
2163                                            _log.warn(nsae.getMessage());
2164                                    }
2165                            }
2166                    }
2167            }
2168    
2169            protected void updateUserLayouts(User user) throws Exception {
2170                    Boolean hasPowerUserRole = null;
2171    
2172                    // Private layouts
2173    
2174                    boolean addDefaultUserPrivateLayouts = false;
2175    
2176                    if (PropsValues.LAYOUT_USER_PRIVATE_LAYOUTS_ENABLED &&
2177                            PropsValues.LAYOUT_USER_PRIVATE_LAYOUTS_AUTO_CREATE) {
2178    
2179                            addDefaultUserPrivateLayouts = true;
2180    
2181                            if (PropsValues.LAYOUT_USER_PRIVATE_LAYOUTS_POWER_USER_REQUIRED) {
2182                                    if (hasPowerUserRole == null) {
2183                                            hasPowerUserRole = hasPowerUserRole(user);
2184                                    }
2185    
2186                                    if (!hasPowerUserRole.booleanValue()) {
2187                                            addDefaultUserPrivateLayouts = false;
2188                                    }
2189                            }
2190                    }
2191    
2192                    Boolean hasPrivateLayouts = null;
2193    
2194                    if (addDefaultUserPrivateLayouts) {
2195                            hasPrivateLayouts = LayoutLocalServiceUtil.hasLayouts(
2196                                    user, true, false);
2197    
2198                            if (!hasPrivateLayouts) {
2199                                    addDefaultUserPrivateLayouts(user);
2200                            }
2201                    }
2202    
2203                    boolean deleteDefaultUserPrivateLayouts = false;
2204    
2205                    if (!PropsValues.LAYOUT_USER_PRIVATE_LAYOUTS_ENABLED) {
2206                            deleteDefaultUserPrivateLayouts = true;
2207                    }
2208                    else if (PropsValues.LAYOUT_USER_PRIVATE_LAYOUTS_POWER_USER_REQUIRED) {
2209                            if (hasPowerUserRole == null) {
2210                                    hasPowerUserRole = hasPowerUserRole(user);
2211                            }
2212    
2213                            if (!hasPowerUserRole.booleanValue()) {
2214                                    deleteDefaultUserPrivateLayouts = true;
2215                            }
2216                    }
2217    
2218                    if (deleteDefaultUserPrivateLayouts) {
2219                            if (hasPrivateLayouts == null) {
2220                                    hasPrivateLayouts = LayoutLocalServiceUtil.hasLayouts(
2221                                            user, true, false);
2222                            }
2223    
2224                            if (hasPrivateLayouts) {
2225                                    deleteDefaultUserPrivateLayouts(user);
2226                            }
2227                    }
2228    
2229                    // Public pages
2230    
2231                    boolean addDefaultUserPublicLayouts = false;
2232    
2233                    if (PropsValues.LAYOUT_USER_PUBLIC_LAYOUTS_ENABLED &&
2234                            PropsValues.LAYOUT_USER_PUBLIC_LAYOUTS_AUTO_CREATE) {
2235    
2236                            addDefaultUserPublicLayouts = true;
2237    
2238                            if (PropsValues.LAYOUT_USER_PUBLIC_LAYOUTS_POWER_USER_REQUIRED) {
2239                                    if (hasPowerUserRole == null) {
2240                                            hasPowerUserRole = hasPowerUserRole(user);
2241                                    }
2242    
2243                                    if (!hasPowerUserRole.booleanValue()) {
2244                                            addDefaultUserPublicLayouts = false;
2245                                    }
2246                            }
2247                    }
2248    
2249                    Boolean hasPublicLayouts = null;
2250    
2251                    if (addDefaultUserPublicLayouts) {
2252                            hasPublicLayouts = LayoutLocalServiceUtil.hasLayouts(
2253                                    user, false, false);
2254    
2255                            if (!hasPublicLayouts) {
2256                                    addDefaultUserPublicLayouts(user);
2257                            }
2258                    }
2259    
2260                    boolean deleteDefaultUserPublicLayouts = false;
2261    
2262                    if (!PropsValues.LAYOUT_USER_PUBLIC_LAYOUTS_ENABLED) {
2263                            deleteDefaultUserPublicLayouts = true;
2264                    }
2265                    else if (PropsValues.LAYOUT_USER_PUBLIC_LAYOUTS_POWER_USER_REQUIRED) {
2266                            if (hasPowerUserRole == null) {
2267                                    hasPowerUserRole = hasPowerUserRole(user);
2268                            }
2269    
2270                            if (!hasPowerUserRole.booleanValue()) {
2271                                    deleteDefaultUserPublicLayouts = true;
2272                            }
2273                    }
2274    
2275                    if (deleteDefaultUserPublicLayouts) {
2276                            if (hasPublicLayouts == null) {
2277                                    hasPublicLayouts = LayoutLocalServiceUtil.hasLayouts(
2278                                            user, false, false);
2279                            }
2280    
2281                            if (hasPublicLayouts) {
2282                                    deleteDefaultUserPublicLayouts(user);
2283                            }
2284                    }
2285            }
2286    
2287            protected File privateLARFile;
2288            protected File publicLARFile;
2289    
2290            private static final String _PATH_PORTAL_LAYOUT = "/portal/layout";
2291    
2292            private static final String _PATH_PORTAL_LOGIN = "/portal/login";
2293    
2294            private static final String _PATH_PORTAL_LOGOUT = "/portal/logout";
2295    
2296            private static Log _log = LogFactoryUtil.getLog(ServicePreAction.class);
2297    
2298    }