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>");
    }
  }
  protected void getRootFolders(CommandArgument argument, Document doc, Element foldersEl)
      throws Exception {

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

    groupParams.put("usersGroups", new Long(argument.getUserId()));

    List<Group> groups =
        GroupLocalServiceUtil.search(
            argument.getCompanyId(), null, null, groupParams, QueryUtil.ALL_POS, QueryUtil.ALL_POS);

    List<Organization> userOrgs =
        OrganizationLocalServiceUtil.getUserOrganizations(argument.getUserId(), true);

    for (Organization organization : userOrgs) {
      groups.add(0, organization.getGroup());
    }

    if (PropsValues.LAYOUT_USER_PRIVATE_LAYOUTS_ENABLED
        || PropsValues.LAYOUT_USER_PUBLIC_LAYOUTS_ENABLED) {

      Group userGroup =
          GroupLocalServiceUtil.getUserGroup(argument.getCompanyId(), argument.getUserId());

      groups.add(0, userGroup);
    }

    ThemeDisplay themeDisplay = argument.getThemeDisplay();

    long scopeGroupId = themeDisplay.getScopeGroupId();

    for (Group group : groups) {
      Element folderEl = doc.createElement("Folder");

      foldersEl.appendChild(folderEl);

      boolean setNameAttribute = false;

      if (group.hasStagingGroup()) {
        Group stagingGroup = group.getStagingGroup();

        if (stagingGroup.getGroupId() == scopeGroupId) {
          folderEl.setAttribute(
              "name",
              stagingGroup.getGroupId()
                  + " - "
                  + HtmlUtil.escape(stagingGroup.getDescriptiveName()));

          setNameAttribute = true;
        }
      }

      if (!setNameAttribute) {
        folderEl.setAttribute(
            "name", group.getGroupId() + " - " + HtmlUtil.escape(group.getDescriptiveName()));
      }
    }
  }
  @Override
  public boolean isChecked(Object obj) {
    Organization organization = (Organization) obj;

    try {
      Group group = organization.getGroup();

      return GroupLocalServiceUtil.hasRoleGroup(_role.getRoleId(), group.getGroupId());
    } catch (Exception e) {
      _log.error(e, e);

      return false;
    }
  }
  @Override
  public List<Group> getUserSitesGroups() throws PortalException {
    try {
      User user = getUser();

      List<Group> groups = new ArrayList<>();

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

      groupParams.put("active", true);
      groupParams.put("usersGroups", user.getUserId());

      List<Group> userSiteGroups =
          groupLocalService.search(
              user.getCompanyId(), null, groupParams, QueryUtil.ALL_POS, QueryUtil.ALL_POS);

      for (Group userSiteGroup : userSiteGroups) {
        if (SyncUtil.isSyncEnabled(userSiteGroup)) {
          userSiteGroup.setName(userSiteGroup.getDescriptiveName());

          groups.add(userSiteGroup);
        }
      }

      List<Organization> organizations =
          organizationLocalService.getOrganizations(
              user.getUserId(), QueryUtil.ALL_POS, QueryUtil.ALL_POS, null);

      for (Organization organization : organizations) {
        Group userOrganizationGroup = organization.getGroup();

        if (SyncUtil.isSyncEnabled(userOrganizationGroup)) {
          groups.add(userOrganizationGroup);
        }

        if (!GetterUtil.getBoolean(PropsUtil.get(PropsKeys.ORGANIZATIONS_MEMBERSHIP_STRICT))) {

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

            Group userAncestorOrganizationGroup = ancestorOrganization.getGroup();

            if (SyncUtil.isSyncEnabled(userAncestorOrganizationGroup)) {

              groups.add(userAncestorOrganizationGroup);
            }
          }
        }
      }

      if (PrefsPropsUtil.getBoolean(
          user.getCompanyId(),
          PortletPropsKeys.SYNC_ALLOW_USER_PERSONAL_SITES,
          PortletPropsValues.SYNC_ALLOW_USER_PERSONAL_SITES)) {

        groups.add(user.getGroup());
      }

      Collections.sort(groups, new GroupNameComparator());

      return ListUtil.unique(groups);
    } catch (PortalException pe) {
      throw new PortalException(pe.getClass().getName(), pe);
    }
  }
  @Override
  public String getDescriptiveName(Locale locale) throws PortalException {
    Group curGroup = this;

    String name = getName(locale);

    if (Validator.isNull(name)) {
      Locale siteDefaultLocale = PortalUtil.getSiteDefaultLocale(getGroupId());

      name = getName(siteDefaultLocale);
    }

    if (isCompany() && !isCompanyStagingGroup()) {
      name = LanguageUtil.get(locale, "global");
    } else if (isControlPanel()) {
      name = LanguageUtil.get(locale, "control-panel");
    } else if (isGuest()) {
      Company company = CompanyLocalServiceUtil.getCompany(getCompanyId());

      Account account = company.getAccount();

      name = account.getName();
    } else if (isLayout()) {
      Layout layout = LayoutLocalServiceUtil.getLayout(getClassPK());

      name = layout.getName(locale);
    } else if (isLayoutPrototype()) {
      LayoutPrototype layoutPrototype =
          LayoutPrototypeLocalServiceUtil.getLayoutPrototype(getClassPK());

      name = layoutPrototype.getName(locale);
    } else if (isLayoutSetPrototype()) {
      LayoutSetPrototype layoutSetPrototype =
          LayoutSetPrototypeLocalServiceUtil.getLayoutSetPrototype(getClassPK());

      name = layoutSetPrototype.getName(locale);
    } else if (isOrganization()) {
      long organizationId = getOrganizationId();

      Organization organization = OrganizationLocalServiceUtil.getOrganization(organizationId);

      name = organization.getName();

      curGroup = organization.getGroup();
    } else if (isUser()) {
      long userId = getClassPK();

      User user = UserLocalServiceUtil.getUser(userId);

      name = user.getFullName();
    } else if (isUserGroup()) {
      long userGroupId = getClassPK();

      UserGroup userGroup = UserGroupLocalServiceUtil.getUserGroup(userGroupId);

      name = userGroup.getName();
    } else if (isUserPersonalSite()) {
      name = LanguageUtil.get(locale, "user-personal-site");
    }

    if (curGroup.isStaged() && !curGroup.isStagedRemotely() && curGroup.isStagingGroup()) {

      Group liveGroup = getLiveGroup();

      name = liveGroup.getDescriptiveName(locale);
    }

    return name;
  }
  protected Organization updateOrganization(ActionRequest actionRequest) throws Exception {

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

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

    long parentOrganizationId =
        ParamUtil.getLong(
            actionRequest,
            "parentOrganizationSearchContainerPrimaryKeys",
            OrganizationConstants.DEFAULT_PARENT_ORGANIZATION_ID);
    String name = ParamUtil.getString(actionRequest, "name");
    int statusId = ParamUtil.getInteger(actionRequest, "statusId");
    String type = ParamUtil.getString(actionRequest, "type");
    long regionId = ParamUtil.getLong(actionRequest, "regionId");
    long countryId = ParamUtil.getLong(actionRequest, "countryId");
    String comments = ParamUtil.getString(actionRequest, "comments");
    boolean deleteLogo = ParamUtil.getBoolean(actionRequest, "deleteLogo");

    byte[] logoBytes = null;

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

    if (fileEntryId > 0) {
      FileEntry fileEntry = DLAppLocalServiceUtil.getFileEntry(fileEntryId);

      logoBytes = FileUtil.getBytes(fileEntry.getContentStream());
    }

    boolean site = ParamUtil.getBoolean(actionRequest, "site");
    List<Address> addresses = UsersAdminUtil.getAddresses(actionRequest);
    List<EmailAddress> emailAddresses = UsersAdminUtil.getEmailAddresses(actionRequest);
    List<OrgLabor> orgLabors = UsersAdminUtil.getOrgLabors(actionRequest);
    List<Phone> phones = UsersAdminUtil.getPhones(actionRequest);
    List<Website> websites = UsersAdminUtil.getWebsites(actionRequest);

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

    Organization organization = null;

    if (organizationId <= 0) {

      // Add organization

      organization =
          OrganizationServiceUtil.addOrganization(
              parentOrganizationId,
              name,
              type,
              regionId,
              countryId,
              statusId,
              comments,
              site,
              addresses,
              emailAddresses,
              orgLabors,
              phones,
              websites,
              serviceContext);
    } else {

      // Update organization

      organization =
          OrganizationServiceUtil.updateOrganization(
              organizationId,
              parentOrganizationId,
              name,
              type,
              regionId,
              countryId,
              statusId,
              comments,
              !deleteLogo,
              logoBytes,
              site,
              addresses,
              emailAddresses,
              orgLabors,
              phones,
              websites,
              serviceContext);
    }

    // Layout set prototypes

    long publicLayoutSetPrototypeId =
        ParamUtil.getLong(actionRequest, "publicLayoutSetPrototypeId");
    long privateLayoutSetPrototypeId =
        ParamUtil.getLong(actionRequest, "privateLayoutSetPrototypeId");
    boolean publicLayoutSetPrototypeLinkEnabled =
        ParamUtil.getBoolean(
            actionRequest, "publicLayoutSetPrototypeLinkEnabled", (publicLayoutSetPrototypeId > 0));
    boolean privateLayoutSetPrototypeLinkEnabled =
        ParamUtil.getBoolean(
            actionRequest,
            "privateLayoutSetPrototypeLinkEnabled",
            (privateLayoutSetPrototypeId > 0));

    Group organizationGroup = organization.getGroup();

    if (GroupPermissionUtil.contains(
        themeDisplay.getPermissionChecker(), organizationGroup, ActionKeys.UPDATE)) {

      SitesUtil.updateLayoutSetPrototypesLinks(
          organizationGroup,
          publicLayoutSetPrototypeId,
          privateLayoutSetPrototypeId,
          publicLayoutSetPrototypeLinkEnabled,
          privateLayoutSetPrototypeLinkEnabled);
    }

    // Reminder queries

    String reminderQueries = actionRequest.getParameter("reminderQueries");

    PortletPreferences portletPreferences = organization.getPreferences();

    LocalizationUtil.setLocalizedPreferencesValues(
        actionRequest, portletPreferences, "reminderQueries");

    portletPreferences.setValue("reminderQueries", reminderQueries);

    portletPreferences.store();

    return organization;
  }
  @Override
  public boolean contains(
      PermissionChecker permissionChecker, long userId, long[] organizationIds, String actionId) {

    if ((actionId.equals(ActionKeys.DELETE)
            || actionId.equals(ActionKeys.IMPERSONATE)
            || actionId.equals(ActionKeys.PERMISSIONS)
            || actionId.equals(ActionKeys.UPDATE))
        && PortalUtil.isOmniadmin(userId)
        && !permissionChecker.isOmniadmin()) {

      return false;
    }

    try {
      User user = null;

      if (userId != ResourceConstants.PRIMKEY_DNE) {
        user = UserLocalServiceUtil.getUserById(userId);

        Contact contact = user.getContact();

        if (permissionChecker.hasOwnerPermission(
                permissionChecker.getCompanyId(),
                User.class.getName(),
                userId,
                contact.getUserId(),
                actionId)
            || (permissionChecker.getUserId() == userId)) {

          return true;
        }
      }

      if (permissionChecker.hasPermission(0, User.class.getName(), userId, actionId)) {

        return true;
      }

      if (user == null) {
        return false;
      }

      if (organizationIds == null) {
        organizationIds = user.getOrganizationIds();
      }

      for (long organizationId : organizationIds) {
        Organization organization = OrganizationLocalServiceUtil.getOrganization(organizationId);

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

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

          Group organizationGroup = organization.getGroup();

          // Organization administrators can only manage normal users.
          // Owners can only manage normal users and administrators.

          if (UserGroupRoleLocalServiceUtil.hasUserGroupRole(
              user.getUserId(),
              organizationGroup.getGroupId(),
              RoleConstants.ORGANIZATION_OWNER,
              true)) {

            continue;
          } else if (UserGroupRoleLocalServiceUtil.hasUserGroupRole(
                  user.getUserId(),
                  organizationGroup.getGroupId(),
                  RoleConstants.ORGANIZATION_ADMINISTRATOR,
                  true)
              && !UserGroupRoleLocalServiceUtil.hasUserGroupRole(
                  permissionChecker.getUserId(),
                  organizationGroup.getGroupId(),
                  RoleConstants.ORGANIZATION_OWNER,
                  true)) {

            continue;
          }

          return true;
        }
      }
    } catch (Exception e) {
      _log.error(e, e);
    }

    return false;
  }