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