From dd806c508cf884bd36590e68fccf502aad1be0b9 Mon Sep 17 00:00:00 2001
From: boombatower <jimmy@boombatower.com>
Date: Tue, 3 Jul 2012 01:47:46 -0500
Subject: Issue #1256938 by marcusx, roderik, and boombatower: Correct
 subuser_load_all().

---
 subuser.module |   33 ++++++++++++++++++++++++++++-----
 1 file changed, 28 insertions(+), 5 deletions(-)

diff --git a/subuser.module b/subuser.module
index d06838f..15469ee 100644
--- a/subuser.module
+++ b/subuser.module
@@ -168,12 +168,35 @@ function subuser_user_register_form_submit($form, &$form_state) {
  *   An associative array of related accounts were key and value is user ID.
  */
 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;
+  $related = &drupal_static(__FUNCTION__);
+
+  // Determine the index we need to look at based on the $children argument.
+  // The subuser relation has the child entity at index 0 and parent at 1. If
+  // $children is TRUE then we want to collect the uids from index 0, otherwise
+  // the uids from index 1.
+  $index = (int) !$children;
+
+  // Check to see if the related accounts are cached, otherwise load them.
+  if (!isset($related[$account->uid][$index])) {
+    // Select all user entities where the given account is either the parent or
+    // child based on the value of $children.
+    $results = relation_query('user', $account->uid, (int) $children)
+      ->entityCondition('bundle', 'subuser')
+      ->execute();
+
+    // Loop over results and collect uids.
+    $uids = array();
+    foreach ($results as $result) {
+      if ($relation = relation_load($result->rid, $result->vid)) {
+        $uids[$uid = (int) $relation->endpoints[LANGUAGE_NONE][$index]['entity_id']] = $uid;
+      }
+    }
+
+    // Store collected uids in static cache.
+    $related[$account->uid][$index] = $uids;
   }
-  return $users;
+
+  return $related[$account->uid][$index];
 }
 
 /**
-- 
1.7.10.4

