/**
   * Updates the role with the primary key.
   *
   * @param roleId the primary key of the role
   * @param name the role's new name
   * @param titleMap the new localized titles (optionally <code>null</code>) to replace those
   *     existing for the role
   * @param descriptionMap the new localized descriptions (optionally <code>null</code>) to replace
   *     those existing for the role
   * @param subtype the role's new subtype (optionally <code>null</code>)
   * @return the role with the primary key
   * @throws PortalException if a role with the primary could not be found or if the role's name was
   *     invalid
   * @throws SystemException if a system exception occurred
   */
  public Role updateRole(
      long roleId,
      String name,
      Map<Locale, String> titleMap,
      Map<Locale, String> descriptionMap,
      String subtype)
      throws PortalException, SystemException {

    Role role = rolePersistence.findByPrimaryKey(roleId);

    validate(roleId, role.getCompanyId(), role.getClassNameId(), name);

    if (PortalUtil.isSystemRole(role.getName())) {
      name = role.getName();
      subtype = null;
    }

    role.setName(name);
    role.setTitleMap(titleMap);
    role.setDescriptionMap(descriptionMap);
    role.setSubtype(subtype);

    rolePersistence.update(role, false);

    return role;
  }
  public void editRoleAssignments(ActionRequest actionRequest, ActionResponse actionResponse)
      throws Exception {

    long roleId = ParamUtil.getLong(actionRequest, "roleId");
    Role role = RoleLocalServiceUtil.getRole(roleId);

    if (role.getName().equals(RoleConstants.OWNER)) {
      throw new RoleAssignmentException(role.getName());
    }

    long[] addUserIds = StringUtil.split(ParamUtil.getString(actionRequest, "addUserIds"), 0L);
    long[] removeUserIds =
        StringUtil.split(ParamUtil.getString(actionRequest, "removeUserIds"), 0L);

    if (!ArrayUtil.isEmpty(addUserIds) || !ArrayUtil.isEmpty(removeUserIds)) {

      UserServiceUtil.addRoleUsers(roleId, addUserIds);
      UserServiceUtil.unsetRoleUsers(roleId, removeUserIds);
    }

    long[] addGroupIds = StringUtil.split(ParamUtil.getString(actionRequest, "addGroupIds"), 0L);
    long[] removeGroupIds =
        StringUtil.split(ParamUtil.getString(actionRequest, "removeGroupIds"), 0L);

    if (!ArrayUtil.isEmpty(addGroupIds) || !ArrayUtil.isEmpty(removeGroupIds)) {

      GroupServiceUtil.addRoleGroups(roleId, addGroupIds);
      GroupServiceUtil.unsetRoleGroups(roleId, removeGroupIds);
    }
  }
  public List<String> getActionIds(Role role) {
    List<String> actionIds = _rolesMap.get(role.getName());

    if (actionIds == null) {
      actionIds = new ArrayList<>();

      _rolesMap.put(role.getName(), actionIds);
    }

    return actionIds;
  }
  public void deletePermission(ActionRequest actionRequest, ActionResponse actionResponse)
      throws Exception {

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

    long roleId = ParamUtil.getLong(actionRequest, "roleId");
    String name = ParamUtil.getString(actionRequest, "name");
    int scope = ParamUtil.getInteger(actionRequest, "scope");
    String primKey = ParamUtil.getString(actionRequest, "primKey");
    String actionId = ParamUtil.getString(actionRequest, "actionId");

    Role role = RoleLocalServiceUtil.getRole(roleId);

    String roleName = role.getName();

    if (roleName.equals(RoleConstants.ADMINISTRATOR)
        || roleName.equals(RoleConstants.ORGANIZATION_ADMINISTRATOR)
        || roleName.equals(RoleConstants.ORGANIZATION_OWNER)
        || roleName.equals(RoleConstants.OWNER)
        || roleName.equals(RoleConstants.SITE_ADMINISTRATOR)
        || roleName.equals(RoleConstants.SITE_OWNER)) {

      throw new RolePermissionsException(roleName);
    }

    if (ResourceBlockLocalServiceUtil.isSupported(name)) {
      if (scope == ResourceConstants.SCOPE_GROUP) {
        ResourceBlockServiceUtil.removeGroupScopePermission(
            themeDisplay.getScopeGroupId(),
            themeDisplay.getCompanyId(),
            GetterUtil.getLong(primKey),
            name,
            roleId,
            actionId);
      } else {
        ResourceBlockServiceUtil.removeCompanyScopePermission(
            themeDisplay.getScopeGroupId(), themeDisplay.getCompanyId(), name, roleId, actionId);
      }
    } else {
      ResourcePermissionServiceUtil.removeResourcePermission(
          themeDisplay.getScopeGroupId(),
          themeDisplay.getCompanyId(),
          name,
          scope,
          primKey,
          roleId,
          actionId);
    }

    // Send redirect

    SessionMessages.add(actionRequest, "permissionDeleted");

    String redirect = PortalUtil.escapeRedirect(ParamUtil.getString(actionRequest, "redirect"));

    if (Validator.isNotNull(redirect)) {
      actionResponse.sendRedirect(redirect);
    }
  }
  public int compareTo(Role role) {
    int value = 0;

    value = getName().compareTo(role.getName());

    if (value != 0) {
      return value;
    }

    return 0;
  }
  /**
   * Derive default permissions based on the logic found in
   * portal-web/docroot/html/taglib/ui/input_permissions/page.jsp. Do not update this logic updating
   * the logic in the JSP.
   */
  public void deriveDefaultPermissions(long repositoryId, String modelName) throws PortalException {

    long siteGroupId = PortalUtil.getSiteGroupId(repositoryId);

    Group siteGroup = GroupLocalServiceUtil.getGroup(siteGroupId);

    Role defaultGroupRole = RoleLocalServiceUtil.getDefaultGroupRole(siteGroupId);

    List<String> groupPermissions = new ArrayList<String>();
    List<String> guestPermissions = new ArrayList<String>();

    String[] roleNames = {RoleConstants.GUEST, defaultGroupRole.getName()};

    List<String> supportedActions = ResourceActionsUtil.getModelResourceActions(modelName);
    List<String> groupDefaultActions =
        ResourceActionsUtil.getModelResourceGroupDefaultActions(modelName);
    List<String> guestDefaultActions =
        ResourceActionsUtil.getModelResourceGuestDefaultActions(modelName);
    List<String> guestUnsupportedActions =
        ResourceActionsUtil.getModelResourceGuestUnsupportedActions(modelName);

    for (String roleName : roleNames) {
      for (String action : supportedActions) {
        if (roleName.equals(RoleConstants.GUEST)
            && !guestUnsupportedActions.contains(action)
            && guestDefaultActions.contains(action)
            && siteGroup.hasPublicLayouts()) {

          guestPermissions.add(action);
        } else if (roleName.equals(defaultGroupRole.getName())
            && groupDefaultActions.contains(action)) {

          groupPermissions.add(action);
        }
      }
    }

    setGroupPermissions(groupPermissions.toArray(new String[groupPermissions.size()]));
    setGuestPermissions(guestPermissions.toArray(new String[guestPermissions.size()]));
  }
  @Override
  protected boolean hasPermissionImplicitlyGranted(
      PermissionChecker permissionChecker, Group group, Portlet portlet) throws Exception {

    List<UserGroupRole> userGroupRoles =
        UserGroupRoleLocalServiceUtil.getUserGroupRoles(permissionChecker.getUserId());

    for (UserGroupRole userGroupRole : userGroupRoles) {
      Role role = userGroupRole.getRole();

      String roleName = role.getName();

      if (roleName.equals(RoleConstants.ORGANIZATION_ADMINISTRATOR)
          || roleName.equals(RoleConstants.ORGANIZATION_OWNER)) {

        return true;
      }
    }

    List<Organization> organizations =
        OrganizationLocalServiceUtil.getUserOrganizations(permissionChecker.getUserId());

    for (Organization organization : organizations) {
      if (OrganizationPermissionUtil.contains(
          permissionChecker, organization, ActionKeys.MANAGE_USERS)) {

        return true;
      }

      if (OrganizationPermissionUtil.contains(
          permissionChecker, organization, ActionKeys.MANAGE_SUBORGANIZATIONS)) {

        return true;
      }

      /*if (OrganizationPermissionUtil.contains(
      		permissionChecker, organization.getOrganizationId(),
      		ActionKeys.VIEW)) {

      	return true;
      }*/
    }

    return false;
  }
  protected Set<Assignment> buildAssigments(String kaleoClassName, long kaleoClassPK)
      throws PortalException, SystemException {

    List<KaleoTaskAssignment> kaleoTaskAssignments =
        kaleoTaskAssignmentLocalService.getKaleoTaskAssignments(kaleoClassName, kaleoClassPK);

    Set<Assignment> assignments = new HashSet<Assignment>(kaleoTaskAssignments.size());

    for (KaleoTaskAssignment kaleoTaskAssignment : kaleoTaskAssignments) {
      String assigneeClassName = kaleoTaskAssignment.getAssigneeClassName();

      long assigneeClassPK = kaleoTaskAssignment.getAssigneeClassPK();

      Assignment assignment = null;

      if (assigneeClassName.equals(AssignmentType.SCRIPT.name())) {
        assignment =
            new ScriptAssignment(
                kaleoTaskAssignment.getAssigneeScript(),
                kaleoTaskAssignment.getAssigneeScriptLanguage(),
                kaleoTaskAssignment.getAssigneeScriptRequiredContexts());
      } else if (assigneeClassName.equals(ResourceAction.class.getName())) {
        assignment = new ResourceActionAssignment(kaleoTaskAssignment.getAssigneeActionId());
      } else if (assigneeClassName.equals(Role.class.getName())) {
        Role role = _roleLocalService.fetchRole(assigneeClassPK);

        assignment = new RoleAssignment(role.getName(), role.getTypeLabel());
      } else if (assigneeClassName.equals(User.class.getName())) {
        if (assigneeClassPK == 0) {
          assignment = new UserAssignment();
        } else {
          User user = _userLocalService.getUser(assigneeClassPK);

          assignment =
              new UserAssignment(user.getUserId(), user.getScreenName(), user.getEmailAddress());
        }
      }

      assignments.add(assignment);
    }

    return assignments;
  }
  @Override
  protected PortletPreferences doDeleteData(
      PortletDataContext portletDataContext,
      String portletId,
      PortletPreferences portletPreferences)
      throws Exception {

    if (portletDataContext.addPrimaryKey(RolesAdminPortletDataHandler.class, "deleteData")) {

      return portletPreferences;
    }

    List<Role> roles = RoleLocalServiceUtil.getRoles(portletDataContext.getCompanyId());

    for (Role role : roles) {
      if (!PortalUtil.isSystemRole(role.getName())) {
        RoleLocalServiceUtil.deleteRole(role);
      }
    }

    return portletPreferences;
  }
  protected void addNotificationRecipients(
      KaleoNotification kaleoNotification, Notification notification)
      throws PortalException, SystemException {

    List<KaleoNotificationRecipient> kaleoNotificationRecipients =
        kaleoNotificationRecipientLocalService.getKaleoNotificationRecipients(
            kaleoNotification.getKaleoNotificationId());

    for (KaleoNotificationRecipient kaleoNotificationRecipient : kaleoNotificationRecipients) {

      String recipientClassName = kaleoNotificationRecipient.getRecipientClassName();

      long recipientClassPK = kaleoNotificationRecipient.getRecipientClassPK();

      Recipient recipient = null;

      if (recipientClassName.equals(RecipientType.ADDRESS.name())) {
        recipient = new AddressRecipient(kaleoNotificationRecipient.getAddress());
      } else if (recipientClassName.equals(RecipientType.ASSIGNEES.name())) {

        recipient = new AssigneesRecipient();
      } else if (recipientClassName.equals(Role.class.getName())) {
        Role role = _roleLocalService.fetchRole(recipientClassPK);

        recipient = new RoleRecipient(role.getName(), role.getTypeLabel());
      } else if (recipientClassName.equals(User.class.getName())) {
        if (recipientClassPK > 0) {
          User user = _userLocalService.getUser(recipientClassPK);

          recipient =
              new UserRecipient(user.getUserId(), user.getScreenName(), user.getEmailAddress());
        } else {
          recipient = new UserRecipient();
        }
      }

      notification.addRecipients(recipient);
    }
  }
  /**
   * Deletes the role and its associated permissions.
   *
   * @param role the role
   * @return the deleted role
   * @throws PortalException if the role is a default system role or if the role's resource could
   *     not be found
   * @throws SystemException if a system exception occurred
   */
  @Override
  public Role deleteRole(Role role) throws PortalException, SystemException {
    if (PortalUtil.isSystemRole(role.getName())) {
      throw new RequiredRoleException();
    }

    // Resources

    String className = role.getClassName();
    long classNameId = role.getClassNameId();

    if ((classNameId <= 0) || className.equals(Role.class.getName())) {
      resourceLocalService.deleteResource(
          role.getCompanyId(),
          Role.class.getName(),
          ResourceConstants.SCOPE_INDIVIDUAL,
          role.getRoleId());
    }

    if ((role.getType() == RoleConstants.TYPE_ORGANIZATION)
        || (role.getType() == RoleConstants.TYPE_SITE)) {

      userGroupRoleLocalService.deleteUserGroupRolesByRoleId(role.getRoleId());

      userGroupGroupRoleLocalService.deleteUserGroupGroupRolesByRoleId(role.getRoleId());
    }

    // Role

    rolePersistence.remove(role);

    // Permission cache

    PermissionCacheUtil.clearCache();

    return role;
  }
 @Override
 public String getDisplayName(Role role) {
   return role.getName();
 }
  @Override
  protected void doImportStagedModel(PortletDataContext portletDataContext, Role role)
      throws Exception {

    long userId = portletDataContext.getUserId(role.getUserUuid());

    ServiceContext serviceContext = portletDataContext.createServiceContext(role);

    Role existingRole =
        RoleLocalServiceUtil.fetchRoleByUuidAndCompanyId(
            role.getUuid(), portletDataContext.getCompanyId());

    if (existingRole == null) {
      existingRole =
          RoleLocalServiceUtil.fetchRole(portletDataContext.getCompanyId(), role.getName());
    }

    Role importedRole = null;

    if (existingRole == null) {
      serviceContext.setUuid(role.getUuid());

      importedRole =
          RoleLocalServiceUtil.addRole(
              userId,
              null,
              0,
              role.getName(),
              role.getTitleMap(),
              role.getDescriptionMap(),
              role.getType(),
              role.getSubtype(),
              serviceContext);
    } else {
      importedRole =
          RoleLocalServiceUtil.updateRole(
              existingRole.getRoleId(),
              role.getName(),
              role.getTitleMap(),
              role.getDescriptionMap(),
              role.getSubtype(),
              serviceContext);

      deleteRolePermissions(portletDataContext, importedRole);
    }

    String permissionsPath = ExportImportPathUtil.getModelPath(role, "permissions.xml");

    List<Permission> permissions =
        (List<Permission>) portletDataContext.getZipEntryAsObject(permissionsPath);

    for (Permission permission : permissions) {
      if (ResourceBlockLocalServiceUtil.isSupported(permission.getName())) {

        importResourceBlock(portletDataContext, importedRole, permission);
      } else {
        importResourcePermissions(portletDataContext, importedRole, permission);
      }
    }

    portletDataContext.importClassedModel(role, importedRole);
  }
 public RoleResponseElement(Role role) {
   _name = role.getName();
   _description = role.getDescription();
   _type = role.getTypeLabel();
 }
  public void addPermissions(String resourceName, long resourcePK)
      throws PortalException, SystemException {

    if (!MapUtil.getBoolean(_parameterMap, PortletDataHandlerKeys.PERMISSIONS)) {

      return;
    }

    List<KeyValuePair> permissions = new ArrayList<KeyValuePair>();

    Group group = GroupLocalServiceUtil.getGroup(_groupId);

    List<Role> roles = RoleLocalServiceUtil.getRoles(_companyId);

    PrimitiveLongList roleIds = new PrimitiveLongList(roles.size());
    Map<Long, String> roleIdsToNames = new HashMap<Long, String>();

    for (Role role : roles) {
      int type = role.getType();

      if ((type == RoleConstants.TYPE_REGULAR)
          || ((type == RoleConstants.TYPE_ORGANIZATION) && group.isOrganization())
          || ((type == RoleConstants.TYPE_SITE)
              && (group.isLayoutSetPrototype() || group.isSite()))) {

        String name = role.getName();

        roleIds.add(role.getRoleId());
        roleIdsToNames.put(role.getRoleId(), name);
      } else if ((type == RoleConstants.TYPE_PROVIDER) && role.isTeam()) {
        Team team = TeamLocalServiceUtil.getTeam(role.getClassPK());

        if (team.getGroupId() == _groupId) {
          String name = PermissionExporter.ROLE_TEAM_PREFIX + team.getName();

          roleIds.add(role.getRoleId());
          roleIdsToNames.put(role.getRoleId(), name);
        }
      }
    }

    List<String> actionIds = ResourceActionsUtil.getModelResourceActions(resourceName);

    Map<Long, Set<String>> roleIdsToActionIds =
        getActionIds(_companyId, roleIds.getArray(), resourceName, resourcePK, actionIds);

    for (Map.Entry<Long, String> entry : roleIdsToNames.entrySet()) {
      long roleId = entry.getKey();
      String name = entry.getValue();

      Set<String> availableActionIds = roleIdsToActionIds.get(roleId);

      if ((availableActionIds == null) || availableActionIds.isEmpty()) {
        continue;
      }

      KeyValuePair permission = new KeyValuePair(name, StringUtil.merge(availableActionIds));

      permissions.add(permission);
    }

    _permissionsMap.put(getPrimaryKeyString(resourceName, resourcePK), permissions);
  }
  /**
   * Checks to ensure that the system roles map has appropriate default roles in the company.
   *
   * @param companyId the primary key of the company
   * @throws PortalException if the current user did not have permission to set applicable
   *     permissions on a role
   * @throws SystemException if a system exception occurred
   */
  @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
  public void checkSystemRoles(long companyId) throws PortalException, SystemException {

    String companyIdHexString = StringUtil.toHexString(companyId);

    for (Role role : roleFinder.findBySystem(companyId)) {
      _systemRolesMap.put(companyIdHexString.concat(role.getName()), role);
    }

    // Regular roles

    String[] systemRoles = PortalUtil.getSystemRoles();

    for (String name : systemRoles) {
      String key =
          "system.role."
              + StringUtil.replace(name, CharPool.SPACE, CharPool.PERIOD)
              + ".description";

      Map<Locale, String> descriptionMap = new HashMap<Locale, String>();

      descriptionMap.put(LocaleUtil.getDefault(), PropsUtil.get(key));

      int type = RoleConstants.TYPE_REGULAR;

      checkSystemRole(companyId, name, descriptionMap, type);
    }

    // Organization roles

    String[] systemOrganizationRoles = PortalUtil.getSystemOrganizationRoles();

    for (String name : systemOrganizationRoles) {
      String key =
          "system.organization.role."
              + StringUtil.replace(name, CharPool.SPACE, CharPool.PERIOD)
              + ".description";

      Map<Locale, String> descriptionMap = new HashMap<Locale, String>();

      descriptionMap.put(LocaleUtil.getDefault(), PropsUtil.get(key));

      int type = RoleConstants.TYPE_ORGANIZATION;

      checkSystemRole(companyId, name, descriptionMap, type);
    }

    // Site roles

    String[] systemSiteRoles = PortalUtil.getSystemSiteRoles();

    for (String name : systemSiteRoles) {
      String key =
          "system.site.role."
              + StringUtil.replace(name, CharPool.SPACE, CharPool.PERIOD)
              + ".description";

      Map<Locale, String> descriptionMap = new HashMap<Locale, String>();

      descriptionMap.put(LocaleUtil.getDefault(), PropsUtil.get(key));

      int type = RoleConstants.TYPE_SITE;

      checkSystemRole(companyId, name, descriptionMap, type);
    }
  }
  public void updateActions(ActionRequest actionRequest, ActionResponse actionResponse)
      throws Exception {

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

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

    Role role = RoleLocalServiceUtil.getRole(roleId);

    String roleName = role.getName();

    if (roleName.equals(RoleConstants.ADMINISTRATOR)
        || roleName.equals(RoleConstants.ORGANIZATION_ADMINISTRATOR)
        || roleName.equals(RoleConstants.ORGANIZATION_OWNER)
        || roleName.equals(RoleConstants.OWNER)
        || roleName.equals(RoleConstants.SITE_ADMINISTRATOR)
        || roleName.equals(RoleConstants.SITE_OWNER)) {

      throw new RolePermissionsException(roleName);
    }

    String portletResource = ParamUtil.getString(actionRequest, "portletResource");
    String[] relatedPortletResources =
        StringUtil.split(ParamUtil.getString(actionRequest, "relatedPortletResources"));
    String[] modelResources =
        StringUtil.split(ParamUtil.getString(actionRequest, "modelResources"));

    Map<String, List<String>> resourceActionsMap = new HashMap<>();

    if (Validator.isNotNull(portletResource)) {
      resourceActionsMap.put(
          portletResource, ResourceActionsUtil.getResourceActions(portletResource, null));
    }

    for (String relatedPortletResource : relatedPortletResources) {
      resourceActionsMap.put(
          relatedPortletResource,
          ResourceActionsUtil.getResourceActions(relatedPortletResource, null));
    }

    for (String modelResource : modelResources) {
      resourceActionsMap.put(
          modelResource, ResourceActionsUtil.getResourceActions(null, modelResource));
    }

    int rootResourceScope = ResourceConstants.SCOPE_COMPANY;
    String[] rootResourceGroupIds = null;

    String[] selectedTargets =
        StringUtil.split(ParamUtil.getString(actionRequest, "selectedTargets"));
    String[] unselectedTargets =
        StringUtil.split(ParamUtil.getString(actionRequest, "unselectedTargets"));

    for (Map.Entry<String, List<String>> entry : resourceActionsMap.entrySet()) {

      String selResource = entry.getKey();
      List<String> actions = entry.getValue();

      actions = ListUtil.sort(actions, new ActionComparator(themeDisplay.getLocale()));

      for (String actionId : actions) {
        String target = selResource + actionId;

        boolean selected = ArrayUtil.contains(selectedTargets, target);

        if (!selected && !ArrayUtil.contains(unselectedTargets, target)) {

          continue;
        }

        String[] groupIds =
            StringUtil.split(ParamUtil.getString(actionRequest, "groupIds" + target));

        groupIds = ArrayUtil.distinct(groupIds);

        int scope = ResourceConstants.SCOPE_COMPANY;

        if ((role.getType() == RoleConstants.TYPE_ORGANIZATION)
            || (role.getType() == RoleConstants.TYPE_PROVIDER)
            || (role.getType() == RoleConstants.TYPE_SITE)) {

          scope = ResourceConstants.SCOPE_GROUP_TEMPLATE;
        } else {
          if (groupIds.length > 0) {
            scope = ResourceConstants.SCOPE_GROUP;
          }
        }

        if (ResourceBlockLocalServiceUtil.isSupported(selResource)) {
          updateActions_Blocks(
              role,
              themeDisplay.getScopeGroupId(),
              selResource,
              actionId,
              selected,
              scope,
              groupIds);
        } else {
          updateAction(
              role,
              themeDisplay.getScopeGroupId(),
              selResource,
              actionId,
              selected,
              scope,
              groupIds);
        }

        if (selected && actionId.equals(ActionKeys.ACCESS_IN_CONTROL_PANEL)) {

          updateViewControlPanelPermission(
              role, themeDisplay.getScopeGroupId(), selResource, scope, groupIds);

          rootResourceScope = scope;
          rootResourceGroupIds = groupIds;
        }
      }
    }

    // LPS-38031

    if (rootResourceGroupIds != null) {
      updateViewRootResourcePermission(
          role,
          themeDisplay.getScopeGroupId(),
          portletResource,
          rootResourceScope,
          rootResourceGroupIds);
    }

    // Send redirect

    SessionMessages.add(actionRequest, "permissionsUpdated");

    String redirect = PortalUtil.escapeRedirect(ParamUtil.getString(actionRequest, "redirect"));

    if (Validator.isNotNull(redirect)) {
      actionResponse.sendRedirect(redirect);
    }
  }
  protected Query doGetPermissionQuery_6(
      long companyId,
      long[] groupIds,
      long userId,
      String className,
      Query query,
      SearchContext searchContext,
      AdvancedPermissionChecker advancedPermissionChecker,
      List<Group> groups,
      List<Role> roles,
      List<UserGroupRole> userGroupRoles,
      Map<Long, List<Role>> groupIdsToRoles)
      throws Exception {

    BooleanQuery permissionQuery = BooleanQueryFactoryUtil.create(searchContext);

    if (userId > 0) {
      permissionQuery.addTerm(Field.USER_ID, userId);
    }

    BooleanQuery groupsQuery = BooleanQueryFactoryUtil.create(searchContext);
    BooleanQuery rolesQuery = BooleanQueryFactoryUtil.create(searchContext);

    for (Role role : roles) {
      String roleName = role.getName();

      if (roleName.equals(RoleConstants.ADMINISTRATOR)) {
        return query;
      }

      if (ResourcePermissionLocalServiceUtil.hasResourcePermission(
          companyId,
          className,
          ResourceConstants.SCOPE_COMPANY,
          String.valueOf(companyId),
          role.getRoleId(),
          ActionKeys.VIEW)) {

        return query;
      }

      if ((role.getType() == RoleConstants.TYPE_REGULAR)
          && ResourcePermissionLocalServiceUtil.hasResourcePermission(
              companyId,
              className,
              ResourceConstants.SCOPE_GROUP_TEMPLATE,
              String.valueOf(GroupConstants.DEFAULT_PARENT_GROUP_ID),
              role.getRoleId(),
              ActionKeys.VIEW)) {

        return query;
      }

      for (Group group : groups) {
        if (ResourcePermissionLocalServiceUtil.hasResourcePermission(
            companyId,
            className,
            ResourceConstants.SCOPE_GROUP,
            String.valueOf(group.getGroupId()),
            role.getRoleId(),
            ActionKeys.VIEW)) {

          groupsQuery.addTerm(Field.GROUP_ID, group.getGroupId());
        }

        if ((role.getType() != RoleConstants.TYPE_REGULAR)
            && ResourcePermissionLocalServiceUtil.hasResourcePermission(
                companyId,
                className,
                ResourceConstants.SCOPE_GROUP_TEMPLATE,
                String.valueOf(GroupConstants.DEFAULT_PARENT_GROUP_ID),
                role.getRoleId(),
                ActionKeys.VIEW)) {

          List<Role> groupRoles = groupIdsToRoles.get(group.getGroupId());

          if (groupRoles.contains(role)) {
            groupsQuery.addTerm(Field.GROUP_ID, group.getGroupId());
          }
        }

        if (group.isSite()
            && !roleName.equals(RoleConstants.SITE_MEMBER)
            && (role.getType() == RoleConstants.TYPE_SITE)) {

          rolesQuery.addTerm(
              Field.GROUP_ROLE_ID, group.getGroupId() + StringPool.DASH + role.getRoleId());
        }
      }

      rolesQuery.addTerm(Field.ROLE_ID, role.getRoleId());
    }

    for (Group group : groups) {
      addRequiredMemberRole(group, rolesQuery);
    }

    for (UserGroupRole userGroupRole : userGroupRoles) {
      rolesQuery.addTerm(
          Field.GROUP_ROLE_ID,
          userGroupRole.getGroupId() + StringPool.DASH + userGroupRole.getRoleId());
    }

    if (groupsQuery.hasClauses()) {
      permissionQuery.add(groupsQuery, BooleanClauseOccur.SHOULD);
    }

    if (rolesQuery.hasClauses()) {
      permissionQuery.add(rolesQuery, BooleanClauseOccur.SHOULD);
    }

    BooleanQuery fullQuery = BooleanQueryFactoryUtil.create(searchContext);

    fullQuery.add(query, BooleanClauseOccur.MUST);
    fullQuery.add(permissionQuery, BooleanClauseOccur.MUST);

    return fullQuery;
  }
  protected void updateActions(ActionRequest actionRequest, ActionResponse actionResponse)
      throws Exception {

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

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

    Role role = RoleLocalServiceUtil.getRole(roleId);

    String roleName = role.getName();

    if (roleName.equals(RoleConstants.ADMINISTRATOR)
        || roleName.equals(RoleConstants.ORGANIZATION_ADMINISTRATOR)
        || roleName.equals(RoleConstants.ORGANIZATION_OWNER)
        || roleName.equals(RoleConstants.OWNER)
        || roleName.equals(RoleConstants.SITE_ADMINISTRATOR)
        || roleName.equals(RoleConstants.SITE_OWNER)) {

      throw new RolePermissionsException(roleName);
    }

    String portletResource = ParamUtil.getString(actionRequest, "portletResource");
    String[] modelResources =
        StringUtil.split(ParamUtil.getString(actionRequest, "modelResources"));
    boolean showModelResources = ParamUtil.getBoolean(actionRequest, "showModelResources");

    Map<String, List<String>> resourceActionsMap = new HashMap<String, List<String>>();

    if (showModelResources) {
      for (String modelResource : modelResources) {
        resourceActionsMap.put(
            modelResource, ResourceActionsUtil.getResourceActions(null, modelResource));
      }
    } else if (Validator.isNotNull(portletResource)) {
      resourceActionsMap.put(
          portletResource, ResourceActionsUtil.getResourceActions(portletResource, null));
    }

    String[] selectedTargets =
        StringUtil.split(ParamUtil.getString(actionRequest, "selectedTargets"));

    for (Map.Entry<String, List<String>> entry : resourceActionsMap.entrySet()) {

      String selResource = entry.getKey();
      List<String> actions = entry.getValue();

      actions = ListUtil.sort(actions, new ActionComparator(themeDisplay.getLocale()));

      for (String actionId : actions) {
        String target = selResource + actionId;

        boolean selected = ArrayUtil.contains(selectedTargets, target);

        String[] groupIds =
            StringUtil.split(ParamUtil.getString(actionRequest, "groupIds" + target));

        groupIds = ArrayUtil.distinct(groupIds);

        int scope = ResourceConstants.SCOPE_COMPANY;

        if ((role.getType() == RoleConstants.TYPE_ORGANIZATION)
            || (role.getType() == RoleConstants.TYPE_PROVIDER)
            || (role.getType() == RoleConstants.TYPE_SITE)) {

          scope = ResourceConstants.SCOPE_GROUP_TEMPLATE;
        } else {
          if (groupIds.length > 0) {
            scope = ResourceConstants.SCOPE_GROUP;
          }
        }

        if (PropsValues.PERMISSIONS_USER_CHECK_ALGORITHM == 6) {
          if (ResourceBlockLocalServiceUtil.isSupported(selResource)) {

            updateActions_6Blocks(
                role,
                themeDisplay.getScopeGroupId(),
                selResource,
                actionId,
                selected,
                scope,
                groupIds);
          } else {
            updateAction_6(
                role,
                themeDisplay.getScopeGroupId(),
                selResource,
                actionId,
                selected,
                scope,
                groupIds);
          }
        } else {
          updateAction_1to5(
              role,
              themeDisplay.getScopeGroupId(),
              selResource,
              actionId,
              selected,
              scope,
              groupIds);
        }
      }
    }

    // Send redirect

    SessionMessages.add(actionRequest, "permissionsUpdated");

    String redirect = PortalUtil.escapeRedirect(ParamUtil.getString(actionRequest, "redirect"));

    if (Validator.isNotNull(redirect)) {
      redirect = redirect + "&" + Constants.CMD + "=" + Constants.VIEW;

      actionResponse.sendRedirect(redirect);
    }
  }
