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