diff --git a/lib/navigationlib.php b/lib/navigationlib.php index 72db666906190..516eb8afc465b 100644 --- a/lib/navigationlib.php +++ b/lib/navigationlib.php @@ -2834,20 +2834,49 @@ protected function load_category($categoryid, $nodetype = self::TYPE_CATEGORY) { $this->add_category($category, $this, $nodetype); $basecategory = $this->addedcategories[$category->id]; } else { - $subcategories[] = $category; + $subcategories[$category->id] = $category; } } $categories->close(); - if (!is_null($basecategory)) { - foreach ($subcategories as $category) { - $this->add_category($category, $basecategory, $nodetype); - } - } - // If category is shown in MyHome then only show enrolled courses, else show all courses. + // If category is shown in MyHome then only show enrolled courses and hide empty subcategories, + // else show all courses. if ($nodetype === self::TYPE_MY_CATEGORY) { $courses = enrol_get_my_courses(); + $categoryids = array(); + + //only search for categories if basecategory was found + if (!is_null($basecategory)) { + // get course parent category ids + foreach ($courses as $course) { + $categoryids[] = $course->category; + } + + // get a unique list of category ids which a part of the path + // to user's courses + $course_subcategories = array(); + $added_subcategories = array(); + + list($sql, $params) = $DB->get_in_or_equal($categoryids); + $categories = $DB->get_recordset_select('course_categories', 'id '.$sql, $params, 'sortorder, id', 'id, path'); + + foreach ($categories as $category){ + $course_subcategories = array_merge($course_subcategories, explode('/', trim($category->path, "/"))); + } + $course_subcategories = array_unique($course_subcategories); + + // only add a subcategory if it is part of the path to user's course and + // wasn't already added + foreach ($subcategories as $sub_id => $subcategory) { + if (in_array($sub_id, $course_subcategories) && + !in_array($sub_id, $added_subcategories)) { + $this->add_category($subcategory, $basecategory, $nodetype); + $added_subcategories[] = $sub_id; + } + } + } + foreach ($courses as $course) { // Add course if it's in category. if (in_array($course->category, $categorylist)) { @@ -2855,6 +2884,11 @@ protected function load_category($categoryid, $nodetype = self::TYPE_CATEGORY) { } } } else { + if (!is_null($basecategory)) { + foreach ($subcategories as $key=>$category) { + $this->add_category($category, $basecategory, $nodetype); + } + } $courses = $DB->get_recordset('course', array('category' => $categoryid), 'sortorder', '*' , 0, $limit); foreach ($courses as $course) { $this->add_course($course);