Beispiel #20
0
  protected void notifyUsers(AnnouncementsEntry entry) throws PortalException {

    Company company = companyPersistence.findByPrimaryKey(entry.getCompanyId());

    String className = entry.getClassName();
    long classPK = entry.getClassPK();

    String toName = PropsValues.ANNOUNCEMENTS_EMAIL_TO_NAME;
    String toAddress = PropsValues.ANNOUNCEMENTS_EMAIL_TO_ADDRESS;

    long teamId = 0;

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

    params.put("announcementsDeliveryEmailOrSms", entry.getType());

    if (classPK > 0) {
      if (className.equals(Group.class.getName())) {
        Group group = groupPersistence.findByPrimaryKey(classPK);

        toName = group.getDescriptiveName();

        params.put("inherit", Boolean.TRUE);
        params.put("usersGroups", classPK);
      } else if (className.equals(Organization.class.getName())) {
        Organization organization = organizationPersistence.findByPrimaryKey(classPK);

        toName = organization.getName();

        params.put("usersOrgsTree", ListUtil.fromArray(new Organization[] {organization}));
      } else if (className.equals(Role.class.getName())) {
        Role role = rolePersistence.findByPrimaryKey(classPK);

        toName = role.getName();

        if (role.getType() == RoleConstants.TYPE_REGULAR) {
          params.put("inherit", Boolean.TRUE);
          params.put("usersRoles", classPK);
        } else if (role.isTeam()) {
          teamId = role.getClassPK();
        } else {
          params.put("userGroupRole", new Long[] {Long.valueOf(0), classPK});
        }
      } else if (className.equals(UserGroup.class.getName())) {
        UserGroup userGroup = userGroupPersistence.findByPrimaryKey(classPK);

        toName = userGroup.getName();

        params.put("usersUserGroups", classPK);
      }
    }

    if (className.equals(User.class.getName())) {
      User user = userPersistence.findByPrimaryKey(classPK);

      if (Validator.isNull(user.getEmailAddress())) {
        return;
      }

      notifyUsers(
          ListUtil.fromArray(new User[] {user}),
          entry,
          company.getLocale(),
          user.getEmailAddress(),
          user.getFullName());
    } else {
      int count = 0;

      if (teamId > 0) {
        count = userLocalService.getTeamUsersCount(teamId);
      } else {
        count =
            userLocalService.searchCount(
                company.getCompanyId(), null, WorkflowConstants.STATUS_APPROVED, params);
      }

      int pages = count / Indexer.DEFAULT_INTERVAL;

      for (int i = 0; i <= pages; i++) {
        int start = (i * Indexer.DEFAULT_INTERVAL);
        int end = start + Indexer.DEFAULT_INTERVAL;

        List<User> users = null;

        if (teamId > 0) {
          users = userLocalService.getTeamUsers(teamId, start, end);
        } else {
          users =
              userLocalService.search(
                  company.getCompanyId(),
                  null,
                  WorkflowConstants.STATUS_APPROVED,
                  params,
                  start,
                  end,
                  (OrderByComparator<User>) null);
        }

        notifyUsers(users, entry, company.getLocale(), toAddress, toName);
      }
    }
  }