/*
Static method, for internal usage only
Finds a user group with the given name and remembers the node ID for it. The first match is always used.
If $createMissingGroups is true, it will create any groups it does not find.
332650
static function getNodeAssignmentsForGroupName( $groupName,
                                $isFirstGroupAssignment,
                                &$defaultUserPlacement,
                                &$extraNodeAssignments,
                                $createMissingGroups,
                                $parentNodeID )
    {
        if ( !is_string( $groupName ) or $groupName === '' )
        {
            eZDebug::writeError( 'The groupName must be a non empty string. Bad groupName: ' . $groupName, __METHOD__ );
            return;
        }

        $db = eZDB::instance();
        $ini = eZINI::instance();
        $userGroupClassID = $ini->variable( "UserSettings", "UserGroupClassID" );

        $groupNameEscaped = $db->escapeString( $groupName );
        $groupQuery = "SELECT ezcontentobject_tree.node_id
                       FROM ezcontentobject, ezcontentobject_tree
                       WHERE ezcontentobject.name like '$groupNameEscaped'
                       AND ezcontentobject.id = ezcontentobject_tree.contentobject_id
                       AND ezcontentobject.contentclass_id = $userGroupClassID";
        $groupRows = $db->arrayQuery( $groupQuery );

        if ( count( $groupRows ) > 0 and $isFirstGroupAssignment )
        {
            $defaultUserPlacement = $groupRows[0]['node_id'];
            return;
        }
        else if ( count( $groupRows ) > 0 )
        {
            $extraNodeAssignments[] = $groupRows[0]['node_id'];
            return;
        }

        // Should we create user groups that are specified in LDAP, but not found in eZ Publish?
        if ( !$createMissingGroups )
        {
            return;
        }

        $newNodeIDs = self::publishNewUserGroup( array( $parentNodeID ), array( 'name' => $groupName ) );

        if ( count( $newNodeIDs ) > 0 and $isFirstGroupAssignment )
        {
            $defaultUserPlacement = $newNodeIDs[0]; // We only supplied one parent to publishNewUserGroup(), so there is only one node
        }
        else if ( count( $newNodeIDs ) > 0 )
        {
            $extraNodeAssignments[] = $newNodeIDs[0]; // We only supplied one parent to publishNewUserGroup(), so there is only one node
        }
    }
1317908
private void setUserGroupNames(String userName, String[] groupNames) {
    if (userName==null || userName.length()==0 ||
        groupNames== null || groupNames.length==0) {
      throw new IllegalArgumentException(
          "Parameters should not be null or an empty string/array");
    }
    for (int i=0; i<groupNames.length; i++) {
      if(groupNames[i] == null || groupNames[i].length() == 0) {
        throw new IllegalArgumentException("A null group name at index " + i);
      }
    }
    this.userName = userName;
    this.groupNames = groupNames;
  }
560431
private void iterateGroupNodes(long groupdId, NodeReader nodeReader)
    {
        // while the index can be a long, the value is always an int
        int currentPointer = (int) headPointers.get(groupdId);
        checkArgument(currentPointer != NULL, "valid group must have non-null head pointer");

        while (currentPointer != NULL) {
            checkState(currentPointer < nextNodePointer, "error, corrupt pointer; max valid %s, found %s", nextNodePointer, currentPointer);
            nodeReader.read(currentPointer);
            currentPointer = nextPointers.get(currentPointer);
        }
    }
616359
function getDefaultUsergroup()
    {
        $usergroups = Groups::get($this->getJname(), true);

        $groups = array();
        if ($usergroups !== null) {
	        $list = $this->getUsergroupList();
	        foreach ($list as $group) {
		        if(in_array($group->id, $usergroups)){
			        $groups[] = $group->name;
		        }
	        }
        }
        return $groups;
    }
500366
@Override
    public boolean contains(IEntityGroup group, IGroupMember member) throws GroupsException {
        boolean found = false;
        Iterator itr = (member.isGroup()) ? findMemberGroups(group) : findEntitiesForGroup(group);
        while (itr.hasNext() && !found) {
            found = member.equals(itr.next());
        }
        return found;
    }
120434
public function findByName($name)
	{
		$model = $this->createModel();

		$group = $model->where('name', '=', $name)->find();

		if ( ! $group->loaded() )
		{
			throw new GroupNotFoundException("A group could not be found with the name [$name].");
		}

		return $group;
	}
642266
public function checkUserGroupExistenceByName( $name, $parentGroupName = null )
    {
        if ( $parentGroupName )
        {
            // find parent group name
            $searchResults = $this->searchUserGroups( $parentGroupName );
            if ( empty( $searchResults ) )
            {
                throw new \Exception( "Could not find parent User Group with name '$parentGroupName'." );
            }
            $parentGroup = $this->loadUserGroup( $searchResults[0]->valueObject->contentInfo->id );
            $parentGroupLocationId = $searchResults[0]->valueObject->contentInfo->mainLocationId;
            $searchResults = $this->searchUserGroups( $name, $parentGroupLocationId );
        }
        else
        {
            $searchResults = $this->searchUserGroups( $name );
        }

        return empty( $searchResults ) ? false : true;
    }
70618
private boolean isSameGroup(Node node) {
        return node.getNodeType().equals(appContext.getConfig().getNodeType())
                && node.getGroup().equals(appContext.getConfig().getNodeGroup());
    }
542558
@Override
    public IEntityGroup find(String key) throws GroupsException {
        if (log.isDebugEnabled()) {
            log.debug(DEBUG_CLASS_NAME + ".find(): group key: " + key);
        }

        String path = getFilePathFromKey(key);
        File f = new File(path);

        GroupHolder groupHolder = cacheGet(key);

        if (groupHolder == null || (groupHolder.getLastModified() != f.lastModified())) {
            if (log.isDebugEnabled()) {
                log.debug(
                        DEBUG_CLASS_NAME
                                + ".find(): retrieving group from file system for "
                                + path);
            }

            if (!f.exists()) {
                if (log.isDebugEnabled()) {
                    log.debug(DEBUG_CLASS_NAME + ".find(): file does not exist: " + path);
                }
                return null;
            }

            IEntityGroup group = newInstance(f);
            groupHolder = new GroupHolder(group, f.lastModified());
            cachePut(key, groupHolder);
        }
        return groupHolder.getGroup();
    }
673276
function createGroup() {

  var aGroup = {
    name: unique('Administrators')
  };

  return application.createGroup(aGroup, function(err, createdGroup) {
    if (err) throw err;
    group = createdGroup;

    return addAccountToGroup(); //next quickstart step
  });
}
979631
function createGroup(name, done) {
  return getModels(function(m) {
    return m.collections.group.create({ name }, done);
  });
}
657992
private MembershipByUserGroupTypeWrapper findMembership(Session session, String id) throws Exception
   {
      IdComponents ids;
      try
      {
         ids = utils.splitId(id);
      }
      catch (IndexOutOfBoundsException e)
      {
         throw new ItemNotFoundException("Can not find membership by id=" + id, e);
      }

      Node groupNode = session.getNodeByUUID(ids.groupNodeId);
      Node refUserNode = groupNode.getNode(JCROrganizationServiceImpl.JOS_MEMBERSHIP).getNode(ids.userName);
      Node refTypeNode =
         refUserNode.getNode(ids.type.equals(MembershipTypeHandler.ANY_MEMBERSHIP_TYPE)
            ? JCROrganizationServiceImpl.JOS_MEMBERSHIP_TYPE_ANY : ids.type);

      String groupId = utils.getGroupIds(groupNode).groupId;

      MembershipImpl membership = new MembershipImpl();
      membership.setId(id);
      membership.setGroupId(groupId);
      membership.setMembershipType(ids.type);
      membership.setUserName(ids.userName);

      putInCache(membership);

      return new MembershipByUserGroupTypeWrapper(membership, refUserNode, refTypeNode);
   }
631750
function user_all_groups($username, $groups_filtering = '') {
        if ($username==NULL){ return (false); }
        if (!$this->_bind){ return (false); }
        $filter = "(&(objectCategory=group)(member:1.2.840.113556.1.4.1941:=".$username.")".$groups_filtering.")";
        // $fields = array($this->_group_cn_identifier,$this->_group_attribute,"distinguishedname");
        $fields = array("cn");
        $sr = ldap_search($this->_conn,$this->_base_dn,$filter, $fields);
        $group_entries = $this->rCountRemover(ldap_get_entries($this->_conn, $sr));

//echo "DEBUG: info group_entries\n";
//print_r($group_entries);
        
        $group_array = array();
        foreach ($group_entries as $group_entry) {
            $group_array[] = $group_entry['cn'][0];
        }
//echo "DEBUG: group_array\n";
//print_r($group_array);

        return ($group_array);
    }
100498
private Collection<Group> findGroups(Session session, Group parent, boolean recursive) throws Exception
   {
      List<Group> groups = new ArrayList<Group>();
      String parentId = parent == null ? "" : parent.getId();

      NodeIterator childNodes = utils.getGroupNode(session, parentId).getNodes();

      while (childNodes.hasNext())
      {
         Node groupNode = childNodes.nextNode();
         if (!groupNode.getName().startsWith(JCROrganizationServiceImpl.JOS_MEMBERSHIP))
         {
            Group group = readGroup(groupNode);
            groups.add(group);

            if (recursive)
            {
               groups.addAll(findGroups(session, group, recursive));
            }
         }
      }

      return groups;
   }
1118568
@Override
    @SuppressWarnings("unchecked")
    public Iterator findEntitiesForGroup(IEntityGroup group) throws GroupsException {

        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Searching Grouper for members of the group with key: " + group.getKey());
        }

        try {

            // execute a search for members of the specified group
            GcGetMembers getGroupsMembers = new GcGetMembers();
            getGroupsMembers.addGroupName(group.getLocalKey());
            getGroupsMembers.assignIncludeSubjectDetail(true);
            WsGetMembersResults results = getGroupsMembers.execute();

            if (results == null
                    || results.getResults() == null
                    || results.getResults().length == 0
                    || results.getResults()[0].getWsSubjects() == null) {
                LOGGER.debug("No members found for Grouper group with key " + group.getLocalKey());
                return Collections.<IGroupMember>emptyList().iterator();
            }

            WsSubject[] gInfos = results.getResults()[0].getWsSubjects();
            final List<IGroupMember> members = new ArrayList<IGroupMember>(gInfos.length);

            // add each result to the member list
            for (WsSubject gInfo : gInfos) {

                // if the member is not a group (aka person)
                if (!StringUtils.equals(gInfo.getSourceId(), "g:gsa")) {

                    if (LOGGER.isDebugEnabled()) {
                        LOGGER.debug(
                                "creating leaf member:"
                                        + gInfo.getId()
                                        + " and name: "
                                        + gInfo.getName()
                                        + " from group: "
                                        + group.getLocalKey());
                    }
                    // use the name instead of id as it shows better in the display
                    IGroupMember member = new EntityImpl(gInfo.getName(), IPerson.class);
                    members.add(member);
                }
            }

            // return an iterator for the assembled group
            return members.iterator();

        } catch (Exception e) {
            LOGGER.warn(
                    "Exception while attempting to retrieve "
                            + "member entities of group with key "
                            + group.getKey()
                            + " from Grouper web services: "
                            + e.getMessage());
            return Collections.<IGroupMember>emptyList().iterator();
        }
    }
481267
@Override
    public Set<Entity> getGroupsForMember(String memberName) {
        Set<Entity> groups = new HashSet<Entity>();
        if (StringUtils.isNotEmpty(memberName)) {
            EntityIdentifier[] identifiers =
                    GroupService.searchForEntities(
                            memberName,
                            GroupService.SearchMethod.DISCRETE,
                            EntityEnum.PERSON.getClazz());
            for (EntityIdentifier entityIdentifier : identifiers) {
                if (entityIdentifier.getType().equals(EntityEnum.PERSON.getClazz())) {
                    IGroupMember groupMember = GroupService.getGroupMember(entityIdentifier);
                    if (memberName.equalsIgnoreCase(groupMember.getKey())) {
                        Iterator it = GroupService.findParentGroups(groupMember);
                        while (it.hasNext()) {
                            IEntityGroup g = (IEntityGroup) it.next();
                            Entity e =
                                    EntityFactory.createEntity(
                                            g, EntityEnum.getEntityEnum(g.getLeafType(), true));
                            groups.add(e);
                        }
                        return groups;
                    }
                }
            }
        }
        return groups;
    }
31005
protected function createMissingSitesNode()
    {
        $this->dispatch(self::EVENT_NOTICE, sprintf('Checking for "%s" node ...', SiteService::SITES_ROOT_PATH));
        $rootNode = $this->contextFactory->create()->getRootNode();
        // We fetch the workspace to be sure it's known to the persistence manager and persist all
        // so the workspace and site node are persisted before we import any nodes to it.
        $rootNode->getContext()->getWorkspace();
        $this->persistenceManager->persistAll();
        $sitesNode = $rootNode->getNode(SiteService::SITES_ROOT_PATH);
        if ($sitesNode === null) {
            $taskDescription = sprintf('Create missing site node "<i>%s</i>"', SiteService::SITES_ROOT_PATH);
            $taskClosure = function () use ($rootNode) {
                $rootNode->createNode(NodePaths::getNodeNameFromPath(SiteService::SITES_ROOT_PATH));
                $this->persistenceManager->persistAll();
            };
            $this->dispatch(self::EVENT_TASK, $taskDescription, $taskClosure);
        }
    }