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