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