1   /**
2    * Copyright (c) 2000-2008 Liferay, Inc. All rights reserved.
3    *
4    * Permission is hereby granted, free of charge, to any person obtaining a copy
5    * of this software and associated documentation files (the "Software"), to deal
6    * in the Software without restriction, including without limitation the rights
7    * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8    * copies of the Software, and to permit persons to whom the Software is
9    * furnished to do so, subject to the following conditions:
10   *
11   * The above copyright notice and this permission notice shall be included in
12   * all copies or substantial portions of the Software.
13   *
14   * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15   * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16   * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17   * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18   * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19   * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
20   * SOFTWARE.
21   */
22  
23  package com.liferay.portal.events;
24  
25  import com.liferay.portal.LayoutPermissionException;
26  import com.liferay.portal.NoSuchGroupException;
27  import com.liferay.portal.NoSuchLayoutException;
28  import com.liferay.portal.PortalException;
29  import com.liferay.portal.SystemException;
30  import com.liferay.portal.kernel.dao.orm.QueryUtil;
31  import com.liferay.portal.kernel.events.Action;
32  import com.liferay.portal.kernel.events.ActionException;
33  import com.liferay.portal.kernel.language.LanguageUtil;
34  import com.liferay.portal.kernel.portlet.LiferayWindowState;
35  import com.liferay.portal.kernel.servlet.BrowserSnifferUtil;
36  import com.liferay.portal.kernel.servlet.ImageServletTokenUtil;
37  import com.liferay.portal.kernel.servlet.SessionErrors;
38  import com.liferay.portal.kernel.util.GetterUtil;
39  import com.liferay.portal.kernel.util.HttpUtil;
40  import com.liferay.portal.kernel.util.LocaleUtil;
41  import com.liferay.portal.kernel.util.ParamUtil;
42  import com.liferay.portal.kernel.util.StringPool;
43  import com.liferay.portal.kernel.util.StringUtil;
44  import com.liferay.portal.kernel.util.UnicodeProperties;
45  import com.liferay.portal.kernel.util.Validator;
46  import com.liferay.portal.lar.PortletDataHandlerKeys;
47  import com.liferay.portal.model.ColorScheme;
48  import com.liferay.portal.model.Company;
49  import com.liferay.portal.model.Group;
50  import com.liferay.portal.model.GroupConstants;
51  import com.liferay.portal.model.Image;
52  import com.liferay.portal.model.Layout;
53  import com.liferay.portal.model.LayoutConstants;
54  import com.liferay.portal.model.LayoutSet;
55  import com.liferay.portal.model.LayoutTypePortlet;
56  import com.liferay.portal.model.Role;
57  import com.liferay.portal.model.RoleConstants;
58  import com.liferay.portal.model.Theme;
59  import com.liferay.portal.model.User;
60  import com.liferay.portal.model.impl.ColorSchemeImpl;
61  import com.liferay.portal.model.impl.LayoutImpl;
62  import com.liferay.portal.model.impl.LayoutTypePortletImpl;
63  import com.liferay.portal.model.impl.ThemeImpl;
64  import com.liferay.portal.security.permission.ActionKeys;
65  import com.liferay.portal.security.permission.PermissionChecker;
66  import com.liferay.portal.security.permission.PermissionCheckerFactory;
67  import com.liferay.portal.security.permission.PermissionThreadLocal;
68  import com.liferay.portal.service.GroupLocalServiceUtil;
69  import com.liferay.portal.service.ImageLocalServiceUtil;
70  import com.liferay.portal.service.LayoutLocalServiceUtil;
71  import com.liferay.portal.service.LayoutSetLocalServiceUtil;
72  import com.liferay.portal.service.OrganizationLocalServiceUtil;
73  import com.liferay.portal.service.RoleLocalServiceUtil;
74  import com.liferay.portal.service.ThemeLocalServiceUtil;
75  import com.liferay.portal.service.UserLocalServiceUtil;
76  import com.liferay.portal.service.permission.GroupPermissionUtil;
77  import com.liferay.portal.service.permission.LayoutPermissionUtil;
78  import com.liferay.portal.service.permission.OrganizationPermissionUtil;
79  import com.liferay.portal.service.permission.UserPermissionUtil;
80  import com.liferay.portal.theme.ThemeDisplay;
81  import com.liferay.portal.theme.ThemeDisplayFactory;
82  import com.liferay.portal.util.CookieKeys;
83  import com.liferay.portal.util.LayoutClone;
84  import com.liferay.portal.util.LayoutCloneFactory;
85  import com.liferay.portal.util.PortalUtil;
86  import com.liferay.portal.util.PortletKeys;
87  import com.liferay.portal.util.PropsKeys;
88  import com.liferay.portal.util.PropsUtil;
89  import com.liferay.portal.util.PropsValues;
90  import com.liferay.portal.util.WebKeys;
91  import com.liferay.portlet.PortletURLImpl;
92  import com.liferay.util.Normalizer;
93  
94  import java.io.File;
95  
96  import java.util.ArrayList;
97  import java.util.HashMap;
98  import java.util.LinkedHashMap;
99  import java.util.List;
100 import java.util.Locale;
101 import java.util.Map;
102 import java.util.TimeZone;
103 
104 import javax.portlet.PortletMode;
105 import javax.portlet.PortletRequest;
106 import javax.portlet.PortletURL;
107 import javax.portlet.WindowState;
108 
109 import javax.servlet.http.HttpServletRequest;
110 import javax.servlet.http.HttpServletResponse;
111 import javax.servlet.http.HttpSession;
112 
113 import org.apache.commons.lang.time.StopWatch;
114 import org.apache.commons.logging.Log;
115 import org.apache.commons.logging.LogFactory;
116 import org.apache.struts.Globals;
117 
118 /**
119  * <a href="ServicePreAction.java.html"><b><i>View Source</i></b></a>
120  *
121  * @author Brian Wing Shun Chan
122  * @author Felix Ventero
123  *
124  */
125 public class ServicePreAction extends Action {
126 
127     public ServicePreAction() {
128         initImportLARFiles();
129     }
130 
131     public void run(HttpServletRequest request, HttpServletResponse response)
132         throws ActionException {
133 
134         StopWatch stopWatch = null;
135 
136         if (_log.isDebugEnabled()) {
137             stopWatch = new StopWatch();
138 
139             stopWatch.start();
140         }
141 
142         try {
143             servicePre(request, response);
144         }
145         catch (Exception e) {
146             throw new ActionException(e);
147         }
148 
149         if (_log.isDebugEnabled()) {
150             _log.debug("Running takes " + stopWatch.getTime() + " ms");
151         }
152     }
153 
154     protected void addDefaultLayoutsByLAR(
155             long userId, long groupId, boolean privateLayout, File larFile)
156         throws PortalException, SystemException {
157 
158         Map<String, String[]> parameterMap = new HashMap<String, String[]>();
159 
160         parameterMap.put(
161             PortletDataHandlerKeys.PERMISSIONS,
162             new String[] {Boolean.TRUE.toString()});
163         parameterMap.put(
164             PortletDataHandlerKeys.PORTLET_DATA,
165             new String[] {Boolean.TRUE.toString()});
166         parameterMap.put(
167             PortletDataHandlerKeys.PORTLET_DATA_CONTROL_DEFAULT,
168             new String[] {Boolean.TRUE.toString()});
169         parameterMap.put(
170             PortletDataHandlerKeys.PORTLET_SETUP,
171             new String[] {Boolean.TRUE.toString()});
172         parameterMap.put(
173             PortletDataHandlerKeys.USER_PERMISSIONS,
174             new String[] {Boolean.FALSE.toString()});
175 
176         LayoutLocalServiceUtil.importLayouts(
177             userId, groupId, privateLayout, parameterMap, larFile);
178     }
179 
180     protected void addDefaultUserPrivateLayoutByProperties(
181             long userId, long groupId)
182         throws PortalException, SystemException {
183 
184         String friendlyURL = getFriendlyURL(
185             PropsValues.DEFAULT_USER_PRIVATE_LAYOUT_FRIENDLY_URL);
186 
187         Layout layout = LayoutLocalServiceUtil.addLayout(
188             userId, groupId, true, LayoutConstants.DEFAULT_PARENT_LAYOUT_ID,
189             PropsValues.DEFAULT_USER_PRIVATE_LAYOUT_NAME, StringPool.BLANK,
190             StringPool.BLANK, LayoutConstants.TYPE_PORTLET, false, friendlyURL);
191 
192         LayoutTypePortlet layoutTypePortlet =
193             (LayoutTypePortlet)layout.getLayoutType();
194 
195         layoutTypePortlet.setLayoutTemplateId(
196             0, PropsValues.DEFAULT_USER_PRIVATE_LAYOUT_TEMPLATE_ID, false);
197 
198         for (int i = 0; i < 10; i++) {
199             String columnId = "column-" + i;
200             String portletIds = PropsUtil.get(
201                 PropsKeys.DEFAULT_USER_PRIVATE_LAYOUT_COLUMN + i);
202 
203             String[] portletIdsArray = StringUtil.split(portletIds);
204 
205             layoutTypePortlet.addPortletIds(
206                 0, portletIdsArray, columnId, false);
207         }
208 
209         LayoutLocalServiceUtil.updateLayout(
210             layout.getGroupId(), layout.isPrivateLayout(), layout.getLayoutId(),
211             layout.getTypeSettings());
212 
213         boolean updateLayoutSet = false;
214 
215         LayoutSet layoutSet = layout.getLayoutSet();
216 
217         if (Validator.isNotNull(
218                 PropsValues.DEFAULT_USER_PRIVATE_LAYOUT_REGULAR_THEME_ID)) {
219 
220             layoutSet.setThemeId(
221                 PropsValues.DEFAULT_USER_PRIVATE_LAYOUT_REGULAR_THEME_ID);
222 
223             updateLayoutSet = true;
224         }
225 
226         if (Validator.isNotNull(
227                 PropsValues.
228                     DEFAULT_USER_PRIVATE_LAYOUT_REGULAR_COLOR_SCHEME_ID)) {
229 
230             layoutSet.setColorSchemeId(
231                 PropsValues.
232                     DEFAULT_USER_PRIVATE_LAYOUT_REGULAR_COLOR_SCHEME_ID);
233 
234             updateLayoutSet = true;
235         }
236 
237         if (Validator.isNotNull(
238                 PropsValues.DEFAULT_USER_PRIVATE_LAYOUT_WAP_THEME_ID)) {
239 
240             layoutSet.setWapThemeId(
241                 PropsValues.DEFAULT_USER_PRIVATE_LAYOUT_WAP_THEME_ID);
242 
243             updateLayoutSet = true;
244         }
245 
246         if (Validator.isNotNull(
247                 PropsValues.DEFAULT_USER_PRIVATE_LAYOUT_WAP_COLOR_SCHEME_ID)) {
248 
249             layoutSet.setWapColorSchemeId(
250                 PropsValues.DEFAULT_USER_PRIVATE_LAYOUT_WAP_COLOR_SCHEME_ID);
251 
252             updateLayoutSet = true;
253         }
254 
255         if (updateLayoutSet) {
256             LayoutSetLocalServiceUtil.updateLayoutSet(layoutSet);
257         }
258     }
259 
260     protected void addDefaultUserPrivateLayouts(User user)
261         throws PortalException, SystemException {
262 
263         Group userGroup = user.getGroup();
264 
265         if (privateLARFile != null) {
266             addDefaultLayoutsByLAR(
267                 user.getUserId(), userGroup.getGroupId(), true, privateLARFile);
268         }
269         else {
270             addDefaultUserPrivateLayoutByProperties(
271                 user.getUserId(), userGroup.getGroupId());
272         }
273     }
274 
275     protected void addDefaultUserPublicLayoutByProperties(
276             long userId, long groupId)
277         throws PortalException, SystemException {
278 
279         String friendlyURL = getFriendlyURL(
280             PropsValues.DEFAULT_USER_PUBLIC_LAYOUT_FRIENDLY_URL);
281 
282         Layout layout = LayoutLocalServiceUtil.addLayout(
283             userId, groupId, false, LayoutConstants.DEFAULT_PARENT_LAYOUT_ID,
284             PropsValues.DEFAULT_USER_PUBLIC_LAYOUT_NAME, StringPool.BLANK,
285             StringPool.BLANK, LayoutConstants.TYPE_PORTLET, false, friendlyURL);
286 
287         LayoutTypePortlet layoutTypePortlet =
288             (LayoutTypePortlet)layout.getLayoutType();
289 
290         layoutTypePortlet.setLayoutTemplateId(
291             0, PropsValues.DEFAULT_USER_PUBLIC_LAYOUT_TEMPLATE_ID, false);
292 
293         for (int i = 0; i < 10; i++) {
294             String columnId = "column-" + i;
295             String portletIds = PropsUtil.get(
296                 PropsKeys.DEFAULT_USER_PUBLIC_LAYOUT_COLUMN + i);
297 
298             String[] portletIdsArray = StringUtil.split(portletIds);
299 
300             layoutTypePortlet.addPortletIds(
301                 0, portletIdsArray, columnId, false);
302         }
303 
304         LayoutLocalServiceUtil.updateLayout(
305             layout.getGroupId(), layout.isPrivateLayout(), layout.getLayoutId(),
306             layout.getTypeSettings());
307 
308         boolean updateLayoutSet = false;
309 
310         LayoutSet layoutSet = layout.getLayoutSet();
311 
312         if (Validator.isNotNull(
313                 PropsValues.DEFAULT_USER_PUBLIC_LAYOUT_REGULAR_THEME_ID)) {
314 
315             layoutSet.setThemeId(
316                 PropsValues.DEFAULT_USER_PUBLIC_LAYOUT_REGULAR_THEME_ID);
317 
318             updateLayoutSet = true;
319         }
320 
321         if (Validator.isNotNull(
322                 PropsValues.
323                     DEFAULT_USER_PUBLIC_LAYOUT_REGULAR_COLOR_SCHEME_ID)) {
324 
325             layoutSet.setColorSchemeId(
326                 PropsValues.DEFAULT_USER_PUBLIC_LAYOUT_REGULAR_COLOR_SCHEME_ID);
327 
328             updateLayoutSet = true;
329         }
330 
331         if (Validator.isNotNull(
332                 PropsValues.DEFAULT_USER_PUBLIC_LAYOUT_WAP_THEME_ID)) {
333 
334             layoutSet.setWapThemeId(
335                 PropsValues.DEFAULT_USER_PUBLIC_LAYOUT_WAP_THEME_ID);
336 
337             updateLayoutSet = true;
338         }
339 
340         if (Validator.isNotNull(
341                 PropsValues.DEFAULT_USER_PUBLIC_LAYOUT_WAP_COLOR_SCHEME_ID)) {
342 
343             layoutSet.setWapColorSchemeId(
344                 PropsValues.DEFAULT_USER_PUBLIC_LAYOUT_WAP_COLOR_SCHEME_ID);
345 
346             updateLayoutSet = true;
347         }
348 
349         if (updateLayoutSet) {
350             LayoutSetLocalServiceUtil.updateLayoutSet(layoutSet);
351         }
352     }
353 
354     protected void addDefaultUserPublicLayouts(User user)
355         throws PortalException, SystemException {
356 
357         Group userGroup = user.getGroup();
358 
359         if (publicLARFile != null) {
360             addDefaultLayoutsByLAR(
361                 user.getUserId(), userGroup.getGroupId(), false, publicLARFile);
362         }
363         else {
364             addDefaultUserPublicLayoutByProperties(
365                 user.getUserId(), userGroup.getGroupId());
366         }
367     }
368 
369     protected void deleteDefaultUserPrivateLayouts(User user)
370         throws PortalException, SystemException {
371 
372         Group userGroup = user.getGroup();
373 
374         LayoutLocalServiceUtil.deleteLayouts(userGroup.getGroupId(), true);
375     }
376 
377     protected void deleteDefaultUserPublicLayouts(User user)
378         throws PortalException, SystemException {
379 
380         Group userGroup = user.getGroup();
381 
382         LayoutLocalServiceUtil.deleteLayouts(userGroup.getGroupId(), false);
383     }
384 
385     protected Object[] getDefaultLayout(
386             HttpServletRequest request, User user, boolean signedIn)
387         throws PortalException, SystemException {
388 
389         // Check the virtual host
390 
391         LayoutSet layoutSet = (LayoutSet)request.getAttribute(
392             WebKeys.VIRTUAL_HOST_LAYOUT_SET);
393 
394         if (layoutSet != null) {
395             List<Layout> layouts = LayoutLocalServiceUtil.getLayouts(
396                 layoutSet.getGroupId(), layoutSet.isPrivateLayout(),
397                 LayoutConstants.DEFAULT_PARENT_LAYOUT_ID);
398 
399             if (layouts.size() > 0) {
400                 Layout layout = layouts.get(0);
401 
402                 return new Object[] {layout, layouts};
403             }
404         }
405 
406         Layout layout = null;
407         List<Layout> layouts = null;
408 
409         if (signedIn) {
410 
411             // Check the user's personal layouts
412 
413             Group userGroup = user.getGroup();
414 
415             layouts = LayoutLocalServiceUtil.getLayouts(
416                 userGroup.getGroupId(), true,
417                 LayoutConstants.DEFAULT_PARENT_LAYOUT_ID);
418 
419             if (layouts.size() == 0) {
420                 layouts = LayoutLocalServiceUtil.getLayouts(
421                     userGroup.getGroupId(), false,
422                     LayoutConstants.DEFAULT_PARENT_LAYOUT_ID);
423             }
424 
425             if (layouts.size() > 0) {
426                 layout = layouts.get(0);
427             }
428 
429             // Check the user's communities
430 
431             if (layout == null) {
432                 LinkedHashMap<String, Object> groupParams =
433                     new LinkedHashMap<String, Object>();
434 
435                 groupParams.put("usersGroups", new Long(user.getUserId()));
436 
437                 List<Group> groups = GroupLocalServiceUtil.search(
438                     user.getCompanyId(), null, null, groupParams,
439                     QueryUtil.ALL_POS, QueryUtil.ALL_POS);
440 
441                 for (int i = 0; i < groups.size(); i++) {
442                     Group group = groups.get(i);
443 
444                     layouts = LayoutLocalServiceUtil.getLayouts(
445                         group.getGroupId(), true,
446                         LayoutConstants.DEFAULT_PARENT_LAYOUT_ID);
447 
448                     if (layouts.size() == 0) {
449                         layouts = LayoutLocalServiceUtil.getLayouts(
450                             group.getGroupId(), false,
451                             LayoutConstants.DEFAULT_PARENT_LAYOUT_ID);
452                     }
453 
454                     if (layouts.size() > 0) {
455                         layout = layouts.get(0);
456 
457                         break;
458                     }
459                 }
460             }
461         }
462         else {
463 
464             // Check the guest community
465 
466             Group guestGroup = GroupLocalServiceUtil.getGroup(
467                 user.getCompanyId(), GroupConstants.GUEST);
468 
469             layouts = LayoutLocalServiceUtil.getLayouts(
470                 guestGroup.getGroupId(), false,
471                 LayoutConstants.DEFAULT_PARENT_LAYOUT_ID);
472 
473             if (layouts.size() > 0) {
474                 layout = layouts.get(0);
475             }
476         }
477 
478         return new Object[] {layout, layouts};
479     }
480 
481     protected String getFriendlyURL(String friendlyURL) {
482         friendlyURL = GetterUtil.getString(friendlyURL);
483 
484         return Normalizer.normalizeToAscii(friendlyURL.trim().toLowerCase());
485     }
486 
487     protected Object[] getViewableLayouts(
488             HttpServletRequest request, User user,
489             PermissionChecker permissionChecker, Layout layout,
490             List<Layout> layouts)
491         throws PortalException, SystemException {
492 
493         if ((layouts == null) || (layouts.size() == 0)) {
494             return new Object[] {layout, layouts};
495         }
496 
497         boolean replaceLayout = true;
498 
499         if (LayoutPermissionUtil.contains(
500                 permissionChecker, layout, ActionKeys.VIEW)) {
501 
502             replaceLayout = false;
503         }
504 
505         List<Layout> accessibleLayouts = new ArrayList<Layout>();
506 
507         for (int i = 0; i < layouts.size(); i++) {
508             Layout curLayout = layouts.get(i);
509 
510             if (!curLayout.isHidden() &&
511                 LayoutPermissionUtil.contains(
512                     permissionChecker, curLayout, ActionKeys.VIEW)) {
513 
514                 if ((accessibleLayouts.size() == 0) && replaceLayout) {
515                     layout = curLayout;
516                 }
517 
518                 accessibleLayouts.add(curLayout);
519             }
520         }
521 
522         if (accessibleLayouts.size() == 0) {
523             layouts = null;
524 
525             SessionErrors.add(
526                 request, LayoutPermissionException.class.getName());
527         }
528         else {
529             layouts = accessibleLayouts;
530         }
531 
532         return new Object[] {layout, layouts};
533     }
534 
535     protected void initImportLARFiles() {
536         String privateLARFileName =
537             PropsValues.DEFAULT_USER_PRIVATE_LAYOUTS_LAR;
538 
539         if (_log.isDebugEnabled()) {
540             _log.debug("Reading private LAR file " + privateLARFileName);
541         }
542 
543         if (Validator.isNotNull(privateLARFileName)) {
544             privateLARFile = new File(privateLARFileName);
545 
546             if (!privateLARFile.exists()) {
547                 _log.error(
548                     "Private LAR file " + privateLARFile + " does not exist");
549 
550                 privateLARFile = null;
551             }
552             else {
553                 if (_log.isDebugEnabled()) {
554                     _log.debug("Using private LAR file " + privateLARFileName);
555                 }
556             }
557         }
558 
559         String publicLARFileName = PropsValues.DEFAULT_USER_PUBLIC_LAYOUTS_LAR;
560 
561         if (_log.isDebugEnabled()) {
562             _log.debug("Reading public LAR file " + publicLARFileName);
563         }
564 
565         if (Validator.isNotNull(publicLARFileName)) {
566             publicLARFile = new File(publicLARFileName);
567 
568             if (!publicLARFile.exists()) {
569                 _log.error(
570                     "Public LAR file " + publicLARFile + " does not exist");
571 
572                 publicLARFile = null;
573             }
574             else {
575                 if (_log.isDebugEnabled()) {
576                     _log.debug("Using public LAR file " + publicLARFileName);
577                 }
578             }
579         }
580     }
581 
582     protected boolean isViewableCommunity(
583             User user, long groupId, boolean privateLayout,
584             PermissionChecker permissionChecker)
585         throws PortalException, SystemException {
586 
587         Group group = GroupLocalServiceUtil.getGroup(groupId);
588 
589         // Inactive communities are not viewable
590 
591         if (!group.isActive()) {
592             return false;
593         }
594         else if (group.isStagingGroup()) {
595             Group liveGroup = group.getLiveGroup();
596 
597             if (!liveGroup.isActive()) {
598                 return false;
599             }
600         }
601 
602         // User private layouts are only viewable by the user and anyone who can
603         // update the user. The user must also be active.
604 
605         if (group.isUser()) {
606             long groupUserId = group.getClassPK();
607 
608             if (groupUserId == user.getUserId()) {
609                 return true;
610             }
611             else {
612                 User groupUser = UserLocalServiceUtil.getUserById(groupUserId);
613 
614                 if (!groupUser.isActive()) {
615                     return false;
616                 }
617 
618                 if (privateLayout) {
619                     if (UserPermissionUtil.contains(
620                             permissionChecker, groupUserId,
621                             groupUser.getOrganizationIds(),
622                             ActionKeys.UPDATE)) {
623 
624                         return true;
625                     }
626                     else {
627                         return false;
628                     }
629                 }
630             }
631         }
632 
633         // Most public layouts are viewable
634 
635         if (!privateLayout) {
636             return true;
637         }
638 
639         // If the current group is staging, the live group should be checked
640         // for membership instead
641 
642         if (group.isStagingGroup()) {
643             groupId = group.getLiveGroupId();
644         }
645 
646         // Community or organization layouts are only viewable by users who
647         // belong to the community or organization, or by users who can update
648         // the community or organization
649 
650         if (group.isCommunity()) {
651             if (GroupLocalServiceUtil.hasUserGroup(user.getUserId(), groupId)) {
652                 return true;
653             }
654             else if (GroupPermissionUtil.contains(
655                         permissionChecker, groupId, ActionKeys.UPDATE)) {
656 
657                 return true;
658             }
659         }
660         else if (group.isOrganization()) {
661             long organizationId = group.getClassPK();
662 
663             if (OrganizationLocalServiceUtil.hasUserOrganization(
664                     user.getUserId(), organizationId)) {
665 
666                 return true;
667             }
668             else if (OrganizationPermissionUtil.contains(
669                         permissionChecker, organizationId, ActionKeys.UPDATE)) {
670 
671                 return true;
672             }
673         }
674         else if (group.isUserGroup()) {
675             if (GroupPermissionUtil.contains(
676                     permissionChecker, groupId, ActionKeys.MANAGE_LAYOUTS)) {
677 
678                 return true;
679             }
680         }
681 
682         return false;
683     }
684 
685     protected List<Layout> mergeAdditionalLayouts(
686             HttpServletRequest request, User user,
687             PermissionChecker permissionChecker, Layout layout,
688             List<Layout> layouts)
689         throws PortalException, SystemException {
690 
691         if ((layout == null) || layout.isPrivateLayout()) {
692             return layouts;
693         }
694 
695         long layoutGroupId = layout.getGroupId();
696 
697         Group guestGroup = GroupLocalServiceUtil.getGroup(
698             user.getCompanyId(), GroupConstants.GUEST);
699 
700         if (layoutGroupId != guestGroup.getGroupId()) {
701             Group layoutGroup = GroupLocalServiceUtil.getGroup(layoutGroupId);
702 
703             UnicodeProperties props = layoutGroup.getTypeSettingsProperties();
704 
705             boolean mergeGuestPublicPages = GetterUtil.getBoolean(
706                 props.getProperty("mergeGuestPublicPages"));
707 
708             if (!mergeGuestPublicPages) {
709                 return layouts;
710             }
711 
712             List<Layout> guestLayouts = LayoutLocalServiceUtil.getLayouts(
713                 guestGroup.getGroupId(), false,
714                 LayoutConstants.DEFAULT_PARENT_LAYOUT_ID);
715 
716             Object[] viewableLayouts = getViewableLayouts(
717                 request, user, permissionChecker, layout, guestLayouts);
718 
719             guestLayouts = (List<Layout>)viewableLayouts[1];
720 
721             layouts.addAll(0, guestLayouts);
722         }
723         else {
724             HttpSession session = request.getSession();
725 
726             Long previousGroupId = (Long)session.getAttribute(
727                 WebKeys.LIFERAY_SHARED_VISITED_GROUP_ID_PREVIOUS);
728 
729             if ((previousGroupId != null) &&
730                 (previousGroupId.longValue() != layoutGroupId)) {
731 
732                 Group previousGroup = null;
733 
734                 try {
735                     previousGroup = GroupLocalServiceUtil.getGroup(
736                         previousGroupId.longValue());
737                 }
738                 catch (NoSuchGroupException nsge) {
739                     if (_log.isWarnEnabled()) {
740                         _log.warn(nsge);
741                     }
742 
743                     return layouts;
744                 }
745 
746                 UnicodeProperties props =
747                     previousGroup.getTypeSettingsProperties();
748 
749                 boolean mergeGuestPublicPages = GetterUtil.getBoolean(
750                     props.getProperty("mergeGuestPublicPages"));
751 
752                 if (!mergeGuestPublicPages) {
753                     return layouts;
754                 }
755 
756                 List<Layout> previousLayouts =
757                     LayoutLocalServiceUtil.getLayouts(
758                         previousGroupId.longValue(), false,
759                         LayoutConstants.DEFAULT_PARENT_LAYOUT_ID);
760 
761                 Object[] viewableLayouts = getViewableLayouts(
762                     request, user, permissionChecker, layout, previousLayouts);
763 
764                 previousLayouts = (List<Layout>)viewableLayouts[1];
765 
766                 layouts.addAll(previousLayouts);
767             }
768         }
769 
770         return layouts;
771     }
772 
773     protected void rememberVisitedGroupIds(
774         HttpServletRequest request, long currentGroupId) {
775 
776         String requestURI = GetterUtil.getString(request.getRequestURI());
777 
778         if (!requestURI.endsWith(_PATH_PORTAL_LAYOUT)) {
779             return;
780         }
781 
782         HttpSession session = request.getSession();
783 
784         Long recentGroupId = (Long)session.getAttribute(
785             WebKeys.LIFERAY_SHARED_VISITED_GROUP_ID_RECENT);
786 
787         Long previousGroupId = (Long)session.getAttribute(
788             WebKeys.LIFERAY_SHARED_VISITED_GROUP_ID_PREVIOUS);
789 
790         if (recentGroupId == null) {
791             recentGroupId = new Long(currentGroupId);
792 
793             session.setAttribute(
794                 WebKeys.LIFERAY_SHARED_VISITED_GROUP_ID_RECENT,
795                 recentGroupId);
796         }
797         else if (recentGroupId.longValue() != currentGroupId) {
798             previousGroupId = new Long(recentGroupId.longValue());
799 
800             recentGroupId = new Long(currentGroupId);
801 
802             session.setAttribute(
803                 WebKeys.LIFERAY_SHARED_VISITED_GROUP_ID_RECENT,
804                 recentGroupId);
805 
806             session.setAttribute(
807                 WebKeys.LIFERAY_SHARED_VISITED_GROUP_ID_PREVIOUS,
808                 previousGroupId);
809         }
810 
811         if (_log.isDebugEnabled()) {
812             _log.debug("Current group id " + currentGroupId);
813             _log.debug("Recent group id " + recentGroupId);
814             _log.debug("Previous group id " + previousGroupId);
815         }
816     }
817 
818     protected void servicePre(
819             HttpServletRequest request, HttpServletResponse response)
820         throws Exception {
821 
822         HttpSession session = request.getSession();
823 
824         // Company
825 
826         Company company = PortalUtil.getCompany(request);
827 
828         long companyId = company.getCompanyId();
829 
830         // CDN host
831 
832         String cdnHost = ParamUtil.getString(
833             request, "cdn_host", PortalUtil.getCDNHost());
834 
835         // Portal URL
836 
837         String portalURL = PortalUtil.getPortalURL(request);
838 
839         // Paths
840 
841         String contextPath = PortalUtil.getPathContext();
842         String friendlyURLPrivateGroupPath =
843             PortalUtil.getPathFriendlyURLPrivateGroup();
844         String friendlyURLPrivateUserPath =
845             PortalUtil.getPathFriendlyURLPrivateUser();
846         String friendlyURLPublicPath = PortalUtil.getPathFriendlyURLPublic();
847         String imagePath = PortalUtil.getPathImage();
848         String mainPath = PortalUtil.getPathMain();
849 
850         String i18nLanguageId = (String)request.getAttribute(
851             WebKeys.I18N_LANGUAGE_ID);
852 
853         if (Validator.isNotNull(i18nLanguageId)) {
854             if (Validator.isNotNull(contextPath)) {
855                 mainPath = StringUtil.replaceFirst(
856                     mainPath, contextPath,
857                     contextPath + StringPool.SLASH + i18nLanguageId);
858             }
859             else {
860                 mainPath = StringPool.SLASH + i18nLanguageId + mainPath;
861             }
862         }
863 
864         // Company logo
865 
866         String companyLogo =
867             imagePath + "/company_logo?img_id=" + company.getLogoId() + "&t=" +
868                 ImageServletTokenUtil.getToken(company.getLogoId());
869 
870         Image companyLogoImage = ImageLocalServiceUtil.getCompanyLogo(
871             company.getLogoId());
872 
873         int companyLogoHeight = companyLogoImage.getHeight();
874         int companyLogoWidth = companyLogoImage.getWidth();
875 
876         String realCompanyLogo = companyLogo;
877         int realCompanyLogoHeight = companyLogoHeight;
878         int realCompanyLogoWidth = companyLogoWidth;
879 
880         // User
881 
882         User user = PortalUtil.getUser(request);
883 
884         boolean signedIn = false;
885 
886         if (user == null) {
887             user = company.getDefaultUser();
888         }
889         else if (!user.isDefaultUser()) {
890             signedIn = true;
891         }
892 
893         User realUser = user;
894 
895         Long realUserId = (Long)session.getAttribute(WebKeys.USER_ID);
896 
897         if (realUserId != null) {
898             if (user.getUserId() != realUserId.longValue()) {
899                 realUser = UserLocalServiceUtil.getUserById(
900                     realUserId.longValue());
901             }
902         }
903 
904         String doAsUserId = ParamUtil.getString(request, "doAsUserId");
905 
906         // Permission checker
907 
908         PermissionChecker permissionChecker = PermissionCheckerFactory.create(
909             user, true);
910 
911         PermissionThreadLocal.setPermissionChecker(permissionChecker);
912 
913         // Locale
914 
915         Locale locale = (Locale)session.getAttribute(Globals.LOCALE_KEY);
916 
917         if (Validator.isNotNull(i18nLanguageId)) {
918             locale = LocaleUtil.fromLanguageId(i18nLanguageId);
919         }
920         else if (locale == null) {
921             if (signedIn) {
922                 locale = user.getLocale();
923             }
924             else {
925 
926                 // User previously set their preferred language
927 
928                 String languageId = CookieKeys.getCookie(
929                     request, CookieKeys.GUEST_LANGUAGE_ID);
930 
931                 if (Validator.isNotNull(languageId)) {
932                     locale = LocaleUtil.fromLanguageId(languageId);
933                 }
934 
935                 // Get locale from the request
936 
937                 if ((locale == null) && PropsValues.LOCALE_DEFAULT_REQUEST) {
938                     locale = request.getLocale();
939                 }
940 
941                 // Get locale from the default user
942 
943                 if (locale == null) {
944                     locale = user.getLocale();
945                 }
946 
947                 if (Validator.isNull(locale.getCountry())) {
948 
949                     // Locales must contain the country code
950 
951                     locale = LanguageUtil.getLocale(locale.getLanguage());
952                 }
953 
954                 if (!LanguageUtil.isAvailableLocale(locale)) {
955                     locale = user.getLocale();
956                 }
957             }
958 
959             session.setAttribute(Globals.LOCALE_KEY, locale);
960 
961             LanguageUtil.updateCookie(response, locale);
962         }
963 
964         // Cookie support
965 
966         try {
967 
968             // LEP-4069
969 
970             CookieKeys.validateSupportCookie(request);
971         }
972         catch (Exception e) {
973             CookieKeys.addSupportCookie(response);
974         }
975 
976         // Time zone
977 
978         TimeZone timeZone = user.getTimeZone();
979 
980         if (timeZone == null) {
981             timeZone = company.getTimeZone();
982         }
983 
984         // Layouts
985 
986         if (signedIn) {
987             updateUserLayouts(user);
988         }
989 
990         Layout layout = null;
991         List<Layout> layouts = null;
992 
993         long plid = ParamUtil.getLong(request, "p_l_id");
994 
995         if (plid > 0) {
996             layout = LayoutLocalServiceUtil.getLayout(plid);
997         }
998         else {
999             long groupId = ParamUtil.getLong(request, "groupId");
1000            boolean privateLayout = ParamUtil.getBoolean(
1001                request, "privateLayout");
1002            long layoutId = ParamUtil.getLong(request, "layoutId");
1003
1004            if ((groupId > 0) && layoutId > 0) {
1005                layout = LayoutLocalServiceUtil.getLayout(
1006                    groupId, privateLayout, layoutId);
1007            }
1008        }
1009
1010        if (layout != null) {
1011            try {
1012                if (!signedIn && PropsValues.AUTH_FORWARD_BY_REDIRECT) {
1013                    request.setAttribute(WebKeys.REQUESTED_LAYOUT, layout);
1014                }
1015
1016                boolean isViewableCommunity = isViewableCommunity(
1017                    user, layout.getGroupId(), layout.isPrivateLayout(),
1018                    permissionChecker);
1019
1020                if (!isViewableCommunity) {
1021                    StringBuilder sb = new StringBuilder();
1022
1023                    sb.append("User ");
1024                    sb.append(user.getUserId());
1025                    sb.append(" is not allowed to access the ");
1026                    sb.append(layout.isPrivateLayout() ? "private": "public");
1027                    sb.append(" pages of group ");
1028                    sb.append(layout.getGroupId());
1029
1030                    _log.warn(sb.toString());
1031
1032                    layout = null;
1033                }
1034                else if (isViewableCommunity &&
1035                        !LayoutPermissionUtil.contains(
1036                            permissionChecker, layout, ActionKeys.VIEW)) {
1037
1038                    layout = null;
1039                }
1040                else {
1041                    layouts = LayoutLocalServiceUtil.getLayouts(
1042                        layout.getGroupId(), layout.isPrivateLayout(),
1043                        LayoutConstants.DEFAULT_PARENT_LAYOUT_ID);
1044                }
1045            }
1046            catch (NoSuchLayoutException nsle) {
1047            }
1048        }
1049
1050        if (layout == null) {
1051            Object[] defaultLayout = getDefaultLayout(request, user, signedIn);
1052
1053            layout = (Layout)defaultLayout[0];
1054            layouts = (List<Layout>)defaultLayout[1];
1055
1056            request.setAttribute(WebKeys.LAYOUT_DEFAULT, Boolean.TRUE);
1057        }
1058
1059        Object[] viewableLayouts = getViewableLayouts(
1060            request, user, permissionChecker, layout, layouts);
1061
1062        String layoutSetLogo = null;
1063
1064        layout = (Layout)viewableLayouts[0];
1065        layouts = (List<Layout>)viewableLayouts[1];
1066
1067        LayoutTypePortlet layoutTypePortlet = null;
1068
1069        long scopeGroupId = PortalUtil.getScopeGroupId(layout);
1070
1071        rememberVisitedGroupIds(request, scopeGroupId);
1072
1073        layouts = mergeAdditionalLayouts(
1074            request, user, permissionChecker, layout, layouts);
1075
1076        if (layout != null) {
1077            if (company.isCommunityLogo()) {
1078                LayoutSet layoutSet = layout.getLayoutSet();
1079
1080                if (layoutSet.isLogo()) {
1081                    long logoId = layoutSet.getLogoId();
1082
1083                    layoutSetLogo =
1084                        imagePath + "/layout_set_logo?img_id=" + logoId +
1085                            "&t=" + ImageServletTokenUtil.getToken(logoId);
1086
1087                    Image layoutSetLogoImage =
1088                        ImageLocalServiceUtil.getCompanyLogo(logoId);
1089
1090                    companyLogo = layoutSetLogo;
1091                    companyLogoHeight = layoutSetLogoImage.getHeight();
1092                    companyLogoWidth = layoutSetLogoImage.getWidth();
1093                }
1094            }
1095
1096            plid = layout.getPlid();
1097
1098            // Updates to shared layouts are not reflected until the next time
1099            // the user logs in because group layouts are cached in the session
1100
1101            layout = (Layout)((LayoutImpl)layout).clone();
1102
1103            layoutTypePortlet = (LayoutTypePortlet)layout.getLayoutType();
1104
1105            LayoutClone layoutClone = LayoutCloneFactory.getInstance();
1106
1107            if (layoutClone != null) {
1108                String typeSettings = layoutClone.get(request, plid);
1109
1110                if (typeSettings != null) {
1111                    UnicodeProperties props = new UnicodeProperties(true);
1112
1113                    props.load(typeSettings);
1114
1115                    String stateMax = props.getProperty(
1116                        LayoutTypePortletImpl.STATE_MAX);
1117                    String stateMin = props.getProperty(
1118                        LayoutTypePortletImpl.STATE_MIN);
1119                    String modeAbout = props.getProperty(
1120                        LayoutTypePortletImpl.MODE_ABOUT);
1121                    String modeConfig = props.getProperty(
1122                        LayoutTypePortletImpl.MODE_CONFIG);
1123                    String modeEdit = props.getProperty(
1124                        LayoutTypePortletImpl.MODE_EDIT);
1125                    String modeEditDefaults = props.getProperty(
1126                        LayoutTypePortletImpl.MODE_EDIT_DEFAULTS);
1127                    String modeEditGuest = props.getProperty(
1128                        LayoutTypePortletImpl.MODE_EDIT_GUEST);
1129                    String modeHelp = props.getProperty(
1130                        LayoutTypePortletImpl.MODE_HELP);
1131                    String modePreview = props.getProperty(
1132                        LayoutTypePortletImpl.MODE_PREVIEW);
1133                    String modePrint = props.getProperty(
1134                        LayoutTypePortletImpl.MODE_PRINT);
1135
1136                    layoutTypePortlet.setStateMax(stateMax);
1137                    layoutTypePortlet.setStateMin(stateMin);
1138                    layoutTypePortlet.setModeAbout(modeAbout);
1139                    layoutTypePortlet.setModeConfig(modeConfig);
1140                    layoutTypePortlet.setModeEdit(modeEdit);
1141                    layoutTypePortlet.setModeEditDefaults(modeEditDefaults);
1142                    layoutTypePortlet.setModeEditGuest(modeEditGuest);
1143                    layoutTypePortlet.setModeHelp(modeHelp);
1144                    layoutTypePortlet.setModePreview(modePreview);
1145                    layoutTypePortlet.setModePrint(modePrint);
1146                }
1147            }
1148
1149            request.setAttribute(WebKeys.LAYOUT, layout);
1150            request.setAttribute(WebKeys.LAYOUTS, layouts);
1151
1152            if (layout.isPrivateLayout()) {
1153                permissionChecker.setCheckGuest(false);
1154            }
1155        }
1156
1157        // Theme and color scheme
1158
1159        Theme theme = null;
1160        ColorScheme colorScheme = null;
1161
1162        boolean wapTheme = BrowserSnifferUtil.isWap(request);
1163
1164        if (layout != null) {
1165            if (wapTheme) {
1166                theme = layout.getWapTheme();
1167                colorScheme = layout.getWapColorScheme();
1168            }
1169            else {
1170                theme = layout.getTheme();
1171                colorScheme = layout.getColorScheme();
1172            }
1173        }
1174        else {
1175            String themeId = null;
1176            String colorSchemeId = null;
1177
1178            if (wapTheme) {
1179                themeId = ThemeImpl.getDefaultWapThemeId();
1180                colorSchemeId = ColorSchemeImpl.getDefaultWapColorSchemeId();
1181            }
1182            else {
1183                themeId = ThemeImpl.getDefaultRegularThemeId();
1184                colorSchemeId =
1185                    ColorSchemeImpl.getDefaultRegularColorSchemeId();
1186            }
1187
1188            theme = ThemeLocalServiceUtil.getTheme(
1189                companyId, themeId, wapTheme);
1190            colorScheme = ThemeLocalServiceUtil.getColorScheme(
1191                companyId, theme.getThemeId(), colorSchemeId, wapTheme);
1192        }
1193
1194        request.setAttribute(WebKeys.THEME, theme);
1195        request.setAttribute(WebKeys.COLOR_SCHEME, colorScheme);
1196
1197        boolean themeCssFastLoad = ParamUtil.getBoolean(
1198            request, "css_fast_load", PropsValues.THEME_CSS_FAST_LOAD);
1199
1200        boolean themeJsBarebone = PropsValues.JAVASCRIPT_BAREBONE_ENABLED;
1201
1202        if (themeJsBarebone) {
1203            if (signedIn) {
1204                themeJsBarebone = false;
1205            }
1206        }
1207
1208        boolean themeJsFastLoad = ParamUtil.getBoolean(
1209            request, "js_fast_load", PropsValues.JAVASCRIPT_FAST_LOAD);
1210
1211        String lifecycle = ParamUtil.getString(request, "p_p_lifecycle");
1212
1213        String facebookCanvasPageURL = (String)request.getAttribute(
1214            WebKeys.FACEBOOK_CANVAS_PAGE_URL);
1215
1216        boolean widget = false;
1217
1218        Boolean widgetObj = (Boolean)request.getAttribute(WebKeys.WIDGET);
1219
1220        if (widgetObj != null) {
1221            widget = widgetObj.booleanValue();
1222        }
1223
1224        // Theme display
1225
1226        ThemeDisplay themeDisplay = ThemeDisplayFactory.create();
1227
1228        // Set the CDN host, portal URL, and Facebook application ID first
1229        // because other methods (setLookAndFeel) depend on them being set
1230
1231        themeDisplay.setCDNHost(cdnHost);
1232        themeDisplay.setPortalURL(portalURL);
1233        themeDisplay.setFacebookCanvasPageURL(facebookCanvasPageURL);
1234        themeDisplay.setWidget(widget);
1235
1236        themeDisplay.setCompany(company);
1237        themeDisplay.setCompanyLogo(companyLogo);
1238        themeDisplay.setCompanyLogoHeight(companyLogoHeight);
1239        themeDisplay.setCompanyLogoWidth(companyLogoWidth);
1240        themeDisplay.setRealCompanyLogo(realCompanyLogo);
1241        themeDisplay.setRealCompanyLogoHeight(realCompanyLogoHeight);
1242        themeDisplay.setRealCompanyLogoWidth(realCompanyLogoWidth);
1243        themeDisplay.setUser(user);
1244        themeDisplay.setRealUser(realUser);
1245        themeDisplay.setDoAsUserId(doAsUserId);
1246        themeDisplay.setLayoutSetLogo(layoutSetLogo);
1247        themeDisplay.setLayout(layout);
1248        themeDisplay.setLayouts(layouts);
1249        themeDisplay.setPlid(plid);
1250        themeDisplay.setLayoutTypePortlet(layoutTypePortlet);
1251        themeDisplay.setScopeGroupId(scopeGroupId);
1252        themeDisplay.setSignedIn(signedIn);
1253        themeDisplay.setPermissionChecker(permissionChecker);
1254        themeDisplay.setLocale(locale);
1255        themeDisplay.setLanguageId(LocaleUtil.toLanguageId(locale));
1256        themeDisplay.setI18nLanguageId(i18nLanguageId);
1257        themeDisplay.setTimeZone(timeZone);
1258        themeDisplay.setLookAndFeel(contextPath, theme, colorScheme);
1259        themeDisplay.setThemeCssFastLoad(themeCssFastLoad);
1260        themeDisplay.setThemeJsBarebone(themeJsBarebone);
1261        themeDisplay.setThemeJsFastLoad(themeJsFastLoad);
1262        themeDisplay.setServerName(request.getServerName());
1263        themeDisplay.setServerPort(request.getServerPort());
1264        themeDisplay.setSecure(request.isSecure());
1265        themeDisplay.setLifecycle(lifecycle);
1266        themeDisplay.setLifecycleAction(lifecycle.equals("1"));
1267        themeDisplay.setLifecycleRender(lifecycle.equals("0"));
1268        themeDisplay.setLifecycleResource(lifecycle.equals("2"));
1269        themeDisplay.setStateExclusive(LiferayWindowState.isExclusive(request));
1270        themeDisplay.setStateMaximized(LiferayWindowState.isMaximized(request));
1271        themeDisplay.setStatePopUp(LiferayWindowState.isPopUp(request));
1272        themeDisplay.setPathApplet(contextPath + "/applets");
1273        themeDisplay.setPathCms(contextPath + "/cms");
1274        themeDisplay.setPathContext(contextPath);
1275        themeDisplay.setPathFlash(contextPath + "/flash");
1276        themeDisplay.setPathFriendlyURLPrivateGroup(
1277            friendlyURLPrivateGroupPath);
1278        themeDisplay.setPathFriendlyURLPrivateUser(friendlyURLPrivateUserPath);
1279        themeDisplay.setPathFriendlyURLPublic(friendlyURLPublicPath);
1280        themeDisplay.setPathImage(imagePath);
1281        themeDisplay.setPathJavaScript(cdnHost + contextPath + "/html/js");
1282        themeDisplay.setPathMain(mainPath);
1283        themeDisplay.setPathSound(contextPath + "/html/sound");
1284
1285        // URLs
1286
1287        themeDisplay.setShowAddContentIcon(false);
1288        themeDisplay.setShowHomeIcon(true);
1289        themeDisplay.setShowMyAccountIcon(signedIn);
1290        themeDisplay.setShowPageSettingsIcon(false);
1291        themeDisplay.setShowPortalIcon(true);
1292        themeDisplay.setShowSignInIcon(!signedIn);
1293        themeDisplay.setShowSignOutIcon(signedIn);
1294        themeDisplay.setShowStagingIcon(false);
1295
1296        PortletURL createAccountURL = new PortletURLImpl(
1297            request, PortletKeys.LOGIN, plid, PortletRequest.ACTION_PHASE);
1298
1299        createAccountURL.setWindowState(WindowState.MAXIMIZED);
1300        createAccountURL.setPortletMode(PortletMode.VIEW);
1301
1302        createAccountURL.setParameter("saveLastPath", "0");
1303        createAccountURL.setParameter(
1304            "struts_action", "/login/create_account");
1305
1306        themeDisplay.setURLCreateAccount(createAccountURL);
1307
1308        String currentURL = PortalUtil.getCurrentURL(request);
1309
1310        themeDisplay.setURLCurrent(currentURL);
1311
1312        String urlHome = portalURL + contextPath;
1313
1314        themeDisplay.setURLHome(urlHome);
1315
1316        if (layout != null) {
1317            Group group = layout.getGroup();
1318
1319            if (layout.getType().equals(LayoutConstants.TYPE_PORTLET)) {
1320                boolean freeformLayout =
1321                    layoutTypePortlet.getLayoutTemplateId().equals(
1322                        "freeform");
1323
1324                themeDisplay.setFreeformLayout(freeformLayout);
1325
1326                boolean hasUpdateLayoutPermission =
1327                    LayoutPermissionUtil.contains(
1328                        permissionChecker, layout, ActionKeys.UPDATE);
1329
1330                if (hasUpdateLayoutPermission) {
1331                    if (!LiferayWindowState.isMaximized(request)) {
1332                        themeDisplay.setShowAddContentIcon(true);
1333                    }
1334
1335                    themeDisplay.setShowLayoutTemplatesIcon(true);
1336
1337                    themeDisplay.setURLAddContent(
1338                        "LayoutConfiguration.toggle('" +
1339                            PortletKeys.LAYOUT_CONFIGURATION + "');");
1340
1341                    themeDisplay.setURLLayoutTemplates(
1342                        "Liferay.Layout.showTemplates();");
1343                }
1344            }
1345
1346            boolean hasManageLayoutsPermission =
1347                GroupPermissionUtil.contains(
1348                    permissionChecker, scopeGroupId, ActionKeys.MANAGE_LAYOUTS);
1349
1350            if (group.isUser()) {
1351                if ((layout.isPrivateLayout() &&
1352                     !PropsValues.LAYOUT_USER_PRIVATE_LAYOUTS_MODIFIABLE) ||
1353                    (layout.isPublicLayout() &&
1354                     !PropsValues.LAYOUT_USER_PUBLIC_LAYOUTS_MODIFIABLE)) {
1355
1356                    hasManageLayoutsPermission = false;
1357                }
1358            }
1359
1360            if (hasManageLayoutsPermission) {
1361                themeDisplay.setShowPageSettingsIcon(true);
1362
1363                PortletURL pageSettingsURL = new PortletURLImpl(
1364                    request, PortletKeys.LAYOUT_MANAGEMENT, plid,
1365                    PortletRequest.RENDER_PHASE);
1366
1367                pageSettingsURL.setWindowState(WindowState.MAXIMIZED);
1368                pageSettingsURL.setPortletMode(PortletMode.VIEW);
1369
1370                pageSettingsURL.setParameter(
1371                    "struts_action", "/layout_management/edit_pages");
1372
1373                if (layout.isPrivateLayout()) {
1374                    pageSettingsURL.setParameter("tabs1", "private-pages");
1375                }
1376                else {
1377                    pageSettingsURL.setParameter("tabs1", "public-pages");
1378                }
1379
1380                pageSettingsURL.setParameter("redirect", currentURL);
1381                pageSettingsURL.setParameter(
1382                    "groupId", String.valueOf(scopeGroupId));
1383                pageSettingsURL.setParameter("selPlid", String.valueOf(plid));
1384
1385                themeDisplay.setURLPageSettings(pageSettingsURL);
1386
1387                PortletURL publishToLiveURL = new PortletURLImpl(
1388                    request, PortletKeys.LAYOUT_MANAGEMENT, plid,
1389                    PortletRequest.RENDER_PHASE);
1390
1391                publishToLiveURL.setWindowState(LiferayWindowState.EXCLUSIVE);
1392                publishToLiveURL.setPortletMode(PortletMode.VIEW);
1393
1394                publishToLiveURL.setParameter(
1395                    "struts_action", "/layout_management/export_pages");
1396
1397                if (layout.isPrivateLayout()) {
1398                    publishToLiveURL.setParameter("tabs1", "private-pages");
1399                }
1400                else {
1401                    publishToLiveURL.setParameter("tabs1", "public-pages");
1402                }
1403
1404                publishToLiveURL.setParameter("pagesRedirect", currentURL);
1405                publishToLiveURL.setParameter(
1406                    "groupId", String.valueOf(scopeGroupId));
1407                publishToLiveURL.setParameter("selPlid", String.valueOf(plid));
1408
1409                themeDisplay.setURLPublishToLive(publishToLiveURL);
1410            }
1411
1412            if (group.hasStagingGroup() && !group.isStagingGroup()) {
1413                themeDisplay.setShowAddContentIcon(false);
1414                themeDisplay.setShowLayoutTemplatesIcon(false);
1415                themeDisplay.setShowPageSettingsIcon(false);
1416                themeDisplay.setURLPublishToLive(null);
1417            }
1418
1419            // LEP-4987
1420
1421            if (group.hasStagingGroup() || group.isStagingGroup()) {
1422                boolean hasApproveProposalPermission =
1423                    GroupPermissionUtil.contains(
1424                        permissionChecker, scopeGroupId,
1425                        ActionKeys.APPROVE_PROPOSAL);
1426
1427                if (hasManageLayoutsPermission) {
1428                    themeDisplay.setShowStagingIcon(true);
1429                }
1430                else if (hasApproveProposalPermission) {
1431                    themeDisplay.setShowStagingIcon(true);
1432                }
1433            }
1434
1435            String myAccountNamespace = PortalUtil.getPortletNamespace(
1436                PortletKeys.MY_ACCOUNT);
1437
1438            String myAccountRedirect = ParamUtil.getString(
1439                request, myAccountNamespace + "backURL", currentURL);
1440
1441            PortletURL myAccountURL = new PortletURLImpl(
1442                request, PortletKeys.MY_ACCOUNT, plid,
1443                PortletRequest.RENDER_PHASE);
1444
1445            myAccountURL.setWindowState(WindowState.MAXIMIZED);
1446            myAccountURL.setPortletMode(PortletMode.VIEW);
1447
1448            myAccountURL.setParameter("struts_action", "/my_account/edit_user");
1449            myAccountURL.setParameter("backURL", myAccountRedirect);
1450
1451            themeDisplay.setURLMyAccount(myAccountURL);
1452        }
1453
1454        if ((!user.isActive()) ||
1455            (PropsValues.TERMS_OF_USE_REQUIRED &&
1456             !user.isAgreedToTermsOfUse())) {
1457
1458            themeDisplay.setShowAddContentIcon(false);
1459            themeDisplay.setShowMyAccountIcon(false);
1460            themeDisplay.setShowPageSettingsIcon(false);
1461        }
1462
1463        themeDisplay.setURLPortal(themeDisplay.getURLHome());
1464
1465        String urlSignIn = mainPath + "/portal/login";
1466
1467        if (layout != null) {
1468            urlSignIn = HttpUtil.addParameter(
1469                urlSignIn, "p_l_id", layout.getPlid());
1470        }
1471
1472        themeDisplay.setURLSignIn(urlSignIn);
1473
1474        themeDisplay.setURLSignOut(mainPath + "/portal/logout");
1475
1476        PortletURL updateManagerURL = new PortletURLImpl(
1477            request, PortletKeys.UPDATE_MANAGER, plid,
1478            PortletRequest.RENDER_PHASE);
1479
1480        updateManagerURL.setWindowState(WindowState.MAXIMIZED);
1481        updateManagerURL.setPortletMode(PortletMode.VIEW);
1482
1483        updateManagerURL.setParameter("struts_action", "/update_manager/view");
1484
1485        themeDisplay.setURLUpdateManager(updateManagerURL);
1486
1487        request.setAttribute(WebKeys.THEME_DISPLAY, themeDisplay);
1488
1489        // Parallel render
1490
1491        boolean parallelRenderEnable = true;
1492
1493        if (layout != null) {
1494            if (layoutTypePortlet.getPortletIds().size() == 1) {
1495                parallelRenderEnable = false;
1496            }
1497        }
1498
1499        Boolean parallelRenderEnableObj = Boolean.valueOf(ParamUtil.getBoolean(
1500            request, "p_p_parallel", parallelRenderEnable));
1501
1502        request.setAttribute(
1503            WebKeys.PORTLET_PARALLEL_RENDER, parallelRenderEnableObj);
1504    }
1505
1506    protected void updateUserLayouts(User user) throws Exception {
1507
1508        // Private layouts
1509
1510        boolean addDefaultUserPrivateLayouts = false;
1511
1512        if (PropsValues.LAYOUT_USER_PRIVATE_LAYOUTS_ENABLED &&
1513            PropsValues.LAYOUT_USER_PRIVATE_LAYOUTS_AUTO_CREATE) {
1514
1515            addDefaultUserPrivateLayouts = true;
1516
1517            if (PropsValues.LAYOUT_USER_PRIVATE_LAYOUTS_POWER_USER_REQUIRED) {
1518                Role powerUserRole = RoleLocalServiceUtil.getRole(
1519                    user.getCompanyId(), RoleConstants.POWER_USER);
1520
1521                if (!UserLocalServiceUtil.hasRoleUser(
1522                        powerUserRole.getRoleId(), user.getUserId())) {
1523
1524                    addDefaultUserPrivateLayouts = false;
1525                }
1526            }
1527        }
1528
1529        if (addDefaultUserPrivateLayouts && !user.hasPrivateLayouts()) {
1530            addDefaultUserPrivateLayouts(user);
1531        }
1532
1533        boolean deleteDefaultUserPrivateLayouts = false;
1534
1535        if (!PropsValues.LAYOUT_USER_PRIVATE_LAYOUTS_ENABLED) {
1536            deleteDefaultUserPrivateLayouts = true;
1537        }
1538        else if (PropsValues.LAYOUT_USER_PRIVATE_LAYOUTS_POWER_USER_REQUIRED) {
1539            Role powerUserRole = RoleLocalServiceUtil.getRole(
1540                user.getCompanyId(), RoleConstants.POWER_USER);
1541
1542            if (!UserLocalServiceUtil.hasRoleUser(
1543                    powerUserRole.getRoleId(), user.getUserId())) {
1544
1545                deleteDefaultUserPrivateLayouts = true;
1546            }
1547        }
1548
1549        if (deleteDefaultUserPrivateLayouts && user.hasPrivateLayouts()) {
1550            deleteDefaultUserPrivateLayouts(user);
1551        }
1552
1553        // Public pages
1554
1555        boolean addDefaultUserPublicLayouts = false;
1556
1557        if (PropsValues.LAYOUT_USER_PUBLIC_LAYOUTS_ENABLED &&
1558            PropsValues.LAYOUT_USER_PUBLIC_LAYOUTS_AUTO_CREATE) {
1559
1560            addDefaultUserPublicLayouts = true;
1561
1562            if (PropsValues.LAYOUT_USER_PUBLIC_LAYOUTS_POWER_USER_REQUIRED) {
1563                Role powerUserRole = RoleLocalServiceUtil.getRole(
1564                    user.getCompanyId(), RoleConstants.POWER_USER);
1565
1566                if (!UserLocalServiceUtil.hasRoleUser(
1567                        powerUserRole.getRoleId(), user.getUserId())) {
1568
1569                    addDefaultUserPublicLayouts = false;
1570                }
1571            }
1572        }
1573
1574        if (addDefaultUserPublicLayouts && !user.hasPublicLayouts()) {
1575            addDefaultUserPublicLayouts(user);
1576        }
1577
1578        boolean deleteDefaultUserPublicLayouts = false;
1579
1580        if (!PropsValues.LAYOUT_USER_PUBLIC_LAYOUTS_ENABLED) {
1581            deleteDefaultUserPublicLayouts = true;
1582        }
1583        else if (PropsValues.LAYOUT_USER_PUBLIC_LAYOUTS_POWER_USER_REQUIRED) {
1584            Role powerUserRole = RoleLocalServiceUtil.getRole(
1585                user.getCompanyId(), RoleConstants.POWER_USER);
1586
1587            if (!UserLocalServiceUtil.hasRoleUser(
1588                    powerUserRole.getRoleId(), user.getUserId())) {
1589
1590                deleteDefaultUserPublicLayouts = true;
1591            }
1592        }
1593
1594        if (deleteDefaultUserPublicLayouts && user.hasPublicLayouts()) {
1595            deleteDefaultUserPublicLayouts(user);
1596        }
1597    }
1598
1599    protected File privateLARFile;
1600    protected File publicLARFile;
1601
1602    private static final String _PATH_PORTAL_LAYOUT = "/portal/layout";
1603
1604    private static Log _log = LogFactory.getLog(ServicePreAction.class);
1605
1606}