From dad183cab943d05cacc91c55a9fd41e589d1fa1b Mon Sep 17 00:00:00 2001
From: Marcus Exner <marcus.exner@gmail.com>
Date: Tue, 23 Aug 2011 00:37:29 +0200
Subject: [PATCH] Fixing subuser_load_all to get back the parent ids if
 children is set to FALSE and only relations to subusers are
 considered.

If we have more then one relation defined with a user endpoint,  subuser_load_all would load all relations from or to a user object. This could be nodes or whatever, we only want users connected with other users via subuser relation. Not any other relation that is pointing to a user object.
---
 .../all/modules/contrib/subuser/subuser.module     |   20 +++++++++++++++++---
 1 files changed, 17 insertions(+), 3 deletions(-)

diff --git a/htdocs/sites/all/modules/contrib/subuser/subuser.module b/htdocs/sites/all/modules/contrib/subuser/subuser.module
index f6f3da5..05aae02 100644
--- a/htdocs/sites/all/modules/contrib/subuser/subuser.module
+++ b/htdocs/sites/all/modules/contrib/subuser/subuser.module
@@ -169,9 +169,23 @@ function subuser_user_register_form_submit($form, &$form_state) {
  */
 function subuser_load_all($account, $children = TRUE) {
   $users = array();
-  foreach (relation_query('user', $account->uid, (int) $children)->execute() as $result) {
-    $relation = relation_load($result->rid, $result->vid);
-    $users[$uid = (int) $relation->endpoints[LANGUAGE_NONE][0]['entity_id']] = $uid;
+  if ($children == TRUE) { // Get the first endpoint (index below = 0) if we want the subusers (=children) of a user.
+    foreach (relation_query('user', $account->uid, (int) $children)->execute() as $result) {
+	    $relation = relation_load($result->rid, $result->vid);
+	    if ($relation->relation_type == 'subuser') { 
+	    	//We need to check if we got a 'subuser' relation.
+	    	//If more than one relation type with user as endpoint is defined (and used)
+	    	//we would get a messy return array which holds other than user ids.
+	      $users[$uid = (int) $relation->endpoints[LANGUAGE_NONE][0]['entity_id']] = $uid;
+	    }
+    }
+  } else { //Get the second endpoint (index = 1) if we want the parents of a subuser.
+      foreach (relation_query('user', $account->uid, (int) $children)->execute() as $result) {
+      $relation = relation_load($result->rid, $result->vid);
+      if ($relation->relation_type == 'subuser') {
+        $users[$uid = (int) $relation->endpoints[LANGUAGE_NONE][1]['entity_id']] = $uid;
+      }
+    }  	
   }
   return $users;
 }
-- 
1.7.5.4

