protected void updateActive(ActionRequest actionRequest, String cmd) throws Exception {

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

    long groupId = ParamUtil.getLong(actionRequest, "groupId");

    if ((groupId == themeDisplay.getDoAsGroupId())
        || (groupId == themeDisplay.getScopeGroupId())
        || (groupId == getRefererGroupId(themeDisplay))) {

      throw new RequiredGroupException(
          String.valueOf(groupId), RequiredGroupException.CURRENT_GROUP);
    }

    Group group = GroupServiceUtil.getGroup(groupId);

    boolean active = false;

    if (cmd.equals(Constants.RESTORE)) {
      active = true;
    }

    ServiceContext serviceContext =
        ServiceContextFactory.getInstance(Group.class.getName(), actionRequest);

    GroupServiceUtil.updateGroup(
        groupId,
        group.getParentGroupId(),
        group.getName(),
        group.getDescription(),
        group.getType(),
        group.getFriendlyURL(),
        active,
        serviceContext);
  }
  protected Group addScopeGroup() throws Exception {
    Group group = GroupTestUtil.addGroup();

    Layout layout = LayoutTestUtil.addLayout(group.getGroupId(), ServiceTestUtil.randomString());

    String name = ServiceTestUtil.randomString();

    ServiceContext serviceContext = ServiceTestUtil.getServiceContext(group.getGroupId());

    Group scopeGroup =
        GroupLocalServiceUtil.addGroup(
            TestPropsValues.getUserId(),
            group.getParentGroupId(),
            Layout.class.getName(),
            layout.getPlid(),
            GroupConstants.DEFAULT_LIVE_GROUP_ID,
            name,
            ServiceTestUtil.randomString(),
            GroupConstants.TYPE_SITE_OPEN,
            true,
            GroupConstants.DEFAULT_MEMBERSHIP_RESTRICTION,
            StringPool.SLASH + FriendlyURLNormalizerUtil.normalize(name),
            false,
            true,
            serviceContext);

    return scopeGroup;
  }
  protected int[] getRoleTypes(long companyId, Group group, String modelResource) {

    int[] types = RoleConstants.TYPES_REGULAR_AND_SITE;

    if (isPortalModelResource(modelResource)) {
      if (modelResource.equals(Organization.class.getName())
          || modelResource.equals(User.class.getName())) {

        types = RoleConstants.TYPES_ORGANIZATION_AND_REGULAR;
      } else {
        types = RoleConstants.TYPES_REGULAR;
      }
    } else {
      if (group != null) {
        if (group.isLayout()) {
          try {
            group = GroupServiceUtil.getGroup(group.getParentGroupId());
          } catch (Exception e) {
          }
        }

        if (group.isOrganization()) {
          types = RoleConstants.TYPES_ORGANIZATION_AND_REGULAR_AND_SITE;
        } else if (group.isUser()) {
          types = RoleConstants.TYPES_REGULAR;
        }
      }
    }

    return types;
  }
  public static long[] getGroupIds(long groupId) throws PortalException, SystemException {

    Group scopeGroup = GroupLocalServiceUtil.getGroup(groupId);

    Group companyGroup = GroupLocalServiceUtil.getCompanyGroup(scopeGroup.getCompanyId());

    if (scopeGroup.isLayout()) {
      return new long[] {scopeGroup.getParentGroupId(), companyGroup.getGroupId()};
    } else {
      return new long[] {groupId, companyGroup.getGroupId()};
    }
  }
  @Test
  public void testVerifyWhenUpdatingGroup() throws Exception {
    Group group = MembershipPolicyTestUtil.addGroup();

    GroupServiceUtil.updateGroup(
        group.getGroupId(), group.getParentGroupId(),
        RandomTestUtil.randomString(), group.getDescription(),
        group.getType(), group.isManualMembership(),
        group.getMembershipRestriction(), group.getFriendlyURL(),
        group.isActive(), ServiceContextTestUtil.getServiceContext());

    Assert.assertTrue(isVerify());
  }
  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;
  }
  public Hits search(
      long companyId,
      long userId,
      String portletId,
      long groupId,
      long[] repositoryIds,
      String keywords,
      int start,
      int end) {

    try {
      SearchContext searchContext = new SearchContext();

      searchContext.setCompanyId(companyId);
      searchContext.setEnd(end);
      searchContext.setEntryClassNames(new String[] {DLFileEntryConstants.getClassName()});
      searchContext.setGroupIds(new long[] {groupId});

      Indexer indexer = IndexerRegistryUtil.getIndexer(DLFileEntryConstants.getClassName());

      searchContext.setSearchEngineId(indexer.getSearchEngineId());

      searchContext.setStart(start);
      searchContext.setUserId(userId);

      BooleanQuery contextQuery = BooleanQueryFactoryUtil.create(searchContext);

      contextQuery.addRequiredTerm(Field.PORTLET_ID, portletId);

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

        if (group.isLayout()) {
          contextQuery.addRequiredTerm(Field.SCOPE_GROUP_ID, groupId);

          groupId = group.getParentGroupId();
        }

        contextQuery.addRequiredTerm(Field.GROUP_ID, groupId);
      }

      if (ArrayUtil.isNotEmpty(repositoryIds)) {
        BooleanQuery repositoryIdsQuery = BooleanQueryFactoryUtil.create(searchContext);

        for (long repositoryId : repositoryIds) {
          try {
            if (userId > 0) {
              PermissionChecker permissionChecker = PermissionThreadLocal.getPermissionChecker();

              DLFolderPermission.check(permissionChecker, groupId, repositoryId, ActionKeys.VIEW);
            }

            if (repositoryId == DLFolderConstants.DEFAULT_PARENT_FOLDER_ID) {

              repositoryId = groupId;
            }

            TermQuery termQuery =
                TermQueryFactoryUtil.create(searchContext, "repositoryId", repositoryId);

            repositoryIdsQuery.add(termQuery, BooleanClauseOccur.SHOULD);
          } catch (Exception e) {
          }
        }

        contextQuery.add(repositoryIdsQuery, BooleanClauseOccur.MUST);
      }

      BooleanQuery searchQuery = BooleanQueryFactoryUtil.create(searchContext);

      searchQuery.addTerms(_KEYWORDS_FIELDS, keywords);

      BooleanQuery fullQuery = BooleanQueryFactoryUtil.create(searchContext);

      fullQuery.add(contextQuery, BooleanClauseOccur.MUST);

      List<BooleanClause> clauses = searchQuery.clauses();

      if (!clauses.isEmpty()) {
        fullQuery.add(searchQuery, BooleanClauseOccur.MUST);
      }

      return SearchEngineUtil.search(searchContext, fullQuery);
    } catch (Exception e) {
      throw new SystemException(e);
    }
  }
  @Override
  public Group updateGroup(
      long groupId,
      long parentGroupId,
      Map<Locale, String> nameMap,
      Map<Locale, String> descriptionMap,
      int type,
      boolean manualMembership,
      int membershipRestriction,
      String friendlyURL,
      boolean inheritContent,
      boolean active,
      ServiceContext serviceContext)
      throws PortalException {

    Group group = groupPersistence.findByPrimaryKey(groupId);

    GroupPermissionUtil.check(getPermissionChecker(), group, ActionKeys.UPDATE);

    if (group.getParentGroupId() != parentGroupId) {
      if (parentGroupId == GroupConstants.DEFAULT_PARENT_GROUP_ID) {
        PortalPermissionUtil.check(getPermissionChecker(), ActionKeys.ADD_COMMUNITY);
      } else {
        GroupPermissionUtil.check(getPermissionChecker(), parentGroupId, ActionKeys.ADD_COMMUNITY);
      }
    }

    if (group.isSite()) {
      Group oldGroup = group;

      List<AssetCategory> oldAssetCategories =
          assetCategoryLocalService.getCategories(Group.class.getName(), groupId);

      List<AssetTag> oldAssetTags = assetTagLocalService.getTags(Group.class.getName(), groupId);

      ExpandoBridge oldExpandoBridge = oldGroup.getExpandoBridge();

      Map<String, Serializable> oldExpandoAttributes = oldExpandoBridge.getAttributes();

      group =
          groupLocalService.updateGroup(
              groupId,
              parentGroupId,
              nameMap,
              descriptionMap,
              type,
              manualMembership,
              membershipRestriction,
              friendlyURL,
              inheritContent,
              active,
              serviceContext);

      SiteMembershipPolicyUtil.verifyPolicy(
          group, oldGroup, oldAssetCategories, oldAssetTags, oldExpandoAttributes, null);

      return group;
    } else {
      return groupLocalService.updateGroup(
          groupId,
          parentGroupId,
          nameMap,
          descriptionMap,
          type,
          manualMembership,
          membershipRestriction,
          friendlyURL,
          inheritContent,
          active,
          serviceContext);
    }
  }
  @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;
  }