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