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