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