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