From 3fc010135bdc8275df2c525bf5322e8c8cf662ae Mon Sep 17 00:00:00 2001
From: fermin831 <fermin.hernandez@artica.es>
Date: Tue, 27 Feb 2018 11:04:49 +0100
Subject: [PATCH] [Console Tree view] Removed empty childs

---
 pandora_console/include/class/Tree.class.php | 32 ++++++++++++++++----
 1 file changed, 26 insertions(+), 6 deletions(-)

diff --git a/pandora_console/include/class/Tree.class.php b/pandora_console/include/class/Tree.class.php
index 507d1d2b1c..805e46376a 100644
--- a/pandora_console/include/class/Tree.class.php
+++ b/pandora_console/include/class/Tree.class.php
@@ -1212,12 +1212,7 @@ class Tree {
 		Tree::processCounters($groups);
 		// Filter groups and eliminates the reference to empty groups
 		if ($remove_empty) {
-			// Filter empty groups
-			$groups = array_filter($groups, function ($group) {
-				return (isset($group['counters']) &&
-						isset($group['counters']['total']) &&
-						!empty($group['counters']['total']));
-			});
+			$groups = Tree::deleteEmptyGroups($groups);
 		}
 		usort($groups, array("Tree", "cmpSortNames"));
 		return $groups;
@@ -1892,6 +1887,31 @@ class Tree {
 		}
 	}
 
+	/**
+	 * @brief Recursive function to remove the empty groups
+	 * 
+	 * @param groups All groups structure
+	 * 
+	 * @return new_groups A new groups structure without empty groups
+	 */
+	protected static function deleteEmptyGroups ($groups) {
+		$new_groups = array();
+		foreach ($groups as $group) {
+			// If a group is empty, do not add to new_groups.
+			if (!isset($group['counters']['total']) || $group['counters']['total'] == 0) {
+				continue;
+			}
+			// Tray to remove the children groups
+			if (!empty($group['children'])) {
+				$children = Tree::deleteEmptyGroups ($group['children']);
+				if (empty($children)) unset($group['children']);
+				else $group['children'] = $children;
+			}
+			$new_groups[] = $group;
+		}
+		return $new_groups;
+	}
+
 	private static function extractGroupsWithIDs ($groups, $ids_hash) {
 		$result_groups = array();
 		foreach ($groups as $group) {