Exemple #1
0
  protected List<Layout> addUserGroupLayouts(
      Group group, LayoutSet layoutSet, List<Layout> layouts, long parentLayoutId)
      throws Exception {

    layouts = ListUtil.copy(layouts);

    List<UserGroup> userUserGroups =
        UserGroupLocalServiceUtil.getUserUserGroups(group.getClassPK());

    for (UserGroup userGroup : userUserGroups) {
      Group userGroupGroup = userGroup.getGroup();

      List<Layout> userGroupLayouts =
          LayoutLocalServiceUtil.getLayouts(
              userGroupGroup.getGroupId(), layoutSet.isPrivateLayout(), parentLayoutId);

      for (Layout userGroupLayout : userGroupLayouts) {
        Layout virtualLayout = new VirtualLayout(userGroupLayout, group);

        layouts.add(virtualLayout);
      }
    }

    return layouts;
  }
  /**
   * Returns the default role for the group with the primary key.
   *
   * <p>If the group is a site, then the default role is {@link
   * com.liferay.portal.model.RoleConstants#SITE_MEMBER}. If the group is an organization, then the
   * default role is {@link com.liferay.portal.model.RoleConstants#ORGANIZATION_USER}. If the group
   * is a user or user group, then the default role is {@link
   * com.liferay.portal.model.RoleConstants#POWER_USER}. For all other group types, the default role
   * is {@link com.liferay.portal.model.RoleConstants#USER}.
   *
   * @param groupId the primary key of the group
   * @return the default role for the group with the primary key
   * @throws PortalException if a group with the primary key could not be found, or if a default
   *     role could not be found for the group
   * @throws SystemException if a system exception occurred
   */
  public Role getDefaultGroupRole(long groupId) throws PortalException, SystemException {

    Group group = groupPersistence.findByPrimaryKey(groupId);

    if (group.isLayout()) {
      Layout layout = layoutLocalService.getLayout(group.getClassPK());

      group = layout.getGroup();
    }

    if (group.isStagingGroup()) {
      group = group.getLiveGroup();
    }

    Role role = null;

    if (group.isCompany()) {
      role = getRole(group.getCompanyId(), RoleConstants.USER);
    } else if (group.isLayoutPrototype()
        || group.isLayoutSetPrototype()
        || group.isRegularSite()
        || group.isSite()) {

      role = getRole(group.getCompanyId(), RoleConstants.SITE_MEMBER);
    } else if (group.isOrganization()) {
      role = getRole(group.getCompanyId(), RoleConstants.ORGANIZATION_USER);
    } else if (group.isUser() || group.isUserGroup()) {
      role = getRole(group.getCompanyId(), RoleConstants.POWER_USER);
    } else {
      role = getRole(group.getCompanyId(), RoleConstants.USER);
    }

    return role;
  }
  @Override
  public String getScopeId(Group group, long scopeGroupId) throws PortalException, SystemException {

    String key = null;

    if (group.isLayout()) {
      Layout layout = LayoutLocalServiceUtil.getLayout(group.getClassPK());

      key = SCOPE_ID_LAYOUT_UUID_PREFIX + layout.getUuid();
    } else if (group.isLayoutPrototype() || (group.getGroupId() == scopeGroupId)) {

      key = SCOPE_ID_GROUP_PREFIX + GroupConstants.DEFAULT;
    } else {
      Group scopeGroup = GroupLocalServiceUtil.getGroup(scopeGroupId);

      if (scopeGroup.hasAncestor(group.getGroupId())) {
        key = SCOPE_ID_PARENT_GROUP_PREFIX + group.getGroupId();
      } else if (group.hasAncestor(scopeGroup.getGroupId())) {
        key = SCOPE_ID_CHILD_GROUP_PREFIX + group.getGroupId();
      } else {
        key = SCOPE_ID_GROUP_PREFIX + group.getGroupId();
      }
    }

    return key;
  }
  protected List<Layout> getCandidateLayouts(long plid, boolean privateLayout, KBArticle kbArticle)
      throws Exception {

    List<Layout> candidateLayouts = new ArrayList<>();

    Group group = GroupLocalServiceUtil.getGroup(kbArticle.getGroupId());

    if (group.isLayout()) {
      Layout layout = LayoutLocalServiceUtil.getLayout(group.getClassPK());

      candidateLayouts.add(layout);

      group = layout.getGroup();
    }

    List<Layout> layouts =
        LayoutLocalServiceUtil.getLayouts(
            group.getGroupId(), privateLayout, LayoutConstants.TYPE_PORTLET);

    candidateLayouts.addAll(layouts);

    Layout layout = LayoutLocalServiceUtil.getLayout(plid);

    if ((layout.getGroupId() == kbArticle.getGroupId()) && layout.isTypePortlet()) {

      candidateLayouts.remove(layout);
      candidateLayouts.add(0, layout);
    }

    return candidateLayouts;
  }
  public WallEntry addWallEntry(
      long groupId, long userId, String comments, ThemeDisplay themeDisplay)
      throws PortalException, SystemException {

    // Wall entry

    Group group = GroupLocalServiceUtil.getGroup(groupId);
    User user = userLocalService.getUserById(userId);
    Date now = new Date();

    long wallEntryId = counterLocalService.increment();

    WallEntry wallEntry = wallEntryPersistence.create(wallEntryId);

    wallEntry.setGroupId(groupId);
    wallEntry.setCompanyId(user.getCompanyId());
    wallEntry.setUserId(user.getUserId());
    wallEntry.setUserName(user.getFullName());
    wallEntry.setCreateDate(now);
    wallEntry.setModifiedDate(now);
    wallEntry.setComments(comments);

    wallEntryPersistence.update(wallEntry, false);

    // Email

    try {
      sendEmail(wallEntry, themeDisplay);
    } catch (Exception e) {
      throw new SystemException(e);
    }

    // Social

    if (userId != group.getClassPK()) {
      SocialActivityLocalServiceUtil.addActivity(
          userId,
          groupId,
          WallEntry.class.getName(),
          wallEntryId,
          WallActivityKeys.ADD_ENTRY,
          StringPool.BLANK,
          group.getClassPK());
    }

    return wallEntry;
  }
  public void joinOrganization(ActionRequest actionRequest, ActionResponse actionResponse)
      throws Exception {

    ThemeDisplay themeDisplay = (ThemeDisplay) actionRequest.getAttribute(WebKeys.THEME_DISPLAY);

    Group group = _groupLocalService.getGroup(themeDisplay.getScopeGroupId());

    Organization organization = _organizationLocalService.getOrganization(group.getClassPK());

    Role role =
        _roleLocalService.getRole(themeDisplay.getCompanyId(), "Organization Administrator");

    LinkedHashMap<String, Object> userParams = new LinkedHashMap<>();

    userParams.put("userGroupRole", new Long[] {group.getGroupId(), role.getRoleId()});

    List<User> users =
        _userLocalService.search(
            themeDisplay.getCompanyId(),
            null,
            WorkflowConstants.STATUS_APPROVED,
            userParams,
            QueryUtil.ALL_POS,
            QueryUtil.ALL_POS,
            (OrderByComparator<User>) null);

    if (users.isEmpty()) {
      Role adminRole =
          _roleLocalService.getRole(themeDisplay.getCompanyId(), RoleConstants.ADMINISTRATOR);

      userParams.clear();

      userParams.put("usersRoles", adminRole.getRoleId());

      users =
          _userLocalService.search(
              themeDisplay.getCompanyId(),
              null,
              WorkflowConstants.STATUS_APPROVED,
              userParams,
              QueryUtil.ALL_POS,
              QueryUtil.ALL_POS,
              (OrderByComparator<User>) null);
    }

    JSONObject extraDataJSONObject = getExtraDataJSONObject(actionRequest);

    for (User user : users) {
      _socialRequestLocalService.addRequest(
          themeDisplay.getUserId(),
          0,
          Organization.class.getName(),
          organization.getOrganizationId(),
          MembersRequestKeys.ADD_MEMBER,
          extraDataJSONObject.toString(),
          user.getUserId());
    }
  }
  private void _buildParentGroupsBreadcrumb(
      LayoutSet layoutSet, PortletURL portletURL, ThemeDisplay themeDisplay, StringBundler sb)
      throws Exception {
    Group group = layoutSet.getGroup();

    if (group.isOrganization()) {
      Organization organization =
          OrganizationLocalServiceUtil.getOrganization(group.getOrganizationId());

      Organization parentOrganization = organization.getParentOrganization();

      if (parentOrganization != null) {
        Group parentGroup = parentOrganization.getGroup();

        LayoutSet parentLayoutSet =
            LayoutSetLocalServiceUtil.getLayoutSet(
                parentGroup.getGroupId(), layoutSet.isPrivateLayout());

        _buildParentGroupsBreadcrumb(parentLayoutSet, portletURL, themeDisplay, sb);
      }
    } else if (group.isUser()) {
      User groupUser = UserLocalServiceUtil.getUser(group.getClassPK());

      List<Organization> organizations =
          OrganizationLocalServiceUtil.getUserOrganizations(groupUser.getUserId(), true);

      if (!organizations.isEmpty()) {
        Organization organization = organizations.get(0);

        Group parentGroup = organization.getGroup();

        LayoutSet parentLayoutSet =
            LayoutSetLocalServiceUtil.getLayoutSet(
                parentGroup.getGroupId(), layoutSet.isPrivateLayout());

        _buildParentGroupsBreadcrumb(parentLayoutSet, portletURL, themeDisplay, sb);
      }
    }

    int layoutsPageCount = 0;

    if (layoutSet.isPrivateLayout()) {
      layoutsPageCount = group.getPrivateLayoutsPageCount();
    } else {
      layoutsPageCount = group.getPublicLayoutsPageCount();
    }

    if ((layoutsPageCount > 0) && !group.getName().equals(GroupConstants.GUEST)) {
      String layoutSetFriendlyURL = PortalUtil.getLayoutSetFriendlyURL(layoutSet, themeDisplay);

      sb.append("<li><span><a href=\"");
      sb.append(layoutSetFriendlyURL);
      sb.append("\">");
      sb.append(HtmlUtil.escape(group.getDescriptiveName()));
      sb.append("</a></span></li>");
    }
  }
  public void leaveOrganization(ActionRequest actionRequest, ActionResponse actionResponse)
      throws Exception {

    ThemeDisplay themeDisplay = (ThemeDisplay) actionRequest.getAttribute(WebKeys.THEME_DISPLAY);

    Group group = _groupLocalService.getGroup(themeDisplay.getScopeGroupId());

    _userLocalService.unsetOrganizationUsers(
        group.getClassPK(), new long[] {themeDisplay.getUserId()});
  }
  public void deleteFriend(ActionRequest actionRequest, ActionResponse actionResponse)
      throws Exception {

    ThemeDisplay themeDisplay = (ThemeDisplay) actionRequest.getAttribute(WebKeys.THEME_DISPLAY);

    Group group = _groupLocalService.getGroup(themeDisplay.getScopeGroupId());

    User user = _userLocalService.getUserById(group.getClassPK());

    _socialRelationLocalService.deleteRelation(
        themeDisplay.getUserId(), user.getUserId(), SocialRelationConstants.TYPE_BI_FRIEND);
  }
  public long getOrganizationId() {
    if (isOrganization()) {
      if (isStagingGroup()) {
        Group liveGroup = getLiveGroup();

        return liveGroup.getClassPK();
      } else {
        return getClassPK();
      }
    }

    return 0;
  }
  public static String getOwnerId(Layout layout) throws PortalException, SystemException {

    Group group = layout.getGroup();

    long classPK = group.getClassPK();

    String ownerId = "G-" + classPK;

    if (group.isUser()) {
      ownerId = String.valueOf(classPK);
    }

    return ownerId;
  }
  public static JSONObject toJSONObject(Group model) {
    JSONObject jsonObj = JSONFactoryUtil.createJSONObject();

    jsonObj.put("groupId", model.getGroupId());
    jsonObj.put("companyId", model.getCompanyId());
    jsonObj.put("creatorUserId", model.getCreatorUserId());
    jsonObj.put("classNameId", model.getClassNameId());
    jsonObj.put("classPK", model.getClassPK());
    jsonObj.put("parentGroupId", model.getParentGroupId());
    jsonObj.put("liveGroupId", model.getLiveGroupId());
    jsonObj.put("name", model.getName());
    jsonObj.put("description", model.getDescription());
    jsonObj.put("type", model.getType());
    jsonObj.put("typeSettings", model.getTypeSettings());
    jsonObj.put("friendlyURL", model.getFriendlyURL());
    jsonObj.put("active", model.getActive());

    return jsonObj;
  }
  protected List<SocialActivity> getSocialActivities(ResourceRequest resourceRequest, int max)
      throws Exception {

    ThemeDisplay themeDisplay = (ThemeDisplay) resourceRequest.getAttribute(WebKeys.THEME_DISPLAY);

    Group group = _groupLocalService.getGroup(themeDisplay.getScopeGroupId());

    int start = 0;

    if (group.isOrganization()) {
      return _socialActivityLocalService.getOrganizationActivities(
          group.getOrganizationId(), start, max);
    } else if (group.isRegularSite()) {
      return _socialActivityLocalService.getGroupActivities(group.getGroupId(), start, max);
    } else if (group.isUser()) {
      return _socialActivityLocalService.getUserActivities(group.getClassPK(), start, max);
    }

    return Collections.emptyList();
  }
  public void updateSummary(ActionRequest actionRequest, ActionResponse actionResponse)
      throws Exception {

    ThemeDisplay themeDisplay = (ThemeDisplay) actionRequest.getAttribute(WebKeys.THEME_DISPLAY);

    if (!themeDisplay.isSignedIn()) {
      return;
    }

    Group group = _groupLocalService.getGroup(themeDisplay.getScopeGroupId());

    User user = null;

    if (group.isUser()) {
      user = _userLocalService.getUserById(group.getClassPK());
    } else {
      return;
    }

    if (!UserPermissionUtil.contains(
        themeDisplay.getPermissionChecker(), user.getUserId(), ActionKeys.UPDATE)) {

      return;
    }

    String jobTitle = ParamUtil.getString(actionRequest, "jobTitle");

    _userLocalService.updateJobTitle(user.getUserId(), jobTitle);

    String aboutMe = ParamUtil.getString(actionRequest, "aboutMe");

    _expandoValueLocalService.addValue(
        themeDisplay.getCompanyId(),
        User.class.getName(),
        "SN",
        "aboutMe",
        user.getUserId(),
        aboutMe);
  }
  public void addFriend(ActionRequest actionRequest, ActionResponse actionResponse)
      throws Exception {

    ThemeDisplay themeDisplay = (ThemeDisplay) actionRequest.getAttribute(WebKeys.THEME_DISPLAY);

    Group group = _groupLocalService.getGroup(themeDisplay.getScopeGroupId());

    User user = _userLocalService.getUserById(group.getClassPK());

    JSONObject extraDataJSONObject = getExtraDataJSONObject(actionRequest);

    String addFriendMessage = ParamUtil.getString(actionRequest, "addFriendMessage");

    extraDataJSONObject.put("addFriendMessage", addFriendMessage);

    _socialRequestLocalService.addRequest(
        themeDisplay.getUserId(),
        0,
        User.class.getName(),
        themeDisplay.getUserId(),
        FriendsRequestKeys.ADD_FRIEND,
        extraDataJSONObject.toString(),
        user.getUserId());
  }
  @Override
  public boolean contains(PermissionChecker permissionChecker, Group group, String actionId)
      throws PortalException, SystemException {

    long groupId = group.getGroupId();

    if (group.isStagingGroup()) {
      group = group.getLiveGroup();
    }

    if (group.isUser()) {

      // An individual user would never reach this block because he would
      // be an administrator of his own layouts. However, a user who
      // manages a set of organizations may be modifying pages of a user
      // he manages.

      User user = UserLocalServiceUtil.getUserById(group.getClassPK());

      if ((permissionChecker.getUserId() != user.getUserId())
          && UserPermissionUtil.contains(
              permissionChecker, user.getUserId(), user.getOrganizationIds(), ActionKeys.UPDATE)) {

        return true;
      }
    }

    if (actionId.equals(ActionKeys.ADD_COMMUNITY)
            && permissionChecker.hasPermission(
                groupId, Group.class.getName(), groupId, ActionKeys.MANAGE_SUBGROUPS)
        || PortalPermissionUtil.contains(permissionChecker, ActionKeys.ADD_COMMUNITY)) {

      return true;
    } else if (actionId.equals(ActionKeys.ADD_LAYOUT)
        && !group.isLayoutPrototype()
        && permissionChecker.hasPermission(
            groupId, Group.class.getName(), groupId, ActionKeys.MANAGE_LAYOUTS)) {

      return true;
    } else if ((actionId.equals(ActionKeys.EXPORT_IMPORT_LAYOUTS)
            || actionId.equals(ActionKeys.EXPORT_IMPORT_PORTLET_INFO))
        && permissionChecker.hasPermission(
            groupId, Group.class.getName(), groupId, ActionKeys.PUBLISH_STAGING)) {

      return true;
    } else if (actionId.equals(ActionKeys.VIEW)
        && (permissionChecker.hasPermission(
                groupId, Group.class.getName(), groupId, ActionKeys.ASSIGN_USER_ROLES)
            || permissionChecker.hasPermission(
                groupId, Group.class.getName(), groupId, ActionKeys.MANAGE_LAYOUTS))) {

      return true;
    } else if (actionId.equals(ActionKeys.VIEW_STAGING)
        && (permissionChecker.hasPermission(
                groupId, Group.class.getName(), groupId, ActionKeys.MANAGE_LAYOUTS)
            || permissionChecker.hasPermission(
                groupId, Group.class.getName(), groupId, ActionKeys.MANAGE_STAGING)
            || permissionChecker.hasPermission(
                groupId, Group.class.getName(), groupId, ActionKeys.PUBLISH_STAGING)
            || permissionChecker.hasPermission(
                groupId, Group.class.getName(), groupId, ActionKeys.UPDATE))) {

      return true;
    }

    // Group id must be set so that users can modify their personal pages

    if (permissionChecker.hasPermission(groupId, Group.class.getName(), groupId, actionId)) {

      return true;
    }

    while (!group.isRoot()) {
      if (contains(permissionChecker, group.getParentGroupId(), ActionKeys.MANAGE_SUBGROUPS)) {

        return true;
      }

      group = group.getParentGroup();
    }

    return false;
  }
  protected void sendEmail(WallEntry wallEntry, ThemeDisplay themeDisplay) throws Exception {

    long companyId = wallEntry.getCompanyId();

    String portalURL = PortalUtil.getPortalURL(themeDisplay);
    String layoutURL = PortalUtil.getLayoutURL(themeDisplay);

    String wallEntryURL = portalURL + layoutURL;

    Group group = GroupLocalServiceUtil.getGroup(wallEntry.getGroupId());

    User user = userLocalService.getUserById(group.getClassPK());
    User wallEntryUser = userLocalService.getUserById(wallEntry.getUserId());

    String fromName = PrefsPropsUtil.getString(companyId, "admin.email.from.name");
    String fromAddress = PrefsPropsUtil.getString(companyId, "admin.email.from.address");

    String toName = user.getFullName();
    String toAddress = user.getEmailAddress();

    ClassLoader classLoader = getClass().getClassLoader();

    String subject =
        StringUtil.read(
            classLoader,
            "com/liferay/socialnetworking/wall/dependencies/" + "wall_entry_added_subject.tmpl");
    String body =
        StringUtil.read(
            classLoader,
            "com/liferay/socialnetworking/wall/dependencies/" + "wall_entry_added_body.tmpl");

    subject =
        StringUtil.replace(
            subject,
            new String[] {
              "[$FROM_ADDRESS$]",
              "[$FROM_NAME$]",
              "[$TO_ADDRESS$]",
              "[$TO_NAME$]",
              "[$WALL_ENTRY_URL$]",
              "[$WALL_ENTRY_USER_ADDRESS$]",
              "[$WALL_ENTRY_USER_NAME$]"
            },
            new String[] {
              fromAddress,
              fromName,
              toAddress,
              toName,
              wallEntryURL,
              wallEntryUser.getEmailAddress(),
              wallEntryUser.getFullName()
            });

    body =
        StringUtil.replace(
            body,
            new String[] {
              "[$FROM_ADDRESS$]",
              "[$FROM_NAME$]",
              "[$TO_ADDRESS$]",
              "[$TO_NAME$]",
              "[$WALL_ENTRY_URL$]",
              "[$WALL_ENTRY_USER_ADDRESS$]",
              "[$WALL_ENTRY_USER_NAME$]"
            },
            new String[] {
              fromAddress,
              fromName,
              toAddress,
              toName,
              wallEntryURL,
              wallEntryUser.getEmailAddress(),
              wallEntryUser.getFullName()
            });

    InternetAddress from = new InternetAddress(fromAddress, fromName);

    InternetAddress to = new InternetAddress(toAddress, toName);

    MailMessage mailMessage = new MailMessage(from, to, subject, body, true);

    MailServiceUtil.sendEmail(mailMessage);
  }
  /**
   * Records an activity with the given time in the database.
   *
   * <p>This method records a social activity done on an asset, identified by its class name and
   * class primary key, in the database. Additional information (such as the original message ID for
   * a reply to a forum post) is passed in via the <code>extraData</code> in JSON format. For
   * activities affecting another user, a mirror activity is generated that describes the action
   * from the user's point of view. The target user's ID is passed in via the <code>receiverUserId
   * </code>.
   *
   * <p>Example for a mirrored activity:<br>
   * When a user replies to a message boards post, the reply action is stored in the database with
   * the <code>receiverUserId</code> being the ID of the author of the original message. The <code>
   * extraData</code> contains the ID of the original message in JSON format. A mirror activity is
   * generated with the values of the <code>userId</code> and the <code>receiverUserId</code>
   * swapped. This mirror activity basically describes a "replied to" event.
   *
   * <p>Mirror activities are most often used in relation to friend requests and activities.
   *
   * @param userId the primary key of the acting user
   * @param groupId the primary key of the group
   * @param createDate the activity's date
   * @param className the target asset's class name
   * @param classPK the primary key of the target asset
   * @param type the activity's type
   * @param extraData any extra data regarding the activity
   * @param receiverUserId the primary key of the receiving user
   * @throws PortalException if the user or group could not be found
   * @throws SystemException if a system exception occurred
   */
  public void addActivity(
      long userId,
      long groupId,
      Date createDate,
      String className,
      long classPK,
      int type,
      String extraData,
      long receiverUserId)
      throws PortalException, SystemException {

    if (ImportExportThreadLocal.isImportInProcess()) {
      return;
    }

    User user = userPersistence.findByPrimaryKey(userId);
    long classNameId = PortalUtil.getClassNameId(className);

    if (groupId > 0) {
      Group group = groupLocalService.getGroup(groupId);

      if (group.isLayout()) {
        Layout layout = layoutLocalService.getLayout(group.getClassPK());

        groupId = layout.getGroupId();
      }
    }

    SocialActivity activity = socialActivityPersistence.create(0);

    activity.setGroupId(groupId);
    activity.setCompanyId(user.getCompanyId());
    activity.setUserId(user.getUserId());
    activity.setCreateDate(createDate.getTime());
    activity.setMirrorActivityId(0);
    activity.setClassNameId(classNameId);
    activity.setClassPK(classPK);
    activity.setType(type);
    activity.setExtraData(extraData);
    activity.setReceiverUserId(receiverUserId);

    AssetEntry assetEntry = assetEntryPersistence.fetchByC_C(classNameId, classPK);

    activity.setAssetEntry(assetEntry);

    SocialActivity mirrorActivity = null;

    if ((receiverUserId > 0) && (userId != receiverUserId)) {
      mirrorActivity = socialActivityPersistence.create(0);

      mirrorActivity.setGroupId(groupId);
      mirrorActivity.setCompanyId(user.getCompanyId());
      mirrorActivity.setUserId(receiverUserId);
      mirrorActivity.setCreateDate(createDate.getTime());
      mirrorActivity.setClassNameId(classNameId);
      mirrorActivity.setClassPK(classPK);
      mirrorActivity.setType(type);
      mirrorActivity.setExtraData(extraData);
      mirrorActivity.setReceiverUserId(user.getUserId());
      mirrorActivity.setAssetEntry(assetEntry);
    }

    socialActivityLocalService.addActivity(activity, mirrorActivity);
  }
  protected void doImportLayouts(
      long userId,
      long groupId,
      boolean privateLayout,
      Map<String, String[]> parameterMap,
      File file)
      throws Exception {

    boolean deleteMissingLayouts =
        MapUtil.getBoolean(
            parameterMap,
            PortletDataHandlerKeys.DELETE_MISSING_LAYOUTS,
            Boolean.TRUE.booleanValue());
    boolean deletePortletData =
        MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.DELETE_PORTLET_DATA);
    boolean importCategories = MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.CATEGORIES);
    boolean importPermissions =
        MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.PERMISSIONS);
    boolean importPublicLayoutPermissions =
        MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.PUBLIC_LAYOUT_PERMISSIONS);
    boolean importUserPermissions =
        MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.USER_PERMISSIONS);
    boolean importPortletData =
        MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.PORTLET_DATA);
    boolean importPortletSetup =
        MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.PORTLET_SETUP);
    boolean importPortletArchivedSetups =
        MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.PORTLET_ARCHIVED_SETUPS);
    boolean importPortletUserPreferences =
        MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.PORTLET_USER_PREFERENCES);
    boolean importTheme = MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.THEME);
    boolean importThemeSettings =
        MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.THEME_REFERENCE);
    boolean importLogo = MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.LOGO);
    boolean importLayoutSetSettings =
        MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.LAYOUT_SET_SETTINGS);

    boolean layoutSetPrototypeLinkEnabled =
        MapUtil.getBoolean(
            parameterMap, PortletDataHandlerKeys.LAYOUT_SET_PROTOTYPE_LINK_ENABLED, true);

    Group group = GroupLocalServiceUtil.getGroup(groupId);

    if (group.isLayoutSetPrototype()) {
      layoutSetPrototypeLinkEnabled = false;
    }

    boolean publishToRemote =
        MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.PUBLISH_TO_REMOTE);
    String layoutsImportMode =
        MapUtil.getString(
            parameterMap,
            PortletDataHandlerKeys.LAYOUTS_IMPORT_MODE,
            PortletDataHandlerKeys.LAYOUTS_IMPORT_MODE_MERGE_BY_LAYOUT_UUID);
    String portletsMergeMode =
        MapUtil.getString(
            parameterMap,
            PortletDataHandlerKeys.PORTLETS_MERGE_MODE,
            PortletDataHandlerKeys.PORTLETS_MERGE_MODE_REPLACE);
    String userIdStrategy =
        MapUtil.getString(parameterMap, PortletDataHandlerKeys.USER_ID_STRATEGY);

    if (_log.isDebugEnabled()) {
      _log.debug("Delete portlet data " + deletePortletData);
      _log.debug("Import categories " + importCategories);
      _log.debug("Import permissions " + importPermissions);
      _log.debug("Import user permissions " + importUserPermissions);
      _log.debug("Import portlet data " + importPortletData);
      _log.debug("Import portlet setup " + importPortletSetup);
      _log.debug("Import portlet archived setups " + importPortletArchivedSetups);
      _log.debug("Import portlet user preferences " + importPortletUserPreferences);
      _log.debug("Import theme " + importTheme);
    }

    StopWatch stopWatch = null;

    if (_log.isInfoEnabled()) {
      stopWatch = new StopWatch();

      stopWatch.start();
    }

    LayoutCache layoutCache = new LayoutCache();

    LayoutSet layoutSet = LayoutSetLocalServiceUtil.getLayoutSet(groupId, privateLayout);

    long companyId = layoutSet.getCompanyId();

    User user = UserUtil.findByPrimaryKey(userId);

    UserIdStrategy strategy = _portletImporter.getUserIdStrategy(user, userIdStrategy);

    ZipReader zipReader = ZipReaderFactoryUtil.getZipReader(file);

    PortletDataContext portletDataContext =
        new PortletDataContextImpl(
            companyId, groupId, parameterMap, new HashSet<String>(), strategy, zipReader);

    portletDataContext.setPortetDataContextListener(
        new PortletDataContextListenerImpl(portletDataContext));

    portletDataContext.setPrivateLayout(privateLayout);

    // Zip

    Element rootElement = null;
    InputStream themeZip = null;

    // Manifest

    String xml = portletDataContext.getZipEntryAsString("/manifest.xml");

    if (xml == null) {
      throw new LARFileException("manifest.xml not found in the LAR");
    }

    try {
      Document document = SAXReaderUtil.read(xml);

      rootElement = document.getRootElement();
    } catch (Exception e) {
      throw new LARFileException(e);
    }

    // Build compatibility

    Element headerElement = rootElement.element("header");

    int buildNumber = ReleaseInfo.getBuildNumber();

    int importBuildNumber = GetterUtil.getInteger(headerElement.attributeValue("build-number"));

    if (buildNumber != importBuildNumber) {
      throw new LayoutImportException(
          "LAR build number "
              + importBuildNumber
              + " does not match "
              + "portal build number "
              + buildNumber);
    }

    // Type compatibility

    String larType = headerElement.attributeValue("type");

    if (!larType.equals("layout-set") && !larType.equals("layout-set-prototype")) {

      throw new LARTypeException("Invalid type of LAR file (" + larType + ")");
    }

    // Group id

    long sourceGroupId = GetterUtil.getLong(headerElement.attributeValue("group-id"));

    portletDataContext.setSourceGroupId(sourceGroupId);

    // Layout set prototype

    if (group.isLayoutSetPrototype() && larType.equals("layout-set-prototype")) {

      LayoutSetPrototype layoutSetPrototype =
          LayoutSetPrototypeLocalServiceUtil.getLayoutSetPrototype(group.getClassPK());

      String layoutSetPrototypeUuid =
          GetterUtil.getString(headerElement.attributeValue("type-uuid"));

      LayoutSetPrototype existingLayoutSetPrototype = null;

      if (Validator.isNotNull(layoutSetPrototypeUuid)) {
        try {
          existingLayoutSetPrototype =
              LayoutSetPrototypeLocalServiceUtil.getLayoutSetPrototypeByUuid(
                  layoutSetPrototypeUuid);
        } catch (NoSuchLayoutSetPrototypeException nslspe) {
        }
      }

      if (existingLayoutSetPrototype == null) {
        layoutSetPrototype.setUuid(layoutSetPrototypeUuid);

        LayoutSetPrototypeLocalServiceUtil.updateLayoutSetPrototype(layoutSetPrototype);
      }
    }

    Element layoutsElement = rootElement.element("layouts");

    String layoutSetPrototypeUuid = layoutsElement.attributeValue("layout-set-prototype-uuid");

    ServiceContext serviceContext = ServiceContextThreadLocal.getServiceContext();

    if (Validator.isNotNull(layoutSetPrototypeUuid)) {
      if (layoutSetPrototypeLinkEnabled) {
        if (publishToRemote) {
          importLayoutSetPrototype(
              portletDataContext, user, layoutSetPrototypeUuid, serviceContext);
        }
      }

      layoutSet.setLayoutSetPrototypeUuid(layoutSetPrototypeUuid);
      layoutSet.setLayoutSetPrototypeLinkEnabled(layoutSetPrototypeLinkEnabled);

      LayoutSetLocalServiceUtil.updateLayoutSet(layoutSet);
    }

    // Look and feel

    if (importTheme) {
      themeZip = portletDataContext.getZipEntryAsInputStream("theme.zip");
    }

    // Look and feel

    String themeId = layoutSet.getThemeId();
    String colorSchemeId = layoutSet.getColorSchemeId();

    if (importThemeSettings) {
      Attribute themeIdAttribute = headerElement.attribute("theme-id");

      if (themeIdAttribute != null) {
        themeId = themeIdAttribute.getValue();
      }

      Attribute colorSchemeIdAttribute = headerElement.attribute("color-scheme-id");

      if (colorSchemeIdAttribute != null) {
        colorSchemeId = colorSchemeIdAttribute.getValue();
      }
    }

    if (importLogo) {
      String logoPath = headerElement.attributeValue("logo-path");

      byte[] iconBytes = portletDataContext.getZipEntryAsByteArray(logoPath);

      if ((iconBytes != null) && (iconBytes.length > 0)) {
        File logo = FileUtil.createTempFile(iconBytes);

        LayoutSetLocalServiceUtil.updateLogo(groupId, privateLayout, true, logo);
      } else {
        LayoutSetLocalServiceUtil.updateLogo(groupId, privateLayout, false, (File) null);
      }
    }

    if (importLayoutSetSettings) {
      String settings = GetterUtil.getString(headerElement.elementText("settings"));

      LayoutSetLocalServiceUtil.updateSettings(groupId, privateLayout, settings);
    }

    String css = GetterUtil.getString(headerElement.elementText("css"));

    if (themeZip != null) {
      String importThemeId = importTheme(layoutSet, themeZip);

      if (importThemeId != null) {
        themeId = importThemeId;
        colorSchemeId = ColorSchemeImpl.getDefaultRegularColorSchemeId();
      }

      if (_log.isDebugEnabled()) {
        _log.debug("Importing theme takes " + stopWatch.getTime() + " ms");
      }
    }

    boolean wapTheme = false;

    LayoutSetLocalServiceUtil.updateLookAndFeel(
        groupId, privateLayout, themeId, colorSchemeId, css, wapTheme);

    // Read asset categories, asset tags, comments, locks, permissions, and
    // ratings entries to make them available to the data handlers through
    // the context

    if (importPermissions) {
      _permissionImporter.readPortletDataPermissions(portletDataContext);
    }

    if (importCategories) {
      _portletImporter.readAssetCategories(portletDataContext);
    }

    _portletImporter.readAssetTags(portletDataContext);
    _portletImporter.readComments(portletDataContext);
    _portletImporter.readExpandoTables(portletDataContext);
    _portletImporter.readLocks(portletDataContext);
    _portletImporter.readRatingsEntries(portletDataContext);

    // Layouts

    List<Layout> previousLayouts = LayoutUtil.findByG_P(groupId, privateLayout);

    // Remove layouts that were deleted from the layout set prototype

    if (Validator.isNotNull(layoutSetPrototypeUuid) && layoutSetPrototypeLinkEnabled) {

      LayoutSetPrototype layoutSetPrototype =
          LayoutSetPrototypeLocalServiceUtil.getLayoutSetPrototypeByUuid(layoutSetPrototypeUuid);

      Group layoutSetPrototypeGroup = layoutSetPrototype.getGroup();

      for (Layout layout : previousLayouts) {
        String sourcePrototypeLayoutUuid = layout.getSourcePrototypeLayoutUuid();

        if (Validator.isNull(layout.getSourcePrototypeLayoutUuid())) {
          continue;
        }

        Layout sourcePrototypeLayout =
            LayoutUtil.fetchByUUID_G(
                sourcePrototypeLayoutUuid, layoutSetPrototypeGroup.getGroupId());

        if (sourcePrototypeLayout == null) {
          LayoutLocalServiceUtil.deleteLayout(layout, false, serviceContext);
        }
      }
    }

    List<Layout> newLayouts = new ArrayList<Layout>();

    Set<Long> newLayoutIds = new HashSet<Long>();

    Map<Long, Layout> newLayoutsMap =
        (Map<Long, Layout>) portletDataContext.getNewPrimaryKeysMap(Layout.class);

    List<Element> layoutElements = layoutsElement.elements("layout");

    if (_log.isDebugEnabled()) {
      if (layoutElements.size() > 0) {
        _log.debug("Importing layouts");
      }
    }

    for (Element layoutElement : layoutElements) {
      importLayout(
          portletDataContext,
          user,
          layoutCache,
          previousLayouts,
          newLayouts,
          newLayoutsMap,
          newLayoutIds,
          portletsMergeMode,
          themeId,
          colorSchemeId,
          layoutsImportMode,
          privateLayout,
          importPermissions,
          importPublicLayoutPermissions,
          importUserPermissions,
          importThemeSettings,
          rootElement,
          layoutElement);
    }

    Element portletsElement = rootElement.element("portlets");

    List<Element> portletElements = portletsElement.elements("portlet");

    // Delete portlet data

    if (deletePortletData) {
      if (_log.isDebugEnabled()) {
        if (portletElements.size() > 0) {
          _log.debug("Deleting portlet data");
        }
      }

      for (Element portletElement : portletElements) {
        String portletId = portletElement.attributeValue("portlet-id");
        long layoutId = GetterUtil.getLong(portletElement.attributeValue("layout-id"));
        long plid = newLayoutsMap.get(layoutId).getPlid();

        portletDataContext.setPlid(plid);

        _portletImporter.deletePortletData(portletDataContext, portletId, plid);
      }
    }

    // Import portlets

    if (_log.isDebugEnabled()) {
      if (portletElements.size() > 0) {
        _log.debug("Importing portlets");
      }
    }

    for (Element portletElement : portletElements) {
      String portletPath = portletElement.attributeValue("path");
      String portletId = portletElement.attributeValue("portlet-id");
      long layoutId = GetterUtil.getLong(portletElement.attributeValue("layout-id"));
      long plid = newLayoutsMap.get(layoutId).getPlid();
      long oldPlid = GetterUtil.getLong(portletElement.attributeValue("old-plid"));

      Portlet portlet =
          PortletLocalServiceUtil.getPortletById(portletDataContext.getCompanyId(), portletId);

      if (!portlet.isActive() || portlet.isUndeployedPortlet()) {
        continue;
      }

      Layout layout = null;

      try {
        layout = LayoutUtil.findByPrimaryKey(plid);
      } catch (NoSuchLayoutException nsle) {
        continue;
      }

      portletDataContext.setPlid(plid);
      portletDataContext.setOldPlid(oldPlid);

      Document portletDocument =
          SAXReaderUtil.read(portletDataContext.getZipEntryAsString(portletPath));

      portletElement = portletDocument.getRootElement();

      // The order of the import is important. You must always import
      // the portlet preferences first, then the portlet data, then
      // the portlet permissions. The import of the portlet data
      // assumes that portlet preferences already exist.

      _portletImporter.setPortletScope(portletDataContext, portletElement);

      try {

        // Portlet preferences

        _portletImporter.importPortletPreferences(
            portletDataContext,
            layoutSet.getCompanyId(),
            layout.getGroupId(),
            layout,
            null,
            portletElement,
            importPortletSetup,
            importPortletArchivedSetups,
            importPortletUserPreferences,
            false);

        // Portlet data

        Element portletDataElement = portletElement.element("portlet-data");

        if (importPortletData && (portletDataElement != null)) {
          _portletImporter.importPortletData(
              portletDataContext, portletId, plid, portletDataElement);
        }
      } finally {
        _portletImporter.resetPortletScope(portletDataContext, layout.getGroupId());
      }

      // Portlet permissions

      if (importPermissions) {
        _permissionImporter.importPortletPermissions(
            layoutCache,
            companyId,
            groupId,
            userId,
            layout,
            portletElement,
            portletId,
            importUserPermissions);
      }

      // Archived setups

      _portletImporter.importPortletPreferences(
          portletDataContext,
          layoutSet.getCompanyId(),
          groupId,
          null,
          null,
          portletElement,
          importPortletSetup,
          importPortletArchivedSetups,
          importPortletUserPreferences,
          false);
    }

    if (importPermissions) {
      if ((userId > 0)
          && ((PropsValues.PERMISSIONS_USER_CHECK_ALGORITHM == 5)
              || (PropsValues.PERMISSIONS_USER_CHECK_ALGORITHM == 6))) {

        Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);

        indexer.reindex(userId);
      }
    }

    // Asset links

    _portletImporter.readAssetLinks(portletDataContext);

    // Delete missing layouts

    if (deleteMissingLayouts) {
      deleteMissingLayouts(groupId, privateLayout, newLayoutIds, previousLayouts, serviceContext);
    }

    // Page count

    LayoutSetLocalServiceUtil.updatePageCount(groupId, privateLayout);

    if (_log.isInfoEnabled()) {
      _log.info("Importing layouts takes " + stopWatch.getTime() + " ms");
    }

    // Site

    GroupLocalServiceUtil.updateSite(groupId, true);

    // Web content layout type

    for (Layout layout : newLayouts) {
      UnicodeProperties typeSettingsProperties = layout.getTypeSettingsProperties();

      String articleId = typeSettingsProperties.getProperty("article-id");

      if (Validator.isNotNull(articleId)) {
        Map<String, String> articleIds =
            (Map<String, String>)
                portletDataContext.getNewPrimaryKeysMap(JournalArticle.class + ".articleId");

        typeSettingsProperties.setProperty(
            "article-id", MapUtil.getString(articleIds, articleId, articleId));

        LayoutUtil.update(layout, false);
      }
    }

    zipReader.close();
  }
  protected File doExportLayoutsAsFile(
      long groupId,
      boolean privateLayout,
      long[] layoutIds,
      Map<String, String[]> parameterMap,
      Date startDate,
      Date endDate)
      throws Exception {

    boolean exportCategories = MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.CATEGORIES);
    boolean exportIgnoreLastPublishDate =
        MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.IGNORE_LAST_PUBLISH_DATE);
    boolean exportPermissions =
        MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.PERMISSIONS);
    boolean exportUserPermissions =
        MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.USER_PERMISSIONS);
    boolean exportPortletArchivedSetups =
        MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.PORTLET_ARCHIVED_SETUPS);
    boolean exportPortletUserPreferences =
        MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.PORTLET_USER_PREFERENCES);
    boolean exportTheme = MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.THEME);
    boolean exportThemeSettings =
        MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.THEME_REFERENCE);
    boolean exportLogo = MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.LOGO);
    boolean exportLayoutSetSettings =
        MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.LAYOUT_SET_SETTINGS);
    boolean publishToRemote =
        MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.PUBLISH_TO_REMOTE);
    boolean updateLastPublishDate =
        MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.UPDATE_LAST_PUBLISH_DATE);

    if (_log.isDebugEnabled()) {
      _log.debug("Export categories " + exportCategories);
      _log.debug("Export permissions " + exportPermissions);
      _log.debug("Export user permissions " + exportUserPermissions);
      _log.debug("Export portlet archived setups " + exportPortletArchivedSetups);
      _log.debug("Export portlet user preferences " + exportPortletUserPreferences);
      _log.debug("Export theme " + exportTheme);
    }

    LayoutSet layoutSet = LayoutSetLocalServiceUtil.getLayoutSet(groupId, privateLayout);

    long companyId = layoutSet.getCompanyId();
    long defaultUserId = UserLocalServiceUtil.getDefaultUserId(companyId);

    ServiceContext serviceContext = ServiceContextThreadLocal.getServiceContext();

    if (serviceContext == null) {
      serviceContext = new ServiceContext();

      serviceContext.setCompanyId(companyId);
      serviceContext.setSignedIn(false);
      serviceContext.setUserId(defaultUserId);

      ServiceContextThreadLocal.pushServiceContext(serviceContext);
    }

    serviceContext.setAttribute("exporting", Boolean.TRUE);

    long layoutSetBranchId = MapUtil.getLong(parameterMap, "layoutSetBranchId");

    serviceContext.setAttribute("layoutSetBranchId", layoutSetBranchId);

    long lastPublishDate = System.currentTimeMillis();

    if (endDate != null) {
      lastPublishDate = endDate.getTime();
    }

    if (exportIgnoreLastPublishDate) {
      endDate = null;
      startDate = null;
    }

    StopWatch stopWatch = null;

    if (_log.isInfoEnabled()) {
      stopWatch = new StopWatch();

      stopWatch.start();
    }

    LayoutCache layoutCache = new LayoutCache();

    ZipWriter zipWriter = ZipWriterFactoryUtil.getZipWriter();

    PortletDataContext portletDataContext =
        new PortletDataContextImpl(
            companyId, groupId, parameterMap, new HashSet<String>(), startDate, endDate, zipWriter);

    portletDataContext.setPortetDataContextListener(
        new PortletDataContextListenerImpl(portletDataContext));

    Document document = SAXReaderUtil.createDocument();

    Element rootElement = document.addElement("root");

    Element headerElement = rootElement.addElement("header");

    headerElement.addAttribute("build-number", String.valueOf(ReleaseInfo.getBuildNumber()));
    headerElement.addAttribute("export-date", Time.getRFC822());

    if (portletDataContext.hasDateRange()) {
      headerElement.addAttribute("start-date", String.valueOf(portletDataContext.getStartDate()));
      headerElement.addAttribute("end-date", String.valueOf(portletDataContext.getEndDate()));
    }

    headerElement.addAttribute("group-id", String.valueOf(groupId));
    headerElement.addAttribute("private-layout", String.valueOf(privateLayout));

    Group group = layoutSet.getGroup();

    String type = "layout-set";

    if (group.isLayoutSetPrototype()) {
      type = "layout-set-prototype";

      LayoutSetPrototype layoutSetPrototype =
          LayoutSetPrototypeLocalServiceUtil.getLayoutSetPrototype(group.getClassPK());

      headerElement.addAttribute("type-uuid", layoutSetPrototype.getUuid());
    }

    headerElement.addAttribute("type", type);

    if (exportTheme || exportThemeSettings) {
      headerElement.addAttribute("theme-id", layoutSet.getThemeId());
      headerElement.addAttribute("color-scheme-id", layoutSet.getColorSchemeId());
    }

    if (exportLogo) {
      Image image = ImageLocalServiceUtil.getImage(layoutSet.getLogoId());

      if (image != null) {
        String logoPath = getLayoutSetLogoPath(portletDataContext);

        headerElement.addAttribute("logo-path", logoPath);

        portletDataContext.addZipEntry(logoPath, image.getTextObj());
      }
    }

    if (exportLayoutSetSettings) {
      Element settingsElement = headerElement.addElement("settings");

      settingsElement.addCDATA(layoutSet.getSettings());
    }

    Element cssElement = headerElement.addElement("css");

    cssElement.addCDATA(layoutSet.getCss());

    Portlet layoutConfigurationPortlet =
        PortletLocalServiceUtil.getPortletById(
            portletDataContext.getCompanyId(), PortletKeys.LAYOUT_CONFIGURATION);

    Map<String, Object[]> portletIds = new LinkedHashMap<String, Object[]>();

    List<Layout> layouts = null;

    if ((layoutIds == null) || (layoutIds.length == 0)) {
      layouts = LayoutLocalServiceUtil.getLayouts(groupId, privateLayout);
    } else {
      layouts = LayoutLocalServiceUtil.getLayouts(groupId, privateLayout, layoutIds);
    }

    List<Portlet> portlets = getAlwaysExportablePortlets(companyId);

    if (!layouts.isEmpty()) {
      Layout firstLayout = layouts.get(0);

      if (group.isStagingGroup()) {
        group = group.getLiveGroup();
      }

      for (Portlet portlet : portlets) {
        String portletId = portlet.getRootPortletId();

        if (!group.isStagedPortlet(portletId)) {
          continue;
        }

        String key = PortletPermissionUtil.getPrimaryKey(0, portletId);

        if (portletIds.get(key) == null) {
          portletIds.put(
              key,
              new Object[] {
                portletId, firstLayout.getPlid(), groupId, StringPool.BLANK, StringPool.BLANK
              });
        }
      }
    }

    Element layoutsElement = rootElement.addElement("layouts");

    String layoutSetPrototypeUuid = layoutSet.getLayoutSetPrototypeUuid();

    if (Validator.isNotNull(layoutSetPrototypeUuid)) {
      LayoutSetPrototype layoutSetPrototype =
          LayoutSetPrototypeLocalServiceUtil.getLayoutSetPrototypeByUuid(layoutSetPrototypeUuid);

      layoutsElement.addAttribute("layout-set-prototype-uuid", layoutSetPrototypeUuid);

      if (publishToRemote) {
        String path = getLayoutSetPrototype(portletDataContext, layoutSetPrototypeUuid);

        File layoutSetPrototypeFile = null;

        InputStream inputStream = null;

        try {
          layoutSetPrototypeFile =
              SitesUtil.exportLayoutSetPrototype(layoutSetPrototype, serviceContext);

          inputStream = new FileInputStream(layoutSetPrototypeFile);

          portletDataContext.addZipEntry(path.concat(".lar"), inputStream);
          portletDataContext.addZipEntry(path.concat(".xml"), layoutSetPrototype);
        } finally {
          StreamUtil.cleanUp(inputStream);

          FileUtil.delete(layoutSetPrototypeFile);
        }
      }
    }

    for (Layout layout : layouts) {
      exportLayout(
          portletDataContext,
          layoutConfigurationPortlet,
          layoutCache,
          portlets,
          portletIds,
          exportPermissions,
          exportUserPermissions,
          layout,
          layoutsElement);
    }

    if (PropsValues.PERMISSIONS_USER_CHECK_ALGORITHM < 5) {
      Element rolesElement = rootElement.addElement("roles");

      if (exportPermissions) {
        _permissionExporter.exportLayoutRoles(layoutCache, companyId, groupId, rolesElement);
      }
    }

    long previousScopeGroupId = portletDataContext.getScopeGroupId();

    Element portletsElement = rootElement.addElement("portlets");

    for (Map.Entry<String, Object[]> portletIdsEntry : portletIds.entrySet()) {

      Object[] portletObjects = portletIdsEntry.getValue();

      String portletId = null;
      long plid = 0;
      long scopeGroupId = 0;
      String scopeType = StringPool.BLANK;
      String scopeLayoutUuid = null;

      if (portletObjects.length == 4) {
        portletId = (String) portletIdsEntry.getValue()[0];
        plid = (Long) portletIdsEntry.getValue()[1];
        scopeGroupId = (Long) portletIdsEntry.getValue()[2];
        scopeLayoutUuid = (String) portletIdsEntry.getValue()[3];
      } else {
        portletId = (String) portletIdsEntry.getValue()[0];
        plid = (Long) portletIdsEntry.getValue()[1];
        scopeGroupId = (Long) portletIdsEntry.getValue()[2];
        scopeType = (String) portletIdsEntry.getValue()[3];
        scopeLayoutUuid = (String) portletIdsEntry.getValue()[4];
      }

      Layout layout = LayoutLocalServiceUtil.getLayout(plid);

      portletDataContext.setPlid(layout.getPlid());
      portletDataContext.setOldPlid(layout.getPlid());
      portletDataContext.setScopeGroupId(scopeGroupId);
      portletDataContext.setScopeType(scopeType);
      portletDataContext.setScopeLayoutUuid(scopeLayoutUuid);

      boolean[] exportPortletControls =
          getExportPortletControls(companyId, portletId, portletDataContext, parameterMap);

      _portletExporter.exportPortlet(
          portletDataContext,
          layoutCache,
          portletId,
          layout,
          portletsElement,
          defaultUserId,
          exportPermissions,
          exportPortletArchivedSetups,
          exportPortletControls[0],
          exportPortletControls[1],
          exportPortletUserPreferences,
          exportUserPermissions);
    }

    portletDataContext.setScopeGroupId(previousScopeGroupId);

    if (exportCategories) {
      exportAssetCategories(portletDataContext);
    }

    _portletExporter.exportAssetLinks(portletDataContext);
    _portletExporter.exportAssetTags(portletDataContext);
    _portletExporter.exportComments(portletDataContext);
    _portletExporter.exportExpandoTables(portletDataContext);
    _portletExporter.exportLocks(portletDataContext);

    if (exportPermissions) {
      _permissionExporter.exportPortletDataPermissions(portletDataContext);
    }

    _portletExporter.exportRatingsEntries(portletDataContext, rootElement);

    if (exportTheme && !portletDataContext.isPerformDirectBinaryImport()) {
      exportTheme(layoutSet, zipWriter);
    }

    if (_log.isInfoEnabled()) {
      if (stopWatch != null) {
        _log.info("Exporting layouts takes " + stopWatch.getTime() + " ms");
      } else {
        _log.info("Exporting layouts is finished");
      }
    }

    portletDataContext.addZipEntry("/manifest.xml", document.formattedString());

    try {
      return zipWriter.getFile();
    } finally {
      if (updateLastPublishDate) {
        updateLastPublishDate(layoutSet, lastPublishDate);
      }
    }
  }
  protected File doExportLayoutsAsFile(
      long groupId,
      boolean privateLayout,
      long[] layoutIds,
      Map<String, String[]> parameterMap,
      Date startDate,
      Date endDate)
      throws Exception {

    boolean exportCategories = MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.CATEGORIES);
    boolean exportIgnoreLastPublishDate =
        MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.IGNORE_LAST_PUBLISH_DATE);
    boolean exportPermissions =
        MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.PERMISSIONS);
    boolean exportPortletDataAll =
        MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.PORTLET_DATA_ALL);
    boolean exportTheme = MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.THEME);
    boolean exportThemeSettings =
        MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.THEME_REFERENCE);
    boolean exportLogo = MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.LOGO);
    boolean exportLayoutSetSettings =
        MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.LAYOUT_SET_SETTINGS);
    boolean updateLastPublishDate =
        MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.UPDATE_LAST_PUBLISH_DATE);

    if (_log.isDebugEnabled()) {
      _log.debug("Export permissions " + exportPermissions);
      _log.debug("Export theme " + exportTheme);
    }

    LayoutSet layoutSet = LayoutSetLocalServiceUtil.getLayoutSet(groupId, privateLayout);

    long companyId = layoutSet.getCompanyId();
    long defaultUserId = UserLocalServiceUtil.getDefaultUserId(companyId);

    ServiceContext serviceContext = ServiceContextThreadLocal.getServiceContext();

    if (serviceContext == null) {
      serviceContext = new ServiceContext();

      serviceContext.setCompanyId(companyId);
      serviceContext.setSignedIn(false);
      serviceContext.setUserId(defaultUserId);

      ServiceContextThreadLocal.pushServiceContext(serviceContext);
    }

    serviceContext.setAttribute("exporting", Boolean.TRUE);

    long layoutSetBranchId = MapUtil.getLong(parameterMap, "layoutSetBranchId");

    serviceContext.setAttribute("layoutSetBranchId", layoutSetBranchId);

    long lastPublishDate = System.currentTimeMillis();

    if (endDate != null) {
      lastPublishDate = endDate.getTime();
    }

    if (exportIgnoreLastPublishDate) {
      endDate = null;
      startDate = null;
    }

    StopWatch stopWatch = null;

    if (_log.isInfoEnabled()) {
      stopWatch = new StopWatch();

      stopWatch.start();
    }

    LayoutCache layoutCache = new LayoutCache();

    ZipWriter zipWriter = ZipWriterFactoryUtil.getZipWriter();

    PortletDataContext portletDataContext =
        PortletDataContextFactoryUtil.createExportPortletDataContext(
            companyId, groupId, parameterMap, startDate, endDate, zipWriter);

    portletDataContext.setPortetDataContextListener(
        new PortletDataContextListenerImpl(portletDataContext));

    Document document = SAXReaderUtil.createDocument();

    Element rootElement = document.addElement("root");

    portletDataContext.setExportDataRootElement(rootElement);

    Element headerElement = rootElement.addElement("header");

    headerElement.addAttribute(
        "available-locales",
        StringUtil.merge(LanguageUtil.getAvailableLocales(portletDataContext.getScopeGroupId())));
    headerElement.addAttribute("build-number", String.valueOf(ReleaseInfo.getBuildNumber()));
    headerElement.addAttribute("export-date", Time.getRFC822());

    if (portletDataContext.hasDateRange()) {
      headerElement.addAttribute("start-date", String.valueOf(portletDataContext.getStartDate()));
      headerElement.addAttribute("end-date", String.valueOf(portletDataContext.getEndDate()));
    }

    headerElement.addAttribute("company-id", String.valueOf(portletDataContext.getCompanyId()));
    headerElement.addAttribute(
        "company-group-id", String.valueOf(portletDataContext.getCompanyGroupId()));
    headerElement.addAttribute("group-id", String.valueOf(groupId));
    headerElement.addAttribute(
        "user-personal-site-group-id",
        String.valueOf(portletDataContext.getUserPersonalSiteGroupId()));
    headerElement.addAttribute("private-layout", String.valueOf(privateLayout));

    Group group = layoutSet.getGroup();

    String type = "layout-set";

    if (group.isLayoutPrototype()) {
      type = "layout-prototype";

      LayoutPrototype layoutPrototype =
          LayoutPrototypeLocalServiceUtil.getLayoutPrototype(group.getClassPK());

      headerElement.addAttribute("type-uuid", layoutPrototype.getUuid());
    } else if (group.isLayoutSetPrototype()) {
      type = "layout-set-prototype";

      LayoutSetPrototype layoutSetPrototype =
          LayoutSetPrototypeLocalServiceUtil.getLayoutSetPrototype(group.getClassPK());

      headerElement.addAttribute("type-uuid", layoutSetPrototype.getUuid());
    }

    headerElement.addAttribute("type", type);

    if (exportTheme || exportThemeSettings) {
      headerElement.addAttribute("theme-id", layoutSet.getThemeId());
      headerElement.addAttribute("color-scheme-id", layoutSet.getColorSchemeId());
    }

    if (exportLogo) {
      Image image = ImageLocalServiceUtil.getImage(layoutSet.getLogoId());

      if ((image != null) && (image.getTextObj() != null)) {
        String logoPath = ExportImportPathUtil.getRootPath(portletDataContext);

        logoPath += "/logo";

        headerElement.addAttribute("logo-path", logoPath);

        portletDataContext.addZipEntry(logoPath, image.getTextObj());
      }
    }

    if (exportLayoutSetSettings) {
      Element settingsElement = headerElement.addElement("settings");

      settingsElement.addCDATA(layoutSet.getSettings());
    }

    Element cssElement = headerElement.addElement("css");

    cssElement.addCDATA(layoutSet.getCss());

    Map<String, Object[]> portletIds = new LinkedHashMap<String, Object[]>();

    List<Layout> layouts = LayoutLocalServiceUtil.getLayouts(groupId, privateLayout);

    List<Portlet> portlets = getDataSiteLevelPortlets(companyId);

    long plid = LayoutConstants.DEFAULT_PLID;

    if (!layouts.isEmpty()) {
      Layout firstLayout = layouts.get(0);

      plid = firstLayout.getPlid();
    }

    if (group.isStagingGroup()) {
      group = group.getLiveGroup();
    }

    for (Portlet portlet : portlets) {
      String portletId = portlet.getRootPortletId();

      if (!group.isStagedPortlet(portletId)) {
        continue;
      }

      String key = PortletPermissionUtil.getPrimaryKey(0, portletId);

      if (portletIds.get(key) == null) {
        portletIds.put(
            key, new Object[] {portletId, plid, groupId, StringPool.BLANK, StringPool.BLANK});
      }
    }

    Element missingReferencesElement = rootElement.addElement("missing-references");

    portletDataContext.setMissingReferencesElement(missingReferencesElement);

    portletDataContext.addDeletionSystemEventStagedModelTypes(new StagedModelType(Layout.class));

    Element layoutsElement = portletDataContext.getExportDataGroupElement(Layout.class);

    String layoutSetPrototypeUuid = layoutSet.getLayoutSetPrototypeUuid();

    if (Validator.isNotNull(layoutSetPrototypeUuid)) {
      LayoutSetPrototype layoutSetPrototype =
          LayoutSetPrototypeLocalServiceUtil.getLayoutSetPrototypeByUuidAndCompanyId(
              layoutSetPrototypeUuid, companyId);

      layoutsElement.addAttribute("layout-set-prototype-uuid", layoutSetPrototypeUuid);

      layoutsElement.addAttribute(
          "layout-set-prototype-name", layoutSetPrototype.getName(LocaleUtil.getDefault()));
    }

    for (Layout layout : layouts) {
      exportLayout(portletDataContext, portlets, layoutIds, portletIds, layout);
    }

    long previousScopeGroupId = portletDataContext.getScopeGroupId();

    Element portletsElement = rootElement.addElement("portlets");

    for (Map.Entry<String, Object[]> portletIdsEntry : portletIds.entrySet()) {

      Object[] portletObjects = portletIdsEntry.getValue();

      String portletId = null;
      plid = LayoutConstants.DEFAULT_PLID;
      long scopeGroupId = 0;
      String scopeType = StringPool.BLANK;
      String scopeLayoutUuid = null;

      if (portletObjects.length == 4) {
        portletId = (String) portletIdsEntry.getValue()[0];
        plid = (Long) portletIdsEntry.getValue()[1];
        scopeGroupId = (Long) portletIdsEntry.getValue()[2];
        scopeLayoutUuid = (String) portletIdsEntry.getValue()[3];
      } else {
        portletId = (String) portletIdsEntry.getValue()[0];
        plid = (Long) portletIdsEntry.getValue()[1];
        scopeGroupId = (Long) portletIdsEntry.getValue()[2];
        scopeType = (String) portletIdsEntry.getValue()[3];
        scopeLayoutUuid = (String) portletIdsEntry.getValue()[4];
      }

      Layout layout = LayoutLocalServiceUtil.fetchLayout(plid);

      if (layout == null) {
        if (!group.isCompany() && (plid <= LayoutConstants.DEFAULT_PLID)) {

          continue;
        }

        if (_log.isWarnEnabled()) {
          _log.warn("Assuming global scope because no layout was found");
        }

        layout = new LayoutImpl();

        layout.setGroupId(groupId);
        layout.setCompanyId(companyId);
      }

      portletDataContext.setPlid(plid);
      portletDataContext.setOldPlid(plid);
      portletDataContext.setScopeGroupId(scopeGroupId);
      portletDataContext.setScopeType(scopeType);
      portletDataContext.setScopeLayoutUuid(scopeLayoutUuid);

      boolean[] exportPortletControls =
          getExportPortletControls(companyId, portletId, parameterMap, type);

      _portletExporter.exportPortlet(
          portletDataContext,
          layoutCache,
          portletId,
          layout,
          portletsElement,
          defaultUserId,
          exportPermissions,
          exportPortletControls[0],
          exportPortletControls[1],
          exportPortletControls[2],
          exportPortletControls[3]);
    }

    portletDataContext.setScopeGroupId(previousScopeGroupId);

    exportAssetCategories(
        portletDataContext, exportPortletDataAll, exportCategories, group.isCompany());

    _portletExporter.exportAssetLinks(portletDataContext);
    _portletExporter.exportAssetTags(portletDataContext);
    _portletExporter.exportComments(portletDataContext);
    _portletExporter.exportExpandoTables(portletDataContext);
    _portletExporter.exportLocks(portletDataContext);

    _deletionSystemEventExporter.exportDeletionSystemEvents(portletDataContext);

    if (exportPermissions) {
      _permissionExporter.exportPortletDataPermissions(portletDataContext);
    }

    _portletExporter.exportRatingsEntries(portletDataContext, rootElement);

    if (exportTheme && !portletDataContext.isPerformDirectBinaryImport()) {
      exportTheme(layoutSet, zipWriter);
    }

    ExportImportHelperUtil.writeManifestSummary(document, portletDataContext.getManifestSummary());

    if (_log.isInfoEnabled()) {
      if (stopWatch != null) {
        _log.info("Exporting layouts takes " + stopWatch.getTime() + " ms");
      } else {
        _log.info("Exporting layouts is finished");
      }
    }

    portletDataContext.addZipEntry("/manifest.xml", document.formattedString());

    try {
      return zipWriter.getFile();
    } finally {
      if (updateLastPublishDate) {
        updateLastPublishDate(layoutSet, lastPublishDate);
      }
    }
  }
  /**
   * Records an activity with the given time in the database.
   *
   * <p>This method records a social activity done on an asset, identified by its class name and
   * class primary key, in the database. Additional information (such as the original message ID for
   * a reply to a forum post) is passed in via the <code>extraData</code> in JSON format. For
   * activities affecting another user, a mirror activity is generated that describes the action
   * from the user's point of view. The target user's ID is passed in via the <code>receiverUserId
   * </code>.
   *
   * <p>Example for a mirrored activity:<br>
   * When a user replies to a message boards post, the reply action is stored in the database with
   * the <code>receiverUserId</code> being the ID of the author of the original message. The <code>
   * extraData</code> contains the ID of the original message in JSON format. A mirror activity is
   * generated with the values of the <code>userId</code> and the <code>receiverUserId</code>
   * swapped. This mirror activity basically describes a "replied to" event.
   *
   * <p>Mirror activities are most often used in relation to friend requests and activities.
   *
   * @param userId the primary key of the acting user
   * @param groupId the primary key of the group
   * @param createDate the activity's date
   * @param className the target asset's class name
   * @param classPK the primary key of the target asset
   * @param type the activity's type
   * @param extraData any extra data regarding the activity
   * @param receiverUserId the primary key of the receiving user
   * @throws PortalException if the user or group could not be found
   */
  @Override
  public void addActivity(
      long userId,
      long groupId,
      Date createDate,
      String className,
      long classPK,
      int type,
      String extraData,
      long receiverUserId)
      throws PortalException {

    if (ExportImportThreadLocal.isImportInProcess()) {
      return;
    }

    User user = userPersistence.findByPrimaryKey(userId);
    long classNameId = classNameLocalService.getClassNameId(className);

    if (groupId > 0) {
      Group group = groupLocalService.getGroup(groupId);

      if (group.isLayout()) {
        Layout layout = layoutLocalService.getLayout(group.getClassPK());

        groupId = layout.getGroupId();
      }
    }

    final SocialActivity activity = socialActivityPersistence.create(0);

    activity.setGroupId(groupId);
    activity.setCompanyId(user.getCompanyId());
    activity.setUserId(user.getUserId());
    activity.setCreateDate(createDate.getTime());
    activity.setMirrorActivityId(0);
    activity.setClassNameId(classNameId);
    activity.setClassPK(classPK);

    SocialActivityHierarchyEntry activityHierarchyEntry =
        SocialActivityHierarchyEntryThreadLocal.peek();

    if (activityHierarchyEntry != null) {
      activity.setParentClassNameId(activityHierarchyEntry.getClassNameId());
      activity.setParentClassPK(activityHierarchyEntry.getClassPK());
    }

    activity.setType(type);
    activity.setExtraData(extraData);
    activity.setReceiverUserId(receiverUserId);

    AssetEntry assetEntry = assetEntryPersistence.fetchByC_C(classNameId, classPK);

    activity.setAssetEntry(assetEntry);

    SocialActivity mirrorActivity = null;

    if ((receiverUserId > 0) && (userId != receiverUserId)) {
      mirrorActivity = socialActivityPersistence.create(0);

      mirrorActivity.setGroupId(groupId);
      mirrorActivity.setCompanyId(user.getCompanyId());
      mirrorActivity.setUserId(receiverUserId);
      mirrorActivity.setCreateDate(createDate.getTime());
      mirrorActivity.setClassNameId(classNameId);
      mirrorActivity.setClassPK(classPK);

      if (activityHierarchyEntry != null) {
        mirrorActivity.setParentClassNameId(activityHierarchyEntry.getClassNameId());
        mirrorActivity.setParentClassPK(activityHierarchyEntry.getClassPK());
      }

      mirrorActivity.setType(type);
      mirrorActivity.setExtraData(extraData);
      mirrorActivity.setReceiverUserId(user.getUserId());
      mirrorActivity.setAssetEntry(assetEntry);
    }

    final SocialActivity finalMirrorActivity = mirrorActivity;

    Callable<Void> callable =
        new Callable<Void>() {

          @Override
          public Void call() throws Exception {
            socialActivityLocalService.addActivity(activity, finalMirrorActivity);

            return null;
          }
        };

    TransactionCommitCallbackUtil.registerCallback(callable);
  }
  protected boolean isViewableGroup(
      PermissionChecker permissionChecker,
      Layout layout,
      String controlPanelCategory,
      boolean checkResourcePermission)
      throws PortalException, SystemException {

    Group group = GroupLocalServiceUtil.getGroup(layout.getGroupId());

    // Inactive sites are not viewable

    if (!group.isActive()) {
      return false;
    } else if (group.isStagingGroup()) {
      Group liveGroup = group.getLiveGroup();

      if (!liveGroup.isActive()) {
        return false;
      }
    }

    // User private layouts are only viewable by the user and anyone who can
    // update the user. The user must also be active.

    if (group.isUser()) {
      long groupUserId = group.getClassPK();

      if (groupUserId == permissionChecker.getUserId()) {
        return true;
      }

      User groupUser = UserLocalServiceUtil.getUserById(groupUserId);

      if (!groupUser.isActive()) {
        return false;
      }

      if (layout.isPrivateLayout()) {
        if (GroupPermissionUtil.contains(
                permissionChecker, groupUser.getGroupId(), ActionKeys.MANAGE_LAYOUTS)
            || UserPermissionUtil.contains(
                permissionChecker,
                groupUserId,
                groupUser.getOrganizationIds(),
                ActionKeys.UPDATE)) {

          return true;
        }

        return false;
      }
    }

    // If the current group is staging, only users with editorial rights
    // can access it

    if (group.isStagingGroup()) {
      if (GroupPermissionUtil.contains(
          permissionChecker, group.getGroupId(), ActionKeys.VIEW_STAGING)) {

        return true;
      }

      return false;
    }

    // Control panel layouts are only viewable by authenticated users

    if (group.isControlPanel()) {
      if (!permissionChecker.isSignedIn()) {
        return false;
      }

      if (PortalPermissionUtil.contains(permissionChecker, ActionKeys.VIEW_CONTROL_PANEL)) {

        return true;
      }

      if (Validator.isNotNull(controlPanelCategory)) {
        return true;
      }

      return false;
    }

    // Site layouts are only viewable by users who are members of the site
    // or by users who can update the site

    if (group.isSite()) {
      if (GroupPermissionUtil.contains(
              permissionChecker, group.getGroupId(), ActionKeys.MANAGE_LAYOUTS)
          || GroupPermissionUtil.contains(
              permissionChecker, group.getGroupId(), ActionKeys.UPDATE)) {

        return true;
      }

      if (layout.isPrivateLayout() && !permissionChecker.isGroupMember(group.getGroupId())) {

        return false;
      }
    }

    // Organization site layouts are also viewable by users who belong to
    // the organization or by users who can update organization

    if (group.isCompany()) {
      return false;
    } else if (group.isLayoutPrototype()) {
      if (LayoutPrototypePermissionUtil.contains(
          permissionChecker, group.getClassPK(), ActionKeys.VIEW)) {

        return true;
      }

      return false;
    } else if (group.isLayoutSetPrototype()) {
      if (LayoutSetPrototypePermissionUtil.contains(
          permissionChecker, group.getClassPK(), ActionKeys.VIEW)) {

        return true;
      }

      return false;
    } else if (group.isOrganization()) {
      long organizationId = group.getOrganizationId();

      if (OrganizationLocalServiceUtil.hasUserOrganization(
          permissionChecker.getUserId(), organizationId, false, false)) {

        return true;
      } else if (OrganizationPermissionUtil.contains(
          permissionChecker, organizationId, ActionKeys.UPDATE)) {

        return true;
      }

      if (!PropsValues.ORGANIZATIONS_MEMBERSHIP_STRICT) {
        List<Organization> userOrgs =
            OrganizationLocalServiceUtil.getUserOrganizations(permissionChecker.getUserId());

        for (Organization organization : userOrgs) {
          for (Organization ancestorOrganization : organization.getAncestors()) {

            if (organizationId == ancestorOrganization.getOrganizationId()) {

              return true;
            }
          }
        }
      }
    } else if (group.isUserGroup()) {
      if (UserGroupPermissionUtil.contains(
          permissionChecker, group.getClassPK(), ActionKeys.UPDATE)) {

        return true;
      }
    }

    // Only check the actual Layout if all of the above failed

    if (containsWithoutViewableGroup(
        permissionChecker, layout, controlPanelCategory, ActionKeys.VIEW)) {

      return true;
    }

    // As a last resort, check if any top level pages are viewable by the
    // user

    List<Layout> layouts =
        LayoutLocalServiceUtil.getLayouts(
            layout.getGroupId(),
            layout.isPrivateLayout(),
            LayoutConstants.DEFAULT_PARENT_LAYOUT_ID);

    for (Layout curLayout : layouts) {
      if (!curLayout.isHidden()
          && containsWithoutViewableGroup(
              permissionChecker, curLayout, controlPanelCategory, ActionKeys.VIEW)) {

        return true;
      }
    }

    return false;
  }
  protected PortletPreferences getPortletSetup(
      long siteGroupId,
      Layout layout,
      String portletId,
      String defaultPreferences,
      boolean strictMode) {

    String originalPortletId = portletId;

    Portlet portlet = PortletLocalServiceUtil.getPortletById(layout.getCompanyId(), portletId);

    boolean uniquePerLayout = false;
    boolean uniquePerGroup = false;

    if (portlet.isPreferencesCompanyWide()) {
      portletId = PortletConstants.getRootPortletId(portletId);
    } else {
      if (portlet.isPreferencesUniquePerLayout()) {
        uniquePerLayout = true;

        if (portlet.isPreferencesOwnedByGroup()) {
          uniquePerGroup = true;
        }
      } else {
        if (portlet.isPreferencesOwnedByGroup()) {
          uniquePerGroup = true;
          portletId = PortletConstants.getRootPortletId(portletId);
        }
      }
    }

    long ownerId = PortletKeys.PREFS_OWNER_ID_DEFAULT;
    int ownerType = PortletKeys.PREFS_OWNER_TYPE_LAYOUT;
    long plid = layout.getPlid();

    Group group = GroupLocalServiceUtil.fetchGroup(siteGroupId);

    if ((group != null) && group.isLayout()) {
      plid = group.getClassPK();
    }

    if (PortletConstants.hasUserId(originalPortletId)) {
      ownerId = PortletConstants.getUserId(originalPortletId);
      ownerType = PortletKeys.PREFS_OWNER_TYPE_USER;
    } else if (!uniquePerLayout) {
      plid = PortletKeys.PREFS_PLID_SHARED;

      if (uniquePerGroup) {
        if (siteGroupId > LayoutConstants.DEFAULT_PLID) {
          ownerId = siteGroupId;
        } else {
          ownerId = layout.getGroupId();
        }

        ownerType = PortletKeys.PREFS_OWNER_TYPE_GROUP;
      } else {
        ownerId = layout.getCompanyId();
        ownerType = PortletKeys.PREFS_OWNER_TYPE_COMPANY;
      }
    }

    if (strictMode) {
      return PortletPreferencesLocalServiceUtil.getStrictPreferences(
          layout.getCompanyId(), ownerId, ownerType, plid, portletId);
    }

    return PortletPreferencesLocalServiceUtil.getPreferences(
        layout.getCompanyId(), ownerId, ownerType, plid, portletId, defaultPreferences);
  }