1   /**
2    * Copyright (c) 2000-2009 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   * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
12   * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
13   * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
14   * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
15   * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
16   * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
17   * SOFTWARE.
18   */
19  
20  package com.liferay.portal.events;
21  
22  import com.liferay.portal.LayoutPermissionException;
23  import com.liferay.portal.NoSuchGroupException;
24  import com.liferay.portal.NoSuchLayoutException;
25  import com.liferay.portal.NoSuchUserException;
26  import com.liferay.portal.PortalException;
27  import com.liferay.portal.SystemException;
28  import com.liferay.portal.kernel.dao.orm.QueryUtil;
29  import com.liferay.portal.kernel.events.Action;
30  import com.liferay.portal.kernel.events.ActionException;
31  import com.liferay.portal.kernel.language.LanguageUtil;
32  import com.liferay.portal.kernel.log.Log;
33  import com.liferay.portal.kernel.log.LogFactoryUtil;
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.FriendlyURLNormalizer;
84  import com.liferay.portal.util.LayoutClone;
85  import com.liferay.portal.util.LayoutCloneFactory;
86  import com.liferay.portal.util.PortalUtil;
87  import com.liferay.portal.util.PortletKeys;
88  import com.liferay.portal.util.PropsKeys;
89  import com.liferay.portal.util.PropsUtil;
90  import com.liferay.portal.util.PropsValues;
91  import com.liferay.portal.util.WebKeys;
92  import com.liferay.portlet.PortletURLImpl;
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.struts.Globals;
115 
116 /**
117  * <a href="ServicePreAction.java.html"><b><i>View Source</i></b></a>
118  *
119  * @author Brian Wing Shun Chan
120  * @author Felix Ventero
121  *
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 (int i = 0; i < groups.size(); i++) {
440                     Group group = groups.get(i);
441 
442                     layouts = LayoutLocalServiceUtil.getLayouts(
443                         group.getGroupId(), true,
444                         LayoutConstants.DEFAULT_PARENT_LAYOUT_ID);
445 
446                     if (layouts.size() == 0) {
447                         layouts = LayoutLocalServiceUtil.getLayouts(
448                             group.getGroupId(), false,
449                             LayoutConstants.DEFAULT_PARENT_LAYOUT_ID);
450                     }
451 
452                     if (layouts.size() > 0) {
453                         layout = layouts.get(0);
454 
455                         break;
456                     }
457                 }
458             }
459         }
460         else {
461 
462             // Check the guest community
463 
464             Group guestGroup = GroupLocalServiceUtil.getGroup(
465                 user.getCompanyId(), GroupConstants.GUEST);
466 
467             layouts = LayoutLocalServiceUtil.getLayouts(
468                 guestGroup.getGroupId(), false,
469                 LayoutConstants.DEFAULT_PARENT_LAYOUT_ID);
470 
471             if (layouts.size() > 0) {
472                 layout = layouts.get(0);
473             }
474         }
475 
476         return new Object[] {layout, layouts};
477     }
478 
479     protected String getFriendlyURL(String friendlyURL) {
480         friendlyURL = GetterUtil.getString(friendlyURL);
481 
482         return FriendlyURLNormalizer.normalize(friendlyURL);
483     }
484 
485     protected Object[] getViewableLayouts(
486             HttpServletRequest request, User user,
487             PermissionChecker permissionChecker, Layout layout,
488             List<Layout> layouts)
489         throws PortalException, SystemException {
490 
491         if ((layouts == null) || (layouts.size() == 0)) {
492             return new Object[] {layout, layouts};
493         }
494 
495         boolean replaceLayout = true;
496 
497         if (LayoutPermissionUtil.contains(
498                 permissionChecker, layout, ActionKeys.VIEW)) {
499 
500             replaceLayout = false;
501         }
502 
503         List<Layout> accessibleLayouts = new ArrayList<Layout>();
504 
505         for (int i = 0; i < layouts.size(); i++) {
506             Layout curLayout = layouts.get(i);
507 
508             if (!curLayout.isHidden() &&
509                 LayoutPermissionUtil.contains(
510                     permissionChecker, curLayout, ActionKeys.VIEW)) {
511 
512                 if ((accessibleLayouts.size() == 0) && replaceLayout) {
513                     layout = curLayout;
514                 }
515 
516                 accessibleLayouts.add(curLayout);
517             }
518         }
519 
520         if (accessibleLayouts.size() == 0) {
521             layouts = null;
522 
523             SessionErrors.add(
524                 request, LayoutPermissionException.class.getName());
525         }
526         else {
527             layouts = accessibleLayouts;
528         }
529 
530         return new Object[] {layout, layouts};
531     }
532 
533     protected void initImportLARFiles() {
534         String privateLARFileName =
535             PropsValues.DEFAULT_USER_PRIVATE_LAYOUTS_LAR;
536 
537         if (_log.isDebugEnabled()) {
538             _log.debug("Reading private LAR file " + privateLARFileName);
539         }
540 
541         if (Validator.isNotNull(privateLARFileName)) {
542             privateLARFile = new File(privateLARFileName);
543 
544             if (!privateLARFile.exists()) {
545                 _log.error(
546                     "Private LAR file " + privateLARFile + " does not exist");
547 
548                 privateLARFile = null;
549             }
550             else {
551                 if (_log.isDebugEnabled()) {
552                     _log.debug("Using private LAR file " + privateLARFileName);
553                 }
554             }
555         }
556 
557         String publicLARFileName = PropsValues.DEFAULT_USER_PUBLIC_LAYOUTS_LAR;
558 
559         if (_log.isDebugEnabled()) {
560             _log.debug("Reading public LAR file " + publicLARFileName);
561         }
562 
563         if (Validator.isNotNull(publicLARFileName)) {
564             publicLARFile = new File(publicLARFileName);
565 
566             if (!publicLARFile.exists()) {
567                 _log.error(
568                     "Public LAR file " + publicLARFile + " does not exist");
569 
570                 publicLARFile = null;
571             }
572             else {
573                 if (_log.isDebugEnabled()) {
574                     _log.debug("Using public LAR file " + publicLARFileName);
575                 }
576             }
577         }
578     }
579 
580     /**
581      * @deprecated Use <code>isViewableGroup</code>.
582      */
583     protected boolean isViewableCommunity(
584             User user, long groupId, boolean privateLayout,
585             PermissionChecker permissionChecker)
586         throws PortalException, SystemException {
587 
588         return isViewableGroup(
589             user, groupId, privateLayout, 0, permissionChecker);
590     }
591 
592     protected boolean isViewableGroup(
593             User user, long groupId, boolean privateLayout, long layoutId,
594             PermissionChecker permissionChecker)
595         throws PortalException, SystemException {
596 
597         Group group = GroupLocalServiceUtil.getGroup(groupId);
598 
599         // Inactive communities are not viewable
600 
601         if (!group.isActive()) {
602             return false;
603         }
604         else if (group.isStagingGroup()) {
605             Group liveGroup = group.getLiveGroup();
606 
607             if (!liveGroup.isActive()) {
608                 return false;
609             }
610         }
611 
612         // User private layouts are only viewable by the user and anyone who can
613         // update the user. The user must also be active.
614 
615         if (group.isUser()) {
616             long groupUserId = group.getClassPK();
617 
618             if (groupUserId == user.getUserId()) {
619                 return true;
620             }
621             else {
622                 User groupUser = UserLocalServiceUtil.getUserById(groupUserId);
623 
624                 if (!groupUser.isActive()) {
625                     return false;
626                 }
627 
628                 if (privateLayout) {
629                     if (UserPermissionUtil.contains(
630                             permissionChecker, groupUserId,
631                             groupUser.getOrganizationIds(),
632                             ActionKeys.UPDATE)) {
633 
634                         return true;
635                     }
636                     else {
637                         return false;
638                     }
639                 }
640             }
641         }
642 
643         // If the current group is staging, only users with editorial rights
644         // can access it
645 
646         if (group.isStagingGroup()) {
647             if (user.isDefaultUser()) {
648                 return false;
649             }
650 
651             if (GroupPermissionUtil.contains(
652                     permissionChecker, groupId, ActionKeys.APPROVE_PROPOSAL) ||
653                 GroupPermissionUtil.contains(
654                     permissionChecker, groupId, ActionKeys.ASSIGN_REVIEWER) ||
655                 GroupPermissionUtil.contains(
656                     permissionChecker, groupId, ActionKeys.MANAGE_LAYOUTS) ||
657                 GroupPermissionUtil.contains(
658                     permissionChecker, groupId, ActionKeys.MANAGE_STAGING) ||
659                 GroupPermissionUtil.contains(
660                     permissionChecker, groupId, ActionKeys.PUBLISH_STAGING) ||
661                 ((layoutId > 0) && LayoutPermissionUtil.contains(
662                     permissionChecker, groupId, privateLayout, layoutId,
663                     ActionKeys.UPDATE))) {
664 
665                 return true;
666             }
667 
668             return false;
669         }
670 
671         // Most public layouts are viewable
672 
673         if (!privateLayout) {
674             return true;
675         }
676 
677         // Community or organization layouts are only viewable by users who
678         // belong to the community or organization, or by users who can update
679         // the community or organization
680 
681         if (group.isCommunity()) {
682             if (GroupLocalServiceUtil.hasUserGroup(user.getUserId(), groupId)) {
683                 return true;
684             }
685             else if (GroupPermissionUtil.contains(
686                         permissionChecker, groupId, ActionKeys.UPDATE)) {
687 
688                 return true;
689             }
690         }
691         else if (group.isOrganization()) {
692             long organizationId = group.getClassPK();
693 
694             if (OrganizationLocalServiceUtil.hasUserOrganization(
695                     user.getUserId(), organizationId)) {
696 
697                 return true;
698             }
699             else if (OrganizationPermissionUtil.contains(
700                         permissionChecker, organizationId, ActionKeys.UPDATE)) {
701 
702                 return true;
703             }
704         }
705         else if (group.isUserGroup()) {
706             if (GroupPermissionUtil.contains(
707                     permissionChecker, groupId, ActionKeys.MANAGE_LAYOUTS)) {
708 
709                 return true;
710             }
711         }
712 
713         return false;
714     }
715 
716     protected List<Layout> mergeAdditionalLayouts(
717             HttpServletRequest request, User user,
718             PermissionChecker permissionChecker, Layout layout,
719             List<Layout> layouts)
720         throws PortalException, SystemException {
721 
722         if ((layout == null) || layout.isPrivateLayout()) {
723             return layouts;
724         }
725 
726         long layoutGroupId = layout.getGroupId();
727 
728         Group guestGroup = GroupLocalServiceUtil.getGroup(
729             user.getCompanyId(), GroupConstants.GUEST);
730 
731         if (layoutGroupId != guestGroup.getGroupId()) {
732             Group layoutGroup = GroupLocalServiceUtil.getGroup(layoutGroupId);
733 
734             UnicodeProperties props = layoutGroup.getTypeSettingsProperties();
735 
736             boolean mergeGuestPublicPages = GetterUtil.getBoolean(
737                 props.getProperty("mergeGuestPublicPages"));
738 
739             if (!mergeGuestPublicPages) {
740                 return layouts;
741             }
742 
743             List<Layout> guestLayouts = LayoutLocalServiceUtil.getLayouts(
744                 guestGroup.getGroupId(), false,
745                 LayoutConstants.DEFAULT_PARENT_LAYOUT_ID);
746 
747             Object[] viewableLayouts = getViewableLayouts(
748                 request, user, permissionChecker, layout, guestLayouts);
749 
750             guestLayouts = (List<Layout>)viewableLayouts[1];
751 
752             layouts.addAll(0, guestLayouts);
753         }
754         else {
755             HttpSession session = request.getSession();
756 
757             Long previousGroupId = (Long)session.getAttribute(
758                 WebKeys.VISITED_GROUP_ID_PREVIOUS);
759 
760             if ((previousGroupId != null) &&
761                 (previousGroupId.longValue() != layoutGroupId)) {
762 
763                 Group previousGroup = null;
764 
765                 try {
766                     previousGroup = GroupLocalServiceUtil.getGroup(
767                         previousGroupId.longValue());
768                 }
769                 catch (NoSuchGroupException nsge) {
770                     if (_log.isWarnEnabled()) {
771                         _log.warn(nsge);
772                     }
773 
774                     return layouts;
775                 }
776 
777                 UnicodeProperties props =
778                     previousGroup.getTypeSettingsProperties();
779 
780                 boolean mergeGuestPublicPages = GetterUtil.getBoolean(
781                     props.getProperty("mergeGuestPublicPages"));
782 
783                 if (!mergeGuestPublicPages) {
784                     return layouts;
785                 }
786 
787                 List<Layout> previousLayouts =
788                     LayoutLocalServiceUtil.getLayouts(
789                         previousGroupId.longValue(), false,
790                         LayoutConstants.DEFAULT_PARENT_LAYOUT_ID);
791 
792                 Object[] viewableLayouts = getViewableLayouts(
793                     request, user, permissionChecker, layout, previousLayouts);
794 
795                 previousLayouts = (List<Layout>)viewableLayouts[1];
796 
797                 layouts.addAll(previousLayouts);
798             }
799         }
800 
801         return layouts;
802     }
803 
804     protected void rememberVisitedGroupIds(
805         HttpServletRequest request, long currentGroupId) {
806 
807         String requestURI = GetterUtil.getString(request.getRequestURI());
808 
809         if (!requestURI.endsWith(_PATH_PORTAL_LAYOUT)) {
810             return;
811         }
812 
813         HttpSession session = request.getSession();
814 
815         Long recentGroupId = (Long)session.getAttribute(
816             WebKeys.VISITED_GROUP_ID_RECENT);
817 
818         Long previousGroupId = (Long)session.getAttribute(
819             WebKeys.VISITED_GROUP_ID_PREVIOUS);
820 
821         if (recentGroupId == null) {
822             recentGroupId = new Long(currentGroupId);
823 
824             session.setAttribute(
825                 WebKeys.VISITED_GROUP_ID_RECENT, recentGroupId);
826         }
827         else if (recentGroupId.longValue() != currentGroupId) {
828             previousGroupId = new Long(recentGroupId.longValue());
829 
830             recentGroupId = new Long(currentGroupId);
831 
832             session.setAttribute(
833                 WebKeys.VISITED_GROUP_ID_RECENT, recentGroupId);
834 
835             session.setAttribute(
836                 WebKeys.VISITED_GROUP_ID_PREVIOUS, previousGroupId);
837         }
838 
839         if (_log.isDebugEnabled()) {
840             _log.debug("Current group id " + currentGroupId);
841             _log.debug("Recent group id " + recentGroupId);
842             _log.debug("Previous group id " + previousGroupId);
843         }
844     }
845 
846     protected void servicePre(
847             HttpServletRequest request, HttpServletResponse response)
848         throws Exception {
849 
850         HttpSession session = request.getSession();
851 
852         // Company
853 
854         Company company = PortalUtil.getCompany(request);
855 
856         long companyId = company.getCompanyId();
857 
858         // CDN host
859 
860         String cdnHost = ParamUtil.getString(
861             request, "cdn_host", PortalUtil.getCDNHost());
862 
863         // Portal URL
864 
865         String portalURL = PortalUtil.getPortalURL(request);
866 
867         // Paths
868 
869         String contextPath = PortalUtil.getPathContext();
870         String friendlyURLPrivateGroupPath =
871             PortalUtil.getPathFriendlyURLPrivateGroup();
872         String friendlyURLPrivateUserPath =
873             PortalUtil.getPathFriendlyURLPrivateUser();
874         String friendlyURLPublicPath = PortalUtil.getPathFriendlyURLPublic();
875         String imagePath = PortalUtil.getPathImage();
876         String mainPath = PortalUtil.getPathMain();
877 
878         String i18nLanguageId = (String)request.getAttribute(
879             WebKeys.I18N_LANGUAGE_ID);
880 
881         if (Validator.isNotNull(i18nLanguageId)) {
882             if (Validator.isNotNull(contextPath)) {
883                 mainPath = StringUtil.replaceFirst(
884                     mainPath, contextPath,
885                     contextPath + StringPool.SLASH + i18nLanguageId);
886             }
887             else {
888                 mainPath = StringPool.SLASH + i18nLanguageId + mainPath;
889             }
890         }
891 
892         // Company logo
893 
894         String companyLogo =
895             imagePath + "/company_logo?img_id=" + company.getLogoId() + "&t=" +
896                 ImageServletTokenUtil.getToken(company.getLogoId());
897 
898         Image companyLogoImage = ImageLocalServiceUtil.getCompanyLogo(
899             company.getLogoId());
900 
901         int companyLogoHeight = companyLogoImage.getHeight();
902         int companyLogoWidth = companyLogoImage.getWidth();
903 
904         String realCompanyLogo = companyLogo;
905         int realCompanyLogoHeight = companyLogoHeight;
906         int realCompanyLogoWidth = companyLogoWidth;
907 
908         // User
909 
910         User user = null;
911 
912         try {
913             user = PortalUtil.getUser(request);
914         }
915         catch (NoSuchUserException nsue) {
916             if (_log.isWarnEnabled()) {
917                 _log.warn(nsue.getMessage());
918             }
919 
920             long userId = PortalUtil.getUserId(request);
921 
922             if (userId > 0) {
923                 session.invalidate();
924             }
925 
926             return;
927         }
928 
929         boolean signedIn = false;
930 
931         if (user == null) {
932             user = company.getDefaultUser();
933         }
934         else if (!user.isDefaultUser()) {
935             signedIn = true;
936         }
937 
938         User realUser = user;
939 
940         Long realUserId = (Long)session.getAttribute(WebKeys.USER_ID);
941 
942         if (realUserId != null) {
943             if (user.getUserId() != realUserId.longValue()) {
944                 realUser = UserLocalServiceUtil.getUserById(
945                     realUserId.longValue());
946             }
947         }
948 
949         String doAsUserId = ParamUtil.getString(request, "doAsUserId");
950 
951         // Permission checker
952 
953         PermissionChecker permissionChecker = PermissionCheckerFactory.create(
954             user, true);
955 
956         PermissionThreadLocal.setPermissionChecker(permissionChecker);
957 
958         // Locale
959 
960         Locale locale = (Locale)session.getAttribute(Globals.LOCALE_KEY);
961 
962         if (Validator.isNotNull(i18nLanguageId)) {
963             locale = LocaleUtil.fromLanguageId(i18nLanguageId);
964         }
965         else if (locale == null) {
966             if (signedIn) {
967                 locale = user.getLocale();
968             }
969             else {
970 
971                 // User previously set their preferred language
972 
973                 String languageId = CookieKeys.getCookie(
974                     request, CookieKeys.GUEST_LANGUAGE_ID);
975 
976                 if (Validator.isNotNull(languageId)) {
977                     locale = LocaleUtil.fromLanguageId(languageId);
978                 }
979 
980                 // Get locale from the request
981 
982                 if ((locale == null) && PropsValues.LOCALE_DEFAULT_REQUEST) {
983                     locale = request.getLocale();
984                 }
985 
986                 // Get locale from the default user
987 
988                 if (locale == null) {
989                     locale = user.getLocale();
990                 }
991 
992                 if (Validator.isNull(locale.getCountry())) {
993 
994                     // Locales must contain the country code
995 
996                     locale = LanguageUtil.getLocale(locale.getLanguage());
997                 }
998 
999                 if (!LanguageUtil.isAvailableLocale(locale)) {
1000                    locale = user.getLocale();
1001                }
1002            }
1003
1004            session.setAttribute(Globals.LOCALE_KEY, locale);
1005
1006            LanguageUtil.updateCookie(request, response, locale);
1007        }
1008
1009        // Cookie support
1010
1011        try {
1012
1013            // LEP-4069
1014
1015            CookieKeys.validateSupportCookie(request);
1016        }
1017        catch (Exception e) {
1018            CookieKeys.addSupportCookie(request, response);
1019        }
1020
1021        // Time zone
1022
1023        TimeZone timeZone = user.getTimeZone();
1024
1025        if (timeZone == null) {
1026            timeZone = company.getTimeZone();
1027        }
1028
1029        // Layouts
1030
1031        if (signedIn) {
1032            updateUserLayouts(user);
1033        }
1034
1035        Layout layout = null;
1036        List<Layout> layouts = null;
1037
1038        long plid = ParamUtil.getLong(request, "p_l_id");
1039
1040        if (plid > 0) {
1041            layout = LayoutLocalServiceUtil.getLayout(plid);
1042        }
1043        else {
1044            long groupId = ParamUtil.getLong(request, "groupId");
1045            boolean privateLayout = ParamUtil.getBoolean(
1046                request, "privateLayout");
1047            long layoutId = ParamUtil.getLong(request, "layoutId");
1048
1049            if ((groupId > 0) && layoutId > 0) {
1050                layout = LayoutLocalServiceUtil.getLayout(
1051                    groupId, privateLayout, layoutId);
1052            }
1053        }
1054
1055        if (layout != null) {
1056            try {
1057                if (!signedIn && PropsValues.AUTH_FORWARD_BY_REDIRECT) {
1058                    request.setAttribute(WebKeys.REQUESTED_LAYOUT, layout);
1059                }
1060
1061                boolean isViewableCommunity = isViewableGroup(
1062                    user, layout.getGroupId(), layout.isPrivateLayout(),
1063                    layout.getLayoutId(), permissionChecker);
1064
1065                if (!isViewableCommunity) {
1066                    StringBuilder sb = new StringBuilder();
1067
1068                    sb.append("User ");
1069                    sb.append(user.getUserId());
1070                    sb.append(" is not allowed to access the ");
1071                    sb.append(layout.isPrivateLayout() ? "private": "public");
1072                    sb.append(" pages of group ");
1073                    sb.append(layout.getGroupId());
1074
1075                    _log.warn(sb.toString());
1076
1077                    layout = null;
1078                }
1079                else if (isViewableCommunity &&
1080                        !LayoutPermissionUtil.contains(
1081                            permissionChecker, layout, ActionKeys.VIEW)) {
1082
1083                    layout = null;
1084                }
1085                else {
1086                    layouts = LayoutLocalServiceUtil.getLayouts(
1087                        layout.getGroupId(), layout.isPrivateLayout(),
1088                        LayoutConstants.DEFAULT_PARENT_LAYOUT_ID);
1089                }
1090            }
1091            catch (NoSuchLayoutException nsle) {
1092            }
1093        }
1094
1095        if (layout == null) {
1096            Object[] defaultLayout = getDefaultLayout(request, user, signedIn);
1097
1098            layout = (Layout)defaultLayout[0];
1099            layouts = (List<Layout>)defaultLayout[1];
1100
1101            request.setAttribute(WebKeys.LAYOUT_DEFAULT, Boolean.TRUE);
1102        }
1103
1104        Object[] viewableLayouts = getViewableLayouts(
1105            request, user, permissionChecker, layout, layouts);
1106
1107        String layoutSetLogo = null;
1108
1109        layout = (Layout)viewableLayouts[0];
1110        layouts = (List<Layout>)viewableLayouts[1];
1111
1112        LayoutTypePortlet layoutTypePortlet = null;
1113
1114        long scopeGroupId = PortalUtil.getScopeGroupId(layout);
1115
1116        rememberVisitedGroupIds(request, scopeGroupId);
1117
1118        layouts = mergeAdditionalLayouts(
1119            request, user, permissionChecker, layout, layouts);
1120
1121        if (layout != null) {
1122            if (company.isCommunityLogo()) {
1123                LayoutSet layoutSet = layout.getLayoutSet();
1124
1125                if (layoutSet.isLogo()) {
1126                    long logoId = layoutSet.getLogoId();
1127
1128                    layoutSetLogo =
1129                        imagePath + "/layout_set_logo?img_id=" + logoId +
1130                            "&t=" + ImageServletTokenUtil.getToken(logoId);
1131
1132                    Image layoutSetLogoImage =
1133                        ImageLocalServiceUtil.getCompanyLogo(logoId);
1134
1135                    companyLogo = layoutSetLogo;
1136                    companyLogoHeight = layoutSetLogoImage.getHeight();
1137                    companyLogoWidth = layoutSetLogoImage.getWidth();
1138                }
1139            }
1140
1141            plid = layout.getPlid();
1142
1143            // Updates to shared layouts are not reflected until the next time
1144            // the user logs in because group layouts are cached in the session
1145
1146            layout = (Layout)((LayoutImpl)layout).clone();
1147
1148            layoutTypePortlet = (LayoutTypePortlet)layout.getLayoutType();
1149
1150            LayoutClone layoutClone = LayoutCloneFactory.getInstance();
1151
1152            if (layoutClone != null) {
1153                String typeSettings = layoutClone.get(request, plid);
1154
1155                if (typeSettings != null) {
1156                    UnicodeProperties props = new UnicodeProperties(true);
1157
1158                    props.load(typeSettings);
1159
1160                    String stateMax = props.getProperty(
1161                        LayoutTypePortletImpl.STATE_MAX);
1162                    String stateMin = props.getProperty(
1163                        LayoutTypePortletImpl.STATE_MIN);
1164                    String modeAbout = props.getProperty(
1165                        LayoutTypePortletImpl.MODE_ABOUT);
1166                    String modeConfig = props.getProperty(
1167                        LayoutTypePortletImpl.MODE_CONFIG);
1168                    String modeEdit = props.getProperty(
1169                        LayoutTypePortletImpl.MODE_EDIT);
1170                    String modeEditDefaults = props.getProperty(
1171                        LayoutTypePortletImpl.MODE_EDIT_DEFAULTS);
1172                    String modeEditGuest = props.getProperty(
1173                        LayoutTypePortletImpl.MODE_EDIT_GUEST);
1174                    String modeHelp = props.getProperty(
1175                        LayoutTypePortletImpl.MODE_HELP);
1176                    String modePreview = props.getProperty(
1177                        LayoutTypePortletImpl.MODE_PREVIEW);
1178                    String modePrint = props.getProperty(
1179                        LayoutTypePortletImpl.MODE_PRINT);
1180
1181                    layoutTypePortlet.setStateMax(stateMax);
1182                    layoutTypePortlet.setStateMin(stateMin);
1183                    layoutTypePortlet.setModeAbout(modeAbout);
1184                    layoutTypePortlet.setModeConfig(modeConfig);
1185                    layoutTypePortlet.setModeEdit(modeEdit);
1186                    layoutTypePortlet.setModeEditDefaults(modeEditDefaults);
1187                    layoutTypePortlet.setModeEditGuest(modeEditGuest);
1188                    layoutTypePortlet.setModeHelp(modeHelp);
1189                    layoutTypePortlet.setModePreview(modePreview);
1190                    layoutTypePortlet.setModePrint(modePrint);
1191                }
1192            }
1193
1194            request.setAttribute(WebKeys.LAYOUT, layout);
1195            request.setAttribute(WebKeys.LAYOUTS, layouts);
1196
1197            if (layout.isPrivateLayout()) {
1198                permissionChecker.setCheckGuest(false);
1199            }
1200        }
1201
1202        // Theme and color scheme
1203
1204        Theme theme = null;
1205        ColorScheme colorScheme = null;
1206
1207        boolean wapTheme = BrowserSnifferUtil.isWap(request);
1208
1209        if (layout != null) {
1210            if (wapTheme) {
1211                theme = layout.getWapTheme();
1212                colorScheme = layout.getWapColorScheme();
1213            }
1214            else {
1215                theme = layout.getTheme();
1216                colorScheme = layout.getColorScheme();
1217            }
1218        }
1219        else {
1220            String themeId = null;
1221            String colorSchemeId = null;
1222
1223            if (wapTheme) {
1224                themeId = ThemeImpl.getDefaultWapThemeId();
1225                colorSchemeId = ColorSchemeImpl.getDefaultWapColorSchemeId();
1226            }
1227            else {
1228                themeId = ThemeImpl.getDefaultRegularThemeId();
1229                colorSchemeId =
1230                    ColorSchemeImpl.getDefaultRegularColorSchemeId();
1231            }
1232
1233            theme = ThemeLocalServiceUtil.getTheme(
1234                companyId, themeId, wapTheme);
1235            colorScheme = ThemeLocalServiceUtil.getColorScheme(
1236                companyId, theme.getThemeId(), colorSchemeId, wapTheme);
1237        }
1238
1239        request.setAttribute(WebKeys.THEME, theme);
1240        request.setAttribute(WebKeys.COLOR_SCHEME, colorScheme);
1241
1242        boolean themeCssFastLoad = ParamUtil.getBoolean(
1243            request, "css_fast_load", PropsValues.THEME_CSS_FAST_LOAD);
1244        boolean themeImagesFastLoad = ParamUtil.getBoolean(
1245            request, "images_fast_load", PropsValues.THEME_IMAGES_FAST_LOAD);
1246
1247        boolean themeJsBarebone = PropsValues.JAVASCRIPT_BAREBONE_ENABLED;
1248
1249        if (themeJsBarebone) {
1250            if (signedIn) {
1251                themeJsBarebone = false;
1252            }
1253        }
1254
1255        boolean themeJsFastLoad = ParamUtil.getBoolean(
1256            request, "js_fast_load", PropsValues.JAVASCRIPT_FAST_LOAD);
1257
1258        String lifecycle = ParamUtil.getString(request, "p_p_lifecycle");
1259
1260        String facebookCanvasPageURL = (String)request.getAttribute(
1261            WebKeys.FACEBOOK_CANVAS_PAGE_URL);
1262
1263        boolean widget = false;
1264
1265        Boolean widgetObj = (Boolean)request.getAttribute(WebKeys.WIDGET);
1266
1267        if (widgetObj != null) {
1268            widget = widgetObj.booleanValue();
1269        }
1270
1271        // Theme display
1272
1273        ThemeDisplay themeDisplay = ThemeDisplayFactory.create();
1274
1275        // Set the CDN host, portal URL, and Facebook application ID first
1276        // because other methods (setLookAndFeel) depend on them being set
1277
1278        themeDisplay.setCDNHost(cdnHost);
1279        themeDisplay.setPortalURL(portalURL);
1280        themeDisplay.setFacebookCanvasPageURL(facebookCanvasPageURL);
1281        themeDisplay.setWidget(widget);
1282
1283        themeDisplay.setCompany(company);
1284        themeDisplay.setCompanyLogo(companyLogo);
1285        themeDisplay.setCompanyLogoHeight(companyLogoHeight);
1286        themeDisplay.setCompanyLogoWidth(companyLogoWidth);
1287        themeDisplay.setRealCompanyLogo(realCompanyLogo);
1288        themeDisplay.setRealCompanyLogoHeight(realCompanyLogoHeight);
1289        themeDisplay.setRealCompanyLogoWidth(realCompanyLogoWidth);
1290        themeDisplay.setUser(user);
1291        themeDisplay.setRealUser(realUser);
1292        themeDisplay.setDoAsUserId(doAsUserId);
1293        themeDisplay.setLayoutSetLogo(layoutSetLogo);
1294        themeDisplay.setLayout(layout);
1295        themeDisplay.setLayouts(layouts);
1296        themeDisplay.setPlid(plid);
1297        themeDisplay.setLayoutTypePortlet(layoutTypePortlet);
1298        themeDisplay.setScopeGroupId(scopeGroupId);
1299        themeDisplay.setSignedIn(signedIn);
1300        themeDisplay.setPermissionChecker(permissionChecker);
1301        themeDisplay.setLocale(locale);
1302        themeDisplay.setLanguageId(LocaleUtil.toLanguageId(locale));
1303        themeDisplay.setI18nLanguageId(i18nLanguageId);
1304        themeDisplay.setTimeZone(timeZone);
1305        themeDisplay.setLookAndFeel(contextPath, theme, colorScheme);
1306        themeDisplay.setThemeCssFastLoad(themeCssFastLoad);
1307        themeDisplay.setThemeImagesFastLoad(themeImagesFastLoad);
1308        themeDisplay.setThemeJsBarebone(themeJsBarebone);
1309        themeDisplay.setThemeJsFastLoad(themeJsFastLoad);
1310        themeDisplay.setServerName(request.getServerName());
1311        themeDisplay.setServerPort(request.getServerPort());
1312        themeDisplay.setSecure(request.isSecure());
1313        themeDisplay.setLifecycle(lifecycle);
1314        themeDisplay.setLifecycleAction(lifecycle.equals("1"));
1315        themeDisplay.setLifecycleRender(lifecycle.equals("0"));
1316        themeDisplay.setLifecycleResource(lifecycle.equals("2"));
1317        themeDisplay.setStateExclusive(LiferayWindowState.isExclusive(request));
1318        themeDisplay.setStateMaximized(LiferayWindowState.isMaximized(request));
1319        themeDisplay.setStatePopUp(LiferayWindowState.isPopUp(request));
1320        themeDisplay.setPathApplet(contextPath + "/applets");
1321        themeDisplay.setPathCms(contextPath + "/cms");
1322        themeDisplay.setPathContext(contextPath);
1323        themeDisplay.setPathFlash(contextPath + "/flash");
1324        themeDisplay.setPathFriendlyURLPrivateGroup(
1325            friendlyURLPrivateGroupPath);
1326        themeDisplay.setPathFriendlyURLPrivateUser(friendlyURLPrivateUserPath);
1327        themeDisplay.setPathFriendlyURLPublic(friendlyURLPublicPath);
1328        themeDisplay.setPathImage(imagePath);
1329        themeDisplay.setPathJavaScript(cdnHost + contextPath + "/html/js");
1330        themeDisplay.setPathMain(mainPath);
1331        themeDisplay.setPathSound(contextPath + "/html/sound");
1332
1333        // URLs
1334
1335        themeDisplay.setShowAddContentIcon(false);
1336        themeDisplay.setShowHomeIcon(true);
1337        themeDisplay.setShowMyAccountIcon(signedIn);
1338        themeDisplay.setShowPageSettingsIcon(false);
1339        themeDisplay.setShowPortalIcon(true);
1340        themeDisplay.setShowSignInIcon(!signedIn);
1341        themeDisplay.setShowSignOutIcon(signedIn);
1342        themeDisplay.setShowStagingIcon(false);
1343
1344        PortletURL createAccountURL = new PortletURLImpl(
1345            request, PortletKeys.LOGIN, plid, PortletRequest.ACTION_PHASE);
1346
1347        createAccountURL.setWindowState(WindowState.MAXIMIZED);
1348        createAccountURL.setPortletMode(PortletMode.VIEW);
1349
1350        createAccountURL.setParameter("saveLastPath", "0");
1351        createAccountURL.setParameter(
1352            "struts_action", "/login/create_account");
1353
1354        themeDisplay.setURLCreateAccount(createAccountURL);
1355
1356        String currentURL = PortalUtil.getCurrentURL(request);
1357
1358        themeDisplay.setURLCurrent(currentURL);
1359
1360        String urlHome = portalURL + contextPath;
1361
1362        themeDisplay.setURLHome(urlHome);
1363
1364        if (layout != null) {
1365            Group group = layout.getGroup();
1366
1367            if (layout.getType().equals(LayoutConstants.TYPE_PORTLET)) {
1368                boolean freeformLayout =
1369                    layoutTypePortlet.getLayoutTemplateId().equals(
1370                        "freeform");
1371
1372                themeDisplay.setFreeformLayout(freeformLayout);
1373
1374                boolean hasUpdateLayoutPermission =
1375                    LayoutPermissionUtil.contains(
1376                        permissionChecker, layout, ActionKeys.UPDATE);
1377
1378                if (hasUpdateLayoutPermission) {
1379                    if (!LiferayWindowState.isMaximized(request)) {
1380                        themeDisplay.setShowAddContentIcon(true);
1381                    }
1382
1383                    themeDisplay.setShowLayoutTemplatesIcon(true);
1384
1385                    themeDisplay.setURLAddContent(
1386                        "LayoutConfiguration.toggle('" +
1387                            PortletKeys.LAYOUT_CONFIGURATION + "');");
1388
1389                    themeDisplay.setURLLayoutTemplates(
1390                        "Liferay.Layout.showTemplates();");
1391                }
1392            }
1393
1394            boolean hasManageLayoutsPermission =
1395                GroupPermissionUtil.contains(
1396                    permissionChecker, scopeGroupId, ActionKeys.MANAGE_LAYOUTS);
1397
1398            if (group.isUser()) {
1399                if ((layout.isPrivateLayout() &&
1400                     !PropsValues.LAYOUT_USER_PRIVATE_LAYOUTS_MODIFIABLE) ||
1401                    (layout.isPublicLayout() &&
1402                     !PropsValues.LAYOUT_USER_PUBLIC_LAYOUTS_MODIFIABLE)) {
1403
1404                    hasManageLayoutsPermission = false;
1405                }
1406            }
1407
1408            if (hasManageLayoutsPermission) {
1409                themeDisplay.setShowPageSettingsIcon(true);
1410
1411                PortletURL pageSettingsURL = new PortletURLImpl(
1412                    request, PortletKeys.LAYOUT_MANAGEMENT, plid,
1413                    PortletRequest.RENDER_PHASE);
1414
1415                pageSettingsURL.setWindowState(WindowState.MAXIMIZED);
1416                pageSettingsURL.setPortletMode(PortletMode.VIEW);
1417
1418                pageSettingsURL.setParameter(
1419                    "struts_action", "/layout_management/edit_pages");
1420
1421                if (layout.isPrivateLayout()) {
1422                    pageSettingsURL.setParameter("tabs1", "private-pages");
1423                }
1424                else {
1425                    pageSettingsURL.setParameter("tabs1", "public-pages");
1426                }
1427
1428                pageSettingsURL.setParameter("redirect", currentURL);
1429                pageSettingsURL.setParameter(
1430                    "groupId", String.valueOf(scopeGroupId));
1431                pageSettingsURL.setParameter("selPlid", String.valueOf(plid));
1432
1433                themeDisplay.setURLPageSettings(pageSettingsURL);
1434
1435                PortletURL publishToLiveURL = new PortletURLImpl(
1436                    request, PortletKeys.LAYOUT_MANAGEMENT, plid,
1437                    PortletRequest.RENDER_PHASE);
1438
1439                publishToLiveURL.setWindowState(LiferayWindowState.EXCLUSIVE);
1440                publishToLiveURL.setPortletMode(PortletMode.VIEW);
1441
1442                publishToLiveURL.setParameter(
1443                    "struts_action", "/layout_management/export_pages");
1444
1445                if (layout.isPrivateLayout()) {
1446                    publishToLiveURL.setParameter("tabs1", "private-pages");
1447                }
1448                else {
1449                    publishToLiveURL.setParameter("tabs1", "public-pages");
1450                }
1451
1452                publishToLiveURL.setParameter("pagesRedirect", currentURL);
1453                publishToLiveURL.setParameter(
1454                    "groupId", String.valueOf(scopeGroupId));
1455                publishToLiveURL.setParameter("selPlid", String.valueOf(plid));
1456
1457                themeDisplay.setURLPublishToLive(publishToLiveURL);
1458            }
1459
1460            if (group.hasStagingGroup() && !group.isStagingGroup()) {
1461                themeDisplay.setShowAddContentIcon(false);
1462                themeDisplay.setShowLayoutTemplatesIcon(false);
1463                themeDisplay.setShowPageSettingsIcon(false);
1464                themeDisplay.setURLPublishToLive(null);
1465            }
1466
1467            // LEP-4987
1468
1469            if (group.hasStagingGroup() || group.isStagingGroup()) {
1470                boolean hasApproveProposalPermission =
1471                    GroupPermissionUtil.contains(
1472                        permissionChecker, scopeGroupId,
1473                        ActionKeys.APPROVE_PROPOSAL);
1474
1475                boolean hasUpdateLayoutPermission =
1476                    LayoutPermissionUtil.contains(
1477                        permissionChecker, layout.getGroupId(),
1478                        layout.isPrivateLayout(), layout.getLayoutId(),
1479                        ActionKeys.UPDATE);
1480
1481                if (hasManageLayoutsPermission) {
1482                    themeDisplay.setShowStagingIcon(true);
1483                }
1484                else if (hasApproveProposalPermission) {
1485                    themeDisplay.setShowStagingIcon(true);
1486                }
1487                else if (hasUpdateLayoutPermission) {
1488                    themeDisplay.setShowStagingIcon(true);
1489                }
1490            }
1491
1492            String myAccountNamespace = PortalUtil.getPortletNamespace(
1493                PortletKeys.MY_ACCOUNT);
1494
1495            String myAccountRedirect = ParamUtil.getString(
1496                request, myAccountNamespace + "backURL", currentURL);
1497
1498            PortletURL myAccountURL = new PortletURLImpl(
1499                request, PortletKeys.MY_ACCOUNT, plid,
1500                PortletRequest.RENDER_PHASE);
1501
1502            myAccountURL.setWindowState(WindowState.MAXIMIZED);
1503            myAccountURL.setPortletMode(PortletMode.VIEW);
1504
1505            myAccountURL.setParameter("struts_action", "/my_account/edit_user");
1506            myAccountURL.setParameter("backURL", myAccountRedirect);
1507
1508            themeDisplay.setURLMyAccount(myAccountURL);
1509        }
1510
1511        if ((!user.isActive()) ||
1512            (PropsValues.TERMS_OF_USE_REQUIRED &&
1513             !user.isAgreedToTermsOfUse())) {
1514
1515            themeDisplay.setShowAddContentIcon(false);
1516            themeDisplay.setShowMyAccountIcon(false);
1517            themeDisplay.setShowPageSettingsIcon(false);
1518        }
1519
1520        themeDisplay.setURLPortal(themeDisplay.getURLHome());
1521
1522        String urlSignIn = mainPath + "/portal/login";
1523
1524        if (layout != null) {
1525            urlSignIn = HttpUtil.addParameter(
1526                urlSignIn, "p_l_id", layout.getPlid());
1527        }
1528
1529        themeDisplay.setURLSignIn(urlSignIn);
1530
1531        themeDisplay.setURLSignOut(mainPath + "/portal/logout");
1532
1533        PortletURL updateManagerURL = new PortletURLImpl(
1534            request, PortletKeys.UPDATE_MANAGER, plid,
1535            PortletRequest.RENDER_PHASE);
1536
1537        updateManagerURL.setWindowState(WindowState.MAXIMIZED);
1538        updateManagerURL.setPortletMode(PortletMode.VIEW);
1539
1540        updateManagerURL.setParameter("struts_action", "/update_manager/view");
1541
1542        themeDisplay.setURLUpdateManager(updateManagerURL);
1543
1544        request.setAttribute(WebKeys.THEME_DISPLAY, themeDisplay);
1545
1546        // Parallel render
1547
1548        boolean parallelRenderEnable = true;
1549
1550        if (layout != null) {
1551            if (layoutTypePortlet.getPortletIds().size() == 1) {
1552                parallelRenderEnable = false;
1553            }
1554        }
1555
1556        Boolean parallelRenderEnableObj = Boolean.valueOf(ParamUtil.getBoolean(
1557            request, "p_p_parallel", parallelRenderEnable));
1558
1559        request.setAttribute(
1560            WebKeys.PORTLET_PARALLEL_RENDER, parallelRenderEnableObj);
1561    }
1562
1563    protected void updateUserLayouts(User user) throws Exception {
1564
1565        // Private layouts
1566
1567        boolean addDefaultUserPrivateLayouts = false;
1568
1569        if (PropsValues.LAYOUT_USER_PRIVATE_LAYOUTS_ENABLED &&
1570            PropsValues.LAYOUT_USER_PRIVATE_LAYOUTS_AUTO_CREATE) {
1571
1572            addDefaultUserPrivateLayouts = true;
1573
1574            if (PropsValues.LAYOUT_USER_PRIVATE_LAYOUTS_POWER_USER_REQUIRED) {
1575                Role powerUserRole = RoleLocalServiceUtil.getRole(
1576                    user.getCompanyId(), RoleConstants.POWER_USER);
1577
1578                if (!UserLocalServiceUtil.hasRoleUser(
1579                        powerUserRole.getRoleId(), user.getUserId())) {
1580
1581                    addDefaultUserPrivateLayouts = false;
1582                }
1583            }
1584        }
1585
1586        if (addDefaultUserPrivateLayouts && !user.hasPrivateLayouts()) {
1587            addDefaultUserPrivateLayouts(user);
1588        }
1589
1590        boolean deleteDefaultUserPrivateLayouts = false;
1591
1592        if (!PropsValues.LAYOUT_USER_PRIVATE_LAYOUTS_ENABLED) {
1593            deleteDefaultUserPrivateLayouts = true;
1594        }
1595        else if (PropsValues.LAYOUT_USER_PRIVATE_LAYOUTS_POWER_USER_REQUIRED) {
1596            Role powerUserRole = RoleLocalServiceUtil.getRole(
1597                user.getCompanyId(), RoleConstants.POWER_USER);
1598
1599            if (!UserLocalServiceUtil.hasRoleUser(
1600                    powerUserRole.getRoleId(), user.getUserId())) {
1601
1602                deleteDefaultUserPrivateLayouts = true;
1603            }
1604        }
1605
1606        if (deleteDefaultUserPrivateLayouts && user.hasPrivateLayouts()) {
1607            deleteDefaultUserPrivateLayouts(user);
1608        }
1609
1610        // Public pages
1611
1612        boolean addDefaultUserPublicLayouts = false;
1613
1614        if (PropsValues.LAYOUT_USER_PUBLIC_LAYOUTS_ENABLED &&
1615            PropsValues.LAYOUT_USER_PUBLIC_LAYOUTS_AUTO_CREATE) {
1616
1617            addDefaultUserPublicLayouts = true;
1618
1619            if (PropsValues.LAYOUT_USER_PUBLIC_LAYOUTS_POWER_USER_REQUIRED) {
1620                Role powerUserRole = RoleLocalServiceUtil.getRole(
1621                    user.getCompanyId(), RoleConstants.POWER_USER);
1622
1623                if (!UserLocalServiceUtil.hasRoleUser(
1624                        powerUserRole.getRoleId(), user.getUserId())) {
1625
1626                    addDefaultUserPublicLayouts = false;
1627                }
1628            }
1629        }
1630
1631        if (addDefaultUserPublicLayouts && !user.hasPublicLayouts()) {
1632            addDefaultUserPublicLayouts(user);
1633        }
1634
1635        boolean deleteDefaultUserPublicLayouts = false;
1636
1637        if (!PropsValues.LAYOUT_USER_PUBLIC_LAYOUTS_ENABLED) {
1638            deleteDefaultUserPublicLayouts = true;
1639        }
1640        else if (PropsValues.LAYOUT_USER_PUBLIC_LAYOUTS_POWER_USER_REQUIRED) {
1641            Role powerUserRole = RoleLocalServiceUtil.getRole(
1642                user.getCompanyId(), RoleConstants.POWER_USER);
1643
1644            if (!UserLocalServiceUtil.hasRoleUser(
1645                    powerUserRole.getRoleId(), user.getUserId())) {
1646
1647                deleteDefaultUserPublicLayouts = true;
1648            }
1649        }
1650
1651        if (deleteDefaultUserPublicLayouts && user.hasPublicLayouts()) {
1652            deleteDefaultUserPublicLayouts(user);
1653        }
1654    }
1655
1656    protected File privateLARFile;
1657    protected File publicLARFile;
1658
1659    private static final String _PATH_PORTAL_LAYOUT = "/portal/layout";
1660
1661    private static Log _log = LogFactoryUtil.getLog(ServicePreAction.class);
1662
1663}