From afc3ef7bb4966650c542a82e55a16e8bd78cb02c Mon Sep 17 00:00:00 2001 From: Andrew Nicols Date: Wed, 30 Jul 2025 23:13:47 +0800 Subject: [PATCH 1/4] MDL-82159 core: Migrate navigation classes to new dirs --- .../navigation/breadcrumb_navigation_node.php | 66 + .../classes/navigation/flat_navigation.php | 156 + .../navigation/flat_navigation_node.php | 151 + .../classes/navigation/global_navigation.php | 2240 ++++++ .../navigation/global_navigation_for_ajax.php | 278 + public/lib/classes/navigation/navbar.php | 371 + .../classes/navigation/navigation_cache.php | 204 + .../classes/navigation/navigation_json.php | 121 + .../classes/navigation/navigation_node.php | 1017 +++ .../navigation/navigation_node_collection.php | 281 + .../navigation/settings_navigation.php | 1570 ++++ .../navigation/settings_navigation_ajax.php | 54 + public/lib/db/legacyclasses.php | 14 + public/lib/navigationlib.php | 6322 ----------------- 14 files changed, 6523 insertions(+), 6322 deletions(-) create mode 100644 public/lib/classes/navigation/breadcrumb_navigation_node.php create mode 100644 public/lib/classes/navigation/flat_navigation.php create mode 100644 public/lib/classes/navigation/flat_navigation_node.php create mode 100644 public/lib/classes/navigation/global_navigation.php create mode 100644 public/lib/classes/navigation/global_navigation_for_ajax.php create mode 100644 public/lib/classes/navigation/navbar.php create mode 100644 public/lib/classes/navigation/navigation_cache.php create mode 100644 public/lib/classes/navigation/navigation_json.php create mode 100644 public/lib/classes/navigation/navigation_node.php create mode 100644 public/lib/classes/navigation/navigation_node_collection.php create mode 100644 public/lib/classes/navigation/settings_navigation.php create mode 100644 public/lib/classes/navigation/settings_navigation_ajax.php diff --git a/public/lib/classes/navigation/breadcrumb_navigation_node.php b/public/lib/classes/navigation/breadcrumb_navigation_node.php new file mode 100644 index 00000000000..e688005e26b --- /dev/null +++ b/public/lib/classes/navigation/breadcrumb_navigation_node.php @@ -0,0 +1,66 @@ +. + +/** + * Subclass of navigation_node allowing different rendering for the breadcrumbs + * in particular adding extra metadata for search engine robots to leverage. + * + * @package core + * @category navigation + * @copyright 2015 Brendan Heywood + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class breadcrumb_navigation_node extends navigation_node { + + /** @var $last boolean A flag indicating this is the last item in the list of breadcrumbs. */ + private $last = false; + + /** + * A proxy constructor + * + * @param mixed $navnode A navigation_node or an array + */ + public function __construct($navnode) { + if (is_array($navnode)) { + parent::__construct($navnode); + } else if ($navnode instanceof navigation_node) { + + // Just clone everything. + $objvalues = get_object_vars($navnode); + foreach ($objvalues as $key => $value) { + $this->$key = $value; + } + } else { + throw new coding_exception('Not a valid breadcrumb_navigation_node'); + } + } + + /** + * Getter for "last" + * @return boolean + */ + public function is_last() { + return $this->last; + } + + /** + * Setter for "last" + * @param $val boolean + */ + public function set_last($val) { + $this->last = $val; + } +} diff --git a/public/lib/classes/navigation/flat_navigation.php b/public/lib/classes/navigation/flat_navigation.php new file mode 100644 index 00000000000..6cc053b8835 --- /dev/null +++ b/public/lib/classes/navigation/flat_navigation.php @@ -0,0 +1,156 @@ +. + +/** + * Class used to generate a collection of navigation nodes most closely related + * to the current page. + * + * @deprecated since Moodle 4.0 - do not use any more. Leverage secondary/tertiary navigation concepts + * @package core + * @copyright 2016 Damyon Wiese + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class flat_navigation extends navigation_node_collection { + /** @var moodle_page the moodle page that the navigation belongs to */ + protected $page; + + /** + * Constructor. + * + * @param moodle_page $page + */ + public function __construct(moodle_page &$page) { + if (during_initial_install()) { + return; + } + debugging("Flat navigation has been deprecated in favour of primary/secondary navigation concepts"); + $this->page = $page; + } + + /** + * Build the list of navigation nodes based on the current navigation and settings trees. + * + */ + public function initialise() { + global $PAGE, $USER, $OUTPUT, $CFG; + if (during_initial_install()) { + return; + } + + $current = false; + + $course = $PAGE->course; + + $this->page->navigation->initialise(); + + // First walk the nav tree looking for "flat_navigation" nodes. + if ($course->id > 1) { + // It's a real course. + $url = new moodle_url('/course/view.php', array('id' => $course->id)); + + $coursecontext = context_course::instance($course->id, MUST_EXIST); + $displaycontext = \context_helper::get_navigation_filter_context($coursecontext); + // This is the name that will be shown for the course. + $coursename = empty($CFG->navshowfullcoursenames) ? + format_string($course->shortname, true, ['context' => $displaycontext]) : + format_string($course->fullname, true, ['context' => $displaycontext]); + + $flat = new flat_navigation_node(navigation_node::create($coursename, $url), 0); + $flat->set_collectionlabel($coursename); + $flat->key = 'coursehome'; + $flat->icon = new pix_icon('i/course', ''); + + $courseformat = course_get_format($course); + $coursenode = $PAGE->navigation->find_active_node(); + $targettype = navigation_node::TYPE_COURSE; + + // Single activity format has no course node - the course node is swapped for the activity node. + if (!$courseformat->has_view_page()) { + $targettype = navigation_node::TYPE_ACTIVITY; + } + + while (!empty($coursenode) && ($coursenode->type != $targettype)) { + $coursenode = $coursenode->parent; + } + // There is one very strange page in mod/feedback/view.php which thinks it is both site and course + // context at the same time. That page is broken but we need to handle it (hence the SITEID). + if ($coursenode && $coursenode->key != SITEID) { + $this->add($flat); + foreach ($coursenode->children as $child) { + if ($child->action) { + $flat = new flat_navigation_node($child, 0); + $this->add($flat); + } + } + } + + $this->page->navigation->build_flat_navigation_list($this, true, get_string('site')); + } else { + $this->page->navigation->build_flat_navigation_list($this, false, get_string('site')); + } + + $admin = $PAGE->settingsnav->find('siteadministration', navigation_node::TYPE_SITE_ADMIN); + if (!$admin) { + // Try again - crazy nav tree! + $admin = $PAGE->settingsnav->find('root', navigation_node::TYPE_SITE_ADMIN); + } + if ($admin) { + $flat = new flat_navigation_node($admin, 0); + $flat->set_showdivider(true, get_string('sitesettings')); + $flat->key = 'sitesettings'; + $flat->icon = new pix_icon('t/preferences', ''); + $this->add($flat); + } + + // Add-a-block in editing mode. + if (isset($this->page->theme->addblockposition) && + $this->page->theme->addblockposition == BLOCK_ADDBLOCK_POSITION_FLATNAV && + $PAGE->user_is_editing() && $PAGE->user_can_edit_blocks()) { + $url = new moodle_url($PAGE->url, ['bui_addblock' => '', 'sesskey' => sesskey()]); + $addablock = navigation_node::create(get_string('addblock'), $url); + $flat = new flat_navigation_node($addablock, 0); + $flat->set_showdivider(true, get_string('blocksaddedit')); + $flat->key = 'addblock'; + $flat->icon = new pix_icon('i/addblock', ''); + $this->add($flat); + + $addblockurl = "?{$url->get_query_string(false)}"; + + $PAGE->requires->js_call_amd('core_block/add_modal', 'init', + [$addblockurl, $this->page->get_edited_page_hash()]); + } + } + + /** + * Override the parent so we can set a label for this collection if it has not been set yet. + * + * @param navigation_node $node Node to add + * @param string $beforekey If specified, adds before a node with this key, + * otherwise adds at end + * @return navigation_node Added node + */ + public function add(navigation_node $node, $beforekey=null) { + $result = parent::add($node, $beforekey); + // Extend the parent to get a name for the collection of nodes if required. + if (empty($this->collectionlabel)) { + if ($node instanceof flat_navigation_node) { + $this->set_collectionlabel($node->get_collectionlabel()); + } + } + + return $result; + } +} diff --git a/public/lib/classes/navigation/flat_navigation_node.php b/public/lib/classes/navigation/flat_navigation_node.php new file mode 100644 index 00000000000..da1ec134121 --- /dev/null +++ b/public/lib/classes/navigation/flat_navigation_node.php @@ -0,0 +1,151 @@ +. + + +/** + * Subclass of navigation_node allowing different rendering for the flat navigation + * in particular allowing dividers and indents. + * + * @deprecated since Moodle 4.0 - do not use any more. Leverage secondary/tertiary navigation concepts + * @package core + * @category navigation + * @copyright 2016 Damyon Wiese + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class flat_navigation_node extends navigation_node { + + /** @var $indent integer The indent level */ + private $indent = 0; + + /** @var $showdivider bool Show a divider before this element */ + private $showdivider = false; + + /** @var $collectionlabel string Label for a group of nodes */ + private $collectionlabel = ''; + + /** + * A proxy constructor + * + * @param mixed $navnode A navigation_node or an array + */ + public function __construct($navnode, $indent) { + debugging("Flat nav has been deprecated in favour of primary/secondary navigation concepts"); + if (is_array($navnode)) { + parent::__construct($navnode); + } else if ($navnode instanceof navigation_node) { + + // Just clone everything. + $objvalues = get_object_vars($navnode); + foreach ($objvalues as $key => $value) { + $this->$key = $value; + } + } else { + throw new coding_exception('Not a valid flat_navigation_node'); + } + $this->indent = $indent; + } + + /** + * Setter, a label is required for a flat navigation node that shows a divider. + * + * @param string $label + */ + public function set_collectionlabel($label) { + $this->collectionlabel = $label; + } + + /** + * Getter, get the label for this flat_navigation node, or it's parent if it doesn't have one. + * + * @return string + */ + public function get_collectionlabel() { + if (!empty($this->collectionlabel)) { + return $this->collectionlabel; + } + if ($this->parent && ($this->parent instanceof flat_navigation_node || $this->parent instanceof flat_navigation)) { + return $this->parent->get_collectionlabel(); + } + debugging('Navigation region requires a label', DEBUG_DEVELOPER); + return ''; + } + + /** + * Does this node represent a course section link. + * @return boolean + */ + public function is_section() { + return $this->type == navigation_node::TYPE_SECTION; + } + + /** + * In flat navigation - sections are active if we are looking at activities in the section. + * @return boolean + */ + public function isactive() { + global $PAGE; + + if ($this->is_section()) { + $active = $PAGE->navigation->find_active_node(); + if ($active) { + while ($active = $active->parent) { + if ($active->key == $this->key && $active->type == $this->type) { + return true; + } + } + } + } + return $this->isactive; + } + + /** + * Getter for "showdivider" + * @return boolean + */ + public function showdivider() { + return $this->showdivider; + } + + /** + * Setter for "showdivider" + * @param $val boolean + * @param $label string Label for the group of nodes + */ + public function set_showdivider($val, $label = '') { + $this->showdivider = $val; + if ($this->showdivider && empty($label)) { + debugging('Navigation region requires a label', DEBUG_DEVELOPER); + } else { + $this->set_collectionlabel($label); + } + } + + /** + * Getter for "indent" + * @return boolean + */ + public function get_indent() { + return $this->indent; + } + + /** + * Setter for "indent" + * @param $val boolean + */ + public function set_indent($val) { + $this->indent = $val; + } +} diff --git a/public/lib/classes/navigation/global_navigation.php b/public/lib/classes/navigation/global_navigation.php new file mode 100644 index 00000000000..97bd2a902ff --- /dev/null +++ b/public/lib/classes/navigation/global_navigation.php @@ -0,0 +1,2240 @@ +. + +/** + * The global navigation class used for... the global navigation + * + * This class is used by PAGE to store the global navigation for the site + * and is then used by the settings nav and navbar to save on processing and DB calls + * + * See + * {@link lib/pagelib.php} {@link moodle_page::initialise_theme_and_output()} + * {@link lib/ajax/getnavbranch.php} Called by ajax + * + * @package core + * @category navigation + * @copyright 2009 Sam Hemelryk + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class global_navigation extends navigation_node { + /** @var moodle_page The Moodle page this navigation object belongs to. */ + protected $page; + /** @var bool switch to let us know if the navigation object is initialised*/ + protected $initialised = false; + /** @var array An array of course information */ + protected $mycourses = array(); + /** @var navigation_node[] An array for containing root navigation nodes */ + protected $rootnodes = array(); + /** @var bool A switch for whether to show empty sections in the navigation */ + protected $showemptysections = true; + /** @var bool A switch for whether courses should be shown within categories on the navigation. */ + protected $showcategories = null; + /** @var null@var bool A switch for whether or not to show categories in the my courses branch. */ + protected $showmycategories = null; + /** @var array An array of stdClasses for users that the navigation is extended for */ + protected $extendforuser = array(); + /** @var navigation_cache */ + protected $cache; + /** @var array An array of course ids that are present in the navigation */ + protected $addedcourses = array(); + /** @var bool */ + protected $allcategoriesloaded = false; + /** @var array An array of category ids that are included in the navigation */ + protected $addedcategories = array(); + /** @var int expansion limit */ + protected $expansionlimit = 0; + /** @var int userid to allow parent to see child's profile page navigation */ + protected $useridtouseforparentchecks = 0; + /** @var cache_session A cache that stores information on expanded courses */ + protected $cacheexpandcourse = null; + + /** Used when loading categories to load all top level categories [parent = 0] **/ + const LOAD_ROOT_CATEGORIES = 0; + /** Used when loading categories to load all categories **/ + const LOAD_ALL_CATEGORIES = -1; + + /** + * Constructs a new global navigation + * + * @param moodle_page $page The page this navigation object belongs to + */ + public function __construct(moodle_page $page) { + global $CFG, $SITE, $USER; + + if (during_initial_install()) { + return; + } + + $homepage = get_home_page(); + if ($homepage == HOMEPAGE_MY) { + // We are using the users my moodle for the root element. + $properties = array( + 'key' => 'myhome', + 'type' => navigation_node::TYPE_SYSTEM, + 'text' => get_string('myhome'), + 'action' => new moodle_url('/my/'), + 'icon' => new pix_icon('i/dashboard', ''), + ); + } else if ($homepage == HOMEPAGE_MYCOURSES) { + // We are using the user's course summary page for the root element. + $properties = array( + 'key' => 'mycourses', + 'type' => navigation_node::TYPE_SYSTEM, + 'text' => get_string('mycourses'), + 'action' => new moodle_url('/my/courses.php'), + 'icon' => new pix_icon('i/course', '') + ); + } else { + // We are using the site home for the root element. + $properties = array( + 'key' => 'home', + 'type' => navigation_node::TYPE_SYSTEM, + 'text' => get_string('home'), + 'action' => new moodle_url('/'), + 'icon' => new pix_icon('i/home', ''), + ); + } + + // Use the parents constructor.... good good reuse + parent::__construct($properties); + $this->showinflatnavigation = true; + + // Initalise and set defaults + $this->page = $page; + $this->forceopen = true; + $this->cache = new navigation_cache(NAVIGATION_CACHE_NAME); + } + + /** + * Mutator to set userid to allow parent to see child's profile + * page navigation. See MDL-25805 for initial issue. Linked to it + * is an issue explaining why this is a REALLY UGLY HACK thats not + * for you to use! + * + * @param int $userid userid of profile page that parent wants to navigate around. + */ + public function set_userid_for_parent_checks($userid) { + $this->useridtouseforparentchecks = $userid; + } + + + /** + * Initialises the navigation object. + * + * This causes the navigation object to look at the current state of the page + * that it is associated with and then load the appropriate content. + * + * This should only occur the first time that the navigation structure is utilised + * which will normally be either when the navbar is called to be displayed or + * when a block makes use of it. + * + * @return bool + */ + public function initialise() { + global $CFG, $SITE, $USER; + // Check if it has already been initialised + if ($this->initialised || during_initial_install()) { + return true; + } + $this->initialised = true; + + // Set up the five base root nodes. These are nodes where we will put our + // content and are as follows: + // site: Navigation for the front page. + // myprofile: User profile information goes here. + // currentcourse: The course being currently viewed. + // mycourses: The users courses get added here. + // courses: Additional courses are added here. + // users: Other users information loaded here. + $this->rootnodes = array(); + $defaulthomepage = get_home_page(); + if ($defaulthomepage == HOMEPAGE_SITE) { + // The home element should be my moodle because the root element is the site + if (isloggedin() && !isguestuser()) { // Makes no sense if you aren't logged in + if (!empty($CFG->enabledashboard)) { + // Only add dashboard to home if it's enabled. + $this->rootnodes['home'] = $this->add(get_string('myhome'), new moodle_url('/my/'), + self::TYPE_SETTING, null, 'myhome', new pix_icon('i/dashboard', '')); + $this->rootnodes['home']->showinflatnavigation = true; + } + } + } else { + // The home element should be the site because the root node is my moodle + $this->rootnodes['home'] = $this->add(get_string('sitehome'), new moodle_url('/'), + self::TYPE_SETTING, null, 'home', new pix_icon('i/home', '')); + $this->rootnodes['home']->showinflatnavigation = true; + if (!empty($CFG->defaulthomepage) && + ($CFG->defaulthomepage == HOMEPAGE_MY || $CFG->defaulthomepage == HOMEPAGE_MYCOURSES)) { + // We need to stop automatic redirection + $this->rootnodes['home']->action->param('redirect', '0'); + } + } + $this->rootnodes['site'] = $this->add_course($SITE); + $this->rootnodes['myprofile'] = $this->add(get_string('profile'), null, self::TYPE_USER, null, 'myprofile'); + $this->rootnodes['currentcourse'] = $this->add(get_string('currentcourse'), null, self::TYPE_ROOTNODE, null, 'currentcourse'); + $this->rootnodes['mycourses'] = $this->add( + get_string('mycourses'), + new moodle_url('/my/courses.php'), + self::TYPE_ROOTNODE, + null, + 'mycourses', + new pix_icon('i/course', '') + ); + // We do not need to show this node in the breadcrumbs if the default homepage is mycourses. + // It will be automatically handled by the breadcrumb generator. + if ($defaulthomepage == HOMEPAGE_MYCOURSES) { + $this->rootnodes['mycourses']->mainnavonly = true; + } + + $this->rootnodes['courses'] = $this->add(get_string('courses'), new moodle_url('/course/index.php'), self::TYPE_ROOTNODE, null, 'courses'); + if (!core_course_category::user_top()) { + $this->rootnodes['courses']->hide(); + } + $this->rootnodes['users'] = $this->add(get_string('users'), null, self::TYPE_ROOTNODE, null, 'users'); + + // We always load the frontpage course to ensure it is available without + // JavaScript enabled. + $this->add_front_page_course_essentials($this->rootnodes['site'], $SITE); + $this->load_course_sections($SITE, $this->rootnodes['site']); + + $course = $this->page->course; + $this->load_courses_enrolled(); + + // $issite gets set to true if the current pages course is the sites frontpage course + $issite = ($this->page->course->id == $SITE->id); + + // Determine if the user is enrolled in any course. + $enrolledinanycourse = enrol_user_sees_own_courses(); + + $this->rootnodes['currentcourse']->mainnavonly = true; + if ($enrolledinanycourse) { + $this->rootnodes['mycourses']->isexpandable = true; + $this->rootnodes['mycourses']->showinflatnavigation = true; + if ($CFG->navshowallcourses) { + // When we show all courses we need to show both the my courses and the regular courses branch. + $this->rootnodes['courses']->isexpandable = true; + } + } else { + $this->rootnodes['courses']->isexpandable = true; + } + $this->rootnodes['mycourses']->forceopen = true; + + $canviewcourseprofile = true; + + // Next load context specific content into the navigation + switch ($this->page->context->contextlevel) { + case CONTEXT_SYSTEM : + // Nothing left to do here I feel. + break; + case CONTEXT_COURSECAT : + // This is essential, we must load categories. + $this->load_all_categories($this->page->context->instanceid, true); + break; + case CONTEXT_BLOCK : + case CONTEXT_COURSE : + if ($issite) { + // Nothing left to do here. + break; + } + + // Load the course associated with the current page into the navigation. + $coursenode = $this->add_course($course, false, self::COURSE_CURRENT); + // If the course wasn't added then don't try going any further. + if (!$coursenode) { + $canviewcourseprofile = false; + break; + } + + // If the user is not enrolled then we only want to show the + // course node and not populate it. + + // Not enrolled, can't view, and hasn't switched roles + if (!can_access_course($course, null, '', true)) { + if ($coursenode->isexpandable === true) { + // Obviously the situation has changed, update the cache and adjust the node. + // This occurs if the user access to a course has been revoked (one way or another) after + // initially logging in for this session. + $this->get_expand_course_cache()->set($course->id, 1); + $coursenode->isexpandable = true; + $coursenode->nodetype = self::NODETYPE_BRANCH; + } + // Very ugly hack - do not force "parents" to enrol into course their child is enrolled in, + // this hack has been propagated from user/view.php to display the navigation node. (MDL-25805) + if (!$this->current_user_is_parent_role()) { + $coursenode->make_active(); + $canviewcourseprofile = false; + break; + } + } else if ($coursenode->isexpandable === false) { + // Obviously the situation has changed, update the cache and adjust the node. + // This occurs if the user has been granted access to a course (one way or another) after initially + // logging in for this session. + $this->get_expand_course_cache()->set($course->id, 1); + $coursenode->isexpandable = true; + $coursenode->nodetype = self::NODETYPE_BRANCH; + } + + // Add the essentials such as reports etc... + $this->add_course_essentials($coursenode, $course); + // Extend course navigation with it's sections/activities + $this->load_course_sections($course, $coursenode); + if (!$coursenode->contains_active_node() && !$coursenode->search_for_active_node()) { + $coursenode->make_active(); + } + + break; + case CONTEXT_MODULE : + if ($issite) { + // If this is the site course then most information will have + // already been loaded. + // However we need to check if there is more content that can + // yet be loaded for the specific module instance. + $activitynode = $this->rootnodes['site']->find($this->page->cm->id, navigation_node::TYPE_ACTIVITY); + if ($activitynode) { + $this->load_activity($this->page->cm, $this->page->course, $activitynode); + } + break; + } + + $course = $this->page->course; + $cm = $this->page->cm; + + // Load the course associated with the page into the navigation + $coursenode = $this->add_course($course, false, self::COURSE_CURRENT); + + // If the course wasn't added then don't try going any further. + if (!$coursenode) { + $canviewcourseprofile = false; + break; + } + + // If the user is not enrolled then we only want to show the + // course node and not populate it. + if (!can_access_course($course, null, '', true)) { + $coursenode->make_active(); + $canviewcourseprofile = false; + break; + } + + $this->add_course_essentials($coursenode, $course); + + // Load the course sections into the page + $this->load_course_sections($course, $coursenode, null, $cm); + $activity = $coursenode->find($cm->id, navigation_node::TYPE_ACTIVITY); + if (!empty($activity)) { + // Finally load the cm specific navigaton information + $this->load_activity($cm, $course, $activity); + // Check if we have an active ndoe + if (!$activity->contains_active_node() && !$activity->search_for_active_node()) { + // And make the activity node active. + $activity->make_active(); + } + } + break; + case CONTEXT_USER : + if ($issite) { + // The users profile information etc is already loaded + // for the front page. + break; + } + $course = $this->page->course; + // Load the course associated with the user into the navigation + $coursenode = $this->add_course($course, false, self::COURSE_CURRENT); + + // If the course wasn't added then don't try going any further. + if (!$coursenode) { + $canviewcourseprofile = false; + break; + } + + // If the user is not enrolled then we only want to show the + // course node and not populate it. + if (!can_access_course($course, null, '', true)) { + $coursenode->make_active(); + $canviewcourseprofile = false; + break; + } + $this->add_course_essentials($coursenode, $course); + $this->load_course_sections($course, $coursenode); + break; + } + + // Load for the current user + $this->load_for_user(); + if ($this->page->context->contextlevel >= CONTEXT_COURSE && $this->page->context->instanceid != $SITE->id && $canviewcourseprofile) { + $this->load_for_user(null, true); + } + // Load each extending user into the navigation. + foreach ($this->extendforuser as $user) { + if ($user->id != $USER->id) { + $this->load_for_user($user); + } + } + + // Give the local plugins a chance to include some navigation if they want. + $this->load_local_plugin_navigation(); + + // Remove any empty root nodes + foreach ($this->rootnodes as $node) { + // Dont remove the home node + /** @var navigation_node $node */ + if (!in_array($node->key, ['home', 'mycourses', 'myhome']) && !$node->has_children() && !$node->isactive) { + $node->remove(); + } + } + + if (!$this->contains_active_node()) { + $this->search_for_active_node(); + } + + // If the user is not logged in modify the navigation structure. + if (!isloggedin()) { + $activities = clone($this->rootnodes['site']->children); + $this->rootnodes['site']->remove(); + $children = clone($this->children); + $this->children = new navigation_node_collection(); + foreach ($activities as $child) { + $this->children->add($child); + } + foreach ($children as $child) { + $this->children->add($child); + } + } + return true; + } + + /** + * This function gives local plugins an opportunity to modify navigation. + */ + protected function load_local_plugin_navigation() { + foreach (get_plugin_list_with_function('local', 'extend_navigation') as $function) { + $function($this); + } + } + + /** + * Returns true if the current user is a parent of the user being currently viewed. + * + * If the current user is not viewing another user, or if the current user does not hold any parent roles over the + * other user being viewed this function returns false. + * In order to set the user for whom we are checking against you must call {@link set_userid_for_parent_checks()} + * + * @since Moodle 2.4 + * @return bool + */ + protected function current_user_is_parent_role() { + global $USER, $DB; + if ($this->useridtouseforparentchecks && $this->useridtouseforparentchecks != $USER->id) { + $usercontext = context_user::instance($this->useridtouseforparentchecks, MUST_EXIST); + if (!has_capability('moodle/user:viewdetails', $usercontext)) { + return false; + } + if ($DB->record_exists('role_assignments', array('userid' => $USER->id, 'contextid' => $usercontext->id))) { + return true; + } + } + return false; + } + + /** + * Returns true if courses should be shown within categories on the navigation. + * + * @param bool $ismycourse Set to true if you are calculating this for a course. + * @return bool + */ + protected function show_categories($ismycourse = false) { + global $CFG, $DB; + if ($ismycourse) { + return $this->show_my_categories(); + } + if ($this->showcategories === null) { + $show = false; + if ($this->page->context->contextlevel == CONTEXT_COURSECAT) { + $show = true; + } else if (!empty($CFG->navshowcategories) && $DB->count_records('course_categories') > 1) { + $show = true; + } + $this->showcategories = $show; + } + return $this->showcategories; + } + + /** + * Returns true if we should show categories in the My Courses branch. + * @return bool + */ + protected function show_my_categories() { + global $CFG; + if ($this->showmycategories === null) { + $this->showmycategories = !empty($CFG->navshowmycoursecategories) && !core_course_category::is_simple_site(); + } + return $this->showmycategories; + } + + /** + * Loads the courses in Moodle into the navigation. + * + * @global moodle_database $DB + * @param string|array $categoryids An array containing categories to load courses + * for, OR null to load courses for all categories. + * @return array An array of navigation_nodes one for each course + */ + protected function load_all_courses($categoryids = null) { + global $CFG, $DB, $SITE; + + // Work out the limit of courses. + $limit = 20; + if (!empty($CFG->navcourselimit)) { + $limit = $CFG->navcourselimit; + } + + $toload = (empty($CFG->navshowallcourses))?self::LOAD_ROOT_CATEGORIES:self::LOAD_ALL_CATEGORIES; + + // If we are going to show all courses AND we are showing categories then + // to save us repeated DB calls load all of the categories now + if ($this->show_categories()) { + $this->load_all_categories($toload); + } + + // Will be the return of our efforts + $coursenodes = array(); + + // Check if we need to show categories. + if ($this->show_categories()) { + // Hmmm we need to show categories... this is going to be painful. + // We now need to fetch up to $limit courses for each category to + // be displayed. + if ($categoryids !== null) { + if (!is_array($categoryids)) { + $categoryids = array($categoryids); + } + list($categorywhere, $categoryparams) = $DB->get_in_or_equal($categoryids, SQL_PARAMS_NAMED, 'cc'); + $categorywhere = 'WHERE cc.id '.$categorywhere; + } else if ($toload == self::LOAD_ROOT_CATEGORIES) { + $categorywhere = 'WHERE cc.depth = 1 OR cc.depth = 2'; + $categoryparams = array(); + } else { + $categorywhere = ''; + $categoryparams = array(); + } + + // First up we are going to get the categories that we are going to + // need so that we can determine how best to load the courses from them. + $sql = "SELECT cc.id, COUNT(c.id) AS coursecount + FROM {course_categories} cc + LEFT JOIN {course} c ON c.category = cc.id + {$categorywhere} + GROUP BY cc.id"; + $categories = $DB->get_recordset_sql($sql, $categoryparams); + $fullfetch = array(); + $partfetch = array(); + foreach ($categories as $category) { + if (!$this->can_add_more_courses_to_category($category->id)) { + continue; + } + if ($category->coursecount > $limit * 5) { + $partfetch[] = $category->id; + } else if ($category->coursecount > 0) { + $fullfetch[] = $category->id; + } + } + $categories->close(); + + if (count($fullfetch)) { + // First up fetch all of the courses in categories where we know that we are going to + // need the majority of courses. + list($categoryids, $categoryparams) = $DB->get_in_or_equal($fullfetch, SQL_PARAMS_NAMED, 'lcategory'); + $ccselect = ', ' . context_helper::get_preload_record_columns_sql('ctx'); + $ccjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)"; + $categoryparams['contextlevel'] = CONTEXT_COURSE; + $sql = "SELECT c.id, c.sortorder, c.visible, c.fullname, c.shortname, c.category $ccselect + FROM {course} c + $ccjoin + WHERE c.category {$categoryids} + ORDER BY c.sortorder ASC"; + $coursesrs = $DB->get_recordset_sql($sql, $categoryparams); + foreach ($coursesrs as $course) { + if ($course->id == $SITE->id) { + // This should not be necessary, frontpage is not in any category. + continue; + } + if (array_key_exists($course->id, $this->addedcourses)) { + // It is probably better to not include the already loaded courses + // directly in SQL because inequalities may confuse query optimisers + // and may interfere with query caching. + continue; + } + if (!$this->can_add_more_courses_to_category($course->category)) { + continue; + } + context_helper::preload_from_record($course); + if (!$course->visible && !is_role_switched($course->id) && !has_capability('moodle/course:viewhiddencourses', context_course::instance($course->id))) { + continue; + } + $coursenodes[$course->id] = $this->add_course($course); + } + $coursesrs->close(); + } + + if (count($partfetch)) { + // Next we will work our way through the categories where we will likely only need a small + // proportion of the courses. + foreach ($partfetch as $categoryid) { + $ccselect = ', ' . context_helper::get_preload_record_columns_sql('ctx'); + $ccjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)"; + $sql = "SELECT c.id, c.sortorder, c.visible, c.fullname, c.shortname, c.category $ccselect + FROM {course} c + $ccjoin + WHERE c.category = :categoryid + ORDER BY c.sortorder ASC"; + $courseparams = array('categoryid' => $categoryid, 'contextlevel' => CONTEXT_COURSE); + $coursesrs = $DB->get_recordset_sql($sql, $courseparams, 0, $limit * 5); + foreach ($coursesrs as $course) { + if ($course->id == $SITE->id) { + // This should not be necessary, frontpage is not in any category. + continue; + } + if (array_key_exists($course->id, $this->addedcourses)) { + // It is probably better to not include the already loaded courses + // directly in SQL because inequalities may confuse query optimisers + // and may interfere with query caching. + // This also helps to respect expected $limit on repeated executions. + continue; + } + if (!$this->can_add_more_courses_to_category($course->category)) { + break; + } + context_helper::preload_from_record($course); + if (!$course->visible && !is_role_switched($course->id) && !has_capability('moodle/course:viewhiddencourses', context_course::instance($course->id))) { + continue; + } + $coursenodes[$course->id] = $this->add_course($course); + } + $coursesrs->close(); + } + } + } else { + // Prepare the SQL to load the courses and their contexts + list($courseids, $courseparams) = $DB->get_in_or_equal(array_keys($this->addedcourses), SQL_PARAMS_NAMED, 'lc', false); + $ccselect = ', ' . context_helper::get_preload_record_columns_sql('ctx'); + $ccjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)"; + $courseparams['contextlevel'] = CONTEXT_COURSE; + $sql = "SELECT c.id, c.sortorder, c.visible, c.fullname, c.shortname, c.category $ccselect + FROM {course} c + $ccjoin + WHERE c.id {$courseids} + ORDER BY c.sortorder ASC"; + $coursesrs = $DB->get_recordset_sql($sql, $courseparams); + foreach ($coursesrs as $course) { + if ($course->id == $SITE->id) { + // frotpage is not wanted here + continue; + } + if ($this->page->course && ($this->page->course->id == $course->id)) { + // Don't include the currentcourse in this nodelist - it's displayed in the Current course node + continue; + } + context_helper::preload_from_record($course); + if (!$course->visible && !is_role_switched($course->id) && !has_capability('moodle/course:viewhiddencourses', context_course::instance($course->id))) { + continue; + } + $coursenodes[$course->id] = $this->add_course($course); + if (count($coursenodes) >= $limit) { + break; + } + } + $coursesrs->close(); + } + + return $coursenodes; + } + + /** + * Returns true if more courses can be added to the provided category. + * + * @param int|navigation_node|stdClass $category + * @return bool + */ + protected function can_add_more_courses_to_category($category) { + global $CFG; + $limit = 20; + if (!empty($CFG->navcourselimit)) { + $limit = (int)$CFG->navcourselimit; + } + if (is_numeric($category)) { + if (!array_key_exists($category, $this->addedcategories)) { + return true; + } + $coursecount = count($this->addedcategories[$category]->children->type(self::TYPE_COURSE)); + } else if ($category instanceof navigation_node) { + if (($category->type != self::TYPE_CATEGORY) || ($category->type != self::TYPE_MY_CATEGORY)) { + return false; + } + $coursecount = count($category->children->type(self::TYPE_COURSE)); + } else if (is_object($category) && property_exists($category,'id')) { + $coursecount = count($this->addedcategories[$category->id]->children->type(self::TYPE_COURSE)); + } + return ($coursecount <= $limit); + } + + /** + * Loads all categories (top level or if an id is specified for that category) + * + * @param int $categoryid The category id to load or null/0 to load all base level categories + * @param bool $showbasecategories If set to true all base level categories will be loaded as well + * as the requested category and any parent categories. + * @return true|void + */ + protected function load_all_categories($categoryid = self::LOAD_ROOT_CATEGORIES, $showbasecategories = false) { + global $CFG, $DB; + + // Check if this category has already been loaded + if ($this->allcategoriesloaded || ($categoryid < 1 && $this->is_category_fully_loaded($categoryid))) { + return true; + } + + $catcontextsql = context_helper::get_preload_record_columns_sql('ctx'); + $sqlselect = "SELECT cc.*, $catcontextsql + FROM {course_categories} cc + JOIN {context} ctx ON cc.id = ctx.instanceid"; + $sqlwhere = "WHERE ctx.contextlevel = ".CONTEXT_COURSECAT; + $sqlorder = "ORDER BY cc.depth ASC, cc.sortorder ASC, cc.id ASC"; + $params = array(); + + $categoriestoload = array(); + if ($categoryid == self::LOAD_ALL_CATEGORIES) { + // We are going to load all categories regardless... prepare to fire + // on the database server! + } else if ($categoryid == self::LOAD_ROOT_CATEGORIES) { // can be 0 + // We are going to load all of the first level categories (categories without parents) + $sqlwhere .= " AND cc.parent = 0"; + } else if (array_key_exists($categoryid, $this->addedcategories)) { + // The category itself has been loaded already so we just need to ensure its subcategories + // have been loaded + $addedcategories = $this->addedcategories; + unset($addedcategories[$categoryid]); + if (count($addedcategories) > 0) { + list($sql, $params) = $DB->get_in_or_equal(array_keys($addedcategories), SQL_PARAMS_NAMED, 'parent', false); + if ($showbasecategories) { + // We need to include categories with parent = 0 as well + $sqlwhere .= " AND (cc.parent = :categoryid OR cc.parent = 0) AND cc.parent {$sql}"; + } else { + // All we need is categories that match the parent + $sqlwhere .= " AND cc.parent = :categoryid AND cc.parent {$sql}"; + } + } + $params['categoryid'] = $categoryid; + } else { + // This category hasn't been loaded yet so we need to fetch it, work out its category path + // and load this category plus all its parents and subcategories + $category = $DB->get_record('course_categories', array('id' => $categoryid), 'path', MUST_EXIST); + $categoriestoload = explode('/', trim($category->path, '/')); + list($select, $params) = $DB->get_in_or_equal($categoriestoload); + // We are going to use select twice so double the params + $params = array_merge($params, $params); + $basecategorysql = ($showbasecategories)?' OR cc.depth = 1':''; + $sqlwhere .= " AND (cc.id {$select} OR cc.parent {$select}{$basecategorysql})"; + } + + $categoriesrs = $DB->get_recordset_sql("$sqlselect $sqlwhere $sqlorder", $params); + $categories = array(); + foreach ($categoriesrs as $category) { + // Preload the context.. we'll need it when adding the category in order + // to format the category name. + context_helper::preload_from_record($category); + if (array_key_exists($category->id, $this->addedcategories)) { + // Do nothing, its already been added. + } else if ($category->parent == '0') { + // This is a root category lets add it immediately + $this->add_category($category, $this->rootnodes['courses']); + } else if (array_key_exists($category->parent, $this->addedcategories)) { + // This categories parent has already been added we can add this immediately + $this->add_category($category, $this->addedcategories[$category->parent]); + } else { + $categories[] = $category; + } + } + $categoriesrs->close(); + + // Now we have an array of categories we need to add them to the navigation. + while (!empty($categories)) { + $category = reset($categories); + if (array_key_exists($category->id, $this->addedcategories)) { + // Do nothing + } else if ($category->parent == '0') { + $this->add_category($category, $this->rootnodes['courses']); + } else if (array_key_exists($category->parent, $this->addedcategories)) { + $this->add_category($category, $this->addedcategories[$category->parent]); + } else { + // This category isn't in the navigation and niether is it's parent (yet). + // We need to go through the category path and add all of its components in order. + $path = explode('/', trim($category->path, '/')); + foreach ($path as $catid) { + if (!array_key_exists($catid, $this->addedcategories)) { + // This category isn't in the navigation yet so add it. + $subcategory = $categories[$catid]; + if ($subcategory->parent == '0') { + // Yay we have a root category - this likely means we will now be able + // to add categories without problems. + $this->add_category($subcategory, $this->rootnodes['courses']); + } else if (array_key_exists($subcategory->parent, $this->addedcategories)) { + // The parent is in the category (as we'd expect) so add it now. + $this->add_category($subcategory, $this->addedcategories[$subcategory->parent]); + // Remove the category from the categories array. + unset($categories[$catid]); + } else { + // We should never ever arrive here - if we have then there is a bigger + // problem at hand. + throw new coding_exception('Category path order is incorrect and/or there are missing categories'); + } + } + } + } + // Remove the category from the categories array now that we know it has been added. + unset($categories[$category->id]); + } + if ($categoryid === self::LOAD_ALL_CATEGORIES) { + $this->allcategoriesloaded = true; + } + // Check if there are any categories to load. + if (count($categoriestoload) > 0) { + $readytoloadcourses = array(); + foreach ($categoriestoload as $category) { + if ($this->can_add_more_courses_to_category($category)) { + $readytoloadcourses[] = $category; + } + } + if (count($readytoloadcourses)) { + $this->load_all_courses($readytoloadcourses); + } + } + + // Look for all categories which have been loaded + if (!empty($this->addedcategories)) { + $categoryids = array(); + foreach ($this->addedcategories as $category) { + if ($this->can_add_more_courses_to_category($category)) { + $categoryids[] = $category->key; + } + } + if ($categoryids) { + list($categoriessql, $params) = $DB->get_in_or_equal($categoryids, SQL_PARAMS_NAMED); + $params['limit'] = (!empty($CFG->navcourselimit))?$CFG->navcourselimit:20; + $sql = "SELECT cc.id, COUNT(c.id) AS coursecount + FROM {course_categories} cc + JOIN {course} c ON c.category = cc.id + WHERE cc.id {$categoriessql} + GROUP BY cc.id + HAVING COUNT(c.id) > :limit"; + $excessivecategories = $DB->get_records_sql($sql, $params); + foreach ($categories as &$category) { + if (array_key_exists($category->key, $excessivecategories) && !$this->can_add_more_courses_to_category($category)) { + $url = new moodle_url('/course/index.php', array('categoryid' => $category->key)); + $category->add(get_string('viewallcourses'), $url, self::TYPE_SETTING); + } + } + } + } + } + + /** + * Adds a structured category to the navigation in the correct order/place + * + * @param stdClass $category category to be added in navigation. + * @param navigation_node $parent parent navigation node + * @param int $nodetype type of node, if category is under MyHome then it's TYPE_MY_CATEGORY + * @return void. + */ + protected function add_category(stdClass $category, navigation_node $parent, $nodetype = self::TYPE_CATEGORY) { + global $CFG; + if (array_key_exists($category->id, $this->addedcategories)) { + return; + } + $canview = core_course_category::can_view_category($category); + $url = $canview ? new moodle_url('/course/index.php', array('categoryid' => $category->id)) : null; + $context = \context_helper::get_navigation_filter_context(context_coursecat::instance($category->id)); + $categoryname = $canview ? format_string($category->name, true, ['context' => $context]) : + get_string('categoryhidden'); + $categorynode = $parent->add($categoryname, $url, $nodetype, $categoryname, $category->id); + if (!$canview) { + // User does not have required capabilities to view category. + $categorynode->display = false; + } else if (!$category->visible) { + // Category is hidden but user has capability to view hidden categories. + $categorynode->hidden = true; + } + $this->addedcategories[$category->id] = $categorynode; + } + + /** + * Loads the given course into the navigation + * + * @param stdClass $course + * @return navigation_node + */ + protected function load_course(stdClass $course) { + global $SITE; + if ($course->id == $SITE->id) { + // This is always loaded during initialisation + return $this->rootnodes['site']; + } else if (array_key_exists($course->id, $this->addedcourses)) { + // The course has already been loaded so return a reference + return $this->addedcourses[$course->id]; + } else { + // Add the course + return $this->add_course($course); + } + } + + /** + * Loads all of the courses section into the navigation. + * + * This function calls method from current course format, see + * core_courseformat\base::extend_course_navigation() + * If course module ($cm) is specified but course format failed to create the node, + * the activity node is created anyway. + * + * By default course formats call the method global_navigation::load_generic_course_sections() + * + * @param stdClass $course Database record for the course + * @param navigation_node $coursenode The course node within the navigation + * @param null|int $sectionnum If specified load the contents of section with this relative number + * @param null|cm_info $cm If specified make sure that activity node is created (either + * in containg section or by calling load_stealth_activity() ) + */ + protected function load_course_sections(stdClass $course, navigation_node $coursenode, $sectionnum = null, $cm = null) { + global $CFG, $SITE; + require_once($CFG->dirroot.'/course/lib.php'); + if (isset($cm->sectionnum)) { + $sectionnum = $cm->sectionnum; + } + if ($sectionnum !== null) { + $this->includesectionnum = $sectionnum; + } + course_get_format($course)->extend_course_navigation($this, $coursenode, $sectionnum, $cm); + if (isset($cm->id)) { + $activity = $coursenode->find($cm->id, self::TYPE_ACTIVITY); + if (empty($activity)) { + $activity = $this->load_stealth_activity($coursenode, get_fast_modinfo($course)); + } + } + } + + /** + * Generates an array of sections and an array of activities for the given course. + * + * This method uses the cache to improve performance and avoid the get_fast_modinfo call + * + * @param stdClass $course + * @return array Array($sections, $activities) + */ + protected function generate_sections_and_activities(stdClass $course) { + global $CFG; + require_once($CFG->dirroot.'/course/lib.php'); + + $modinfo = get_fast_modinfo($course); + $sections = $modinfo->get_section_info_all(); + $format = course_get_format($course); + + // For course formats using 'numsections' trim the sections list + $courseformatoptions = $format->get_format_options(); + if (isset($courseformatoptions['numsections'])) { + $sections = array_slice($sections, 0, $courseformatoptions['numsections']+1, true); + } + + $activities = []; + + foreach ($sections as $key => $section) { + // Clone and unset summary to prevent $SESSION bloat (MDL-31802). + $sections[$key] = clone($section); + unset($sections[$key]->summary); + $sections[$key]->hasactivites = false; + if (!array_key_exists($section->sectionnum, $modinfo->sections)) { + continue; + } + foreach ($section->get_sequence_cm_infos() as $cm) { + $activity = new stdClass; + $activity->id = $cm->id; + $activity->course = $course->id; + $activity->section = $section->sectionnum; + $activity->name = $cm->name; + $activity->icon = $cm->icon; + $activity->iconcomponent = $cm->iconcomponent; + $activity->hidden = (!$cm->visible); + $activity->modname = $cm->modname; + $activity->nodetype = navigation_node::NODETYPE_LEAF; + $activity->onclick = $cm->onclick; + $url = $cm->url; + + // Activities witout url but with delegated section uses the section url. + $activity->delegatedsection = $cm->get_delegated_section_info(); + if (empty($cm->url) && $activity->delegatedsection) { + $url = $format->get_view_url( + $activity->delegatedsection->sectionnum, + ['navigation' => true] + ); + } + + if (!$url) { + $activity->url = null; + $activity->display = false; + } else { + $activity->url = $url->out(); + $activity->display = $cm->is_visible_on_course_page() ? true : false; + if (self::module_extends_navigation($cm->modname)) { + $activity->nodetype = navigation_node::NODETYPE_BRANCH; + } + } + $activities[$cm->id] = $activity; + if ($activity->display) { + $sections[$key]->hasactivites = true; + } + } + } + + return [$sections, $activities]; + } + + /** + * Generically loads the course sections into the course's navigation. + * + * @param stdClass $course + * @param navigation_node $coursenode + * @return array An array of course section nodes + */ + public function load_generic_course_sections(stdClass $course, navigation_node $coursenode) { + global $CFG, $DB, $USER, $SITE; + require_once($CFG->dirroot.'/course/lib.php'); + + list($sections, $activities) = $this->generate_sections_and_activities($course); + + $navigationsections = []; + foreach ($sections as $sectionid => $section) { + if ($course->id == $SITE->id) { + $this->load_section_activities_navigation($coursenode, $section, $activities); + continue; + } + + if ( + !$section->uservisible + || ( + !$this->showemptysections + && !$section->hasactivites + && $this->includesectionnum !== $section->section + ) + ) { + continue; + } + + // Delegated sections are added from the activity node. + if ($section->get_component_instance()) { + continue; + } + + $navigationsections[$sectionid] = $this->load_section_navigation( + parentnode: $coursenode, + section: $section, + activitiesdata: $activities, + ); + } + return $navigationsections; + } + + /** + * Returns true if the section is included in the breadcrumb. + * + * @param section_info $section + * @param moodle_url|null $sectionurl + * @return bool + */ + protected function is_section_in_breadcrumb(section_info $section, ?moodle_url $sectionurl): bool { + // Ajax requests uses includesectionnum as param. + if ($this->includesectionnum !== false && $this->includesectionnum == $section->sectionnum) { + return true; + } + + // If we are in a section page, we need to check for any child section. + $checkchildrenurls = false; + $format = null; + if ($sectionurl && $this->page->url->compare($sectionurl, URL_MATCH_BASE)) { + $checkchildrenurls = true; + $format = course_get_format($section->course); + } + + // Activities can have delegated sections that acts as a child section. + foreach ($section->get_sequence_cm_infos() as $cm) { + $delegatedsection = $cm->get_delegated_section_info(); + if (!$delegatedsection) { + continue; + } + // Check if the child node is requested via Ajax. + if ($this->includesectionnum == $delegatedsection->sectionnum) { + return true; + } + + if ($checkchildrenurls) { + $childurl = $format->get_view_url($delegatedsection, ['navigation' => true]); + if ($childurl && $this->page->url->compare($childurl, URL_MATCH_EXACT)) { + return true; + } + } + } + + return false; + } + + /** + * Loads a section into the navigation structure. + * + * @param navigation_node $parentnode + * @param section_info $section + * @param stdClass[] $activitiesdata Array of objects containing activities data indexed by cmid. + * @return navigation_node the section navigaiton node + */ + public function load_section_navigation($parentnode, $section, $activitiesdata): navigation_node { + $format = course_get_format($section->course); + $sectionname = $format->get_section_name($section); + $url = $format->get_view_url($section, ['navigation' => true]); + + $sectionnode = $parentnode->add( + text: $sectionname, + action: $url, + type: navigation_node::TYPE_SECTION, + key: $section->id, + icon: new pix_icon('i/section', ''), + ); + $sectionnode->nodetype = navigation_node::NODETYPE_BRANCH; + $sectionnode->hidden = (!$section->visible || !$section->available); + $sectionnode->add_attribute('data-section-name-for', $section->id); + + // Sections content are usually loaded via ajax but the sections from the requested breadcrumb. + if ($this->is_section_in_breadcrumb($section, $url)) { + $this->load_section_activities_navigation($sectionnode, $section, $activitiesdata); + } + return $sectionnode; + } + + /** + * Loads the activities for a section into the navigation structure. + * + * This method is called from global_navigation::load_section_navigation(), + * It is not intended to be called directly. + * + * @param navigation_node $sectionnode + * @param section_info $section + * @param stdClass[] $activitiesdata Array of objects containing activities data indexed by cmid. + */ + protected function load_section_activities_navigation( + navigation_node $sectionnode, + section_info $section, + array $activitiesdata + ): array { + global $CFG, $SITE; + + $activitynodes = []; + if (empty($activitiesdata)) { + return $activitynodes; + } + + foreach ($section->get_sequence_cm_infos() as $cm) { + $activitydata = $activitiesdata[$cm->id]; + + // If activity is a delegated section, load a section node instead of the activity one. + if ($activitydata->delegatedsection) { + $activitynodes[$activitydata->id] = $this->load_section_navigation( + parentnode: $sectionnode, + section: $activitydata->delegatedsection, + activitiesdata: $activitiesdata, + ); + continue; + } + + $activitynodes[$activitydata->id] = $this->load_activity_navigation($sectionnode, $activitydata); + } + + return $activitynodes; + } + + /** + * Loads an activity into the navigation structure. + * + * This method is called from global_navigation::load_section_activities_navigation(), + * It is not intended to be called directly. + * + * @param navigation_node $sectionnode + * @param stdClass $activitydata The acitivy navigation data generated from generate_sections_and_activities + * @return navigation_node + */ + protected function load_activity_navigation( + navigation_node $sectionnode, + stdClass $activitydata, + ): navigation_node { + global $SITE, $CFG; + + $showactivities = ($activitydata->course != $SITE->id || !empty($CFG->navshowfrontpagemods)); + + $icon = new pix_icon( + $activitydata->icon ?: 'monologo', + get_string('modulename', $activitydata->modname), + $activitydata->icon ? $activitydata->iconcomponent : $activitydata->modname, + ); + + // Prepare the default name and url for the node. + $displaycontext = \context_helper::get_navigation_filter_context(context_module::instance($activitydata->id)); + $activityname = format_string($activitydata->name, true, ['context' => $displaycontext]); + + $activitynode = $sectionnode->add( + text: $activityname, + action: $this->get_activity_action($activitydata, $activityname), + type: navigation_node::TYPE_ACTIVITY, + key: $activitydata->id, + icon: $icon, + ); + $activitynode->title(get_string('modulename', $activitydata->modname)); + $activitynode->hidden = $activitydata->hidden; + $activitynode->display = $showactivities && $activitydata->display; + $activitynode->nodetype = $activitydata->nodetype; + + return $activitynode; + } + + /** + * Returns the action for the activity. + * + * @param stdClass $activitydata The acitivy navigation data generated from generate_sections_and_activities + * @param string $activityname + * @return moodle_url|action_link + */ + protected function get_activity_action(stdClass $activitydata, string $activityname): moodle_url|action_link { + // A static counter for JS function naming. + static $legacyonclickcounter = 0; + + $action = new moodle_url($activitydata->url); + + // Check if the onclick property is set (puke!). + if (!empty($activitydata->onclick)) { + // Increment the counter so that we have a unique number. + $legacyonclickcounter++; + // Generate the function name we will use. + $functionname = 'legacy_activity_onclick_handler_' . $legacyonclickcounter; + $propogrationhandler = ''; + // Check if we need to cancel propogation. Remember inline onclick + // events would return false if they wanted to prevent propogation and the + // default action. + if (strpos($activitydata->onclick, 'return false')) { + $propogrationhandler = 'e.halt();'; + } + // Decode the onclick - it has already been encoded for display (puke). + $onclick = htmlspecialchars_decode($activitydata->onclick, ENT_QUOTES); + // Build the JS function the click event will call. + $jscode = "function {$functionname}(e) { $propogrationhandler $onclick }"; + $this->page->requires->js_amd_inline($jscode); + // Override the default url with the new action link. + $action = new action_link($action, $activityname, new component_action('click', $functionname)); + } + return $action; + } + + /** + * Loads all of the activities for a section into the navigation structure. + * + * @param navigation_node $sectionnode + * @param int $sectionnumber + * @param array $activities An array of activites as returned by {@link global_navigation::generate_sections_and_activities()} + * @param stdClass $course The course object the section and activities relate to. + * @return array Array of activity nodes + */ + #[\core\attribute\deprecated( + replacement: 'load_section_activities_navigation', + since: '4.5', + mdl: 'MDL-82845', + )] + protected function load_section_activities(navigation_node $sectionnode, $sectionnumber, array $activities, $course = null) { + \core\deprecation::emit_deprecation([self::class, __FUNCTION__]); + if (!is_object($course)) { + $activity = reset($activities); + $courseid = $activity->course; + } else { + $courseid = $course->id; + } + $sectionifo = get_fast_modinfo($courseid)->get_section_info($sectionnumber); + return $this->load_section_activities_navigation($sectionnode, $sectionifo, $activities); + } + /** + * Loads a stealth module from unavailable section + * @param navigation_node $coursenode + * @param stdClass|course_modinfo $modinfo + * @return navigation_node or null if not accessible + */ + protected function load_stealth_activity(navigation_node $coursenode, $modinfo) { + if (empty($modinfo->cms[$this->page->cm->id])) { + return null; + } + $cm = $modinfo->cms[$this->page->cm->id]; + if ($cm->icon) { + $icon = new pix_icon($cm->icon, get_string('modulename', $cm->modname), $cm->iconcomponent); + } else { + $icon = new pix_icon('monologo', get_string('modulename', $cm->modname), $cm->modname); + } + $url = $cm->url; + $activitynode = $coursenode->add(format_string($cm->name), $url, navigation_node::TYPE_ACTIVITY, null, $cm->id, $icon); + $activitynode->title(get_string('modulename', $cm->modname)); + $activitynode->hidden = (!$cm->visible); + if (!$cm->is_visible_on_course_page()) { + // Do not show any error here, let the page handle exception that activity is not visible for the current user. + // Also there may be no exception at all in case when teacher is logged in as student. + $activitynode->display = false; + } else if (!$url) { + // Don't show activities that don't have links! + $activitynode->display = false; + } else if (self::module_extends_navigation($cm->modname)) { + $activitynode->nodetype = navigation_node::NODETYPE_BRANCH; + } + return $activitynode; + } + /** + * Loads the navigation structure for the given activity into the activities node. + * + * This method utilises a callback within the modules lib.php file to load the + * content specific to activity given. + * + * The callback is a method: {modulename}_extend_navigation() + * Examples: + * * {@link forum_extend_navigation()} + * * {@link workshop_extend_navigation()} + * + * @param cm_info|stdClass $cm + * @param stdClass $course + * @param navigation_node $activity + * @return bool + */ + protected function load_activity($cm, stdClass $course, navigation_node $activity) { + global $CFG, $DB; + + // make sure we have a $cm from get_fast_modinfo as this contains activity access details + if (!($cm instanceof cm_info)) { + $modinfo = get_fast_modinfo($course); + $cm = $modinfo->get_cm($cm->id); + } + $activity->nodetype = navigation_node::NODETYPE_LEAF; + $activity->make_active(); + $file = $CFG->dirroot.'/mod/'.$cm->modname.'/lib.php'; + $function = $cm->modname.'_extend_navigation'; + + if (file_exists($file)) { + require_once($file); + if (function_exists($function)) { + $activtyrecord = $DB->get_record($cm->modname, array('id' => $cm->instance), '*', MUST_EXIST); + $function($activity, $course, $activtyrecord, $cm); + } + } + + // Allow the active advanced grading method plugin to append module navigation + $featuresfunc = $cm->modname.'_supports'; + if (function_exists($featuresfunc) && $featuresfunc(FEATURE_ADVANCED_GRADING)) { + require_once($CFG->dirroot.'/grade/grading/lib.php'); + $gradingman = get_grading_manager($cm->context, 'mod_'.$cm->modname); + $gradingman->extend_navigation($this, $activity); + } + + return $activity->has_children(); + } + /** + * Loads user specific information into the navigation in the appropriate place. + * + * If no user is provided the current user is assumed. + * + * @param stdClass $user + * @param bool $forceforcontext probably force something to be loaded somewhere (ask SamH if not sure what this means) + * @return bool + */ + protected function load_for_user($user=null, $forceforcontext=false) { + global $DB, $CFG, $USER, $SITE; + + require_once($CFG->dirroot . '/course/lib.php'); + + if ($user === null) { + // We can't require login here but if the user isn't logged in we don't + // want to show anything + if (!isloggedin() || isguestuser()) { + return false; + } + $user = $USER; + } else if (!is_object($user)) { + // If the user is not an object then get them from the database + $select = context_helper::get_preload_record_columns_sql('ctx'); + $sql = "SELECT u.*, $select + FROM {user} u + JOIN {context} ctx ON u.id = ctx.instanceid + WHERE u.id = :userid AND + ctx.contextlevel = :contextlevel"; + $user = $DB->get_record_sql($sql, array('userid' => (int)$user, 'contextlevel' => CONTEXT_USER), MUST_EXIST); + context_helper::preload_from_record($user); + } + + $iscurrentuser = ($user->id == $USER->id); + + $usercontext = context_user::instance($user->id); + + // Get the course set against the page, by default this will be the site + $course = $this->page->course; + $baseargs = array('id'=>$user->id); + if ($course->id != $SITE->id && (!$iscurrentuser || $forceforcontext)) { + $coursenode = $this->add_course($course, false, self::COURSE_CURRENT); + $baseargs['course'] = $course->id; + $coursecontext = context_course::instance($course->id); + $issitecourse = false; + } else { + // Load all categories and get the context for the system + $coursecontext = context_system::instance(); + $issitecourse = true; + } + + // Create a node to add user information under. + $usersnode = null; + if (!$issitecourse) { + // Not the current user so add it to the participants node for the current course. + $usersnode = $coursenode->get('participants', navigation_node::TYPE_CONTAINER); + $userviewurl = new moodle_url('/user/view.php', $baseargs); + } else if ($USER->id != $user->id) { + // This is the site so add a users node to the root branch. + $usersnode = $this->rootnodes['users']; + if (course_can_view_participants($coursecontext)) { + $usersnode->action = new moodle_url('/user/index.php', array('id' => $course->id)); + } + $userviewurl = new moodle_url('/user/profile.php', $baseargs); + } + if (!$usersnode) { + // We should NEVER get here, if the course hasn't been populated + // with a participants node then the navigaiton either wasn't generated + // for it (you are missing a require_login or set_context call) or + // you don't have access.... in the interests of no leaking informatin + // we simply quit... + return false; + } + // Add a branch for the current user. + // Only reveal user details if $user is the current user, or a user to which the current user has access. + $viewprofile = true; + if (!$iscurrentuser) { + require_once($CFG->dirroot . '/user/lib.php'); + if ($this->page->context->contextlevel == CONTEXT_USER && !has_capability('moodle/user:viewdetails', $usercontext) ) { + $viewprofile = false; + } else if ($this->page->context->contextlevel != CONTEXT_USER && !user_can_view_profile($user, $course, $usercontext)) { + $viewprofile = false; + } + if (!$viewprofile) { + $viewprofile = user_can_view_profile($user, null, $usercontext); + } + } + + // Now, conditionally add the user node. + if ($viewprofile) { + $canseefullname = has_capability('moodle/site:viewfullnames', $coursecontext); + $usernode = $usersnode->add(fullname($user, $canseefullname), $userviewurl, self::TYPE_USER, null, 'user' . $user->id); + } else { + $usernode = $usersnode->add(get_string('user')); + } + + if ($this->page->context->contextlevel == CONTEXT_USER && $user->id == $this->page->context->instanceid) { + $usernode->make_active(); + } + + // Add user information to the participants or user node. + if ($issitecourse) { + + // If the user is the current user or has permission to view the details of the requested + // user than add a view profile link. + if ($iscurrentuser || has_capability('moodle/user:viewdetails', $coursecontext) || + has_capability('moodle/user:viewdetails', $usercontext)) { + if ($issitecourse || ($iscurrentuser && !$forceforcontext)) { + $usernode->add(get_string('viewprofile'), new moodle_url('/user/profile.php', $baseargs)); + } else { + $usernode->add(get_string('viewprofile'), new moodle_url('/user/view.php', $baseargs)); + } + } + + // Add blog nodes. + if (!empty($CFG->enableblogs)) { + if (!$this->cache->cached('userblogoptions'.$user->id)) { + require_once($CFG->dirroot.'/blog/lib.php'); + // Get all options for the user. + $options = blog_get_options_for_user($user); + $this->cache->set('userblogoptions'.$user->id, $options); + } else { + $options = $this->cache->{'userblogoptions'.$user->id}; + } + + if (count($options) > 0) { + $blogs = $usernode->add(get_string('blogs', 'blog'), null, navigation_node::TYPE_CONTAINER); + foreach ($options as $type => $option) { + if ($type == "rss") { + $blogs->add($option['string'], $option['link'], settings_navigation::TYPE_SETTING, null, null, + new pix_icon('i/rss', '')); + } else { + $blogs->add($option['string'], $option['link']); + } + } + } + } + + // Add the messages link. + // It is context based so can appear in the user's profile and in course participants information. + if (!empty($CFG->messaging)) { + $messageargs = array('user1' => $USER->id); + if ($USER->id != $user->id) { + $messageargs['user2'] = $user->id; + } + $url = new moodle_url('/message/index.php', $messageargs); + $usernode->add(get_string('messages', 'message'), $url, self::TYPE_SETTING, null, 'messages'); + } + + // Add the "My private files" link. + // This link doesn't have a unique display for course context so only display it under the user's profile. + if ($issitecourse && $iscurrentuser && has_capability('moodle/user:manageownfiles', $usercontext)) { + $url = new moodle_url('/user/files.php'); + $usernode->add(get_string('privatefiles'), $url, self::TYPE_SETTING, null, 'privatefiles'); + } + + // Add a node to view the users notes if permitted. + if (!empty($CFG->enablenotes) && + has_any_capability(array('moodle/notes:manage', 'moodle/notes:view'), $coursecontext)) { + $url = new moodle_url('/notes/index.php', array('user' => $user->id)); + if ($coursecontext->instanceid != SITEID) { + $url->param('course', $coursecontext->instanceid); + } + $usernode->add(get_string('notes', 'notes'), $url); + } + + // Show the grades node. + if (($issitecourse && $iscurrentuser) || has_capability('moodle/user:viewdetails', $usercontext)) { + require_once($CFG->dirroot . '/user/lib.php'); + // Set the grades node to link to the "Grades" page. + if ($course->id == SITEID) { + $url = user_mygrades_url($user->id, $course->id); + } else { // Otherwise we are in a course and should redirect to the user grade report (Activity report version). + $url = new moodle_url('/course/user.php', array('mode' => 'grade', 'id' => $course->id, 'user' => $user->id)); + } + if ($USER->id != $user->id) { + $usernode->add(get_string('grades', 'grades'), $url, self::TYPE_SETTING, null, 'usergrades'); + } else { + $usernode->add(get_string('grades', 'grades'), $url); + } + } + + // If the user is the current user add the repositories for the current user. + $hiddenfields = array_flip(explode(',', $CFG->hiddenuserfields)); + if (!$iscurrentuser && + $course->id == $SITE->id && + has_capability('moodle/user:viewdetails', $usercontext) && + (!in_array('mycourses', $hiddenfields) || has_capability('moodle/user:viewhiddendetails', $coursecontext))) { + + // Add view grade report is permitted. + $reports = core_component::get_plugin_list('gradereport'); + arsort($reports); // User is last, we want to test it first. + + $userscourses = enrol_get_users_courses($user->id, false, '*'); + $userscoursesnode = $usernode->add(get_string('courses')); + + $count = 0; + foreach ($userscourses as $usercourse) { + if ($count === (int)$CFG->navcourselimit) { + $url = new moodle_url('/user/profile.php', array('id' => $user->id, 'showallcourses' => 1)); + $userscoursesnode->add(get_string('showallcourses'), $url); + break; + } + $count++; + $usercoursecontext = context_course::instance($usercourse->id); + $usercourseshortname = format_string($usercourse->shortname, true, array('context' => $usercoursecontext)); + $usercoursenode = $userscoursesnode->add($usercourseshortname, new moodle_url('/user/view.php', + array('id' => $user->id, 'course' => $usercourse->id)), self::TYPE_CONTAINER); + + $gradeavailable = has_capability('moodle/grade:view', $usercoursecontext); + if (!$gradeavailable && !empty($usercourse->showgrades) && is_array($reports) && !empty($reports)) { + foreach ($reports as $plugin => $plugindir) { + if (has_capability('gradereport/'.$plugin.':view', $usercoursecontext)) { + // Stop when the first visible plugin is found. + $gradeavailable = true; + break; + } + } + } + + if ($gradeavailable) { + $url = new moodle_url('/grade/report/index.php', array('id' => $usercourse->id)); + $usercoursenode->add(get_string('grades'), $url, self::TYPE_SETTING, null, null, + new pix_icon('i/grades', '')); + } + + // Add a node to view the users notes if permitted. + if (!empty($CFG->enablenotes) && + has_any_capability(array('moodle/notes:manage', 'moodle/notes:view'), $usercoursecontext)) { + $url = new moodle_url('/notes/index.php', array('user' => $user->id, 'course' => $usercourse->id)); + $usercoursenode->add(get_string('notes', 'notes'), $url, self::TYPE_SETTING); + } + + if (can_access_course($usercourse, $user->id, '', true)) { + $usercoursenode->add(get_string('entercourse'), new moodle_url('/course/view.php', + array('id' => $usercourse->id)), self::TYPE_SETTING, null, null, new pix_icon('i/course', '')); + } + + $reporttab = $usercoursenode->add(get_string('activityreports')); + + $reportfunctions = get_plugin_list_with_function('report', 'extend_navigation_user', 'lib.php'); + foreach ($reportfunctions as $reportfunction) { + $reportfunction($reporttab, $user, $usercourse); + } + + $reporttab->trim_if_empty(); + } + } + + // Let plugins hook into user navigation. + $pluginsfunction = get_plugins_with_function('extend_navigation_user', 'lib.php'); + foreach ($pluginsfunction as $plugintype => $plugins) { + if ($plugintype != 'report') { + foreach ($plugins as $pluginfunction) { + $pluginfunction($usernode, $user, $usercontext, $course, $coursecontext); + } + } + } + } + return true; + } + + /** + * This method simply checks to see if a given module can extend the navigation. + * + * @todo (MDL-25290) A shared caching solution should be used to save details on what extends navigation. + * + * @param string $modname + * @return bool + */ + public static function module_extends_navigation($modname) { + global $CFG; + static $extendingmodules = array(); + if (!array_key_exists($modname, $extendingmodules)) { + $extendingmodules[$modname] = false; + $file = $CFG->dirroot.'/mod/'.$modname.'/lib.php'; + if (file_exists($file)) { + $function = $modname.'_extend_navigation'; + require_once($file); + $extendingmodules[$modname] = (function_exists($function)); + } + } + return $extendingmodules[$modname]; + } + /** + * Extends the navigation for the given user. + * + * @param stdClass $user A user from the database + */ + public function extend_for_user($user) { + $this->extendforuser[] = $user; + } + + /** + * Returns all of the users the navigation is being extended for + * + * @return array An array of extending users. + */ + public function get_extending_users() { + return $this->extendforuser; + } + /** + * Adds the given course to the navigation structure. + * + * @param stdClass $course + * @param bool $forcegeneric + * @param bool $ismycourse + * @return navigation_node + */ + public function add_course(stdClass $course, $forcegeneric = false, $coursetype = self::COURSE_OTHER) { + global $CFG, $SITE; + + // We found the course... we can return it now :) + if (!$forcegeneric && array_key_exists($course->id, $this->addedcourses)) { + return $this->addedcourses[$course->id]; + } + + $coursecontext = context_course::instance($course->id); + + if ($coursetype != self::COURSE_MY && $coursetype != self::COURSE_CURRENT && $course->id != $SITE->id) { + if (is_role_switched($course->id)) { + // user has to be able to access course in order to switch, let's skip the visibility test here + } else if (!core_course_category::can_view_course_info($course)) { + return false; + } + } + + $issite = ($course->id == $SITE->id); + $displaycontext = \context_helper::get_navigation_filter_context($coursecontext); + $shortname = format_string($course->shortname, true, ['context' => $displaycontext]); + $fullname = format_string($course->fullname, true, ['context' => $displaycontext]); + // This is the name that will be shown for the course. + $coursename = empty($CFG->navshowfullcoursenames) ? $shortname : $fullname; + + if ($coursetype == self::COURSE_CURRENT) { + if ($coursenode = $this->rootnodes['mycourses']->find($course->id, self::TYPE_COURSE)) { + return $coursenode; + } else { + $coursetype = self::COURSE_OTHER; + } + } + + // Can the user expand the course to see its content. + $canexpandcourse = true; + if ($issite) { + $parent = $this; + $url = null; + if (empty($CFG->usesitenameforsitepages)) { + $coursename = get_string('sitepages'); + } + } else if ($coursetype == self::COURSE_CURRENT) { + $parent = $this->rootnodes['currentcourse']; + $url = new moodle_url('/course/view.php', array('id'=>$course->id)); + $canexpandcourse = $this->can_expand_course($course); + } else if ($coursetype == self::COURSE_MY && !$forcegeneric) { + if (!empty($CFG->navshowmycoursecategories) && ($parent = $this->rootnodes['mycourses']->find($course->category, self::TYPE_MY_CATEGORY))) { + // Nothing to do here the above statement set $parent to the category within mycourses. + } else { + $parent = $this->rootnodes['mycourses']; + } + $url = new moodle_url('/course/view.php', array('id'=>$course->id)); + } else { + $parent = $this->rootnodes['courses']; + $url = new moodle_url('/course/view.php', array('id'=>$course->id)); + // They can only expand the course if they can access it. + $canexpandcourse = $this->can_expand_course($course); + if (!empty($course->category) && $this->show_categories($coursetype == self::COURSE_MY)) { + if (!$this->is_category_fully_loaded($course->category)) { + // We need to load the category structure for this course + $this->load_all_categories($course->category, false); + } + if (array_key_exists($course->category, $this->addedcategories)) { + $parent = $this->addedcategories[$course->category]; + // This could lead to the course being created so we should check whether it is the case again + if (!$forcegeneric && array_key_exists($course->id, $this->addedcourses)) { + return $this->addedcourses[$course->id]; + } + } + } + } + + $coursenode = $parent->add($coursename, $url, self::TYPE_COURSE, $shortname, $course->id, new pix_icon('i/course', '')); + $coursenode->showinflatnavigation = $coursetype == self::COURSE_MY; + + $coursenode->hidden = (!$course->visible); + $coursenode->title(format_string($course->fullname, true, ['context' => $displaycontext, 'escape' => false])); + if ($canexpandcourse) { + // This course can be expanded by the user, make it a branch to make the system aware that its expandable by ajax. + $coursenode->nodetype = self::NODETYPE_BRANCH; + $coursenode->isexpandable = true; + } else { + $coursenode->nodetype = self::NODETYPE_LEAF; + $coursenode->isexpandable = false; + } + if (!$forcegeneric) { + $this->addedcourses[$course->id] = $coursenode; + } + + return $coursenode; + } + + /** + * Returns a cache instance to use for the expand course cache. + * @return cache_session + */ + protected function get_expand_course_cache() { + if ($this->cacheexpandcourse === null) { + $this->cacheexpandcourse = cache::make('core', 'navigation_expandcourse'); + } + return $this->cacheexpandcourse; + } + + /** + * Checks if a user can expand a course in the navigation. + * + * We use a cache here because in order to be accurate we need to call can_access_course which is a costly function. + * Because this functionality is basic + non-essential and because we lack good event triggering this cache + * permits stale data. + * In the situation the user is granted access to a course after we've initialised this session cache the cache + * will be stale. + * It is brought up to date in only one of two ways. + * 1. The user logs out and in again. + * 2. The user browses to the course they've just being given access to. + * + * Really all this controls is whether the node is shown as expandable or not. It is uber un-important. + * + * @param stdClass $course + * @return bool + */ + protected function can_expand_course($course) { + $cache = $this->get_expand_course_cache(); + $canexpand = $cache->get($course->id); + if ($canexpand === false) { + $canexpand = isloggedin() && can_access_course($course, null, '', true); + $canexpand = (int)$canexpand; + $cache->set($course->id, $canexpand); + } + return ($canexpand === 1); + } + + /** + * Returns true if the category has already been loaded as have any child categories + * + * @param int $categoryid + * @return bool + */ + protected function is_category_fully_loaded($categoryid) { + return (array_key_exists($categoryid, $this->addedcategories) && ($this->allcategoriesloaded || $this->addedcategories[$categoryid]->children->count() > 0)); + } + + /** + * Adds essential course nodes to the navigation for the given course. + * + * This method adds nodes such as reports, blogs and participants + * + * @param navigation_node $coursenode + * @param stdClass $course + * @return bool returns true on successful addition of a node. + */ + public function add_course_essentials($coursenode, stdClass $course) { + global $CFG, $SITE; + require_once($CFG->dirroot . '/course/lib.php'); + + if ($course->id == $SITE->id) { + return $this->add_front_page_course_essentials($coursenode, $course); + } + + if ($coursenode == false || !($coursenode instanceof navigation_node) || $coursenode->get('participants', navigation_node::TYPE_CONTAINER)) { + return true; + } + + $navoptions = course_get_user_navigation_options($this->page->context, $course); + + //Participants + if ($navoptions->participants) { + $participants = $coursenode->add(get_string('participants'), new moodle_url('/user/index.php?id='.$course->id), + self::TYPE_CONTAINER, get_string('participants'), 'participants', new pix_icon('i/users', '')); + + if ($navoptions->blogs) { + $blogsurls = new moodle_url('/blog/index.php'); + if ($currentgroup = groups_get_course_group($course, true)) { + $blogsurls->param('groupid', $currentgroup); + } else { + $blogsurls->param('courseid', $course->id); + } + $participants->add(get_string('blogscourse', 'blog'), $blogsurls->out(), self::TYPE_SETTING, null, 'courseblogs'); + } + + if ($navoptions->notes) { + $participants->add(get_string('notes', 'notes'), new moodle_url('/notes/index.php', array('filtertype' => 'course', 'filterselect' => $course->id)), self::TYPE_SETTING, null, 'currentcoursenotes'); + } + } else if (count($this->extendforuser) > 0) { + $coursenode->add(get_string('participants'), null, self::TYPE_CONTAINER, get_string('participants'), 'participants'); + } else if ($siteparticipantsnode = $this->rootnodes['site']->get('participants', self::TYPE_CUSTOM)) { + // The participants node was added for the site, but cannot be viewed inside the course itself, so remove. + $siteparticipantsnode->remove(); + } + + // Badges. + if ($navoptions->badges) { + $url = new moodle_url('/badges/index.php', ['type' => 2, 'id' => $course->id]); + + $coursenode->add(get_string('coursebadges', 'badges'), $url, + navigation_node::TYPE_SETTING, null, 'badgesview', + new pix_icon('i/badge', get_string('coursebadges', 'badges'))); + } + + // Check access to the course and competencies page. + if ($navoptions->competencies) { + // Just a link to course competency. + $title = get_string('competencies', 'core_competency'); + $path = new moodle_url("/admin/tool/lp/coursecompetencies.php", array('courseid' => $course->id)); + $coursenode->add($title, $path, navigation_node::TYPE_SETTING, null, 'competencies', + new pix_icon('i/competencies', '')); + } + if ($navoptions->grades) { + $url = new moodle_url('/grade/report/index.php', array('id'=>$course->id)); + $gradenode = $coursenode->add(get_string('grades'), $url, self::TYPE_SETTING, null, + 'grades', new pix_icon('i/grades', '')); + // If the page type matches the grade part, then make the nav drawer grade node (incl. all sub pages) active. + if ($this->page->context->contextlevel < CONTEXT_MODULE && strpos($this->page->pagetype, 'grade-') === 0) { + $gradenode->make_active(); + } + } + + // Add link for configuring communication. + if ($navoptions->communication) { + $url = new moodle_url('/communication/configure.php', [ + 'contextid' => \core\context\course::instance($course->id)->id, + 'instanceid' => $course->id, + 'instancetype' => 'coursecommunication', + 'component' => 'core_course', + ]); + $coursenode->add(get_string('communication', 'communication'), $url, + navigation_node::TYPE_SETTING, null, 'communication'); + } + + if ($navoptions->overview) { + $coursenode->add( + text: get_string('activities'), + action: new moodle_url('/course/overview.php', ['id' => $course->id]), + type: self::TYPE_CONTAINER, + key: 'courseoverview', + icon: new pix_icon('i/info', ''), + ); + } + + return true; + } + /** + * This generates the structure of the course that won't be generated when + * the modules and sections are added. + * + * Things such as the reports branch, the participants branch, blogs... get + * added to the course node by this method. + * + * @param navigation_node $coursenode + * @param stdClass $course + * @return bool True for successfull generation + */ + public function add_front_page_course_essentials(navigation_node $coursenode, stdClass $course) { + global $CFG, $USER, $COURSE, $SITE; + require_once($CFG->dirroot . '/course/lib.php'); + + if ($coursenode == false || $coursenode->get('frontpageloaded', navigation_node::TYPE_CUSTOM)) { + return true; + } + + $systemcontext = context_system::instance(); + $navoptions = course_get_user_navigation_options($systemcontext, $course); + + // Hidden node that we use to determine if the front page navigation is loaded. + // This required as there are not other guaranteed nodes that may be loaded. + $coursenode->add('frontpageloaded', null, self::TYPE_CUSTOM, null, 'frontpageloaded')->display = false; + + // Add My courses to the site pages within the navigation structure so the block can read it. + $coursenode->add(get_string('mycourses'), new moodle_url('/my/courses.php'), self::TYPE_CUSTOM, null, 'mycourses'); + + // Participants. + if ($navoptions->participants) { + $coursenode->add(get_string('participants'), new moodle_url('/user/index.php?id='.$course->id), + self::TYPE_CUSTOM, get_string('participants'), 'participants'); + } + + // Blogs. + if ($navoptions->blogs) { + $blogsurls = new moodle_url('/blog/index.php'); + $coursenode->add(get_string('blogssite', 'blog'), $blogsurls->out(), self::TYPE_SYSTEM, null, 'siteblog'); + } + + $filterselect = 0; + + // Badges. + if ($navoptions->badges) { + $url = new moodle_url($CFG->wwwroot . '/badges/index.php', ['type' => 1]); + $coursenode->add(get_string('sitebadges', 'badges'), $url, navigation_node::TYPE_CUSTOM); + } + + // Notes. + if ($navoptions->notes) { + $coursenode->add(get_string('notes', 'notes'), new moodle_url('/notes/index.php', + array('filtertype' => 'course', 'filterselect' => $filterselect)), self::TYPE_SETTING, null, 'notes'); + } + + // Tags + if ($navoptions->tags) { + $node = $coursenode->add(get_string('tags', 'tag'), new moodle_url('/tag/search.php'), + self::TYPE_SETTING, null, 'tags'); + } + + // Search. + if ($navoptions->search) { + $node = $coursenode->add(get_string('search', 'search'), new moodle_url('/search/index.php'), + self::TYPE_SETTING, null, 'search'); + } + + if (isloggedin()) { + $usercontext = context_user::instance($USER->id); + if (has_capability('moodle/user:manageownfiles', $usercontext)) { + $url = new moodle_url('/user/files.php'); + $node = $coursenode->add(get_string('privatefiles'), $url, + self::TYPE_SETTING, null, 'privatefiles', new pix_icon('i/privatefiles', '')); + $node->display = false; + $node->showinflatnavigation = true; + $node->mainnavonly = true; + } + } + + if (isloggedin()) { + $context = $this->page->context; + switch ($context->contextlevel) { + case CONTEXT_COURSECAT: + // OK, expected context level. + break; + case CONTEXT_COURSE: + // OK, expected context level if not on frontpage. + if ($COURSE->id != $SITE->id) { + break; + } + default: + // If this context is part of a course (excluding frontpage), use the course context. + // Otherwise, use the system context. + $coursecontext = $context->get_course_context(false); + if ($coursecontext && $coursecontext->instanceid !== $SITE->id) { + $context = $coursecontext; + } else { + $context = $systemcontext; + } + } + + $params = ['contextid' => $context->id]; + if (has_capability('moodle/contentbank:access', $context)) { + $url = new moodle_url('/contentbank/index.php', $params); + $node = $coursenode->add(get_string('contentbank'), $url, + self::TYPE_CUSTOM, null, 'contentbank', new pix_icon('i/contentbank', '')); + $node->showinflatnavigation = true; + } + } + + return true; + } + + /** + * Clears the navigation cache + */ + public function clear_cache() { + $this->cache->clear(); + } + + /** + * Sets an expansion limit for the navigation + * + * The expansion limit is used to prevent the display of content that has a type + * greater than the provided $type. + * + * Can be used to ensure things such as activities or activity content don't get + * shown on the navigation. + * They are still generated in order to ensure the navbar still makes sense. + * + * @param int $type One of navigation_node::TYPE_* + * @return bool true when complete. + */ + public function set_expansion_limit($type) { + global $SITE; + $nodes = $this->find_all_of_type($type); + + // We only want to hide specific types of nodes. + // Only nodes that represent "structure" in the navigation tree should be hidden. + // If we hide all nodes then we risk hiding vital information. + $typestohide = array( + self::TYPE_CATEGORY, + self::TYPE_COURSE, + self::TYPE_SECTION, + self::TYPE_ACTIVITY + ); + + foreach ($nodes as $node) { + // We need to generate the full site node + if ($type == self::TYPE_COURSE && $node->key == $SITE->id) { + continue; + } + foreach ($node->children as $child) { + $child->hide($typestohide); + } + } + return true; + } + /** + * Attempts to get the navigation with the given key from this nodes children. + * + * This function only looks at this nodes children, it does NOT look recursivily. + * If the node can't be found then false is returned. + * + * If you need to search recursivily then use the {@link global_navigation::find()} method. + * + * Note: If you are trying to set the active node {@link navigation_node::override_active_url()} + * may be of more use to you. + * + * @param string|int $key The key of the node you wish to receive. + * @param int $type One of navigation_node::TYPE_* + * @return navigation_node|false + */ + public function get($key, $type = null) { + if (!$this->initialised) { + $this->initialise(); + } + return parent::get($key, $type); + } + + /** + * Searches this nodes children and their children to find a navigation node + * with the matching key and type. + * + * This method is recursive and searches children so until either a node is + * found or there are no more nodes to search. + * + * If you know that the node being searched for is a child of this node + * then use the {@link global_navigation::get()} method instead. + * + * Note: If you are trying to set the active node {@link navigation_node::override_active_url()} + * may be of more use to you. + * + * @param string|int $key The key of the node you wish to receive. + * @param ?int $type One of navigation_node::TYPE_* + * @return navigation_node|false + */ + public function find($key, $type) { + if (!$this->initialised) { + $this->initialise(); + } + if ($type == self::TYPE_ROOTNODE && array_key_exists($key, $this->rootnodes)) { + return $this->rootnodes[$key]; + } + return parent::find($key, $type); + } + + /** + * They've expanded the 'my courses' branch. + */ + protected function load_courses_enrolled() { + global $CFG; + + $limit = (int) $CFG->navcourselimit; + + $courses = enrol_get_my_courses('*'); + $flatnavcourses = []; + + // Go through the courses and see which ones we want to display in the flatnav. + foreach ($courses as $course) { + $classify = course_classify_for_timeline($course); + + if ($classify == COURSE_TIMELINE_INPROGRESS) { + $flatnavcourses[$course->id] = $course; + } + } + + // Get the number of courses that can be displayed in the nav block and in the flatnav. + $numtotalcourses = count($courses); + $numtotalflatnavcourses = count($flatnavcourses); + + // Reduce the size of the arrays to abide by the 'navcourselimit' setting. + $courses = array_slice($courses, 0, $limit, true); + $flatnavcourses = array_slice($flatnavcourses, 0, $limit, true); + + // Get the number of courses we are going to show for each. + $numshowncourses = count($courses); + $numshownflatnavcourses = count($flatnavcourses); + if ($numshowncourses && $this->show_my_categories()) { + // Generate an array containing unique values of all the courses' categories. + $categoryids = array(); + foreach ($courses as $course) { + if (in_array($course->category, $categoryids)) { + continue; + } + $categoryids[] = $course->category; + } + + // Array of category IDs that include the categories of the user's courses and the related course categories. + $fullpathcategoryids = []; + // Get the course categories for the enrolled courses' category IDs. + $mycoursecategories = core_course_category::get_many($categoryids); + // Loop over each of these categories and build the category tree using each category's path. + foreach ($mycoursecategories as $mycoursecat) { + $pathcategoryids = explode('/', $mycoursecat->path); + // First element of the exploded path is empty since paths begin with '/'. + array_shift($pathcategoryids); + // Merge the exploded category IDs into the full list of category IDs that we will fetch. + $fullpathcategoryids = array_merge($fullpathcategoryids, $pathcategoryids); + } + + // Fetch all of the categories related to the user's courses. + $pathcategories = core_course_category::get_many($fullpathcategoryids); + // Loop over each of these categories and build the category tree. + foreach ($pathcategories as $coursecat) { + // No need to process categories that have already been added. + if (isset($this->addedcategories[$coursecat->id])) { + continue; + } + // Skip categories that are not visible. + if (!$coursecat->is_uservisible()) { + continue; + } + + // Get this course category's parent node. + $parent = null; + if ($coursecat->parent && isset($this->addedcategories[$coursecat->parent])) { + $parent = $this->addedcategories[$coursecat->parent]; + } + if (!$parent) { + // If it has no parent, then it should be right under the My courses node. + $parent = $this->rootnodes['mycourses']; + } + + // Build the category object based from the coursecat object. + $mycategory = new stdClass(); + $mycategory->id = $coursecat->id; + $mycategory->name = $coursecat->name; + $mycategory->visible = $coursecat->visible; + + // Add this category to the nav tree. + $this->add_category($mycategory, $parent, self::TYPE_MY_CATEGORY); + } + } + + // Go through each course now and add it to the nav block, and the flatnav if applicable. + foreach ($courses as $course) { + $node = $this->add_course($course, false, self::COURSE_MY); + if ($node) { + $node->showinflatnavigation = false; + // Check if we should also add this to the flat nav as well. + if (isset($flatnavcourses[$course->id])) { + $node->showinflatnavigation = true; + } + } + } + + // Go through each course in the flatnav now. + foreach ($flatnavcourses as $course) { + // Check if we haven't already added it. + if (!isset($courses[$course->id])) { + // Ok, add it to the flatnav only. + $node = $this->add_course($course, false, self::COURSE_MY); + $node->display = false; + $node->showinflatnavigation = true; + } + } + + $showmorelinkinnav = $numtotalcourses > $numshowncourses; + $showmorelinkinflatnav = $numtotalflatnavcourses > $numshownflatnavcourses; + // Show a link to the course page if there are more courses the user is enrolled in. + if ($showmorelinkinnav || $showmorelinkinflatnav) { + // Adding hash to URL so the link is not highlighted in the navigation when clicked. + $url = new moodle_url('/my/courses.php'); + $parent = $this->rootnodes['mycourses']; + $coursenode = $parent->add(get_string('morenavigationlinks'), $url, self::TYPE_CUSTOM, null, self::COURSE_INDEX_PAGE); + + if ($showmorelinkinnav) { + $coursenode->display = true; + } + + if ($showmorelinkinflatnav) { + $coursenode->showinflatnavigation = true; + } + } + } +} diff --git a/public/lib/classes/navigation/global_navigation_for_ajax.php b/public/lib/classes/navigation/global_navigation_for_ajax.php new file mode 100644 index 00000000000..b0fc9d27904 --- /dev/null +++ b/public/lib/classes/navigation/global_navigation_for_ajax.php @@ -0,0 +1,278 @@ +. + +/** + * The global navigation class used especially for AJAX requests. + * + * The primary methods that are used in the global navigation class have been overriden + * to ensure that only the relevant branch is generated at the root of the tree. + * This can be done because AJAX is only used when the backwards structure for the + * requested branch exists. + * This has been done only because it shortens the amounts of information that is generated + * which of course will speed up the response time.. because no one likes laggy AJAX. + * + * @package core + * @category navigation + * @copyright 2009 Sam Hemelryk + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class global_navigation_for_ajax extends global_navigation { + + /** @var int used for determining what type of navigation_node::TYPE_* is being used */ + protected $branchtype; + + /** @var int the instance id */ + protected $instanceid; + + /** @var array Holds an array of expandable nodes */ + protected $expandable = array(); + + /** + * Constructs the navigation for use in an AJAX request + * + * @param moodle_page $page moodle_page object + * @param int $branchtype + * @param int $id + */ + public function __construct($page, $branchtype, $id) { + $this->page = $page; + $this->cache = new navigation_cache(NAVIGATION_CACHE_NAME); + $this->children = new navigation_node_collection(); + $this->branchtype = $branchtype; + $this->instanceid = $id; + $this->initialise(); + } + /** + * Initialise the navigation given the type and id for the branch to expand. + * + * @return array An array of the expandable nodes + */ + public function initialise() { + global $DB, $SITE; + + if ($this->initialised || during_initial_install()) { + return $this->expandable; + } + $this->initialised = true; + + $this->rootnodes = array(); + $this->rootnodes['site'] = $this->add_course($SITE); + $this->rootnodes['mycourses'] = $this->add( + get_string('mycourses'), + new moodle_url('/my/courses.php'), + self::TYPE_ROOTNODE, + null, + 'mycourses' + ); + $this->rootnodes['courses'] = $this->add(get_string('courses'), null, self::TYPE_ROOTNODE, null, 'courses'); + // The courses branch is always displayed, and is always expandable (although may be empty). + // This mimicks what is done during {@link global_navigation::initialise()}. + $this->rootnodes['courses']->isexpandable = true; + + // Branchtype will be one of navigation_node::TYPE_* + switch ($this->branchtype) { + case 0: + if ($this->instanceid === 'mycourses') { + $this->load_courses_enrolled(); + } else if ($this->instanceid === 'courses') { + $this->load_courses_other(); + } + break; + case self::TYPE_CATEGORY : + $this->load_category($this->instanceid); + break; + case self::TYPE_MY_CATEGORY : + $this->load_category($this->instanceid, self::TYPE_MY_CATEGORY); + break; + case self::TYPE_COURSE : + $course = $DB->get_record('course', array('id' => $this->instanceid), '*', MUST_EXIST); + if (!can_access_course($course, null, '', true)) { + // Thats OK all courses are expandable by default. We don't need to actually expand it we can just + // add the course node and break. This leads to an empty node. + $this->add_course($course); + break; + } + require_course_login($course, true, null, false, true); + $this->page->set_context(context_course::instance($course->id)); + $coursenode = $this->add_course($course, false, self::COURSE_CURRENT); + $this->add_course_essentials($coursenode, $course); + $this->load_course_sections($course, $coursenode); + break; + case self::TYPE_SECTION : + $sql = 'SELECT c.*, cs.section AS sectionnumber + FROM {course} c + LEFT JOIN {course_sections} cs ON cs.course = c.id + WHERE cs.id = ?'; + $course = $DB->get_record_sql($sql, array($this->instanceid), MUST_EXIST); + require_course_login($course, true, null, false, true); + $this->page->set_context(context_course::instance($course->id)); + $coursenode = $this->add_course($course, false, self::COURSE_CURRENT); + $this->add_course_essentials($coursenode, $course); + $this->load_course_sections($course, $coursenode, $course->sectionnumber); + break; + case self::TYPE_ACTIVITY : + $sql = "SELECT c.* + FROM {course} c + JOIN {course_modules} cm ON cm.course = c.id + WHERE cm.id = :cmid"; + $params = array('cmid' => $this->instanceid); + $course = $DB->get_record_sql($sql, $params, MUST_EXIST); + $modinfo = get_fast_modinfo($course); + $cm = $modinfo->get_cm($this->instanceid); + require_course_login($course, true, $cm, false, true); + $this->page->set_context(context_module::instance($cm->id)); + $coursenode = $this->add_course($course, false, self::COURSE_CURRENT); + $this->load_course_sections($course, $coursenode, null, $cm); + $activitynode = $coursenode->find($cm->id, self::TYPE_ACTIVITY); + if ($activitynode) { + $modulenode = $this->load_activity($cm, $course, $activitynode); + } + break; + default: + throw new Exception('Unknown type'); + return $this->expandable; + } + + if ($this->page->context->contextlevel == CONTEXT_COURSE && $this->page->context->instanceid != $SITE->id) { + $this->load_for_user(null, true); + } + + // Give the local plugins a chance to include some navigation if they want. + $this->load_local_plugin_navigation(); + + $this->find_expandable($this->expandable); + return $this->expandable; + } + + /** + * They've expanded the general 'courses' branch. + */ + protected function load_courses_other() { + $this->load_all_courses(); + } + + /** + * Loads a single category into the AJAX navigation. + * + * This function is special in that it doesn't concern itself with the parent of + * the requested category or its siblings. + * This is because with the AJAX navigation we know exactly what is wanted and only need to + * request that. + * + * @global moodle_database $DB + * @param int $categoryid id of category to load in navigation. + * @param int $nodetype type of node, if category is under MyHome then it's TYPE_MY_CATEGORY + * @return void. + */ + protected function load_category($categoryid, $nodetype = self::TYPE_CATEGORY) { + global $CFG, $DB; + + $limit = 20; + if (!empty($CFG->navcourselimit)) { + $limit = (int)$CFG->navcourselimit; + } + + $catcontextsql = context_helper::get_preload_record_columns_sql('ctx'); + $sql = "SELECT cc.*, $catcontextsql + FROM {course_categories} cc + JOIN {context} ctx ON cc.id = ctx.instanceid + WHERE ctx.contextlevel = ".CONTEXT_COURSECAT." AND + (cc.id = :categoryid1 OR cc.parent = :categoryid2) + ORDER BY cc.depth ASC, cc.sortorder ASC, cc.id ASC"; + $params = array('categoryid1' => $categoryid, 'categoryid2' => $categoryid); + $categories = $DB->get_recordset_sql($sql, $params, 0, $limit); + $categorylist = array(); + $subcategories = array(); + $basecategory = null; + foreach ($categories as $category) { + $categorylist[] = $category->id; + context_helper::preload_from_record($category); + if ($category->id == $categoryid) { + $this->add_category($category, $this, $nodetype); + $basecategory = $this->addedcategories[$category->id]; + } else { + $subcategories[$category->id] = $category; + } + } + $categories->close(); + + + // 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. + $coursesubcategories = array(); + $addedsubcategories = 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){ + $coursesubcategories = array_merge($coursesubcategories, explode('/', trim($category->path, "/"))); + } + $categories->close(); + $coursesubcategories = array_unique($coursesubcategories); + + // Only add a subcategory if it is part of the path to user's course and + // wasn't already added. + foreach ($subcategories as $subid => $subcategory) { + if (in_array($subid, $coursesubcategories) && + !in_array($subid, $addedsubcategories)) { + $this->add_category($subcategory, $basecategory, $nodetype); + $addedsubcategories[] = $subid; + } + } + } + + foreach ($courses as $course) { + // Add course if it's in category. + if (in_array($course->category, $categorylist)) { + $this->add_course($course, true, self::COURSE_MY); + } + } + } 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); + } + $courses->close(); + } + } + + /** + * Returns an array of expandable nodes + * @return array + */ + public function get_expandable() { + return $this->expandable; + } +} diff --git a/public/lib/classes/navigation/navbar.php b/public/lib/classes/navigation/navbar.php new file mode 100644 index 00000000000..9fec988e835 --- /dev/null +++ b/public/lib/classes/navigation/navbar.php @@ -0,0 +1,371 @@ +. + +/** + * Navbar class + * + * This class is used to manage the navbar, which is initialised from the navigation + * object held by PAGE + * + * @package core + * @category navigation + * @copyright 2009 Sam Hemelryk + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class navbar extends navigation_node { + /** @var bool A switch for whether the navbar is initialised or not */ + protected $initialised = false; + /** @var mixed keys used to reference the nodes on the navbar */ + protected $keys = array(); + /** @var null|string content of the navbar */ + protected $content = null; + /** @var moodle_page object the moodle page that this navbar belongs to */ + protected $page; + /** @var bool A switch for whether to ignore the active navigation information */ + protected $ignoreactive = false; + /** @var bool A switch to let us know if we are in the middle of an install */ + protected $duringinstall = false; + /** @var bool A switch for whether the navbar has items */ + protected $hasitems = false; + /** @var array An array of navigation nodes for the navbar */ + protected $items; + /** @var array An array of child node objects */ + public $children = array(); + /** @var bool A switch for whether we want to include the root node in the navbar */ + public $includesettingsbase = false; + /** @var breadcrumb_navigation_node[] $prependchildren */ + protected $prependchildren = array(); + + /** + * The almighty constructor + * + * @param moodle_page $page + */ + public function __construct(moodle_page $page) { + global $CFG; + if (during_initial_install()) { + $this->duringinstall = true; + return; + } + $this->page = $page; + $this->text = get_string('home'); + $this->shorttext = get_string('home'); + $this->action = new moodle_url($CFG->wwwroot); + $this->nodetype = self::NODETYPE_BRANCH; + $this->type = self::TYPE_SYSTEM; + } + + /** + * Quick check to see if the navbar will have items in. + * + * @return bool Returns true if the navbar will have items, false otherwise + */ + public function has_items() { + if ($this->duringinstall) { + return false; + } else if ($this->hasitems !== false) { + return true; + } + $outcome = false; + if (count($this->children) > 0 || count($this->prependchildren) > 0) { + // There have been manually added items - there are definitely items. + $outcome = true; + } else if (!$this->ignoreactive) { + // We will need to initialise the navigation structure to check if there are active items. + $this->page->navigation->initialise($this->page); + $outcome = ($this->page->navigation->contains_active_node() || $this->page->settingsnav->contains_active_node()); + } + $this->hasitems = $outcome; + return $outcome; + } + + /** + * Turn on/off ignore active + * + * @param bool $setting + */ + public function ignore_active($setting=true) { + $this->ignoreactive = ($setting); + } + + /** + * Gets a navigation node + * + * @param string|int $key for referencing the navbar nodes + * @param int $type breadcrumb_navigation_node::TYPE_* + * @return breadcrumb_navigation_node|bool + */ + public function get($key, $type = null) { + foreach ($this->children as &$child) { + if ($child->key === $key && ($type == null || $type == $child->type)) { + return $child; + } + } + foreach ($this->prependchildren as &$child) { + if ($child->key === $key && ($type == null || $type == $child->type)) { + return $child; + } + } + return false; + } + /** + * Returns an array of breadcrumb_navigation_nodes that make up the navbar. + * + * @return array + */ + public function get_items() { + global $CFG; + $items = array(); + // Make sure that navigation is initialised + if (!$this->has_items()) { + return $items; + } + if ($this->items !== null) { + return $this->items; + } + + if (count($this->children) > 0) { + // Add the custom children. + $items = array_reverse($this->children); + } + + // Check if navigation contains the active node + if (!$this->ignoreactive) { + // We will need to ensure the navigation has been initialised. + $this->page->navigation->initialise($this->page); + // Now find the active nodes on both the navigation and settings. + $navigationactivenode = $this->page->navigation->find_active_node(); + $settingsactivenode = $this->page->settingsnav->find_active_node(); + + if ($navigationactivenode && $settingsactivenode) { + // Parse a combined navigation tree + while ($settingsactivenode && $settingsactivenode->parent !== null) { + if (!$settingsactivenode->mainnavonly) { + $items[] = new breadcrumb_navigation_node($settingsactivenode); + } + $settingsactivenode = $settingsactivenode->parent; + } + if (!$this->includesettingsbase) { + // Removes the first node from the settings (root node) from the list + array_pop($items); + } + while ($navigationactivenode && $navigationactivenode->parent !== null) { + if (!$navigationactivenode->mainnavonly) { + $items[] = new breadcrumb_navigation_node($navigationactivenode); + } + if (!empty($CFG->navshowcategories) && + $navigationactivenode->type === self::TYPE_COURSE && + $navigationactivenode->parent->key === 'currentcourse') { + foreach ($this->get_course_categories() as $item) { + $items[] = new breadcrumb_navigation_node($item); + } + } + $navigationactivenode = $navigationactivenode->parent; + } + } else if ($navigationactivenode) { + // Parse the navigation tree to get the active node + while ($navigationactivenode && $navigationactivenode->parent !== null) { + if (!$navigationactivenode->mainnavonly) { + $items[] = new breadcrumb_navigation_node($navigationactivenode); + } + if (!empty($CFG->navshowcategories) && + $navigationactivenode->type === self::TYPE_COURSE && + $navigationactivenode->parent->key === 'currentcourse') { + foreach ($this->get_course_categories() as $item) { + $items[] = new breadcrumb_navigation_node($item); + } + } + $navigationactivenode = $navigationactivenode->parent; + } + } else if ($settingsactivenode) { + // Parse the settings navigation to get the active node + while ($settingsactivenode && $settingsactivenode->parent !== null) { + if (!$settingsactivenode->mainnavonly) { + $items[] = new breadcrumb_navigation_node($settingsactivenode); + } + $settingsactivenode = $settingsactivenode->parent; + } + } + } + + $items[] = new breadcrumb_navigation_node(array( + 'text' => $this->page->navigation->text, + 'shorttext' => $this->page->navigation->shorttext, + 'key' => $this->page->navigation->key, + 'action' => $this->page->navigation->action + )); + + if (count($this->prependchildren) > 0) { + // Add the custom children + $items = array_merge($items, array_reverse($this->prependchildren)); + } + + $last = reset($items); + if ($last) { + $last->set_last(true); + } + $this->items = array_reverse($items); + return $this->items; + } + + /** + * Get the list of categories leading to this course. + * + * This function is used by {@link navbar::get_items()} to add back the "courses" + * node and category chain leading to the current course. Note that this is only ever + * called for the current course, so we don't need to bother taking in any parameters. + * + * @return array + */ + private function get_course_categories() { + global $CFG; + require_once($CFG->dirroot.'/course/lib.php'); + + $categories = array(); + $cap = 'moodle/category:viewhiddencategories'; + $showcategories = !core_course_category::is_simple_site(); + + if ($showcategories) { + foreach ($this->page->categories as $category) { + $context = context_coursecat::instance($category->id); + if (!core_course_category::can_view_category($category)) { + continue; + } + + $displaycontext = \context_helper::get_navigation_filter_context($context); + $url = new moodle_url('/course/index.php', ['categoryid' => $category->id]); + $name = format_string($category->name, true, ['context' => $displaycontext]); + $categorynode = breadcrumb_navigation_node::create($name, $url, self::TYPE_CATEGORY, null, $category->id); + if (!$category->visible) { + $categorynode->hidden = true; + } + $categories[] = $categorynode; + } + } + + // Don't show the 'course' node if enrolled in this course. + $coursecontext = context_course::instance($this->page->course->id); + if (!is_enrolled($coursecontext, null, '', true)) { + $courses = $this->page->navigation->get('courses'); + if (!$courses) { + // Courses node may not be present. + $courses = breadcrumb_navigation_node::create( + get_string('courses'), + new moodle_url('/course/index.php'), + self::TYPE_CONTAINER + ); + } + $categories[] = $courses; + } + + return $categories; + } + + /** + * Add a new breadcrumb_navigation_node to the navbar, overrides parent::add + * + * This function overrides {@link breadcrumb_navigation_node::add()} so that we can change + * the way nodes get added to allow us to simply call add and have the node added to the + * end of the navbar + * + * @param string $text + * @param string|moodle_url|action_link $action An action to associate with this node. + * @param int $type One of navigation_node::TYPE_* + * @param string $shorttext + * @param string|int $key A key to identify this node with. Key + type is unique to a parent. + * @param pix_icon $icon An optional icon to use for this node. + * @return navigation_node + */ + public function add($text, $action=null, $type=self::TYPE_CUSTOM, $shorttext=null, $key=null, ?pix_icon $icon=null) { + if ($this->content !== null) { + debugging('Nav bar items must be printed before $OUTPUT->header() has been called', DEBUG_DEVELOPER); + } + + // Properties array used when creating the new navigation node + $itemarray = array( + 'text' => $text, + 'type' => $type + ); + // Set the action if one was provided + if ($action!==null) { + $itemarray['action'] = $action; + } + // Set the shorttext if one was provided + if ($shorttext!==null) { + $itemarray['shorttext'] = $shorttext; + } + // Set the icon if one was provided + if ($icon!==null) { + $itemarray['icon'] = $icon; + } + // Default the key to the number of children if not provided + if ($key === null) { + $key = count($this->children); + } + // Set the key + $itemarray['key'] = $key; + // Set the parent to this node + $itemarray['parent'] = $this; + // Add the child using the navigation_node_collections add method + $this->children[] = new breadcrumb_navigation_node($itemarray); + return $this; + } + + /** + * Prepends a new navigation_node to the start of the navbar + * + * @param string $text + * @param string|moodle_url|action_link $action An action to associate with this node. + * @param int $type One of navigation_node::TYPE_* + * @param string $shorttext + * @param string|int $key A key to identify this node with. Key + type is unique to a parent. + * @param pix_icon $icon An optional icon to use for this node. + * @return navigation_node + */ + public function prepend($text, $action=null, $type=self::TYPE_CUSTOM, $shorttext=null, $key=null, ?pix_icon $icon=null) { + if ($this->content !== null) { + debugging('Nav bar items must be printed before $OUTPUT->header() has been called', DEBUG_DEVELOPER); + } + // Properties array used when creating the new navigation node. + $itemarray = array( + 'text' => $text, + 'type' => $type + ); + // Set the action if one was provided. + if ($action!==null) { + $itemarray['action'] = $action; + } + // Set the shorttext if one was provided. + if ($shorttext!==null) { + $itemarray['shorttext'] = $shorttext; + } + // Set the icon if one was provided. + if ($icon!==null) { + $itemarray['icon'] = $icon; + } + // Default the key to the number of children if not provided. + if ($key === null) { + $key = count($this->children); + } + // Set the key. + $itemarray['key'] = $key; + // Set the parent to this node. + $itemarray['parent'] = $this; + // Add the child node to the prepend list. + $this->prependchildren[] = new breadcrumb_navigation_node($itemarray); + return $this; + } +} diff --git a/public/lib/classes/navigation/navigation_cache.php b/public/lib/classes/navigation/navigation_cache.php new file mode 100644 index 00000000000..4ce73eb36ce --- /dev/null +++ b/public/lib/classes/navigation/navigation_cache.php @@ -0,0 +1,204 @@ +. + +/** + * Class navigation_cache + * + * @package core + * @copyright 2025 Andrew Lyons + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +/** + * The navigation_cache class is used for global and settings navigation data. + * + * It provides an easy access to the session cache with TTL of 1800 seconds. + * + * Example use: + * + * if (!$cache->viewdiscussion()) { + * // Code to do stuff and produce cachable content + * $cache->viewdiscussion = has_capability('mod/forum:viewdiscussion', $coursecontext); + * } + * $content = $cache->viewdiscussion; + * + * + * @package core + * @category navigation + * @copyright 2009 Sam Hemelryk + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class navigation_cache { + /** @var cache_session The session cache instance */ + protected $cache; + /** @var array The current cache area data */ + protected $session = []; + + /** + * @var string A unique string to segregate this particular cache. + * It can either be unique to start a fresh cache or shared to use an existing cache. + */ + protected $area; + /** @var int cache time information */ + #[\core\attribute\deprecated(null, since: '4.5', reason: 'This constant is no longer needed.', mdl: 'MDL-79628')] + const CACHETIME = 0; + /** @var int cache user id */ + #[\core\attribute\deprecated(null, since: '4.5', reason: 'This constant is no longer needed.', mdl: 'MDL-79628')] + const CACHEUSERID = 1; + /** @var int cache value */ + const CACHEVALUE = 2; + /** @var null|array An array of cache areas to expire on shutdown */ + public static $volatilecaches = null; + + /** + * Contructor for the cache. Requires a area string be passed in. + * + * @param string $area The unique string to segregate this particular cache. + * @param int $timeout Deprecated since Moodle 4.5. The number of seconds to time the information out after + */ + public function __construct($area, $timeout = null) { + if ($timeout !== null) { + debugging( + 'The timeout argument has been deprecated. Please remove it from your method calls.', + DEBUG_DEVELOPER, + ); + } + global $USER; + $this->area = "user_{$USER->id}_{$area}"; + $this->cache = cache::make('core', 'navigation_cache'); + } + + /** + * Ensure the navigation cache is initialised + * + * This is called for each access and ensures that no data is put into the cache before it is required. + */ + protected function ensure_navigation_cache_initialised() { + if (empty($this->session)) { + $this->session = $this->cache->get($this->area); + if (!is_array($this->session)) { + $this->session = []; + } + } + } + + /** + * Magic Method to retrieve a cached item by simply calling using = cache->key + * + * @param mixed $key The identifier for the cached information + * @return mixed|void The cached information or void if not found + */ + public function __get($key) { + if (!$this->cached($key)) { + return; + } + return unserialize($this->session[$key][self::CACHEVALUE]); + } + + /** + * Magic method that simply uses {@see navigation_cache::set()} to store an item in the cache + * + * @param string|int $key The key to store the information against + * @param mixed $information The information to cache + */ + public function __set($key, $information) { + $this->set($key, $information); + } + + /** + * Sets some information in the session cache for later retrieval + * + * @param string|int $key + * @param mixed $information + */ + public function set($key, $information) { + $this->ensure_navigation_cache_initialised(); + $information = serialize($information); + $this->session[$key] = [self::CACHEVALUE => $information]; + $this->cache->set($this->area, $this->session); + } + /** + * Check the existence of the identifier in the cache + * + * @param string|int $key The identifier to check + * @return bool True if the item exists in the cache, false otherwise + */ + public function cached($key) { + $this->ensure_navigation_cache_initialised(); + return isset($this->session[$key]) && + is_array($this->session[$key]); + } + /** + * Compare something to it's equivilant in the cache + * + * @param string $key The key to check + * @param mixed $value The value to compare + * @param bool $serialise Whether to serialise the value before comparison + * this should only be set to false if the value is already + * serialised + * @return bool True if the value is the same as the cached one, false otherwise + */ + public function compare($key, $value, $serialise = true) { + if ($this->cached($key)) { + if ($serialise) { + $value = serialize($value); + } + return $this->session[$key][self::CACHEVALUE] === $value; + } + return false; + } + /** + * Deletes the entire cache area, forcing a fresh cache to be created + */ + public function clear() { + $this->cache->delete($this->area); + $this->session = []; + } + /** + * Marks the cache as volatile (likely to change) + * + * Any caches marked as volatile will be destroyed on shutdown by {@see navigation_node::destroy_volatile_caches()} + * + * @param bool $setting True to mark the cache as volatile, false to remove the volatile flag + */ + public function volatile($setting = true) { + if (self::$volatilecaches === null) { + self::$volatilecaches = []; + core_shutdown_manager::register_function(['navigation_cache', 'destroy_volatile_caches']); + } + + if ($setting) { + self::$volatilecaches[$this->area] = $this->area; + } else if (array_key_exists($this->area, self::$volatilecaches)) { + unset(self::$volatilecaches[$this->area]); + } + } + + /** + * Destroys all caches marked as volatile + * + * This function is static and works with the static volatilecaches property of navigation cache. + * It manually resets the cached areas back to an empty array. + */ + public static function destroy_volatile_caches() { + if (is_array(self::$volatilecaches) && count(self::$volatilecaches) > 0) { + $cache = cache::make('core', 'navigation_cache'); + foreach (self::$volatilecaches as $area) { + $cache->delete($area); + } + self::$volatilecaches = null; + } + } +} diff --git a/public/lib/classes/navigation/navigation_json.php b/public/lib/classes/navigation/navigation_json.php new file mode 100644 index 00000000000..c576603faac --- /dev/null +++ b/public/lib/classes/navigation/navigation_json.php @@ -0,0 +1,121 @@ +. + +/** + * Simple class used to output a navigation branch in XML + * + * @package core + * @category navigation + * @copyright 2009 Sam Hemelryk + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class navigation_json { + /** @var array An array of different node types */ + protected $nodetype = array('node','branch'); + /** @var array An array of node keys and types */ + protected $expandable = array(); + /** + * Turns a branch and all of its children into XML + * + * @param navigation_node $branch + * @return string XML string + */ + public function convert($branch) { + $xml = $this->convert_child($branch); + return $xml; + } + /** + * Set the expandable items in the array so that we have enough information + * to attach AJAX events + * @param array $expandable + */ + public function set_expandable($expandable) { + foreach ($expandable as $node) { + $this->expandable[$node['key'].':'.$node['type']] = $node; + } + } + /** + * Recusively converts a child node and its children to XML for output + * + * @param navigation_node $child The child to convert + * @param int $depth Pointlessly used to track the depth of the XML structure + * @return string JSON + */ + protected function convert_child($child, $depth=1) { + if (!$child->display) { + return ''; + } + $attributes = array(); + $attributes['id'] = $child->id; + $attributes['name'] = (string)$child->text; // This can be lang_string object so typecast it. + $attributes['type'] = $child->type; + $attributes['key'] = $child->key; + $attributes['class'] = $child->get_css_type(); + $attributes['requiresajaxloading'] = $child->requiresajaxloading; + + if ($child->icon instanceof pix_icon) { + $attributes['icon'] = array( + 'component' => $child->icon->component, + 'pix' => $child->icon->pix, + ); + foreach ($child->icon->attributes as $key=>$value) { + if ($key == 'class') { + $attributes['icon']['classes'] = explode(' ', $value); + } else if (!array_key_exists($key, $attributes['icon'])) { + $attributes['icon'][$key] = $value; + } + + } + } else if (!empty($child->icon)) { + $attributes['icon'] = (string)$child->icon; + } + + if ($child->forcetitle || $child->title !== $child->text) { + $attributes['title'] = htmlentities($child->title ?? '', ENT_QUOTES, 'UTF-8'); + } + if (array_key_exists($child->key.':'.$child->type, $this->expandable)) { + $attributes['expandable'] = $child->key; + $child->add_class($this->expandable[$child->key.':'.$child->type]['id']); + } + + if (count($child->classes)>0) { + $attributes['class'] .= ' '.join(' ',$child->classes); + } + if (is_string($child->action)) { + $attributes['link'] = $child->action; + } else if ($child->action instanceof moodle_url) { + $attributes['link'] = $child->action->out(); + } else if ($child->action instanceof action_link) { + $attributes['link'] = $child->action->url->out(); + } + $attributes['hidden'] = ($child->hidden); + $attributes['haschildren'] = ($child->children->count()>0 || $child->type == navigation_node::TYPE_CATEGORY); + $attributes['haschildren'] = $attributes['haschildren'] || $child->type == navigation_node::TYPE_MY_CATEGORY; + + if ($child->children->count() > 0) { + $attributes['children'] = array(); + foreach ($child->children as $subchild) { + $attributes['children'][] = $this->convert_child($subchild, $depth+1); + } + } + + if ($depth > 1) { + return $attributes; + } else { + return json_encode($attributes); + } + } +} diff --git a/public/lib/classes/navigation/navigation_node.php b/public/lib/classes/navigation/navigation_node.php new file mode 100644 index 00000000000..fbb830583ba --- /dev/null +++ b/public/lib/classes/navigation/navigation_node.php @@ -0,0 +1,1017 @@ +. + +/** + * This class is used to represent a node in a navigation tree + * + * This class is used to represent a node in a navigation tree within Moodle, + * the tree could be one of global navigation, settings navigation, or the navbar. + * Each node can be one of two types either a Leaf (default) or a branch. + * When a node is first created it is created as a leaf, when/if children are added + * the node then becomes a branch. + * + * @package core + * @category navigation + * @copyright 2009 Sam Hemelryk + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class navigation_node implements renderable { + /** @var int Used to identify this node a leaf (default) 0 */ + const NODETYPE_LEAF = 0; + /** @var int Used to identify this node a branch, happens with children 1 */ + const NODETYPE_BRANCH = 1; + /** @var null Unknown node type null */ + const TYPE_UNKNOWN = null; + /** @var int System node type 0 */ + const TYPE_ROOTNODE = 0; + /** @var int System node type 1 */ + const TYPE_SYSTEM = 1; + /** @var int Category node type 10 */ + const TYPE_CATEGORY = 10; + /** var int Category displayed in MyHome navigation node */ + const TYPE_MY_CATEGORY = 11; + /** @var int Course node type 20 */ + const TYPE_COURSE = 20; + /** @var int Course Structure node type 30 */ + const TYPE_SECTION = 30; + /** @var int Activity node type, e.g. Forum, Quiz 40 */ + const TYPE_ACTIVITY = 40; + /** @var int Resource node type, e.g. Link to a file, or label 50 */ + const TYPE_RESOURCE = 50; + /** @var int A custom node type, default when adding without specifing type 60 */ + const TYPE_CUSTOM = 60; + /** @var int Setting node type, used only within settings nav 70 */ + const TYPE_SETTING = 70; + /** @var int site admin branch node type, used only within settings nav 71 */ + const TYPE_SITE_ADMIN = 71; + /** @var int Setting node type, used only within settings nav 80 */ + const TYPE_USER = 80; + /** @var int Setting node type, used for containers of no importance 90 */ + const TYPE_CONTAINER = 90; + /** var int Course the current user is not enrolled in */ + const COURSE_OTHER = 0; + /** var int Course the current user is enrolled in but not viewing */ + const COURSE_MY = 1; + /** var int Course the current user is currently viewing */ + const COURSE_CURRENT = 2; + /** var string The course index page navigation node */ + const COURSE_INDEX_PAGE = 'courseindexpage'; + + /** @var int Parameter to aid the coder in tracking [optional] */ + public $id = null; + /** @var string|int The identifier for the node, used to retrieve the node */ + public $key = null; + /** @var string|lang_string The text to use for the node */ + public $text = null; + /** @var string Short text to use if requested [optional] */ + public $shorttext = null; + /** @var string The title attribute for an action if one is defined */ + public $title = null; + /** @var string A string that can be used to build a help button */ + public $helpbutton = null; + /** @var moodle_url|action_link|null An action for the node (link) */ + public $action = null; + /** @var pix_icon The path to an icon to use for this node */ + public $icon = null; + /** @var int See TYPE_* constants defined for this class */ + public $type = self::TYPE_UNKNOWN; + /** @var int See NODETYPE_* constants defined for this class */ + public $nodetype = self::NODETYPE_LEAF; + /** @var bool If set to true the node will be collapsed by default */ + public $collapse = false; + /** @var bool If set to true the node will be expanded by default */ + public $forceopen = false; + /** @var array An array of CSS classes for the node */ + public $classes = array(); + /** @var array An array of HTML attributes for the node */ + public $attributes = []; + /** @var navigation_node_collection An array of child nodes */ + public $children = array(); + /** @var bool If set to true the node will be recognised as active */ + public $isactive = false; + /** @var bool If set to true the node will be dimmed */ + public $hidden = false; + /** @var bool If set to false the node will not be displayed */ + public $display = true; + /** @var bool If set to true then an HR will be printed before the node */ + public $preceedwithhr = false; + /** @var bool If set to true the the navigation bar should ignore this node */ + public $mainnavonly = false; + /** @var bool If set to true a title will be added to the action no matter what */ + public $forcetitle = false; + /** @var navigation_node A reference to the node parent, you should never set this directly you should always call set_parent */ + public $parent = null; + /** @var bool Override to not display the icon even if one is provided **/ + public $hideicon = false; + /** @var bool Set to true if we KNOW that this node can be expanded. */ + public $isexpandable = false; + /** @var array */ + protected $namedtypes = array(0 => 'system', 10 => 'category', 20 => 'course', 30 => 'structure', 40 => 'activity', + 50 => 'resource', 60 => 'custom', 70 => 'setting', 71 => 'siteadmin', 80 => 'user', + 90 => 'container'); + /** @var moodle_url */ + protected static $fullmeurl = null; + /** @var bool toogles auto matching of active node */ + public static $autofindactive = true; + /** @var bool should we load full admin tree or rely on AJAX for performance reasons */ + protected static $loadadmintree = false; + /** @var mixed If set to an int, that section will be included even if it has no activities */ + public $includesectionnum = false; + /** @var bool does the node need to be loaded via ajax */ + public $requiresajaxloading = false; + /** @var bool If set to true this node will be added to the "flat" navigation */ + public $showinflatnavigation = false; + /** @var bool If set to true this node will be forced into a "more" menu whenever possible */ + public $forceintomoremenu = false; + /** @var bool If set to true this node will be displayed in the "secondary" navigation when applicable */ + public $showinsecondarynavigation = true; + /** @var bool If set to true the children of this node will be displayed within a submenu when applicable */ + public $showchildreninsubmenu = false; + /** @var string tab element ID. */ + public $tab; + /** @var string unique identifier. */ + public $moremenuid; + /** @var bool node that have children. */ + public $haschildren; + + /** + * Constructs a new navigation_node + * + * @param array|string $properties Either an array of properties or a string to use + * as the text for the node + */ + public function __construct($properties) { + if (is_array($properties)) { + // Check the array for each property that we allow to set at construction. + // text - The main content for the node + // shorttext - A short text if required for the node + // icon - The icon to display for the node + // type - The type of the node + // key - The key to use to identify the node + // parent - A reference to the nodes parent + // action - The action to attribute to this node, usually a URL to link to + if (array_key_exists('text', $properties)) { + $this->text = $properties['text']; + } + if (array_key_exists('shorttext', $properties)) { + $this->shorttext = $properties['shorttext']; + } + if (!array_key_exists('icon', $properties)) { + $properties['icon'] = new pix_icon('i/navigationitem', ''); + } + $this->icon = $properties['icon']; + if ($this->icon instanceof pix_icon) { + if (empty($this->icon->attributes['class'])) { + $this->icon->attributes['class'] = 'navicon'; + } else { + $this->icon->attributes['class'] .= ' navicon'; + } + } + if (array_key_exists('type', $properties)) { + $this->type = $properties['type']; + } else { + $this->type = self::TYPE_CUSTOM; + } + if (array_key_exists('key', $properties)) { + $this->key = $properties['key']; + } + // This needs to happen last because of the check_if_active call that occurs + if (array_key_exists('action', $properties)) { + $this->action = $properties['action']; + if (is_string($this->action)) { + $this->action = new moodle_url($this->action); + } + if (self::$autofindactive) { + $this->check_if_active(); + } + } + if (array_key_exists('parent', $properties)) { + $this->set_parent($properties['parent']); + } + } else if (is_string($properties)) { + $this->text = $properties; + } + if ($this->text === null) { + throw new coding_exception('You must set the text for the node when you create it.'); + } + // Instantiate a new navigation node collection for this nodes children + $this->children = new navigation_node_collection(); + } + + /** + * Checks if this node is the active node. + * + * This is determined by comparing the action for the node against the + * defined URL for the page. A match will see this node marked as active. + * + * @param int $strength One of URL_MATCH_EXACT, URL_MATCH_PARAMS, or URL_MATCH_BASE + * @return bool + */ + public function check_if_active($strength=URL_MATCH_EXACT) { + global $FULLME, $PAGE; + // Set fullmeurl if it hasn't already been set + if (self::$fullmeurl == null) { + if ($PAGE->has_set_url()) { + self::override_active_url(new moodle_url($PAGE->url)); + } else { + self::override_active_url(new moodle_url($FULLME)); + } + } + + // Compare the action of this node against the fullmeurl + if ($this->action instanceof moodle_url && $this->action->compare(self::$fullmeurl, $strength)) { + $this->make_active(); + return true; + } + return false; + } + + /** + * True if this nav node has siblings in the tree. + * + * @return bool + */ + public function has_siblings() { + if (empty($this->parent) || empty($this->parent->children)) { + return false; + } + if ($this->parent->children instanceof navigation_node_collection) { + $count = $this->parent->children->count(); + } else { + $count = count($this->parent->children); + } + return ($count > 1); + } + + /** + * Get a list of sibling navigation nodes at the same level as this one. + * + * @return bool|array of navigation_node + */ + public function get_siblings() { + // Returns a list of the siblings of the current node for display in a flat navigation element. Either + // the in-page links or the breadcrumb links. + $siblings = false; + + if ($this->has_siblings()) { + $siblings = []; + foreach ($this->parent->children as $child) { + if ($child->display) { + $siblings[] = $child; + } + } + } + return $siblings; + } + + /** + * This sets the URL that the URL of new nodes get compared to when locating + * the active node. + * + * The active node is the node that matches the URL set here. By default this + * is either $PAGE->url or if that hasn't been set $FULLME. + * + * @param moodle_url $url The url to use for the fullmeurl. + * @param bool $loadadmintree use true if the URL point to administration tree + */ + public static function override_active_url(moodle_url $url, $loadadmintree = false) { + // Clone the URL, in case the calling script changes their URL later. + self::$fullmeurl = new moodle_url($url); + // True means we do not want AJAX loaded admin tree, required for all admin pages. + if ($loadadmintree) { + // Do not change back to false if already set. + self::$loadadmintree = true; + } + } + + /** + * Use when page is linked from the admin tree, + * if not used navigation could not find the page using current URL + * because the tree is not fully loaded. + */ + public static function require_admin_tree() { + self::$loadadmintree = true; + } + + /** + * Creates a navigation node, ready to add it as a child using add_node + * function. (The created node needs to be added before you can use it.) + * @param string $text + * @param moodle_url|action_link $action + * @param int $type + * @param string $shorttext + * @param string|int $key + * @param pix_icon $icon + * @return navigation_node + */ + public static function create($text, $action=null, $type=self::TYPE_CUSTOM, + $shorttext=null, $key=null, ?pix_icon $icon=null) { + if ($action && !($action instanceof moodle_url || $action instanceof action_link)) { + debugging( + "It is required that the action provided be either an action_url|moodle_url." . + " Please update your definition.", E_NOTICE); + } + // Properties array used when creating the new navigation node + $itemarray = array( + 'text' => $text, + 'type' => $type + ); + // Set the action if one was provided + if ($action!==null) { + $itemarray['action'] = $action; + } + // Set the shorttext if one was provided + if ($shorttext!==null) { + $itemarray['shorttext'] = $shorttext; + } + // Set the icon if one was provided + if ($icon!==null) { + $itemarray['icon'] = $icon; + } + // Set the key + $itemarray['key'] = $key; + // Construct and return + return new navigation_node($itemarray); + } + + /** + * Adds a navigation node as a child of this node. + * + * @param string $text + * @param moodle_url|action_link|string $action + * @param ?int $type + * @param string $shorttext + * @param string|int $key + * @param pix_icon $icon + * @return navigation_node + */ + public function add($text, $action=null, $type=self::TYPE_CUSTOM, $shorttext=null, $key=null, ?pix_icon $icon=null) { + if ($action && is_string($action)) { + $action = new moodle_url($action); + } + // Create child node + $childnode = self::create($text, $action, $type, $shorttext, $key, $icon); + + // Add the child to end and return + return $this->add_node($childnode); + } + + /** + * Adds a navigation node as a child of this one, given a $node object + * created using the create function. + * @param navigation_node $childnode Node to add + * @param string $beforekey + * @return navigation_node The added node + */ + public function add_node(navigation_node $childnode, $beforekey=null) { + // First convert the nodetype for this node to a branch as it will now have children + if ($this->nodetype !== self::NODETYPE_BRANCH) { + $this->nodetype = self::NODETYPE_BRANCH; + } + // Set the parent to this node + $childnode->set_parent($this); + + // Default the key to the number of children if not provided + if ($childnode->key === null) { + $childnode->key = $this->children->count(); + } + + // Add the child using the navigation_node_collections add method + $node = $this->children->add($childnode, $beforekey); + + // If added node is a category node or the user is logged in and it's a course + // then mark added node as a branch (makes it expandable by AJAX) + $type = $childnode->type; + if (($type == self::TYPE_CATEGORY) || (isloggedin() && ($type == self::TYPE_COURSE)) || ($type == self::TYPE_MY_CATEGORY) || + ($type === self::TYPE_SITE_ADMIN)) { + $node->nodetype = self::NODETYPE_BRANCH; + } + // If this node is hidden mark it's children as hidden also + if ($this->hidden) { + $node->hidden = true; + } + // Return added node (reference returned by $this->children->add() + return $node; + } + + /** + * Return a list of all the keys of all the child nodes. + * @return array the keys. + */ + public function get_children_key_list() { + return $this->children->get_key_list(); + } + + /** + * Searches for a node of the given type with the given key. + * + * This searches this node plus all of its children, and their children.... + * If you know the node you are looking for is a child of this node then please + * use the get method instead. + * + * @param int|string $key The key of the node we are looking for + * @param ?int $type One of navigation_node::TYPE_* + * @return navigation_node|false + */ + public function find($key, $type) { + return $this->children->find($key, $type); + } + + /** + * Walk the tree building up a list of all the flat navigation nodes. + * + * @deprecated since Moodle 4.0 + * @param flat_navigation $nodes List of the found flat navigation nodes. + * @param boolean $showdivider Show a divider before the first node. + * @param string $label A label for the collection of navigation links. + */ + public function build_flat_navigation_list(flat_navigation $nodes, $showdivider = false, $label = '') { + debugging("Function has been deprecated with the deprecation of the flat_navigation class."); + if ($this->showinflatnavigation) { + $indent = 0; + if ($this->type == self::TYPE_COURSE || $this->key === self::COURSE_INDEX_PAGE) { + $indent = 1; + } + $flat = new flat_navigation_node($this, $indent); + $flat->set_showdivider($showdivider, $label); + $nodes->add($flat); + } + foreach ($this->children as $child) { + $child->build_flat_navigation_list($nodes, false); + } + } + + /** + * Get the child of this node that has the given key + (optional) type. + * + * If you are looking for a node and want to search all children + their children + * then please use the find method instead. + * + * @param int|string $key The key of the node we are looking for + * @param int $type One of navigation_node::TYPE_* + * @return navigation_node|false + */ + public function get($key, $type=null) { + return $this->children->get($key, $type); + } + + /** + * Removes this node. + * + * @return bool + */ + public function remove() { + return $this->parent->children->remove($this->key, $this->type); + } + + /** + * Checks if this node has or could have any children + * + * @return bool Returns true if it has children or could have (by AJAX expansion) + */ + public function has_children() { + return ($this->nodetype === navigation_node::NODETYPE_BRANCH || $this->children->count()>0 || $this->isexpandable); + } + + /** + * Marks this node as active and forces it open. + * + * Important: If you are here because you need to mark a node active to get + * the navigation to do what you want have you looked at {@link navigation_node::override_active_url()}? + * You can use it to specify a different URL to match the active navigation node on + * rather than having to locate and manually mark a node active. + */ + public function make_active() { + $this->isactive = true; + $this->add_class('active_tree_node'); + $this->force_open(); + if ($this->parent !== null) { + $this->parent->make_inactive(); + } + } + + /** + * Marks a node as inactive and recusised back to the base of the tree + * doing the same to all parents. + */ + public function make_inactive() { + $this->isactive = false; + $this->remove_class('active_tree_node'); + if ($this->parent !== null) { + $this->parent->make_inactive(); + } + } + + /** + * Forces this node to be open and at the same time forces open all + * parents until the root node. + * + * Recursive. + */ + public function force_open() { + $this->forceopen = true; + if ($this->parent !== null) { + $this->parent->force_open(); + } + } + + /** + * Adds a CSS class to this node. + * + * @param string $class + * @return bool + */ + public function add_class($class) { + if (!in_array($class, $this->classes)) { + $this->classes[] = $class; + } + return true; + } + + /** + * Adds an HTML attribute to this node. + * + * @param string $name + * @param string $value + */ + public function add_attribute(string $name, string $value): void { + $this->attributes[] = ['name' => $name, 'value' => $value]; + } + + /** + * Removes a CSS class from this node. + * + * @param string $class + * @return bool True if the class was successfully removed. + */ + public function remove_class($class) { + if (in_array($class, $this->classes)) { + $key = array_search($class,$this->classes); + if ($key!==false) { + // Remove the class' array element. + unset($this->classes[$key]); + // Reindex the array to avoid failures when the classes array is iterated later in mustache templates. + $this->classes = array_values($this->classes); + + return true; + } + } + return false; + } + + /** + * Sets the title for this node and forces Moodle to utilise it. + * + * Note that this method is named identically to the public "title" property of the class, which unfortunately confuses + * our Mustache renderer, because it will see the method and try and call it without any arguments (hence must be nullable) + * before trying to access the public property + * + * @param string|null $title + * @return string + */ + public function title(?string $title = null): string { + if ($title !== null) { + $this->title = $title; + $this->forcetitle = true; + } + return (string) $this->title; + } + + /** + * Resets the page specific information on this node if it is being unserialised. + */ + public function __wakeup(){ + $this->forceopen = false; + $this->isactive = false; + $this->remove_class('active_tree_node'); + } + + /** + * Checks if this node or any of its children contain the active node. + * + * Recursive. + * + * @return bool + */ + public function contains_active_node() { + if ($this->isactive) { + return true; + } else { + foreach ($this->children as $child) { + if ($child->isactive || $child->contains_active_node()) { + return true; + } + } + } + return false; + } + + /** + * To better balance the admin tree, we want to group all the short top branches together. + * + * This means < 8 nodes and no subtrees. + * + * @return bool + */ + public function is_short_branch() { + $limit = 8; + if ($this->children->count() >= $limit) { + return false; + } + foreach ($this->children as $child) { + if ($child->has_children()) { + return false; + } + } + return true; + } + + /** + * Finds the active node. + * + * Searches this nodes children plus all of the children for the active node + * and returns it if found. + * + * Recursive. + * + * @return navigation_node|false + */ + public function find_active_node() { + if ($this->isactive) { + return $this; + } else { + foreach ($this->children as &$child) { + $outcome = $child->find_active_node(); + if ($outcome !== false) { + return $outcome; + } + } + } + return false; + } + + /** + * Searches all children for the best matching active node + * @param int $strength The url match to be made. + * @return navigation_node|false + */ + public function search_for_active_node($strength = URL_MATCH_BASE) { + if ($this->check_if_active($strength)) { + return $this; + } else { + foreach ($this->children as &$child) { + $outcome = $child->search_for_active_node($strength); + if ($outcome !== false) { + return $outcome; + } + } + } + return false; + } + + /** + * Gets the content for this node. + * + * @param bool $shorttext If true shorttext is used rather than the normal text + * @return string + */ + public function get_content($shorttext=false) { + $navcontext = \context_helper::get_navigation_filter_context(null); + $options = !empty($navcontext) ? ['context' => $navcontext] : null; + + if ($shorttext && $this->shorttext!==null) { + return format_string($this->shorttext, null, $options); + } else { + return format_string($this->text, null, $options); + } + } + + /** + * Gets the title to use for this node. + * + * @return string + */ + public function get_title() { + if ($this->forcetitle || $this->action != null){ + return $this->title; + } else { + return ''; + } + } + + /** + * Used to easily determine if this link in the breadcrumbs has a valid action/url. + * + * @return boolean + */ + public function has_action() { + return !empty($this->action); + } + + /** + * Used to easily determine if the action is an internal link. + * + * @return bool + */ + public function has_internal_action(): bool { + global $CFG; + if ($this->has_action()) { + $url = $this->action(); + if ($this->action() instanceof \action_link) { + $url = $this->action()->url; + } + + if (($url->out() === $CFG->wwwroot) || (strpos($url->out(), $CFG->wwwroot.'/') === 0)) { + return true; + } + } + return false; + } + + /** + * Used to easily determine if this link in the breadcrumbs is hidden. + * + * @return boolean + */ + public function is_hidden() { + return $this->hidden; + } + + /** + * Gets the CSS class to add to this node to describe its type + * + * @return string + */ + public function get_css_type() { + if (array_key_exists($this->type, $this->namedtypes)) { + return 'type_'.$this->namedtypes[$this->type]; + } + return 'type_unknown'; + } + + /** + * Finds all nodes that are expandable by AJAX + * + * @param array $expandable An array by reference to populate with expandable nodes. + */ + public function find_expandable(array &$expandable) { + foreach ($this->children as &$child) { + if ($child->display && $child->has_children() && $child->children->count() == 0) { + $child->id = 'expandable_branch_'.$child->type.'_'.clean_param($child->key, PARAM_ALPHANUMEXT); + $this->add_class('canexpand'); + $child->requiresajaxloading = true; + $expandable[] = array('id' => $child->id, 'key' => $child->key, 'type' => $child->type); + } + $child->find_expandable($expandable); + } + } + + /** + * Finds all nodes of a given type (recursive) + * + * @param int $type One of navigation_node::TYPE_* + * @return array + */ + public function find_all_of_type($type) { + $nodes = $this->children->type($type); + foreach ($this->children as &$node) { + $childnodes = $node->find_all_of_type($type); + $nodes = array_merge($nodes, $childnodes); + } + return $nodes; + } + + /** + * Removes this node if it is empty + */ + public function trim_if_empty() { + if ($this->children->count() == 0) { + $this->remove(); + } + } + + /** + * Creates a tab representation of this nodes children that can be used + * with print_tabs to produce the tabs on a page. + * + * call_user_func_array('print_tabs', $node->get_tabs_array()); + * + * @param array $inactive + * @param bool $return + * @return array Array (tabs, selected, inactive, activated, return) + */ + public function get_tabs_array(array $inactive=array(), $return=false) { + $tabs = array(); + $rows = array(); + $selected = null; + $activated = array(); + foreach ($this->children as $node) { + $tabs[] = new tabobject($node->key, $node->action, $node->get_content(), $node->get_title()); + if ($node->contains_active_node()) { + if ($node->children->count() > 0) { + $activated[] = $node->key; + foreach ($node->children as $child) { + if ($child->contains_active_node()) { + $selected = $child->key; + } + $rows[] = new tabobject($child->key, $child->action, $child->get_content(), $child->get_title()); + } + } else { + $selected = $node->key; + } + } + } + return array(array($tabs, $rows), $selected, $inactive, $activated, $return); + } + + /** + * Sets the parent for this node and if this node is active ensures that the tree is properly + * adjusted as well. + * + * @param navigation_node $parent + */ + public function set_parent(navigation_node $parent) { + // Set the parent (thats the easy part) + $this->parent = $parent; + // Check if this node is active (this is checked during construction) + if ($this->isactive) { + // Force all of the parent nodes open so you can see this node + $this->parent->force_open(); + // Make all parents inactive so that its clear where we are. + $this->parent->make_inactive(); + } + } + + /** + * Hides the node and any children it has. + * + * @since Moodle 2.5 + * @param array $typestohide Optional. An array of node types that should be hidden. + * If null all nodes will be hidden. + * If an array is given then nodes will only be hidden if their type mtatches an element in the array. + * e.g. array(navigation_node::TYPE_COURSE) would hide only course nodes. + */ + public function hide(?array $typestohide = null) { + if ($typestohide === null || in_array($this->type, $typestohide)) { + $this->display = false; + if ($this->has_children()) { + foreach ($this->children as $child) { + $child->hide($typestohide); + } + } + } + } + + /** + * Get the action url for this navigation node. + * Called from templates. + * + * @since Moodle 3.2 + */ + public function action() { + if ($this->action instanceof moodle_url) { + return $this->action; + } else if ($this->action instanceof action_link) { + return $this->action->url; + } + return $this->action; + } + + /** + * Return an array consisting of the additional attributes for the action url. + * + * @return array Formatted array to parse in a template + */ + public function actionattributes() { + if ($this->action instanceof action_link) { + return array_map(function($key, $value) { + return [ + 'name' => $key, + 'value' => $value + ]; + }, array_keys($this->action->attributes), $this->action->attributes); + } + + return []; + } + + /** + * Check whether the node's action is of type action_link. + * + * @return bool + */ + public function is_action_link() { + return $this->action instanceof action_link; + } + + /** + * Return an array consisting of the actions for the action link. + * + * @return array Formatted array to parse in a template + */ + public function action_link_actions() { + global $PAGE; + + if (!$this->is_action_link()) { + return []; + } + + $actionid = $this->action->attributes['id']; + $actionsdata = array_map(function($action) use ($PAGE, $actionid) { + $data = $action->export_for_template($PAGE->get_renderer('core')); + $data->id = $actionid; + return $data; + }, !empty($this->action->actions) ? $this->action->actions : []); + + return ['actions' => $actionsdata]; + } + + /** + * Sets whether the node and its children should be added into a "more" menu whenever possible. + * + * @param bool $forceintomoremenu + */ + public function set_force_into_more_menu(bool $forceintomoremenu = false) { + $this->forceintomoremenu = $forceintomoremenu; + foreach ($this->children as $child) { + $child->set_force_into_more_menu($forceintomoremenu); + } + } + + /** + * Sets whether the node and its children should be displayed in the "secondary" navigation when applicable. + * + * @param bool $show + */ + public function set_show_in_secondary_navigation(bool $show = true) { + $this->showinsecondarynavigation = $show; + foreach ($this->children as $child) { + $child->set_show_in_secondary_navigation($show); + } + } + + /** + * Add the menu item to handle locking and unlocking of a conext. + * + * @param \navigation_node $node Node to add + * @param \context $context The context to be locked + */ + protected function add_context_locking_node(\navigation_node $node, \context $context) { + global $CFG; + // Manage context locking. + if (!empty($CFG->contextlocking) && has_capability('moodle/site:managecontextlocks', $context)) { + $parentcontext = $context->get_parent_context(); + if (empty($parentcontext) || !$parentcontext->locked) { + if ($context->locked) { + $lockicon = 'i/unlock'; + $lockstring = get_string('managecontextunlock', 'admin'); + } else { + $lockicon = 'i/lock'; + $lockstring = get_string('managecontextlock', 'admin'); + } + $node->add( + $lockstring, + new moodle_url( + '/admin/lock.php', + [ + 'id' => $context->id, + ] + ), + self::TYPE_SETTING, + null, + 'contextlocking', + new pix_icon($lockicon, '') + ); + } + } + + } + + /** + * Reset all static data. + * + * @throws coding_exception if called outside of a unit test + */ + public static function reset_all_data(): void { + if (!defined('PHPUNIT_TEST') || !PHPUNIT_TEST) { + throw new coding_exception('Resetting all data is not allowed outside of PHPUnit tests.'); + } + + self::$fullmeurl = null; + self::$autofindactive = true; + self::$loadadmintree = false; + } +} diff --git a/public/lib/classes/navigation/navigation_node_collection.php b/public/lib/classes/navigation/navigation_node_collection.php new file mode 100644 index 00000000000..78e9698c532 --- /dev/null +++ b/public/lib/classes/navigation/navigation_node_collection.php @@ -0,0 +1,281 @@ +. + +/** + * Navigation node collection + * + * This class is responsible for managing a collection of navigation nodes. + * It is required because a node's unique identifier is a combination of both its + * key and its type. + * + * Originally an array was used with a string key that was a combination of the two + * however it was decided that a better solution would be to use a class that + * implements the standard IteratorAggregate interface. + * + * @package core + * @category navigation + * @copyright 2010 Sam Hemelryk + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class navigation_node_collection implements IteratorAggregate, Countable { + /** + * A multidimensional array to where the first key is the type and the second + * key is the nodes key. + * @var array + */ + protected $collection = array(); + /** + * An array that contains references to nodes in the same order they were added. + * This is maintained as a progressive array. + * @var array + */ + protected $orderedcollection = array(); + /** + * A reference to the last node that was added to the collection + * @var navigation_node + */ + protected $last = null; + /** + * The total number of items added to this array. + * @var int + */ + protected $count = 0; + + /** + * Label for collection of nodes. + * @var string + */ + protected $collectionlabel = ''; + + /** + * Adds a navigation node to the collection + * + * @param navigation_node $node Node to add + * @param string $beforekey If specified, adds before a node with this key, + * otherwise adds at end + * @return navigation_node Added node + */ + public function add(navigation_node $node, $beforekey=null) { + global $CFG; + $key = $node->key; + $type = $node->type; + + // First check we have a 2nd dimension for this type + if (!array_key_exists($type, $this->orderedcollection)) { + $this->orderedcollection[$type] = array(); + } + // Check for a collision and report if debugging is turned on + if ($CFG->debug && array_key_exists($key, $this->orderedcollection[$type])) { + debugging('Navigation node intersect: Adding a node that already exists '.$key, DEBUG_DEVELOPER); + } + + // Find the key to add before + $newindex = $this->count; + $last = true; + if ($beforekey !== null) { + foreach ($this->collection as $index => $othernode) { + if ($othernode->key === $beforekey) { + $newindex = $index; + $last = false; + break; + } + } + if ($newindex === $this->count) { + debugging('Navigation node add_before: Reference node not found ' . $beforekey . + ', options: ' . implode(' ', $this->get_key_list()), DEBUG_DEVELOPER); + } + } + + // Add the node to the appropriate place in the by-type structure (which + // is not ordered, despite the variable name) + $this->orderedcollection[$type][$key] = $node; + if (!$last) { + // Update existing references in the ordered collection (which is the + // one that isn't called 'ordered') to shuffle them along if required + for ($oldindex = $this->count; $oldindex > $newindex; $oldindex--) { + $this->collection[$oldindex] = $this->collection[$oldindex - 1]; + } + } + // Add a reference to the node to the progressive collection. + $this->collection[$newindex] = $this->orderedcollection[$type][$key]; + // Update the last property to a reference to this new node. + $this->last = $this->orderedcollection[$type][$key]; + + // Reorder the array by index if needed + if (!$last) { + ksort($this->collection); + } + $this->count++; + // Return the reference to the now added node + return $node; + } + + /** + * Return a list of all the keys of all the nodes. + * @return array the keys. + */ + public function get_key_list() { + $keys = array(); + foreach ($this->collection as $node) { + $keys[] = $node->key; + } + return $keys; + } + + /** + * Set a label for this collection. + * + * @param string $label + */ + public function set_collectionlabel($label) { + $this->collectionlabel = $label; + } + + /** + * Return a label for this collection. + * + * @return string + */ + public function get_collectionlabel() { + return $this->collectionlabel; + } + + /** + * Fetches a node from this collection. + * + * @param string|int $key The key of the node we want to find. + * @param int $type One of navigation_node::TYPE_*. + * @return navigation_node|null|false + */ + public function get($key, $type=null) { + if ($type !== null) { + // If the type is known then we can simply check and fetch + if (!empty($this->orderedcollection[$type][$key])) { + return $this->orderedcollection[$type][$key]; + } + } else { + // Because we don't know the type we look in the progressive array + foreach ($this->collection as $node) { + if ($node->key === $key) { + return $node; + } + } + } + return false; + } + + /** + * Searches for a node with matching key and type. + * + * This function searches both the nodes in this collection and all of + * the nodes in each collection belonging to the nodes in this collection. + * + * Recursive. + * + * @param string|int $key The key of the node we want to find. + * @param int $type One of navigation_node::TYPE_*. + * @return navigation_node|false + */ + public function find($key, $type=null) { + if ($type !== null && array_key_exists($type, $this->orderedcollection) && array_key_exists($key, $this->orderedcollection[$type])) { + return $this->orderedcollection[$type][$key]; + } else { + $nodes = $this->getIterator(); + // Search immediate children first + foreach ($nodes as &$node) { + if ($node->key === $key && ($type === null || $type === $node->type)) { + return $node; + } + } + // Now search each childs children + foreach ($nodes as &$node) { + $result = $node->children->find($key, $type); + if ($result !== false) { + return $result; + } + } + } + return false; + } + + /** + * Fetches the last node that was added to this collection + * + * @return navigation_node + */ + public function last() { + return $this->last; + } + + /** + * Fetches all nodes of a given type from this collection + * + * @param string|int $type node type being searched for. + * @return array ordered collection + */ + public function type($type) { + if (!array_key_exists($type, $this->orderedcollection)) { + $this->orderedcollection[$type] = array(); + } + return $this->orderedcollection[$type]; + } + /** + * Removes the node with the given key and type from the collection + * + * @param string|int $key The key of the node we want to find. + * @param int $type + * @return bool + */ + public function remove($key, $type=null) { + $child = $this->get($key, $type); + if ($child !== false) { + foreach ($this->collection as $colkey => $node) { + if ($node->key === $key && (is_null($type) || $node->type == $type)) { + unset($this->collection[$colkey]); + $this->collection = array_values($this->collection); + break; + } + } + unset($this->orderedcollection[$child->type][$child->key]); + $this->count--; + return true; + } + return false; + } + + /** + * Gets the number of nodes in this collection + * + * This option uses an internal count rather than counting the actual options to avoid + * a performance hit through the count function. + * + * @return int + */ + public function count(): int { + return $this->count; + } + /** + * Gets an array iterator for the collection. + * + * This is required by the IteratorAggregator interface and is used by routines + * such as the foreach loop. + * + * @return ArrayIterator + */ + public function getIterator(): Traversable { + return new ArrayIterator($this->collection); + } +} diff --git a/public/lib/classes/navigation/settings_navigation.php b/public/lib/classes/navigation/settings_navigation.php new file mode 100644 index 00000000000..a02831f3cbd --- /dev/null +++ b/public/lib/classes/navigation/settings_navigation.php @@ -0,0 +1,1570 @@ +. + +use core\moodlenet\utilities; +use core_contentbank\contentbank; + +/** + * Class used to manage the settings option for the current page + * + * This class is used to manage the settings options in a tree format (recursively) + * and was created initially for use with the settings blocks. + * + * @package core + * @category navigation + * @copyright 2009 Sam Hemelryk + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class settings_navigation extends navigation_node { + /** @var context the current context */ + protected $context; + /** @var moodle_page the moodle page that the navigation belongs to */ + protected $page; + /** @var string contains administration section navigation_nodes */ + protected $adminsection; + /** @var bool A switch to see if the navigation node is initialised */ + protected $initialised = false; + /** @var array An array of users that the nodes can extend for. */ + protected $userstoextendfor = array(); + /** @var navigation_cache **/ + protected $cache; + + /** + * Sets up the object with basic settings and preparse it for use + * + * @param moodle_page $page + */ + public function __construct(moodle_page &$page) { + if (during_initial_install()) { + return; + } + $this->page = $page; + // Initialise the main navigation. It is most important that this is done + // before we try anything + $this->page->navigation->initialise(); + // Initialise the navigation cache + $this->cache = new navigation_cache(NAVIGATION_CACHE_NAME); + $this->children = new navigation_node_collection(); + } + + /** + * Initialise the settings navigation based on the current context + * + * This function initialises the settings navigation tree for a given context + * by calling supporting functions to generate major parts of the tree. + * + */ + public function initialise() { + global $DB, $SESSION, $SITE; + + if (during_initial_install()) { + return false; + } else if ($this->initialised) { + return true; + } + $this->id = 'settingsnav'; + $this->context = $this->page->context; + + $context = $this->context; + if ($context->contextlevel == CONTEXT_BLOCK) { + $this->load_block_settings(); + $context = $context->get_parent_context(); + $this->context = $context; + } + switch ($context->contextlevel) { + case CONTEXT_SYSTEM: + if ($this->page->url->compare(new moodle_url('/admin/settings.php', array('section'=>'frontpagesettings')))) { + $this->load_front_page_settings(($context->id == $this->context->id)); + } + break; + case CONTEXT_COURSECAT: + $this->load_category_settings(); + break; + case CONTEXT_COURSE: + if ($this->page->course->id != $SITE->id) { + $this->load_course_settings(($context->id == $this->context->id)); + } else { + $this->load_front_page_settings(($context->id == $this->context->id)); + } + break; + case CONTEXT_MODULE: + $this->load_module_settings(); + $this->load_course_settings(); + break; + case CONTEXT_USER: + if ($this->page->course->id != $SITE->id) { + $this->load_course_settings(); + } + break; + } + + $usersettings = $this->load_user_settings($this->page->course->id); + + $adminsettings = false; + if (isloggedin() && !isguestuser() && (!isset($SESSION->load_navigation_admin) || $SESSION->load_navigation_admin)) { + $isadminpage = $this->is_admin_tree_needed(); + + if (has_capability('moodle/site:configview', context_system::instance())) { + if (has_capability('moodle/site:config', context_system::instance())) { + // Make sure this works even if config capability changes on the fly + // and also make it fast for admin right after login. + $SESSION->load_navigation_admin = 1; + if ($isadminpage) { + $adminsettings = $this->load_administration_settings(); + } + + } else if (!isset($SESSION->load_navigation_admin)) { + $adminsettings = $this->load_administration_settings(); + $SESSION->load_navigation_admin = (int)($adminsettings->children->count() > 0); + + } else if ($SESSION->load_navigation_admin) { + if ($isadminpage) { + $adminsettings = $this->load_administration_settings(); + } + } + + // Print empty navigation node, if needed. + if ($SESSION->load_navigation_admin && !$isadminpage) { + if ($adminsettings) { + // Do not print settings tree on pages that do not need it, this helps with performance. + $adminsettings->remove(); + $adminsettings = false; + } + $siteadminnode = $this->add(get_string('administrationsite'), new moodle_url('/admin/search.php'), + self::TYPE_SITE_ADMIN, null, 'siteadministration'); + $siteadminnode->id = 'expandable_branch_' . $siteadminnode->type . '_' . + clean_param($siteadminnode->key, PARAM_ALPHANUMEXT); + $siteadminnode->requiresajaxloading = 'true'; + } + } + } + + if ($context->contextlevel == CONTEXT_SYSTEM && $adminsettings) { + $adminsettings->force_open(); + } else if ($context->contextlevel == CONTEXT_USER && $usersettings) { + $usersettings->force_open(); + } + + // At this point we give any local plugins the ability to extend/tinker with the navigation settings. + $this->load_local_plugin_settings(); + + foreach ($this->children as $key=>$node) { + if ($node->nodetype == self::NODETYPE_BRANCH && $node->children->count() == 0) { + // Site administration is shown as link. + if (!empty($SESSION->load_navigation_admin) && ($node->type === self::TYPE_SITE_ADMIN)) { + continue; + } + $node->remove(); + } + } + $this->initialised = true; + } + /** + * Override the parent function so that we can add preceeding hr's and set a + * root node class against all first level element + * + * It does this by first calling the parent's add method {@link navigation_node::add()} + * and then proceeds to use the key to set class and hr + * + * @param string $text text to be used for the link. + * @param string|moodle_url $url url for the new node + * @param int $type the type of node navigation_node::TYPE_* + * @param string $shorttext + * @param string|int $key a key to access the node by. + * @param pix_icon $icon An icon that appears next to the node. + * @return navigation_node with the new node added to it. + */ + public function add($text, $url=null, $type=null, $shorttext=null, $key=null, ?pix_icon $icon=null) { + $node = parent::add($text, $url, $type, $shorttext, $key, $icon); + $node->add_class('root_node'); + return $node; + } + + /** + * This function allows the user to add something to the start of the settings + * navigation, which means it will be at the top of the settings navigation block + * + * @param string $text text to be used for the link. + * @param string|moodle_url $url url for the new node + * @param int $type the type of node navigation_node::TYPE_* + * @param string $shorttext + * @param string|int $key a key to access the node by. + * @param pix_icon $icon An icon that appears next to the node. + * @return navigation_node $node with the new node added to it. + */ + public function prepend($text, $url=null, $type=null, $shorttext=null, $key=null, ?pix_icon $icon=null) { + $children = $this->children; + $childrenclass = get_class($children); + $this->children = new $childrenclass; + $node = $this->add($text, $url, $type, $shorttext, $key, $icon); + foreach ($children as $child) { + $this->children->add($child); + } + return $node; + } + + /** + * Does this page require loading of full admin tree or is + * it enough rely on AJAX? + * + * @return bool + */ + protected function is_admin_tree_needed() { + if (self::$loadadmintree) { + // Usually external admin page or settings page. + return true; + } + + if ($this->page->pagelayout === 'admin' or strpos($this->page->pagetype, 'admin-') === 0) { + // Admin settings tree is intended for system level settings and management only, use navigation for the rest! + if ($this->page->context->contextlevel != CONTEXT_SYSTEM) { + return false; + } + return true; + } + + return false; + } + + /** + * Load the site administration tree + * + * This function loads the site administration tree by using the lib/adminlib library functions + * + * @param navigation_node $referencebranch A reference to a branch in the settings + * navigation tree + * @param part_of_admin_tree $adminbranch The branch to add, if null generate the admin + * tree and start at the beginning + * @return mixed A key to access the admin tree by + */ + protected function load_administration_settings(?navigation_node $referencebranch=null, ?part_of_admin_tree $adminbranch=null) { + global $CFG; + + // Check if we are just starting to generate this navigation. + if ($referencebranch === null) { + + // Require the admin lib then get an admin structure + if (!function_exists('admin_get_root')) { + require_once($CFG->dirroot.'/lib/adminlib.php'); + } + $adminroot = admin_get_root(false, false); + // This is the active section identifier + $this->adminsection = $this->page->url->param('section'); + + // Disable the navigation from automatically finding the active node + navigation_node::$autofindactive = false; + $referencebranch = $this->add(get_string('administrationsite'), '/admin/search.php', self::TYPE_SITE_ADMIN, null, 'root'); + foreach ($adminroot->children as $adminbranch) { + $this->load_administration_settings($referencebranch, $adminbranch); + } + navigation_node::$autofindactive = true; + + // Use the admin structure to locate the active page + if (!$this->contains_active_node() && $current = $adminroot->locate($this->adminsection, true)) { + $currentnode = $this; + while (($pathkey = array_pop($current->path))!==null && $currentnode) { + $currentnode = $currentnode->get($pathkey); + } + if ($currentnode) { + $currentnode->make_active(); + } + } else { + $this->scan_for_active_node($referencebranch); + } + return $referencebranch; + } else if ($adminbranch->check_access()) { + // We have a reference branch that we can access and is not hidden `hurrah` + // Now we need to display it and any children it may have + $url = null; + $icon = null; + + if ($adminbranch instanceof \core_admin\local\settings\linkable_settings_page) { + if (empty($CFG->linkadmincategories) && $adminbranch instanceof admin_category) { + $url = null; + } else { + $url = $adminbranch->get_settings_page_url(); + } + } + + // Add the branch + $reference = $referencebranch->add($adminbranch->visiblename, $url, self::TYPE_SETTING, null, $adminbranch->name, $icon); + + if ($adminbranch->is_hidden()) { + if (($adminbranch instanceof admin_externalpage || $adminbranch instanceof admin_settingpage) && $adminbranch->name == $this->adminsection) { + $reference->add_class('hidden'); + } else { + $reference->display = false; + } + } + + // Check if we are generating the admin notifications and whether notificiations exist + if ($adminbranch->name === 'adminnotifications' && admin_critical_warnings_present()) { + $reference->add_class('criticalnotification'); + } + // Check if this branch has children + if ($reference && isset($adminbranch->children) && is_array($adminbranch->children) && count($adminbranch->children)>0) { + foreach ($adminbranch->children as $branch) { + // Generate the child branches as well now using this branch as the reference + $this->load_administration_settings($reference, $branch); + } + } else { + $reference->icon = new pix_icon('i/settings', ''); + } + } + } + + /** + * This function recursivily scans nodes until it finds the active node or there + * are no more nodes. + * @param navigation_node $node + */ + protected function scan_for_active_node(navigation_node $node) { + if (!$node->check_if_active() && $node->children->count()>0) { + foreach ($node->children as &$child) { + $this->scan_for_active_node($child); + } + } + } + + /** + * Gets a navigation node given an array of keys that represent the path to + * the desired node. + * + * @param array $path + * @return navigation_node|false + */ + protected function get_by_path(array $path) { + $node = $this->get(array_shift($path)); + foreach ($path as $key) { + $node->get($key); + } + return $node; + } + + /** + * This function loads the course settings that are available for the user + * + * @param bool $forceopen If set to true the course node will be forced open + * @return navigation_node|false + */ + protected function load_course_settings($forceopen = false) { + global $CFG, $USER; + require_once($CFG->dirroot . '/course/lib.php'); + + $course = $this->page->course; + $coursecontext = context_course::instance($course->id); + $adminoptions = course_get_user_administration_options($course, $coursecontext); + + // note: do not test if enrolled or viewing here because we need the enrol link in Course administration section + + $coursenode = $this->add(get_string('courseadministration'), null, self::TYPE_COURSE, null, 'courseadmin'); + if ($forceopen) { + $coursenode->force_open(); + } + + // MoodleNet links. + if ($this->page->user_is_editing()) { + $this->page->requires->js_call_amd('core/moodlenet/mutations', 'init'); + } + $usercanshare = utilities::can_user_share($coursecontext, $USER->id, 'course'); + $issuerid = get_config('moodlenet', 'oauthservice'); + try { + $issuer = \core\oauth2\api::get_issuer($issuerid); + $isvalidinstance = utilities::is_valid_instance($issuer); + if ($usercanshare && $isvalidinstance) { + $this->page->requires->js_call_amd('core/moodlenet/send_resource', 'init'); + $action = new action_link(new moodle_url(''), '', null, [ + 'data-action' => 'sendtomoodlenet', + 'data-type' => 'course', + ]); + // Share course to MoodleNet link. + $coursenode->add(get_string('moodlenet:sharetomoodlenet', 'moodle'), + $action, self::TYPE_SETTING, null, 'exportcoursetomoodlenet')->set_force_into_more_menu(true); + // MoodleNet share progress link. + $url = new moodle_url('/moodlenet/shareprogress.php'); + $coursenode->add(get_string('moodlenet:shareprogress'), + $url, self::TYPE_SETTING, null, 'moodlenetshareprogress')->set_force_into_more_menu(true); + } + } catch (dml_missing_record_exception $e) { + debugging("Invalid MoodleNet OAuth 2 service set in site administration: 'moodlenet | oauthservice'. " . + "This must be a valid issuer."); + } + + if ($adminoptions->update) { + // Add the course settings link + $url = new moodle_url('/course/edit.php', array('id'=>$course->id)); + $coursenode->add(get_string('settings'), $url, self::TYPE_SETTING, null, + 'editsettings', new pix_icon('i/settings', '')); + } + + if ($adminoptions->editcompletion) { + // Add the course completion settings link + $url = new moodle_url('/course/completion.php', array('id' => $course->id)); + $coursenode->add(get_string('coursecompletion', 'completion'), $url, self::TYPE_SETTING, null, 'coursecompletion', + new pix_icon('i/settings', '')); + } + + if (!$adminoptions->update && $adminoptions->tags) { + $url = \core\router\util::get_path_for_callable([ + \core_course\route\controller\tags_controller::class, + 'administer_tags', + ], ['course' => $course->id]); + $coursenode->add(get_string('coursetags', 'tag'), $url, self::TYPE_SETTING, null, 'coursetags', new pix_icon('i/settings', '')); + $coursenode->get('coursetags')->set_force_into_more_menu(); + } + + // add enrol nodes + enrol_add_course_navigation($coursenode, $course); + + // Manage filters + if ($adminoptions->filters) { + $url = new moodle_url('/filter/manage.php', array('contextid'=>$coursecontext->id)); + $coursenode->add(get_string('filters', 'admin'), $url, self::TYPE_SETTING, + null, 'filtermanagement', new pix_icon('i/filter', '')); + } + + // View course reports. + if ($adminoptions->reports) { + $reportnav = $coursenode->add(get_string('reports'), + new moodle_url('/report/view.php', ['courseid' => $coursecontext->instanceid]), + self::TYPE_CONTAINER, null, 'coursereports', new pix_icon('i/stats', '')); + $coursereports = core_component::get_plugin_list('coursereport'); + foreach ($coursereports as $report => $dir) { + $libfile = $CFG->dirroot.'/course/report/'.$report.'/lib.php'; + if (file_exists($libfile)) { + require_once($libfile); + $reportfunction = $report.'_report_extend_navigation'; + if (function_exists($report.'_report_extend_navigation')) { + $reportfunction($reportnav, $course, $coursecontext); + } + } + } + + $reports = get_plugin_list_with_function('report', 'extend_navigation_course', 'lib.php'); + foreach ($reports as $reportfunction) { + $reportfunction($reportnav, $course, $coursecontext); + } + + if (!$reportnav->has_children()) { + $reportnav->remove(); + } + } + + // Grade penalty navigation. + \core_grades\penalty_manager::extend_navigation_course($coursenode, $course, $coursecontext); + + // Check if we can view the gradebook's setup page. + if ($adminoptions->gradebook) { + $url = new moodle_url('/grade/edit/tree/index.php', array('id' => $course->id)); + $coursenode->add(get_string('gradebooksetup', 'grades'), $url, self::TYPE_SETTING, + null, 'gradebooksetup', new pix_icon('i/settings', '')); + } + + // Add the context locking node. + $this->add_context_locking_node($coursenode, $coursecontext); + + // Add outcome if permitted + if ($adminoptions->outcomes) { + $url = new moodle_url('/grade/edit/outcome/course.php', array('id'=>$course->id)); + $coursenode->add(get_string('outcomes', 'grades'), $url, self::TYPE_SETTING, null, 'outcomes', new pix_icon('i/outcomes', '')); + } + + //Add badges navigation + if ($adminoptions->badges) { + require_once($CFG->libdir .'/badgeslib.php'); + badges_add_course_navigation($coursenode, $course); + } + + // Questions + require_once($CFG->libdir . '/questionlib.php'); + $baseurl = \core_question\local\bank\question_bank_helper::get_url_for_qbank_list($course->id); + question_extend_settings_navigation($coursenode, $coursecontext, $baseurl)->trim_if_empty(); + + if ($adminoptions->update) { + // Repository Instances + if (!$this->cache->cached('contexthasrepos'.$coursecontext->id)) { + require_once($CFG->dirroot . '/repository/lib.php'); + $editabletypes = repository::get_editable_types($coursecontext); + $haseditabletypes = !empty($editabletypes); + unset($editabletypes); + $this->cache->set('contexthasrepos'.$coursecontext->id, $haseditabletypes); + } else { + $haseditabletypes = $this->cache->{'contexthasrepos'.$coursecontext->id}; + } + if ($haseditabletypes) { + $url = new moodle_url('/repository/manage_instances.php', array('contextid' => $coursecontext->id)); + $coursenode->add(get_string('repositories'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/repository', '')); + } + } + + // Manage files + if ($adminoptions->files) { + // hidden in new courses and courses where legacy files were turned off + $url = new moodle_url('/files/index.php', array('contextid'=>$coursecontext->id)); + $coursenode->add(get_string('courselegacyfiles'), $url, self::TYPE_SETTING, null, 'coursefiles', new pix_icon('i/folder', '')); + + } + + // Let plugins hook into course navigation. + $pluginsfunction = get_plugins_with_function('extend_navigation_course', 'lib.php'); + foreach ($pluginsfunction as $plugintype => $plugins) { + // Ignore the report and gradepenalty plugins as they were already loaded above. + if ($plugintype == 'report' || $plugintype == 'gradepenalty') { + continue; + } + foreach ($plugins as $pluginfunction) { + $pluginfunction($coursenode, $course, $coursecontext); + } + } + + // Prepare data for course content download functionality if it is enabled. + if (\core\content::can_export_context($coursecontext, $USER)) { + $linkattr = \core_course\output\content_export_link::get_attributes($coursecontext); + $actionlink = new action_link($linkattr->url, $linkattr->displaystring, null, $linkattr->elementattributes); + + $coursenode->add($linkattr->displaystring, $actionlink, self::TYPE_SETTING, null, 'download', + new pix_icon('t/download', '')); + $coursenode->get('download')->set_force_into_more_menu(true); + } + + // Course reuse options. + if ($adminoptions->import + || $adminoptions->backup + || $adminoptions->restore + || $adminoptions->copy + || $adminoptions->reset) { + $coursereusenav = $coursenode->add( + get_string('coursereuse'), + new moodle_url('/backup/view.php', ['id' => $course->id]), + self::TYPE_CONTAINER, null, 'coursereuse', new pix_icon('t/edit', ''), + ); + + // Import data from other courses. + if ($adminoptions->import) { + $url = new moodle_url('/backup/import.php', ['id' => $course->id]); + $coursereusenav->add(get_string('import'), $url, self::TYPE_SETTING, null, 'import', new pix_icon('i/import', '')); + } + + // Backup this course. + if ($adminoptions->backup) { + $url = new moodle_url('/backup/backup.php', ['id' => $course->id]); + $coursereusenav->add(get_string('backup'), $url, self::TYPE_SETTING, null, 'backup', new pix_icon('i/backup', '')); + } + + // Restore to this course. + if ($adminoptions->restore) { + $url = new moodle_url('/backup/restorefile.php', ['contextid' => $coursecontext->id]); + $coursereusenav->add( + get_string('restore'), + $url, + self::TYPE_SETTING, + null, + 'restore', + new pix_icon('i/restore', ''), + ); + } + + // Copy this course. + if ($adminoptions->copy) { + $url = new moodle_url('/backup/copy.php', ['id' => $course->id]); + $coursereusenav->add(get_string('copycourse'), $url, self::TYPE_SETTING, null, 'copy', new pix_icon('t/copy', '')); + } + + // Reset this course. + if ($adminoptions->reset) { + $url = new moodle_url('/course/reset.php', ['id' => $course->id]); + $coursereusenav->add(get_string('reset'), $url, self::TYPE_SETTING, null, 'reset', new pix_icon('i/return', '')); + } + } + + // Return we are done + return $coursenode; + } + + /** + * Get the moodle_page object associated to the current settings navigation. + * + * @return moodle_page + */ + public function get_page(): moodle_page { + return $this->page; + } + + /** + * This function calls the module function to inject module settings into the + * settings navigation tree. + * + * This only gets called if there is a corrosponding function in the modules + * lib file. + * + * For examples mod/forum/lib.php {@link forum_extend_settings_navigation()} + * + * @return navigation_node|false + */ + protected function load_module_settings() { + global $CFG, $USER; + + if (!$this->page->cm && $this->context->contextlevel == CONTEXT_MODULE && $this->context->instanceid) { + $cm = get_coursemodule_from_id(false, $this->context->instanceid, 0, false, MUST_EXIST); + $this->page->set_cm($cm, $this->page->course); + } + + $file = $CFG->dirroot.'/mod/'.$this->page->activityname.'/lib.php'; + if (file_exists($file)) { + require_once($file); + } + + $modulenode = $this->add(get_string('pluginadministration', $this->page->activityname), null, self::TYPE_SETTING, null, 'modulesettings'); + $modulenode->nodetype = navigation_node::NODETYPE_BRANCH; + $modulenode->force_open(); + + // Settings for the module + if (has_capability('moodle/course:manageactivities', $this->page->cm->context)) { + $url = new moodle_url('/course/modedit.php', array('update' => $this->page->cm->id, 'return' => 1)); + $modulenode->add(get_string('settings'), $url, self::TYPE_SETTING, null, 'modedit', new pix_icon('i/settings', '')); + } + // Assign local roles + if (count(get_assignable_roles($this->page->cm->context))>0) { + $url = new moodle_url('/'.$CFG->admin.'/roles/assign.php', array('contextid'=>$this->page->cm->context->id)); + $modulenode->add(get_string('localroles', 'role'), $url, self::TYPE_SETTING, null, 'roleassign', + new pix_icon('i/role', '')); + } + // Override roles + if (has_capability('moodle/role:review', $this->page->cm->context) or count(get_overridable_roles($this->page->cm->context))>0) { + $url = new moodle_url('/'.$CFG->admin.'/roles/permissions.php', array('contextid'=>$this->page->cm->context->id)); + $modulenode->add(get_string('permissions', 'role'), $url, self::TYPE_SETTING, null, 'roleoverride', + new pix_icon('i/permissions', '')); + } + // Check role permissions + if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride','moodle/role:override', 'moodle/role:assign'), $this->page->cm->context)) { + $url = new moodle_url('/'.$CFG->admin.'/roles/check.php', array('contextid'=>$this->page->cm->context->id)); + $modulenode->add(get_string('checkpermissions', 'role'), $url, self::TYPE_SETTING, null, 'rolecheck', + new pix_icon('i/checkpermissions', '')); + } + + // Add the context locking node. + $this->add_context_locking_node($modulenode, $this->page->cm->context); + + // Manage filters + if (has_capability('moodle/filter:manage', $this->page->cm->context) && count(filter_get_available_in_context($this->page->cm->context))>0) { + $url = new moodle_url('/filter/manage.php', array('contextid'=>$this->page->cm->context->id)); + $modulenode->add(get_string('filters', 'admin'), $url, self::TYPE_SETTING, null, 'filtermanage', + new pix_icon('i/filter', '')); + } + // Add reports + $reports = get_plugin_list_with_function('report', 'extend_navigation_module', 'lib.php'); + foreach ($reports as $reportfunction) { + $reportfunction($modulenode, $this->page->cm); + } + // Add a backup link + $featuresfunc = $this->page->activityname.'_supports'; + if (function_exists($featuresfunc) && $featuresfunc(FEATURE_BACKUP_MOODLE2) && has_capability('moodle/backup:backupactivity', $this->page->cm->context)) { + $url = new moodle_url('/backup/backup.php', array('id'=>$this->page->cm->course, 'cm'=>$this->page->cm->id)); + $modulenode->add(get_string('backup'), $url, self::TYPE_SETTING, null, 'backup', new pix_icon('i/backup', '')); + } + + // Restore this activity + $featuresfunc = $this->page->activityname.'_supports'; + if (function_exists($featuresfunc) && $featuresfunc(FEATURE_BACKUP_MOODLE2) && has_capability('moodle/restore:restoreactivity', $this->page->cm->context)) { + $url = new moodle_url('/backup/restorefile.php', array('contextid'=>$this->page->cm->context->id)); + $modulenode->add(get_string('restore'), $url, self::TYPE_SETTING, null, 'restore', new pix_icon('i/restore', '')); + } + + // Allow the active advanced grading method plugin to append its settings + $featuresfunc = $this->page->activityname.'_supports'; + if (function_exists($featuresfunc) && $featuresfunc(FEATURE_ADVANCED_GRADING) && has_capability('moodle/grade:managegradingforms', $this->page->cm->context)) { + require_once($CFG->dirroot.'/grade/grading/lib.php'); + $gradingman = get_grading_manager($this->page->cm->context, 'mod_'.$this->page->activityname); + $gradingman->extend_settings_navigation($this, $modulenode); + } + + $function = $this->page->activityname.'_extend_settings_navigation'; + if (function_exists($function)) { + $function($this, $modulenode); + } + + // Send activity to MoodleNet. + $usercanshare = utilities::can_user_share($this->context->get_course_context(), $USER->id); + $issuerid = get_config('moodlenet', 'oauthservice'); + try { + $issuer = \core\oauth2\api::get_issuer($issuerid); + $isvalidinstance = utilities::is_valid_instance($issuer); + if ($usercanshare && $isvalidinstance) { + $this->page->requires->js_call_amd('core/moodlenet/send_resource', 'init'); + $action = new action_link(new moodle_url(''), '', null, [ + 'data-action' => 'sendtomoodlenet', + 'data-type' => 'activity', + ]); + $modulenode->add(get_string('moodlenet:sharetomoodlenet', 'moodle'), + $action, self::TYPE_SETTING, null, 'exportmoodlenet')->set_force_into_more_menu(true); + } + } catch (dml_missing_record_exception $e) { + debugging("Invalid MoodleNet OAuth 2 service set in site administration: 'moodlenet | oauthservice'. " . + "This must be a valid issuer."); + } + + // Remove the module node if there are no children. + if ($modulenode->children->count() <= 0) { + $modulenode->remove(); + } + + return $modulenode; + } + + /** + * Loads the user settings block of the settings nav + * + * This function is simply works out the userid and whether we need to load + * just the current users profile settings, or the current user and the user the + * current user is viewing. + * + * This function has some very ugly code to work out the user, if anyone has + * any bright ideas please feel free to intervene. + * + * @param int $courseid The course id of the current course + * @return navigation_node|false + */ + protected function load_user_settings($courseid = SITEID) { + global $USER, $CFG; + + if (isguestuser() || !isloggedin()) { + return false; + } + + $navusers = $this->page->navigation->get_extending_users(); + + if (count($this->userstoextendfor) > 0 || count($navusers) > 0) { + $usernode = null; + foreach ($this->userstoextendfor as $userid) { + if ($userid == $USER->id) { + continue; + } + $node = $this->generate_user_settings($courseid, $userid, 'userviewingsettings'); + if (is_null($usernode)) { + $usernode = $node; + } + } + foreach ($navusers as $user) { + if ($user->id == $USER->id) { + continue; + } + $node = $this->generate_user_settings($courseid, $user->id, 'userviewingsettings'); + if (is_null($usernode)) { + $usernode = $node; + } + } + $this->generate_user_settings($courseid, $USER->id); + } else { + $usernode = $this->generate_user_settings($courseid, $USER->id); + } + return $usernode; + } + + /** + * Extends the settings navigation for the given user. + * + * Note: This method gets called automatically if you call + * $PAGE->navigation->extend_for_user($userid) + * + * @param int $userid + */ + public function extend_for_user($userid) { + global $CFG; + + if (!in_array($userid, $this->userstoextendfor)) { + $this->userstoextendfor[] = $userid; + if ($this->initialised) { + $this->generate_user_settings($this->page->course->id, $userid, 'userviewingsettings'); + $children = array(); + foreach ($this->children as $child) { + $children[] = $child; + } + array_unshift($children, array_pop($children)); + $this->children = new navigation_node_collection(); + foreach ($children as $child) { + $this->children->add($child); + } + } + } + } + + /** + * This function gets called by {@link settings_navigation::load_user_settings()} and actually works out + * what can be shown/done + * + * @param int $courseid The current course' id + * @param int $userid The user id to load for + * @param string $gstitle The string to pass to get_string for the branch title + * @return navigation_node|false + */ + protected function generate_user_settings($courseid, $userid, $gstitle='usercurrentsettings') { + global $DB, $CFG, $USER, $SITE; + + if ($courseid != $SITE->id) { + if (!empty($this->page->course->id) && $this->page->course->id == $courseid) { + $course = $this->page->course; + } else { + $select = context_helper::get_preload_record_columns_sql('ctx'); + $sql = "SELECT c.*, $select + FROM {course} c + JOIN {context} ctx ON c.id = ctx.instanceid + WHERE c.id = :courseid AND ctx.contextlevel = :contextlevel"; + $params = array('courseid' => $courseid, 'contextlevel' => CONTEXT_COURSE); + $course = $DB->get_record_sql($sql, $params, MUST_EXIST); + context_helper::preload_from_record($course); + } + } else { + $course = $SITE; + } + + $coursecontext = context_course::instance($course->id); // Course context + $systemcontext = context_system::instance(); + $currentuser = ($USER->id == $userid); + + if ($currentuser) { + $user = $USER; + $usercontext = context_user::instance($user->id); // User context + } else { + $select = context_helper::get_preload_record_columns_sql('ctx'); + $sql = "SELECT u.*, $select + FROM {user} u + JOIN {context} ctx ON u.id = ctx.instanceid + WHERE u.id = :userid AND ctx.contextlevel = :contextlevel"; + $params = array('userid' => $userid, 'contextlevel' => CONTEXT_USER); + $user = $DB->get_record_sql($sql, $params, IGNORE_MISSING); + if (!$user) { + return false; + } + context_helper::preload_from_record($user); + + // Check that the user can view the profile + $usercontext = context_user::instance($user->id); // User context + $canviewuser = has_capability('moodle/user:viewdetails', $usercontext); + + if ($course->id == $SITE->id) { + if ($CFG->forceloginforprofiles && !has_coursecontact_role($user->id) && !$canviewuser) { // Reduce possibility of "browsing" userbase at site level + // Teachers can browse and be browsed at site level. If not forceloginforprofiles, allow access (bug #4366) + return false; + } + } else { + $canviewusercourse = has_capability('moodle/user:viewdetails', $coursecontext); + $userisenrolled = is_enrolled($coursecontext, $user->id, '', true); + if ((!$canviewusercourse && !$canviewuser) || !$userisenrolled) { + return false; + } + $canaccessallgroups = has_capability('moodle/site:accessallgroups', $coursecontext); + if (!$canaccessallgroups && groups_get_course_groupmode($course) == SEPARATEGROUPS && !$canviewuser) { + // If groups are in use, make sure we can see that group (MDL-45874). That does not apply to parents. + if ($courseid == $this->page->course->id) { + $mygroups = get_fast_modinfo($this->page->course)->groups; + } else { + $mygroups = groups_get_user_groups($courseid); + } + $usergroups = groups_get_user_groups($courseid, $userid); + if (!array_intersect_key($mygroups[0], $usergroups[0])) { + return false; + } + } + } + } + + $fullname = fullname($user, has_capability('moodle/site:viewfullnames', $this->page->context)); + + $key = $gstitle; + $prefurl = new moodle_url('/user/preferences.php'); + if ($gstitle != 'usercurrentsettings') { + $key .= $userid; + $prefurl->param('userid', $userid); + } + + // Add a user setting branch. + if ($gstitle == 'usercurrentsettings') { + $mainpage = $this->add(get_string('home'), new moodle_url('/'), self::TYPE_CONTAINER, null, 'site'); + + // This should be set to false as we don't want to show this to the user. It's only for generating the correct + // breadcrumb. + $mainpage->display = false; + $homepage = get_home_page(); + if (($homepage == HOMEPAGE_MY || $homepage == HOMEPAGE_MYCOURSES)) { + $mainpage->mainnavonly = true; + } + + $iscurrentuser = ($user->id == $USER->id); + + $baseargs = array('id' => $user->id); + if ($course->id != $SITE->id && !$iscurrentuser) { + $baseargs['course'] = $course->id; + $issitecourse = false; + } else { + // Load all categories and get the context for the system. + $issitecourse = true; + } + + // Add the user profile to the dashboard. + $profilenode = $mainpage->add(get_string('profile'), new moodle_url('/user/profile.php', + array('id' => $user->id)), self::TYPE_SETTING, null, 'myprofile'); + + // Add blog nodes. + if (!empty($CFG->enableblogs)) { + if (!$this->cache->cached('userblogoptions'.$user->id)) { + require_once($CFG->dirroot.'/blog/lib.php'); + // Get all options for the user. + $options = blog_get_options_for_user($user); + $this->cache->set('userblogoptions'.$user->id, $options); + } else { + $options = $this->cache->{'userblogoptions'.$user->id}; + } + + if (count($options) > 0) { + $blogs = $profilenode->add(get_string('blogs', 'blog'), null, navigation_node::TYPE_CONTAINER); + foreach ($options as $type => $option) { + if ($type == "rss") { + $blogs->add($option['string'], $option['link'], self::TYPE_SETTING, null, null, + new pix_icon('i/rss', '')); + } else { + $blogs->add($option['string'], $option['link'], self::TYPE_SETTING, null, 'blog' . $type); + } + } + } + } + + // Add the messages link. + // It is context based so can appear in the user's profile and in course participants information. + if (!empty($CFG->messaging)) { + $messageargs = array('user1' => $USER->id); + if ($USER->id != $user->id) { + $messageargs['user2'] = $user->id; + } + $url = new moodle_url('/message/index.php', $messageargs); + $mainpage->add(get_string('messages', 'message'), $url, self::TYPE_SETTING, null, 'messages'); + } + + // Add the "My private files" link. + // This link doesn't have a unique display for course context so only display it under the user's profile. + if ($issitecourse && $iscurrentuser && has_capability('moodle/user:manageownfiles', $usercontext)) { + $url = new moodle_url('/user/files.php'); + $mainpage->add(get_string('privatefiles'), $url, self::TYPE_SETTING, null, 'privatefiles'); + } + + // Add a node to view the users notes if permitted. + if (!empty($CFG->enablenotes) && + has_any_capability(array('moodle/notes:manage', 'moodle/notes:view'), $coursecontext)) { + $url = new moodle_url('/notes/index.php', array('user' => $user->id)); + if ($coursecontext->instanceid != SITEID) { + $url->param('course', $coursecontext->instanceid); + } + $profilenode->add(get_string('notes', 'notes'), $url); + } + + // Show the grades node. + if (($issitecourse && $iscurrentuser) || has_capability('moodle/user:viewdetails', $usercontext)) { + require_once($CFG->dirroot . '/user/lib.php'); + // Set the grades node to link to the "Grades" page. + if ($course->id == SITEID) { + $url = user_mygrades_url($user->id, $course->id); + } else { // Otherwise we are in a course and should redirect to the user grade report (Activity report version). + $url = new moodle_url('/course/user.php', array('mode' => 'grade', 'id' => $course->id, 'user' => $user->id)); + } + $mainpage->add(get_string('grades', 'grades'), $url, self::TYPE_SETTING, null, 'mygrades'); + } + + // Let plugins hook into user navigation. + $pluginsfunction = get_plugins_with_function('extend_navigation_user', 'lib.php'); + foreach ($pluginsfunction as $plugintype => $plugins) { + if ($plugintype != 'report') { + foreach ($plugins as $pluginfunction) { + $pluginfunction($profilenode, $user, $usercontext, $course, $coursecontext); + } + } + } + + $usersetting = navigation_node::create(get_string('preferences', 'moodle'), $prefurl, self::TYPE_CONTAINER, null, $key); + $mainpage->add_node($usersetting); + } else { + $usersetting = $this->add(get_string('preferences', 'moodle'), $prefurl, self::TYPE_CONTAINER, null, $key); + $usersetting->display = false; + } + $usersetting->id = 'usersettings'; + + // Check if the user has been deleted. + if ($user->deleted) { + if (!has_capability('moodle/user:update', $coursecontext)) { + // We can't edit the user so just show the user deleted message. + $usersetting->add(get_string('userdeleted'), null, self::TYPE_SETTING); + } else { + // We can edit the user so show the user deleted message and link it to the profile. + if ($course->id == $SITE->id) { + $profileurl = new moodle_url('/user/profile.php', array('id'=>$user->id)); + } else { + $profileurl = new moodle_url('/user/view.php', array('id'=>$user->id, 'course'=>$course->id)); + } + $usersetting->add(get_string('userdeleted'), $profileurl, self::TYPE_SETTING); + } + return true; + } + + $userauthplugin = false; + if (!empty($user->auth)) { + $userauthplugin = get_auth_plugin($user->auth); + } + + $useraccount = $usersetting->add(get_string('useraccount'), null, self::TYPE_CONTAINER, null, 'useraccount'); + + // Add the profile edit link. + if (isloggedin() && !isguestuser($user) && !is_mnet_remote_user($user)) { + if (($currentuser || is_siteadmin($USER) || !is_siteadmin($user)) && + has_capability('moodle/user:update', $systemcontext)) { + $url = new moodle_url('/user/editadvanced.php', array('id'=>$user->id, 'course'=>$course->id)); + $useraccount->add(get_string('editmyprofile'), $url, self::TYPE_SETTING, null, 'editprofile'); + } else if ((has_capability('moodle/user:editprofile', $usercontext) && !is_siteadmin($user)) || + ($currentuser && has_capability('moodle/user:editownprofile', $systemcontext))) { + if ($userauthplugin && $userauthplugin->can_edit_profile()) { + $url = $userauthplugin->edit_profile_url(); + if (empty($url)) { + $url = new moodle_url('/user/edit.php', array('id'=>$user->id, 'course'=>$course->id)); + } + $useraccount->add(get_string('editmyprofile'), $url, self::TYPE_SETTING, null, 'editprofile'); + } + } + } + + // Change password link. + if ($userauthplugin && $currentuser && !\core\session\manager::is_loggedinas() && !isguestuser() && + has_capability('moodle/user:changeownpassword', $systemcontext) && $userauthplugin->can_change_password()) { + $passwordchangeurl = $userauthplugin->change_password_url(); + if (empty($passwordchangeurl)) { + $passwordchangeurl = new moodle_url('/login/change_password.php', array('id'=>$course->id)); + } + $useraccount->add(get_string("changepassword"), $passwordchangeurl, self::TYPE_SETTING, null, 'changepassword'); + } + + // Default homepage. + $defaulthomepageuser = (!empty($CFG->defaulthomepage) && ($CFG->defaulthomepage == HOMEPAGE_USER)); + if (isloggedin() && !isguestuser($user) && $defaulthomepageuser) { + if ($currentuser && has_capability('moodle/user:editownprofile', $systemcontext) || + has_capability('moodle/user:editprofile', $usercontext)) { + $url = new moodle_url('/user/defaulthomepage.php', ['id' => $user->id]); + $useraccount->add(get_string('defaulthomepageuser'), $url, self::TYPE_SETTING, null, 'defaulthomepageuser'); + } + } + + if (isloggedin() && !isguestuser($user) && !is_mnet_remote_user($user)) { + if ($currentuser && has_capability('moodle/user:editownprofile', $systemcontext) || + has_capability('moodle/user:editprofile', $usercontext)) { + $url = new moodle_url('/user/language.php', array('id' => $user->id, 'course' => $course->id)); + $useraccount->add(get_string('preferredlanguage'), $url, self::TYPE_SETTING, null, 'preferredlanguage'); + } + } + $pluginmanager = core_plugin_manager::instance(); + $enabled = $pluginmanager->get_enabled_plugins('mod'); + if (isset($enabled['forum']) && isloggedin() && !isguestuser($user) && !is_mnet_remote_user($user)) { + if ($currentuser && has_capability('moodle/user:editownprofile', $systemcontext) || + has_capability('moodle/user:editprofile', $usercontext)) { + $url = new moodle_url('/user/forum.php', array('id' => $user->id, 'course' => $course->id)); + $useraccount->add(get_string('forumpreferences'), $url, self::TYPE_SETTING); + } + } + $editors = editors_get_enabled(); + if (count($editors) > 1) { + if (isloggedin() && !isguestuser($user) && !is_mnet_remote_user($user)) { + if ($currentuser && has_capability('moodle/user:editownprofile', $systemcontext) || + has_capability('moodle/user:editprofile', $usercontext)) { + $url = new moodle_url('/user/editor.php', array('id' => $user->id, 'course' => $course->id)); + $useraccount->add(get_string('editorpreferences'), $url, self::TYPE_SETTING); + } + } + } + + // Add "Calendar preferences" link. + if (isloggedin() && !isguestuser($user)) { + if ($currentuser && has_capability('moodle/user:editownprofile', $systemcontext) || + has_capability('moodle/user:editprofile', $usercontext)) { + $url = new moodle_url('/user/calendar.php', array('id' => $user->id)); + $useraccount->add(get_string('calendarpreferences', 'calendar'), $url, self::TYPE_SETTING, null, 'preferredcalendar'); + } + } + + // Add "Content bank preferences" link. + if (isloggedin() && !isguestuser($user)) { + if ($currentuser && has_capability('moodle/user:editownprofile', $systemcontext) || + has_capability('moodle/user:editprofile', $usercontext)) { + $url = new moodle_url('/user/contentbank.php', ['id' => $user->id]); + $useraccount->add(get_string('contentbankpreferences', 'core_contentbank'), $url, self::TYPE_SETTING, + null, 'contentbankpreferences'); + } + } + + // View the roles settings. + if (has_any_capability(['moodle/role:assign', 'moodle/role:safeoverride', 'moodle/role:override', + 'moodle/role:manage'], $usercontext)) { + $roles = $usersetting->add(get_string('roles'), null, self::TYPE_SETTING); + + $url = new moodle_url('/admin/roles/usersroles.php', ['userid' => $user->id, 'courseid' => $course->id]); + $roles->add(get_string('thisusersroles', 'role'), $url, self::TYPE_SETTING); + + $assignableroles = get_assignable_roles($usercontext, ROLENAME_BOTH); + + if (!empty($assignableroles)) { + $url = new moodle_url('/admin/roles/assign.php', + array('contextid' => $usercontext->id, 'userid' => $user->id, 'courseid' => $course->id)); + $roles->add(get_string('assignrolesrelativetothisuser', 'role'), $url, self::TYPE_SETTING); + } + + if (has_capability('moodle/role:review', $usercontext) || count(get_overridable_roles($usercontext, ROLENAME_BOTH))>0) { + $url = new moodle_url('/admin/roles/permissions.php', + array('contextid' => $usercontext->id, 'userid' => $user->id, 'courseid' => $course->id)); + $roles->add(get_string('permissions', 'role'), $url, self::TYPE_SETTING); + } + + $url = new moodle_url('/admin/roles/check.php', + array('contextid' => $usercontext->id, 'userid' => $user->id, 'courseid' => $course->id)); + $roles->add(get_string('checkpermissions', 'role'), $url, self::TYPE_SETTING); + } + + // Repositories. + if (!$this->cache->cached('contexthasrepos'.$usercontext->id)) { + require_once($CFG->dirroot . '/repository/lib.php'); + $editabletypes = repository::get_editable_types($usercontext); + $haseditabletypes = !empty($editabletypes); + unset($editabletypes); + $this->cache->set('contexthasrepos'.$usercontext->id, $haseditabletypes); + } else { + $haseditabletypes = $this->cache->{'contexthasrepos'.$usercontext->id}; + } + if ($haseditabletypes) { + $repositories = $usersetting->add(get_string('repositories', 'repository'), null, self::TYPE_SETTING); + $repositories->add(get_string('manageinstances', 'repository'), new moodle_url('/repository/manage_instances.php', + array('contextid' => $usercontext->id))); + } + + // Portfolio. + if ($currentuser && !empty($CFG->enableportfolios) && has_capability('moodle/portfolio:export', $systemcontext)) { + require_once($CFG->libdir . '/portfoliolib.php'); + if (portfolio_has_visible_instances()) { + $portfolio = $usersetting->add(get_string('portfolios', 'portfolio'), null, self::TYPE_SETTING); + + $url = new moodle_url('/user/portfolio.php', array('courseid'=>$course->id)); + $portfolio->add(get_string('configure', 'portfolio'), $url, self::TYPE_SETTING); + + $url = new moodle_url('/user/portfoliologs.php', array('courseid'=>$course->id)); + $portfolio->add(get_string('logs', 'portfolio'), $url, self::TYPE_SETTING); + } + } + + $enablemanagetokens = false; + if (!empty($CFG->enablerssfeeds)) { + $enablemanagetokens = true; + } else if (!is_siteadmin($USER->id) + && !empty($CFG->enablewebservices) + && has_capability('moodle/webservice:createtoken', context_system::instance()) ) { + $enablemanagetokens = true; + } + // Security keys. + if ($currentuser && $enablemanagetokens) { + $url = new moodle_url('/user/managetoken.php'); + $useraccount->add(get_string('securitykeys', 'webservice'), $url, self::TYPE_SETTING); + } + + // Messaging. + if (($currentuser && has_capability('moodle/user:editownmessageprofile', $systemcontext)) || (!isguestuser($user) && + has_capability('moodle/user:editmessageprofile', $usercontext) && !is_primary_admin($user->id))) { + $messagingurl = new moodle_url('/message/edit.php', array('id' => $user->id)); + $notificationsurl = new moodle_url('/message/notificationpreferences.php', array('userid' => $user->id)); + $useraccount->add(get_string('messagepreferences', 'message'), $messagingurl, self::TYPE_SETTING); + $useraccount->add(get_string('notificationpreferences', 'message'), $notificationsurl, self::TYPE_SETTING); + } + + // Blogs. + if ($currentuser && !empty($CFG->enableblogs)) { + $blog = $usersetting->add(get_string('blogs', 'blog'), null, navigation_node::TYPE_CONTAINER, null, 'blogs'); + if (has_capability('moodle/blog:view', $systemcontext)) { + $blog->add(get_string('preferences', 'blog'), new moodle_url('/blog/preferences.php'), + navigation_node::TYPE_SETTING); + } + if (!empty($CFG->useexternalblogs) && $CFG->maxexternalblogsperuser > 0 && + has_capability('moodle/blog:manageexternal', $systemcontext)) { + $blog->add(get_string('externalblogs', 'blog'), new moodle_url('/blog/external_blogs.php'), + navigation_node::TYPE_SETTING); + $blog->add(get_string('addnewexternalblog', 'blog'), new moodle_url('/blog/external_blog_edit.php'), + navigation_node::TYPE_SETTING); + } + // Remove the blog node if empty. + $blog->trim_if_empty(); + } + + // Badges. + if ($currentuser && !empty($CFG->enablebadges)) { + $badges = $usersetting->add(get_string('badges'), null, navigation_node::TYPE_CONTAINER, null, 'badges'); + if (has_capability('moodle/badges:manageownbadges', $usercontext)) { + $url = new moodle_url('/badges/mybadges.php'); + $badges->add(get_string('managebadges', 'badges'), $url, self::TYPE_SETTING); + } + $badges->add(get_string('preferences', 'badges'), new moodle_url('/badges/preferences.php'), + navigation_node::TYPE_SETTING); + if (!empty($CFG->badges_allowexternalbackpack)) { + $badges->add(get_string('backpackdetails', 'badges'), new moodle_url('/badges/mybackpack.php'), + navigation_node::TYPE_SETTING); + } + } + + // Let plugins hook into user settings navigation. + $pluginsfunction = get_plugins_with_function('extend_navigation_user_settings', 'lib.php'); + foreach ($pluginsfunction as $plugintype => $plugins) { + foreach ($plugins as $pluginfunction) { + $pluginfunction($usersetting, $user, $usercontext, $course, $coursecontext); + } + } + + return $usersetting; + } + + /** + * Loads block specific settings in the navigation + * + * @return navigation_node + */ + protected function load_block_settings() { + global $CFG; + + $blocknode = $this->add($this->context->get_context_name(), null, self::TYPE_SETTING, null, 'blocksettings'); + $blocknode->force_open(); + + // Assign local roles + if (get_assignable_roles($this->context, ROLENAME_ORIGINAL)) { + $assignurl = new moodle_url('/'.$CFG->admin.'/roles/assign.php', array('contextid' => $this->context->id)); + $blocknode->add(get_string('assignroles', 'role'), $assignurl, self::TYPE_SETTING, null, + 'roles', new pix_icon('i/assignroles', '')); + } + + // Override roles + if (has_capability('moodle/role:review', $this->context) or count(get_overridable_roles($this->context))>0) { + $url = new moodle_url('/'.$CFG->admin.'/roles/permissions.php', array('contextid'=>$this->context->id)); + $blocknode->add(get_string('permissions', 'role'), $url, self::TYPE_SETTING, null, + 'permissions', new pix_icon('i/permissions', '')); + } + // Check role permissions + if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride','moodle/role:override', 'moodle/role:assign'), $this->context)) { + $url = new moodle_url('/'.$CFG->admin.'/roles/check.php', array('contextid'=>$this->context->id)); + $blocknode->add(get_string('checkpermissions', 'role'), $url, self::TYPE_SETTING, null, + 'checkpermissions', new pix_icon('i/checkpermissions', '')); + } + + // Add the context locking node. + $this->add_context_locking_node($blocknode, $this->context); + + return $blocknode; + } + + /** + * Loads category specific settings in the navigation + * + * @return navigation_node + */ + protected function load_category_settings() { + global $CFG; + + // We can land here while being in the context of a block, in which case we + // should get the parent context which should be the category one. See self::initialise(). + if ($this->context->contextlevel == CONTEXT_BLOCK) { + $catcontext = $this->context->get_parent_context(); + } else { + $catcontext = $this->context; + } + + // Let's make sure that we always have the right context when getting here. + if ($catcontext->contextlevel != CONTEXT_COURSECAT) { + throw new coding_exception('Unexpected context while loading category settings.'); + } + + $categorynodetype = navigation_node::TYPE_CONTAINER; + $categorynode = $this->add($catcontext->get_context_name(), null, $categorynodetype, null, 'categorysettings'); + $categorynode->nodetype = navigation_node::NODETYPE_BRANCH; + $categorynode->force_open(); + + if (can_edit_in_category($catcontext->instanceid)) { + $url = new moodle_url('/course/management.php', array('categoryid' => $catcontext->instanceid)); + $editstring = get_string('managecategorythis'); + $node = $categorynode->add($editstring, $url, self::TYPE_SETTING, null, 'managecategory', new pix_icon('i/edit', '')); + $node->set_show_in_secondary_navigation(false); + } + + if (has_capability('moodle/category:manage', $catcontext)) { + $editurl = new moodle_url('/course/editcategory.php', array('id' => $catcontext->instanceid)); + $categorynode->add(get_string('settings'), $editurl, self::TYPE_SETTING, null, 'edit', new pix_icon('i/edit', '')); + + $addsubcaturl = new moodle_url('/course/editcategory.php', array('parent' => $catcontext->instanceid)); + $categorynode->add(get_string('addsubcategory'), $addsubcaturl, self::TYPE_SETTING, null, + 'addsubcat', new pix_icon('i/withsubcat', ''))->set_show_in_secondary_navigation(false); + } + + // Assign local roles + $assignableroles = get_assignable_roles($catcontext); + if (!empty($assignableroles)) { + $assignurl = new moodle_url('/'.$CFG->admin.'/roles/assign.php', array('contextid' => $catcontext->id)); + $categorynode->add(get_string('assignroles', 'role'), $assignurl, self::TYPE_SETTING, null, 'roles', new pix_icon('i/assignroles', '')); + } + + // Override roles + if (has_capability('moodle/role:review', $catcontext) or count(get_overridable_roles($catcontext)) > 0) { + $url = new moodle_url('/'.$CFG->admin.'/roles/permissions.php', array('contextid' => $catcontext->id)); + $categorynode->add(get_string('permissions', 'role'), $url, self::TYPE_SETTING, null, 'permissions', new pix_icon('i/permissions', '')); + } + // Check role permissions + if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride', + 'moodle/role:override', 'moodle/role:assign'), $catcontext)) { + $url = new moodle_url('/'.$CFG->admin.'/roles/check.php', array('contextid' => $catcontext->id)); + $categorynode->add(get_string('checkpermissions', 'role'), $url, self::TYPE_SETTING, null, 'rolecheck', new pix_icon('i/checkpermissions', '')); + } + + // Add the context locking node. + $this->add_context_locking_node($categorynode, $catcontext); + + // Cohorts + if (has_any_capability(array('moodle/cohort:view', 'moodle/cohort:manage'), $catcontext)) { + $categorynode->add(get_string('cohorts', 'cohort'), new moodle_url('/cohort/index.php', + array('contextid' => $catcontext->id)), self::TYPE_SETTING, null, 'cohort', new pix_icon('i/cohort', '')); + } + + // Manage filters + if (has_capability('moodle/filter:manage', $catcontext) && count(filter_get_available_in_context($catcontext)) > 0) { + $url = new moodle_url('/filter/manage.php', array('contextid' => $catcontext->id)); + $categorynode->add(get_string('filters', 'admin'), $url, self::TYPE_SETTING, null, 'filters', new pix_icon('i/filter', '')); + } + + // Restore. + if (has_capability('moodle/restore:restorecourse', $catcontext)) { + $url = new moodle_url('/backup/restorefile.php', array('contextid' => $catcontext->id)); + $categorynode->add(get_string('restorecourse', 'admin'), $url, self::TYPE_SETTING, null, 'restorecourse', new pix_icon('i/restore', '')); + } + + // Let plugins hook into category settings navigation. + $pluginsfunction = get_plugins_with_function('extend_navigation_category_settings', 'lib.php'); + foreach ($pluginsfunction as $plugintype => $plugins) { + foreach ($plugins as $pluginfunction) { + $pluginfunction($categorynode, $catcontext); + } + } + + $cb = new contentbank(); + if ($cb->is_context_allowed($catcontext) + && has_capability('moodle/contentbank:access', $catcontext)) { + $url = new \moodle_url('/contentbank/index.php', ['contextid' => $catcontext->id]); + $categorynode->add(get_string('contentbank'), $url, self::TYPE_CUSTOM, null, + 'contentbank', new \pix_icon('i/contentbank', '')); + } + + return $categorynode; + } + + /** + * Determine whether the user is assuming another role + * + * This function checks to see if the user is assuming another role by means of + * role switching. In doing this we compare each RSW key (context path) against + * the current context path. This ensures that we can provide the switching + * options against both the course and any page shown under the course. + * + * @return bool|int The role(int) if the user is in another role, false otherwise + */ + protected function in_alternative_role() { + global $USER; + if (!empty($USER->access['rsw']) && is_array($USER->access['rsw'])) { + if (!empty($this->page->context) && !empty($USER->access['rsw'][$this->page->context->path])) { + return $USER->access['rsw'][$this->page->context->path]; + } + foreach ($USER->access['rsw'] as $key=>$role) { + if (strpos($this->context->path,$key)===0) { + return $role; + } + } + } + return false; + } + + /** + * This function loads all of the front page settings into the settings navigation. + * This function is called when the user is on the front page, or $COURSE==$SITE + * @param bool $forceopen (optional) + * @return navigation_node + */ + protected function load_front_page_settings($forceopen = false) { + global $SITE, $CFG; + require_once($CFG->dirroot . '/course/lib.php'); + + $course = clone($SITE); + $coursecontext = context_course::instance($course->id); // Course context + $adminoptions = course_get_user_administration_options($course, $coursecontext); + + $frontpage = $this->add(get_string('frontpagesettings'), null, self::TYPE_SETTING, null, 'frontpage'); + if ($forceopen) { + $frontpage->force_open(); + } + $frontpage->id = 'frontpagesettings'; + + if ($this->page->user_allowed_editing() && !$this->page->theme->haseditswitch) { + + // Add the turn on/off settings + $url = new moodle_url('/course/view.php', array('id'=>$course->id, 'sesskey'=>sesskey())); + if ($this->page->user_is_editing()) { + $url->param('edit', 'off'); + $editstring = get_string('turneditingoff'); + } else { + $url->param('edit', 'on'); + $editstring = get_string('turneditingon'); + } + $frontpage->add($editstring, $url, self::TYPE_SETTING, null, null, new pix_icon('i/edit', '')); + } + + if ($adminoptions->update) { + // Add the course settings link + $url = new moodle_url('/admin/settings.php', array('section'=>'frontpagesettings')); + $frontpage->add(get_string('settings'), $url, self::TYPE_SETTING, null, + 'editsettings', new pix_icon('i/settings', '')); + } + + // add enrol nodes + enrol_add_course_navigation($frontpage, $course); + + // Manage filters + if ($adminoptions->filters) { + $url = new moodle_url('/filter/manage.php', array('contextid'=>$coursecontext->id)); + $frontpage->add(get_string('filters', 'admin'), $url, self::TYPE_SETTING, + null, 'filtermanagement', new pix_icon('i/filter', '')); + } + + // View course reports. + if ($adminoptions->reports) { + $frontpagenav = $frontpage->add(get_string('reports'), new moodle_url('/report/view.php', + ['courseid' => $coursecontext->instanceid]), + self::TYPE_CONTAINER, null, 'coursereports', + new pix_icon('i/stats', '')); + $coursereports = core_component::get_plugin_list('coursereport'); + foreach ($coursereports as $report=>$dir) { + $libfile = $CFG->dirroot.'/course/report/'.$report.'/lib.php'; + if (file_exists($libfile)) { + require_once($libfile); + $reportfunction = $report.'_report_extend_navigation'; + if (function_exists($report.'_report_extend_navigation')) { + $reportfunction($frontpagenav, $course, $coursecontext); + } + } + } + + $reports = get_plugin_list_with_function('report', 'extend_navigation_course', 'lib.php'); + foreach ($reports as $reportfunction) { + $reportfunction($frontpagenav, $course, $coursecontext); + } + + if (!$frontpagenav->has_children()) { + $frontpagenav->remove(); + } + } + + // Questions + require_once($CFG->libdir . '/questionlib.php'); + $baseurl = \core_question\local\bank\question_bank_helper::get_url_for_qbank_list($course->id); + question_extend_settings_navigation($frontpage, $coursecontext, $baseurl)->trim_if_empty(); + + // Manage files + if ($adminoptions->files) { + //hiden in new installs + $url = new moodle_url('/files/index.php', array('contextid'=>$coursecontext->id)); + $frontpage->add(get_string('sitelegacyfiles'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/folder', '')); + } + + // Let plugins hook into frontpage navigation. + $pluginsfunction = get_plugins_with_function('extend_navigation_frontpage', 'lib.php'); + foreach ($pluginsfunction as $plugintype => $plugins) { + foreach ($plugins as $pluginfunction) { + $pluginfunction($frontpage, $course, $coursecontext); + } + } + + // Course reuse options. + if ($adminoptions->backup || $adminoptions->restore) { + $coursereusenav = $frontpage->add( + get_string('coursereuse'), + new moodle_url('/backup/view.php', ['id' => $course->id]), + self::TYPE_CONTAINER, null, 'coursereuse', new pix_icon('t/edit', ''), + ); + + // Backup this course. + if ($adminoptions->backup) { + $url = new moodle_url('/backup/backup.php', ['id' => $course->id]); + $coursereusenav->add(get_string('backup'), $url, self::TYPE_SETTING, null, 'backup', new pix_icon('i/backup', '')); + } + + // Restore to this course. + if ($adminoptions->restore) { + $url = new moodle_url('/backup/restorefile.php', ['contextid' => $coursecontext->id]); + $coursereusenav->add( + get_string('restore'), + $url, + self::TYPE_SETTING, + null, + 'restore', + new pix_icon('i/restore', ''), + ); + } + } + + return $frontpage; + } + + /** + * This function gives local plugins an opportunity to modify the settings navigation. + */ + protected function load_local_plugin_settings() { + + foreach (get_plugin_list_with_function('local', 'extend_settings_navigation') as $function) { + $function($this, $this->context); + } + } + + /** + * This function marks the cache as volatile so it is cleared during shutdown + */ + public function clear_cache() { + $this->cache->volatile(); + } + + /** + * Checks to see if there are child nodes available in the specific user's preference node. + * If so, then they have the appropriate permissions view this user's preferences. + * + * @since Moodle 2.9.3 + * @param int $userid The user's ID. + * @return bool True if child nodes exist to view, otherwise false. + */ + public function can_view_user_preferences($userid) { + if (is_siteadmin()) { + return true; + } + // See if any nodes are present in the preferences section for this user. + $preferencenode = $this->find('userviewingsettings' . $userid, null); + if ($preferencenode && $preferencenode->has_children()) { + // Run through each child node. + foreach ($preferencenode->children as $childnode) { + // If the child node has children then this user has access to a link in the preferences page. + if ($childnode->has_children()) { + return true; + } + } + } + // No links found for the user to access on the preferences page. + return false; + } +} diff --git a/public/lib/classes/navigation/settings_navigation_ajax.php b/public/lib/classes/navigation/settings_navigation_ajax.php new file mode 100644 index 00000000000..8b6970704ce --- /dev/null +++ b/public/lib/classes/navigation/settings_navigation_ajax.php @@ -0,0 +1,54 @@ +. + + +/** + * Class used to populate site admin navigation for ajax. + * + * @package core + * @category navigation + * @copyright 2013 Rajesh Taneja + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class settings_navigation_ajax extends settings_navigation { + /** + * Constructs the navigation for use in an AJAX request + * + * @param moodle_page $page + */ + public function __construct(moodle_page &$page) { + $this->page = $page; + $this->cache = new navigation_cache(NAVIGATION_CACHE_NAME); + $this->children = new navigation_node_collection(); + $this->initialise(); + } + + /** + * Initialise the site admin navigation. + */ + public function initialise() { + if ($this->initialised || during_initial_install()) { + return false; + } + $this->context = $this->page->context; + $this->load_administration_settings(); + + // Check if local plugins is adding node to site admin. + $this->load_local_plugin_settings(); + + $this->initialised = true; + } +} diff --git a/public/lib/db/legacyclasses.php b/public/lib/db/legacyclasses.php index 1723e26708f..fe21db53e77 100644 --- a/public/lib/db/legacyclasses.php +++ b/public/lib/db/legacyclasses.php @@ -188,6 +188,20 @@ $legacyclasses = [ 'form/cachestore_addinstance_form.php', ], + // Navigation API. + \breadcrumb_navigation_node::class => 'navigation/breadcrumb_navigation_node.php', + \flat_navigation::class => 'navigation/flat_navigation.php', + \flat_navigation_node::class => 'navigation/flat_navigation_node.php', + \global_navigation::class => 'navigation/global_navigation.php', + \global_navigation_for_ajax::class => 'navigation/global_navigation_for_ajax.php', + \navbar::class => 'navigation/navbar.php', + \navigation_cache::class => 'navigation/navigation_cache.php', + \navigation_json::class => 'navigation/navigation_json.php', + \navigation_node::class => 'navigation/navigation_node.php', + \navigation_node_collection::class => 'navigation/navigation_node_collection.php', + \settings_navigation::class => 'navigation/settings_navigation.php', + \settings_navigation_ajax::class => 'navigation/settings_navigation_ajax.php', + // Output API. \theme_config::class => 'output/theme_config.php', \xhtml_container_stack::class => 'output/xhtml_container_stack.php', diff --git a/public/lib/navigationlib.php b/public/lib/navigationlib.php index 88ecb3fc802..88ff1a1a24e 100644 --- a/public/lib/navigationlib.php +++ b/public/lib/navigationlib.php @@ -23,6330 +23,8 @@ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ -use core\moodlenet\utilities; -use core_contentbank\contentbank; - -defined('MOODLE_INTERNAL') || die(); - /** * The name that will be used to separate the navigation cache within SESSION */ define('NAVIGATION_CACHE_NAME', 'navigation'); define('NAVIGATION_SITE_ADMIN_CACHE_NAME', 'navigationsiteadmin'); - -/** - * This class is used to represent a node in a navigation tree - * - * This class is used to represent a node in a navigation tree within Moodle, - * the tree could be one of global navigation, settings navigation, or the navbar. - * Each node can be one of two types either a Leaf (default) or a branch. - * When a node is first created it is created as a leaf, when/if children are added - * the node then becomes a branch. - * - * @package core - * @category navigation - * @copyright 2009 Sam Hemelryk - * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later - */ -class navigation_node implements renderable { - /** @var int Used to identify this node a leaf (default) 0 */ - const NODETYPE_LEAF = 0; - /** @var int Used to identify this node a branch, happens with children 1 */ - const NODETYPE_BRANCH = 1; - /** @var null Unknown node type null */ - const TYPE_UNKNOWN = null; - /** @var int System node type 0 */ - const TYPE_ROOTNODE = 0; - /** @var int System node type 1 */ - const TYPE_SYSTEM = 1; - /** @var int Category node type 10 */ - const TYPE_CATEGORY = 10; - /** var int Category displayed in MyHome navigation node */ - const TYPE_MY_CATEGORY = 11; - /** @var int Course node type 20 */ - const TYPE_COURSE = 20; - /** @var int Course Structure node type 30 */ - const TYPE_SECTION = 30; - /** @var int Activity node type, e.g. Forum, Quiz 40 */ - const TYPE_ACTIVITY = 40; - /** @var int Resource node type, e.g. Link to a file, or label 50 */ - const TYPE_RESOURCE = 50; - /** @var int A custom node type, default when adding without specifing type 60 */ - const TYPE_CUSTOM = 60; - /** @var int Setting node type, used only within settings nav 70 */ - const TYPE_SETTING = 70; - /** @var int site admin branch node type, used only within settings nav 71 */ - const TYPE_SITE_ADMIN = 71; - /** @var int Setting node type, used only within settings nav 80 */ - const TYPE_USER = 80; - /** @var int Setting node type, used for containers of no importance 90 */ - const TYPE_CONTAINER = 90; - /** var int Course the current user is not enrolled in */ - const COURSE_OTHER = 0; - /** var int Course the current user is enrolled in but not viewing */ - const COURSE_MY = 1; - /** var int Course the current user is currently viewing */ - const COURSE_CURRENT = 2; - /** var string The course index page navigation node */ - const COURSE_INDEX_PAGE = 'courseindexpage'; - - /** @var int Parameter to aid the coder in tracking [optional] */ - public $id = null; - /** @var string|int The identifier for the node, used to retrieve the node */ - public $key = null; - /** @var string|lang_string The text to use for the node */ - public $text = null; - /** @var string Short text to use if requested [optional] */ - public $shorttext = null; - /** @var string The title attribute for an action if one is defined */ - public $title = null; - /** @var string A string that can be used to build a help button */ - public $helpbutton = null; - /** @var moodle_url|action_link|null An action for the node (link) */ - public $action = null; - /** @var pix_icon The path to an icon to use for this node */ - public $icon = null; - /** @var int See TYPE_* constants defined for this class */ - public $type = self::TYPE_UNKNOWN; - /** @var int See NODETYPE_* constants defined for this class */ - public $nodetype = self::NODETYPE_LEAF; - /** @var bool If set to true the node will be collapsed by default */ - public $collapse = false; - /** @var bool If set to true the node will be expanded by default */ - public $forceopen = false; - /** @var array An array of CSS classes for the node */ - public $classes = array(); - /** @var array An array of HTML attributes for the node */ - public $attributes = []; - /** @var navigation_node_collection An array of child nodes */ - public $children = array(); - /** @var bool If set to true the node will be recognised as active */ - public $isactive = false; - /** @var bool If set to true the node will be dimmed */ - public $hidden = false; - /** @var bool If set to false the node will not be displayed */ - public $display = true; - /** @var bool If set to true then an HR will be printed before the node */ - public $preceedwithhr = false; - /** @var bool If set to true the the navigation bar should ignore this node */ - public $mainnavonly = false; - /** @var bool If set to true a title will be added to the action no matter what */ - public $forcetitle = false; - /** @var navigation_node A reference to the node parent, you should never set this directly you should always call set_parent */ - public $parent = null; - /** @var bool Override to not display the icon even if one is provided **/ - public $hideicon = false; - /** @var bool Set to true if we KNOW that this node can be expanded. */ - public $isexpandable = false; - /** @var array */ - protected $namedtypes = array(0 => 'system', 10 => 'category', 20 => 'course', 30 => 'structure', 40 => 'activity', - 50 => 'resource', 60 => 'custom', 70 => 'setting', 71 => 'siteadmin', 80 => 'user', - 90 => 'container'); - /** @var moodle_url */ - protected static $fullmeurl = null; - /** @var bool toogles auto matching of active node */ - public static $autofindactive = true; - /** @var bool should we load full admin tree or rely on AJAX for performance reasons */ - protected static $loadadmintree = false; - /** @var mixed If set to an int, that section will be included even if it has no activities */ - public $includesectionnum = false; - /** @var bool does the node need to be loaded via ajax */ - public $requiresajaxloading = false; - /** @var bool If set to true this node will be added to the "flat" navigation */ - public $showinflatnavigation = false; - /** @var bool If set to true this node will be forced into a "more" menu whenever possible */ - public $forceintomoremenu = false; - /** @var bool If set to true this node will be displayed in the "secondary" navigation when applicable */ - public $showinsecondarynavigation = true; - /** @var bool If set to true the children of this node will be displayed within a submenu when applicable */ - public $showchildreninsubmenu = false; - /** @var string tab element ID. */ - public $tab; - /** @var string unique identifier. */ - public $moremenuid; - /** @var bool node that have children. */ - public $haschildren; - - /** - * Constructs a new navigation_node - * - * @param array|string $properties Either an array of properties or a string to use - * as the text for the node - */ - public function __construct($properties) { - if (is_array($properties)) { - // Check the array for each property that we allow to set at construction. - // text - The main content for the node - // shorttext - A short text if required for the node - // icon - The icon to display for the node - // type - The type of the node - // key - The key to use to identify the node - // parent - A reference to the nodes parent - // action - The action to attribute to this node, usually a URL to link to - if (array_key_exists('text', $properties)) { - $this->text = $properties['text']; - } - if (array_key_exists('shorttext', $properties)) { - $this->shorttext = $properties['shorttext']; - } - if (!array_key_exists('icon', $properties)) { - $properties['icon'] = new pix_icon('i/navigationitem', ''); - } - $this->icon = $properties['icon']; - if ($this->icon instanceof pix_icon) { - if (empty($this->icon->attributes['class'])) { - $this->icon->attributes['class'] = 'navicon'; - } else { - $this->icon->attributes['class'] .= ' navicon'; - } - } - if (array_key_exists('type', $properties)) { - $this->type = $properties['type']; - } else { - $this->type = self::TYPE_CUSTOM; - } - if (array_key_exists('key', $properties)) { - $this->key = $properties['key']; - } - // This needs to happen last because of the check_if_active call that occurs - if (array_key_exists('action', $properties)) { - $this->action = $properties['action']; - if (is_string($this->action)) { - $this->action = new moodle_url($this->action); - } - if (self::$autofindactive) { - $this->check_if_active(); - } - } - if (array_key_exists('parent', $properties)) { - $this->set_parent($properties['parent']); - } - } else if (is_string($properties)) { - $this->text = $properties; - } - if ($this->text === null) { - throw new coding_exception('You must set the text for the node when you create it.'); - } - // Instantiate a new navigation node collection for this nodes children - $this->children = new navigation_node_collection(); - } - - /** - * Checks if this node is the active node. - * - * This is determined by comparing the action for the node against the - * defined URL for the page. A match will see this node marked as active. - * - * @param int $strength One of URL_MATCH_EXACT, URL_MATCH_PARAMS, or URL_MATCH_BASE - * @return bool - */ - public function check_if_active($strength=URL_MATCH_EXACT) { - global $FULLME, $PAGE; - // Set fullmeurl if it hasn't already been set - if (self::$fullmeurl == null) { - if ($PAGE->has_set_url()) { - self::override_active_url(new moodle_url($PAGE->url)); - } else { - self::override_active_url(new moodle_url($FULLME)); - } - } - - // Compare the action of this node against the fullmeurl - if ($this->action instanceof moodle_url && $this->action->compare(self::$fullmeurl, $strength)) { - $this->make_active(); - return true; - } - return false; - } - - /** - * True if this nav node has siblings in the tree. - * - * @return bool - */ - public function has_siblings() { - if (empty($this->parent) || empty($this->parent->children)) { - return false; - } - if ($this->parent->children instanceof navigation_node_collection) { - $count = $this->parent->children->count(); - } else { - $count = count($this->parent->children); - } - return ($count > 1); - } - - /** - * Get a list of sibling navigation nodes at the same level as this one. - * - * @return bool|array of navigation_node - */ - public function get_siblings() { - // Returns a list of the siblings of the current node for display in a flat navigation element. Either - // the in-page links or the breadcrumb links. - $siblings = false; - - if ($this->has_siblings()) { - $siblings = []; - foreach ($this->parent->children as $child) { - if ($child->display) { - $siblings[] = $child; - } - } - } - return $siblings; - } - - /** - * This sets the URL that the URL of new nodes get compared to when locating - * the active node. - * - * The active node is the node that matches the URL set here. By default this - * is either $PAGE->url or if that hasn't been set $FULLME. - * - * @param moodle_url $url The url to use for the fullmeurl. - * @param bool $loadadmintree use true if the URL point to administration tree - */ - public static function override_active_url(moodle_url $url, $loadadmintree = false) { - // Clone the URL, in case the calling script changes their URL later. - self::$fullmeurl = new moodle_url($url); - // True means we do not want AJAX loaded admin tree, required for all admin pages. - if ($loadadmintree) { - // Do not change back to false if already set. - self::$loadadmintree = true; - } - } - - /** - * Use when page is linked from the admin tree, - * if not used navigation could not find the page using current URL - * because the tree is not fully loaded. - */ - public static function require_admin_tree() { - self::$loadadmintree = true; - } - - /** - * Creates a navigation node, ready to add it as a child using add_node - * function. (The created node needs to be added before you can use it.) - * @param string $text - * @param moodle_url|action_link $action - * @param int $type - * @param string $shorttext - * @param string|int $key - * @param pix_icon $icon - * @return navigation_node - */ - public static function create($text, $action=null, $type=self::TYPE_CUSTOM, - $shorttext=null, $key=null, ?pix_icon $icon=null) { - if ($action && !($action instanceof moodle_url || $action instanceof action_link)) { - debugging( - "It is required that the action provided be either an action_url|moodle_url." . - " Please update your definition.", E_NOTICE); - } - // Properties array used when creating the new navigation node - $itemarray = array( - 'text' => $text, - 'type' => $type - ); - // Set the action if one was provided - if ($action!==null) { - $itemarray['action'] = $action; - } - // Set the shorttext if one was provided - if ($shorttext!==null) { - $itemarray['shorttext'] = $shorttext; - } - // Set the icon if one was provided - if ($icon!==null) { - $itemarray['icon'] = $icon; - } - // Set the key - $itemarray['key'] = $key; - // Construct and return - return new navigation_node($itemarray); - } - - /** - * Adds a navigation node as a child of this node. - * - * @param string $text - * @param moodle_url|action_link|string $action - * @param ?int $type - * @param string $shorttext - * @param string|int $key - * @param pix_icon $icon - * @return navigation_node - */ - public function add($text, $action=null, $type=self::TYPE_CUSTOM, $shorttext=null, $key=null, ?pix_icon $icon=null) { - if ($action && is_string($action)) { - $action = new moodle_url($action); - } - // Create child node - $childnode = self::create($text, $action, $type, $shorttext, $key, $icon); - - // Add the child to end and return - return $this->add_node($childnode); - } - - /** - * Adds a navigation node as a child of this one, given a $node object - * created using the create function. - * @param navigation_node $childnode Node to add - * @param string $beforekey - * @return navigation_node The added node - */ - public function add_node(navigation_node $childnode, $beforekey=null) { - // First convert the nodetype for this node to a branch as it will now have children - if ($this->nodetype !== self::NODETYPE_BRANCH) { - $this->nodetype = self::NODETYPE_BRANCH; - } - // Set the parent to this node - $childnode->set_parent($this); - - // Default the key to the number of children if not provided - if ($childnode->key === null) { - $childnode->key = $this->children->count(); - } - - // Add the child using the navigation_node_collections add method - $node = $this->children->add($childnode, $beforekey); - - // If added node is a category node or the user is logged in and it's a course - // then mark added node as a branch (makes it expandable by AJAX) - $type = $childnode->type; - if (($type == self::TYPE_CATEGORY) || (isloggedin() && ($type == self::TYPE_COURSE)) || ($type == self::TYPE_MY_CATEGORY) || - ($type === self::TYPE_SITE_ADMIN)) { - $node->nodetype = self::NODETYPE_BRANCH; - } - // If this node is hidden mark it's children as hidden also - if ($this->hidden) { - $node->hidden = true; - } - // Return added node (reference returned by $this->children->add() - return $node; - } - - /** - * Return a list of all the keys of all the child nodes. - * @return array the keys. - */ - public function get_children_key_list() { - return $this->children->get_key_list(); - } - - /** - * Searches for a node of the given type with the given key. - * - * This searches this node plus all of its children, and their children.... - * If you know the node you are looking for is a child of this node then please - * use the get method instead. - * - * @param int|string $key The key of the node we are looking for - * @param ?int $type One of navigation_node::TYPE_* - * @return navigation_node|false - */ - public function find($key, $type) { - return $this->children->find($key, $type); - } - - /** - * Walk the tree building up a list of all the flat navigation nodes. - * - * @deprecated since Moodle 4.0 - * @param flat_navigation $nodes List of the found flat navigation nodes. - * @param boolean $showdivider Show a divider before the first node. - * @param string $label A label for the collection of navigation links. - */ - public function build_flat_navigation_list(flat_navigation $nodes, $showdivider = false, $label = '') { - debugging("Function has been deprecated with the deprecation of the flat_navigation class."); - if ($this->showinflatnavigation) { - $indent = 0; - if ($this->type == self::TYPE_COURSE || $this->key === self::COURSE_INDEX_PAGE) { - $indent = 1; - } - $flat = new flat_navigation_node($this, $indent); - $flat->set_showdivider($showdivider, $label); - $nodes->add($flat); - } - foreach ($this->children as $child) { - $child->build_flat_navigation_list($nodes, false); - } - } - - /** - * Get the child of this node that has the given key + (optional) type. - * - * If you are looking for a node and want to search all children + their children - * then please use the find method instead. - * - * @param int|string $key The key of the node we are looking for - * @param int $type One of navigation_node::TYPE_* - * @return navigation_node|false - */ - public function get($key, $type=null) { - return $this->children->get($key, $type); - } - - /** - * Removes this node. - * - * @return bool - */ - public function remove() { - return $this->parent->children->remove($this->key, $this->type); - } - - /** - * Checks if this node has or could have any children - * - * @return bool Returns true if it has children or could have (by AJAX expansion) - */ - public function has_children() { - return ($this->nodetype === navigation_node::NODETYPE_BRANCH || $this->children->count()>0 || $this->isexpandable); - } - - /** - * Marks this node as active and forces it open. - * - * Important: If you are here because you need to mark a node active to get - * the navigation to do what you want have you looked at {@link navigation_node::override_active_url()}? - * You can use it to specify a different URL to match the active navigation node on - * rather than having to locate and manually mark a node active. - */ - public function make_active() { - $this->isactive = true; - $this->add_class('active_tree_node'); - $this->force_open(); - if ($this->parent !== null) { - $this->parent->make_inactive(); - } - } - - /** - * Marks a node as inactive and recusised back to the base of the tree - * doing the same to all parents. - */ - public function make_inactive() { - $this->isactive = false; - $this->remove_class('active_tree_node'); - if ($this->parent !== null) { - $this->parent->make_inactive(); - } - } - - /** - * Forces this node to be open and at the same time forces open all - * parents until the root node. - * - * Recursive. - */ - public function force_open() { - $this->forceopen = true; - if ($this->parent !== null) { - $this->parent->force_open(); - } - } - - /** - * Adds a CSS class to this node. - * - * @param string $class - * @return bool - */ - public function add_class($class) { - if (!in_array($class, $this->classes)) { - $this->classes[] = $class; - } - return true; - } - - /** - * Adds an HTML attribute to this node. - * - * @param string $name - * @param string $value - */ - public function add_attribute(string $name, string $value): void { - $this->attributes[] = ['name' => $name, 'value' => $value]; - } - - /** - * Removes a CSS class from this node. - * - * @param string $class - * @return bool True if the class was successfully removed. - */ - public function remove_class($class) { - if (in_array($class, $this->classes)) { - $key = array_search($class,$this->classes); - if ($key!==false) { - // Remove the class' array element. - unset($this->classes[$key]); - // Reindex the array to avoid failures when the classes array is iterated later in mustache templates. - $this->classes = array_values($this->classes); - - return true; - } - } - return false; - } - - /** - * Sets the title for this node and forces Moodle to utilise it. - * - * Note that this method is named identically to the public "title" property of the class, which unfortunately confuses - * our Mustache renderer, because it will see the method and try and call it without any arguments (hence must be nullable) - * before trying to access the public property - * - * @param string|null $title - * @return string - */ - public function title(?string $title = null): string { - if ($title !== null) { - $this->title = $title; - $this->forcetitle = true; - } - return (string) $this->title; - } - - /** - * Resets the page specific information on this node if it is being unserialised. - */ - public function __wakeup(){ - $this->forceopen = false; - $this->isactive = false; - $this->remove_class('active_tree_node'); - } - - /** - * Checks if this node or any of its children contain the active node. - * - * Recursive. - * - * @return bool - */ - public function contains_active_node() { - if ($this->isactive) { - return true; - } else { - foreach ($this->children as $child) { - if ($child->isactive || $child->contains_active_node()) { - return true; - } - } - } - return false; - } - - /** - * To better balance the admin tree, we want to group all the short top branches together. - * - * This means < 8 nodes and no subtrees. - * - * @return bool - */ - public function is_short_branch() { - $limit = 8; - if ($this->children->count() >= $limit) { - return false; - } - foreach ($this->children as $child) { - if ($child->has_children()) { - return false; - } - } - return true; - } - - /** - * Finds the active node. - * - * Searches this nodes children plus all of the children for the active node - * and returns it if found. - * - * Recursive. - * - * @return navigation_node|false - */ - public function find_active_node() { - if ($this->isactive) { - return $this; - } else { - foreach ($this->children as &$child) { - $outcome = $child->find_active_node(); - if ($outcome !== false) { - return $outcome; - } - } - } - return false; - } - - /** - * Searches all children for the best matching active node - * @param int $strength The url match to be made. - * @return navigation_node|false - */ - public function search_for_active_node($strength = URL_MATCH_BASE) { - if ($this->check_if_active($strength)) { - return $this; - } else { - foreach ($this->children as &$child) { - $outcome = $child->search_for_active_node($strength); - if ($outcome !== false) { - return $outcome; - } - } - } - return false; - } - - /** - * Gets the content for this node. - * - * @param bool $shorttext If true shorttext is used rather than the normal text - * @return string - */ - public function get_content($shorttext=false) { - $navcontext = \context_helper::get_navigation_filter_context(null); - $options = !empty($navcontext) ? ['context' => $navcontext] : null; - - if ($shorttext && $this->shorttext!==null) { - return format_string($this->shorttext, null, $options); - } else { - return format_string($this->text, null, $options); - } - } - - /** - * Gets the title to use for this node. - * - * @return string - */ - public function get_title() { - if ($this->forcetitle || $this->action != null){ - return $this->title; - } else { - return ''; - } - } - - /** - * Used to easily determine if this link in the breadcrumbs has a valid action/url. - * - * @return boolean - */ - public function has_action() { - return !empty($this->action); - } - - /** - * Used to easily determine if the action is an internal link. - * - * @return bool - */ - public function has_internal_action(): bool { - global $CFG; - if ($this->has_action()) { - $url = $this->action(); - if ($this->action() instanceof \action_link) { - $url = $this->action()->url; - } - - if (($url->out() === $CFG->wwwroot) || (strpos($url->out(), $CFG->wwwroot.'/') === 0)) { - return true; - } - } - return false; - } - - /** - * Used to easily determine if this link in the breadcrumbs is hidden. - * - * @return boolean - */ - public function is_hidden() { - return $this->hidden; - } - - /** - * Gets the CSS class to add to this node to describe its type - * - * @return string - */ - public function get_css_type() { - if (array_key_exists($this->type, $this->namedtypes)) { - return 'type_'.$this->namedtypes[$this->type]; - } - return 'type_unknown'; - } - - /** - * Finds all nodes that are expandable by AJAX - * - * @param array $expandable An array by reference to populate with expandable nodes. - */ - public function find_expandable(array &$expandable) { - foreach ($this->children as &$child) { - if ($child->display && $child->has_children() && $child->children->count() == 0) { - $child->id = 'expandable_branch_'.$child->type.'_'.clean_param($child->key, PARAM_ALPHANUMEXT); - $this->add_class('canexpand'); - $child->requiresajaxloading = true; - $expandable[] = array('id' => $child->id, 'key' => $child->key, 'type' => $child->type); - } - $child->find_expandable($expandable); - } - } - - /** - * Finds all nodes of a given type (recursive) - * - * @param int $type One of navigation_node::TYPE_* - * @return array - */ - public function find_all_of_type($type) { - $nodes = $this->children->type($type); - foreach ($this->children as &$node) { - $childnodes = $node->find_all_of_type($type); - $nodes = array_merge($nodes, $childnodes); - } - return $nodes; - } - - /** - * Removes this node if it is empty - */ - public function trim_if_empty() { - if ($this->children->count() == 0) { - $this->remove(); - } - } - - /** - * Creates a tab representation of this nodes children that can be used - * with print_tabs to produce the tabs on a page. - * - * call_user_func_array('print_tabs', $node->get_tabs_array()); - * - * @param array $inactive - * @param bool $return - * @return array Array (tabs, selected, inactive, activated, return) - */ - public function get_tabs_array(array $inactive=array(), $return=false) { - $tabs = array(); - $rows = array(); - $selected = null; - $activated = array(); - foreach ($this->children as $node) { - $tabs[] = new tabobject($node->key, $node->action, $node->get_content(), $node->get_title()); - if ($node->contains_active_node()) { - if ($node->children->count() > 0) { - $activated[] = $node->key; - foreach ($node->children as $child) { - if ($child->contains_active_node()) { - $selected = $child->key; - } - $rows[] = new tabobject($child->key, $child->action, $child->get_content(), $child->get_title()); - } - } else { - $selected = $node->key; - } - } - } - return array(array($tabs, $rows), $selected, $inactive, $activated, $return); - } - - /** - * Sets the parent for this node and if this node is active ensures that the tree is properly - * adjusted as well. - * - * @param navigation_node $parent - */ - public function set_parent(navigation_node $parent) { - // Set the parent (thats the easy part) - $this->parent = $parent; - // Check if this node is active (this is checked during construction) - if ($this->isactive) { - // Force all of the parent nodes open so you can see this node - $this->parent->force_open(); - // Make all parents inactive so that its clear where we are. - $this->parent->make_inactive(); - } - } - - /** - * Hides the node and any children it has. - * - * @since Moodle 2.5 - * @param array $typestohide Optional. An array of node types that should be hidden. - * If null all nodes will be hidden. - * If an array is given then nodes will only be hidden if their type mtatches an element in the array. - * e.g. array(navigation_node::TYPE_COURSE) would hide only course nodes. - */ - public function hide(?array $typestohide = null) { - if ($typestohide === null || in_array($this->type, $typestohide)) { - $this->display = false; - if ($this->has_children()) { - foreach ($this->children as $child) { - $child->hide($typestohide); - } - } - } - } - - /** - * Get the action url for this navigation node. - * Called from templates. - * - * @since Moodle 3.2 - */ - public function action() { - if ($this->action instanceof moodle_url) { - return $this->action; - } else if ($this->action instanceof action_link) { - return $this->action->url; - } - return $this->action; - } - - /** - * Return an array consisting of the additional attributes for the action url. - * - * @return array Formatted array to parse in a template - */ - public function actionattributes() { - if ($this->action instanceof action_link) { - return array_map(function($key, $value) { - return [ - 'name' => $key, - 'value' => $value - ]; - }, array_keys($this->action->attributes), $this->action->attributes); - } - - return []; - } - - /** - * Check whether the node's action is of type action_link. - * - * @return bool - */ - public function is_action_link() { - return $this->action instanceof action_link; - } - - /** - * Return an array consisting of the actions for the action link. - * - * @return array Formatted array to parse in a template - */ - public function action_link_actions() { - global $PAGE; - - if (!$this->is_action_link()) { - return []; - } - - $actionid = $this->action->attributes['id']; - $actionsdata = array_map(function($action) use ($PAGE, $actionid) { - $data = $action->export_for_template($PAGE->get_renderer('core')); - $data->id = $actionid; - return $data; - }, !empty($this->action->actions) ? $this->action->actions : []); - - return ['actions' => $actionsdata]; - } - - /** - * Sets whether the node and its children should be added into a "more" menu whenever possible. - * - * @param bool $forceintomoremenu - */ - public function set_force_into_more_menu(bool $forceintomoremenu = false) { - $this->forceintomoremenu = $forceintomoremenu; - foreach ($this->children as $child) { - $child->set_force_into_more_menu($forceintomoremenu); - } - } - - /** - * Sets whether the node and its children should be displayed in the "secondary" navigation when applicable. - * - * @param bool $show - */ - public function set_show_in_secondary_navigation(bool $show = true) { - $this->showinsecondarynavigation = $show; - foreach ($this->children as $child) { - $child->set_show_in_secondary_navigation($show); - } - } - - /** - * Add the menu item to handle locking and unlocking of a conext. - * - * @param \navigation_node $node Node to add - * @param \context $context The context to be locked - */ - protected function add_context_locking_node(\navigation_node $node, \context $context) { - global $CFG; - // Manage context locking. - if (!empty($CFG->contextlocking) && has_capability('moodle/site:managecontextlocks', $context)) { - $parentcontext = $context->get_parent_context(); - if (empty($parentcontext) || !$parentcontext->locked) { - if ($context->locked) { - $lockicon = 'i/unlock'; - $lockstring = get_string('managecontextunlock', 'admin'); - } else { - $lockicon = 'i/lock'; - $lockstring = get_string('managecontextlock', 'admin'); - } - $node->add( - $lockstring, - new moodle_url( - '/admin/lock.php', - [ - 'id' => $context->id, - ] - ), - self::TYPE_SETTING, - null, - 'contextlocking', - new pix_icon($lockicon, '') - ); - } - } - - } - - /** - * Reset all static data. - * - * @throws coding_exception if called outside of a unit test - */ - public static function reset_all_data(): void { - if (!defined('PHPUNIT_TEST') || !PHPUNIT_TEST) { - throw new coding_exception('Resetting all data is not allowed outside of PHPUnit tests.'); - } - - self::$fullmeurl = null; - self::$autofindactive = true; - self::$loadadmintree = false; - } -} - -/** - * Navigation node collection - * - * This class is responsible for managing a collection of navigation nodes. - * It is required because a node's unique identifier is a combination of both its - * key and its type. - * - * Originally an array was used with a string key that was a combination of the two - * however it was decided that a better solution would be to use a class that - * implements the standard IteratorAggregate interface. - * - * @package core - * @category navigation - * @copyright 2010 Sam Hemelryk - * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later - */ -class navigation_node_collection implements IteratorAggregate, Countable { - /** - * A multidimensional array to where the first key is the type and the second - * key is the nodes key. - * @var array - */ - protected $collection = array(); - /** - * An array that contains references to nodes in the same order they were added. - * This is maintained as a progressive array. - * @var array - */ - protected $orderedcollection = array(); - /** - * A reference to the last node that was added to the collection - * @var navigation_node - */ - protected $last = null; - /** - * The total number of items added to this array. - * @var int - */ - protected $count = 0; - - /** - * Label for collection of nodes. - * @var string - */ - protected $collectionlabel = ''; - - /** - * Adds a navigation node to the collection - * - * @param navigation_node $node Node to add - * @param string $beforekey If specified, adds before a node with this key, - * otherwise adds at end - * @return navigation_node Added node - */ - public function add(navigation_node $node, $beforekey=null) { - global $CFG; - $key = $node->key; - $type = $node->type; - - // First check we have a 2nd dimension for this type - if (!array_key_exists($type, $this->orderedcollection)) { - $this->orderedcollection[$type] = array(); - } - // Check for a collision and report if debugging is turned on - if ($CFG->debug && array_key_exists($key, $this->orderedcollection[$type])) { - debugging('Navigation node intersect: Adding a node that already exists '.$key, DEBUG_DEVELOPER); - } - - // Find the key to add before - $newindex = $this->count; - $last = true; - if ($beforekey !== null) { - foreach ($this->collection as $index => $othernode) { - if ($othernode->key === $beforekey) { - $newindex = $index; - $last = false; - break; - } - } - if ($newindex === $this->count) { - debugging('Navigation node add_before: Reference node not found ' . $beforekey . - ', options: ' . implode(' ', $this->get_key_list()), DEBUG_DEVELOPER); - } - } - - // Add the node to the appropriate place in the by-type structure (which - // is not ordered, despite the variable name) - $this->orderedcollection[$type][$key] = $node; - if (!$last) { - // Update existing references in the ordered collection (which is the - // one that isn't called 'ordered') to shuffle them along if required - for ($oldindex = $this->count; $oldindex > $newindex; $oldindex--) { - $this->collection[$oldindex] = $this->collection[$oldindex - 1]; - } - } - // Add a reference to the node to the progressive collection. - $this->collection[$newindex] = $this->orderedcollection[$type][$key]; - // Update the last property to a reference to this new node. - $this->last = $this->orderedcollection[$type][$key]; - - // Reorder the array by index if needed - if (!$last) { - ksort($this->collection); - } - $this->count++; - // Return the reference to the now added node - return $node; - } - - /** - * Return a list of all the keys of all the nodes. - * @return array the keys. - */ - public function get_key_list() { - $keys = array(); - foreach ($this->collection as $node) { - $keys[] = $node->key; - } - return $keys; - } - - /** - * Set a label for this collection. - * - * @param string $label - */ - public function set_collectionlabel($label) { - $this->collectionlabel = $label; - } - - /** - * Return a label for this collection. - * - * @return string - */ - public function get_collectionlabel() { - return $this->collectionlabel; - } - - /** - * Fetches a node from this collection. - * - * @param string|int $key The key of the node we want to find. - * @param int $type One of navigation_node::TYPE_*. - * @return navigation_node|null|false - */ - public function get($key, $type=null) { - if ($type !== null) { - // If the type is known then we can simply check and fetch - if (!empty($this->orderedcollection[$type][$key])) { - return $this->orderedcollection[$type][$key]; - } - } else { - // Because we don't know the type we look in the progressive array - foreach ($this->collection as $node) { - if ($node->key === $key) { - return $node; - } - } - } - return false; - } - - /** - * Searches for a node with matching key and type. - * - * This function searches both the nodes in this collection and all of - * the nodes in each collection belonging to the nodes in this collection. - * - * Recursive. - * - * @param string|int $key The key of the node we want to find. - * @param int $type One of navigation_node::TYPE_*. - * @return navigation_node|false - */ - public function find($key, $type=null) { - if ($type !== null && array_key_exists($type, $this->orderedcollection) && array_key_exists($key, $this->orderedcollection[$type])) { - return $this->orderedcollection[$type][$key]; - } else { - $nodes = $this->getIterator(); - // Search immediate children first - foreach ($nodes as &$node) { - if ($node->key === $key && ($type === null || $type === $node->type)) { - return $node; - } - } - // Now search each childs children - foreach ($nodes as &$node) { - $result = $node->children->find($key, $type); - if ($result !== false) { - return $result; - } - } - } - return false; - } - - /** - * Fetches the last node that was added to this collection - * - * @return navigation_node - */ - public function last() { - return $this->last; - } - - /** - * Fetches all nodes of a given type from this collection - * - * @param string|int $type node type being searched for. - * @return array ordered collection - */ - public function type($type) { - if (!array_key_exists($type, $this->orderedcollection)) { - $this->orderedcollection[$type] = array(); - } - return $this->orderedcollection[$type]; - } - /** - * Removes the node with the given key and type from the collection - * - * @param string|int $key The key of the node we want to find. - * @param int $type - * @return bool - */ - public function remove($key, $type=null) { - $child = $this->get($key, $type); - if ($child !== false) { - foreach ($this->collection as $colkey => $node) { - if ($node->key === $key && (is_null($type) || $node->type == $type)) { - unset($this->collection[$colkey]); - $this->collection = array_values($this->collection); - break; - } - } - unset($this->orderedcollection[$child->type][$child->key]); - $this->count--; - return true; - } - return false; - } - - /** - * Gets the number of nodes in this collection - * - * This option uses an internal count rather than counting the actual options to avoid - * a performance hit through the count function. - * - * @return int - */ - public function count(): int { - return $this->count; - } - /** - * Gets an array iterator for the collection. - * - * This is required by the IteratorAggregator interface and is used by routines - * such as the foreach loop. - * - * @return ArrayIterator - */ - public function getIterator(): Traversable { - return new ArrayIterator($this->collection); - } -} - -/** - * The global navigation class used for... the global navigation - * - * This class is used by PAGE to store the global navigation for the site - * and is then used by the settings nav and navbar to save on processing and DB calls - * - * See - * {@link lib/pagelib.php} {@link moodle_page::initialise_theme_and_output()} - * {@link lib/ajax/getnavbranch.php} Called by ajax - * - * @package core - * @category navigation - * @copyright 2009 Sam Hemelryk - * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later - */ -class global_navigation extends navigation_node { - /** @var moodle_page The Moodle page this navigation object belongs to. */ - protected $page; - /** @var bool switch to let us know if the navigation object is initialised*/ - protected $initialised = false; - /** @var array An array of course information */ - protected $mycourses = array(); - /** @var navigation_node[] An array for containing root navigation nodes */ - protected $rootnodes = array(); - /** @var bool A switch for whether to show empty sections in the navigation */ - protected $showemptysections = true; - /** @var bool A switch for whether courses should be shown within categories on the navigation. */ - protected $showcategories = null; - /** @var null@var bool A switch for whether or not to show categories in the my courses branch. */ - protected $showmycategories = null; - /** @var array An array of stdClasses for users that the navigation is extended for */ - protected $extendforuser = array(); - /** @var navigation_cache */ - protected $cache; - /** @var array An array of course ids that are present in the navigation */ - protected $addedcourses = array(); - /** @var bool */ - protected $allcategoriesloaded = false; - /** @var array An array of category ids that are included in the navigation */ - protected $addedcategories = array(); - /** @var int expansion limit */ - protected $expansionlimit = 0; - /** @var int userid to allow parent to see child's profile page navigation */ - protected $useridtouseforparentchecks = 0; - /** @var cache_session A cache that stores information on expanded courses */ - protected $cacheexpandcourse = null; - - /** Used when loading categories to load all top level categories [parent = 0] **/ - const LOAD_ROOT_CATEGORIES = 0; - /** Used when loading categories to load all categories **/ - const LOAD_ALL_CATEGORIES = -1; - - /** - * Constructs a new global navigation - * - * @param moodle_page $page The page this navigation object belongs to - */ - public function __construct(moodle_page $page) { - global $CFG, $SITE, $USER; - - if (during_initial_install()) { - return; - } - - $homepage = get_home_page(); - if ($homepage == HOMEPAGE_MY) { - // We are using the users my moodle for the root element. - $properties = array( - 'key' => 'myhome', - 'type' => navigation_node::TYPE_SYSTEM, - 'text' => get_string('myhome'), - 'action' => new moodle_url('/my/'), - 'icon' => new pix_icon('i/dashboard', ''), - ); - } else if ($homepage == HOMEPAGE_MYCOURSES) { - // We are using the user's course summary page for the root element. - $properties = array( - 'key' => 'mycourses', - 'type' => navigation_node::TYPE_SYSTEM, - 'text' => get_string('mycourses'), - 'action' => new moodle_url('/my/courses.php'), - 'icon' => new pix_icon('i/course', '') - ); - } else { - // We are using the site home for the root element. - $properties = array( - 'key' => 'home', - 'type' => navigation_node::TYPE_SYSTEM, - 'text' => get_string('home'), - 'action' => new moodle_url('/'), - 'icon' => new pix_icon('i/home', ''), - ); - } - - // Use the parents constructor.... good good reuse - parent::__construct($properties); - $this->showinflatnavigation = true; - - // Initalise and set defaults - $this->page = $page; - $this->forceopen = true; - $this->cache = new navigation_cache(NAVIGATION_CACHE_NAME); - } - - /** - * Mutator to set userid to allow parent to see child's profile - * page navigation. See MDL-25805 for initial issue. Linked to it - * is an issue explaining why this is a REALLY UGLY HACK thats not - * for you to use! - * - * @param int $userid userid of profile page that parent wants to navigate around. - */ - public function set_userid_for_parent_checks($userid) { - $this->useridtouseforparentchecks = $userid; - } - - - /** - * Initialises the navigation object. - * - * This causes the navigation object to look at the current state of the page - * that it is associated with and then load the appropriate content. - * - * This should only occur the first time that the navigation structure is utilised - * which will normally be either when the navbar is called to be displayed or - * when a block makes use of it. - * - * @return bool - */ - public function initialise() { - global $CFG, $SITE, $USER; - // Check if it has already been initialised - if ($this->initialised || during_initial_install()) { - return true; - } - $this->initialised = true; - - // Set up the five base root nodes. These are nodes where we will put our - // content and are as follows: - // site: Navigation for the front page. - // myprofile: User profile information goes here. - // currentcourse: The course being currently viewed. - // mycourses: The users courses get added here. - // courses: Additional courses are added here. - // users: Other users information loaded here. - $this->rootnodes = array(); - $defaulthomepage = get_home_page(); - if ($defaulthomepage == HOMEPAGE_SITE) { - // The home element should be my moodle because the root element is the site - if (isloggedin() && !isguestuser()) { // Makes no sense if you aren't logged in - if (!empty($CFG->enabledashboard)) { - // Only add dashboard to home if it's enabled. - $this->rootnodes['home'] = $this->add(get_string('myhome'), new moodle_url('/my/'), - self::TYPE_SETTING, null, 'myhome', new pix_icon('i/dashboard', '')); - $this->rootnodes['home']->showinflatnavigation = true; - } - } - } else { - // The home element should be the site because the root node is my moodle - $this->rootnodes['home'] = $this->add(get_string('sitehome'), new moodle_url('/'), - self::TYPE_SETTING, null, 'home', new pix_icon('i/home', '')); - $this->rootnodes['home']->showinflatnavigation = true; - if (!empty($CFG->defaulthomepage) && - ($CFG->defaulthomepage == HOMEPAGE_MY || $CFG->defaulthomepage == HOMEPAGE_MYCOURSES)) { - // We need to stop automatic redirection - $this->rootnodes['home']->action->param('redirect', '0'); - } - } - $this->rootnodes['site'] = $this->add_course($SITE); - $this->rootnodes['myprofile'] = $this->add(get_string('profile'), null, self::TYPE_USER, null, 'myprofile'); - $this->rootnodes['currentcourse'] = $this->add(get_string('currentcourse'), null, self::TYPE_ROOTNODE, null, 'currentcourse'); - $this->rootnodes['mycourses'] = $this->add( - get_string('mycourses'), - new moodle_url('/my/courses.php'), - self::TYPE_ROOTNODE, - null, - 'mycourses', - new pix_icon('i/course', '') - ); - // We do not need to show this node in the breadcrumbs if the default homepage is mycourses. - // It will be automatically handled by the breadcrumb generator. - if ($defaulthomepage == HOMEPAGE_MYCOURSES) { - $this->rootnodes['mycourses']->mainnavonly = true; - } - - $this->rootnodes['courses'] = $this->add(get_string('courses'), new moodle_url('/course/index.php'), self::TYPE_ROOTNODE, null, 'courses'); - if (!core_course_category::user_top()) { - $this->rootnodes['courses']->hide(); - } - $this->rootnodes['users'] = $this->add(get_string('users'), null, self::TYPE_ROOTNODE, null, 'users'); - - // We always load the frontpage course to ensure it is available without - // JavaScript enabled. - $this->add_front_page_course_essentials($this->rootnodes['site'], $SITE); - $this->load_course_sections($SITE, $this->rootnodes['site']); - - $course = $this->page->course; - $this->load_courses_enrolled(); - - // $issite gets set to true if the current pages course is the sites frontpage course - $issite = ($this->page->course->id == $SITE->id); - - // Determine if the user is enrolled in any course. - $enrolledinanycourse = enrol_user_sees_own_courses(); - - $this->rootnodes['currentcourse']->mainnavonly = true; - if ($enrolledinanycourse) { - $this->rootnodes['mycourses']->isexpandable = true; - $this->rootnodes['mycourses']->showinflatnavigation = true; - if ($CFG->navshowallcourses) { - // When we show all courses we need to show both the my courses and the regular courses branch. - $this->rootnodes['courses']->isexpandable = true; - } - } else { - $this->rootnodes['courses']->isexpandable = true; - } - $this->rootnodes['mycourses']->forceopen = true; - - $canviewcourseprofile = true; - - // Next load context specific content into the navigation - switch ($this->page->context->contextlevel) { - case CONTEXT_SYSTEM : - // Nothing left to do here I feel. - break; - case CONTEXT_COURSECAT : - // This is essential, we must load categories. - $this->load_all_categories($this->page->context->instanceid, true); - break; - case CONTEXT_BLOCK : - case CONTEXT_COURSE : - if ($issite) { - // Nothing left to do here. - break; - } - - // Load the course associated with the current page into the navigation. - $coursenode = $this->add_course($course, false, self::COURSE_CURRENT); - // If the course wasn't added then don't try going any further. - if (!$coursenode) { - $canviewcourseprofile = false; - break; - } - - // If the user is not enrolled then we only want to show the - // course node and not populate it. - - // Not enrolled, can't view, and hasn't switched roles - if (!can_access_course($course, null, '', true)) { - if ($coursenode->isexpandable === true) { - // Obviously the situation has changed, update the cache and adjust the node. - // This occurs if the user access to a course has been revoked (one way or another) after - // initially logging in for this session. - $this->get_expand_course_cache()->set($course->id, 1); - $coursenode->isexpandable = true; - $coursenode->nodetype = self::NODETYPE_BRANCH; - } - // Very ugly hack - do not force "parents" to enrol into course their child is enrolled in, - // this hack has been propagated from user/view.php to display the navigation node. (MDL-25805) - if (!$this->current_user_is_parent_role()) { - $coursenode->make_active(); - $canviewcourseprofile = false; - break; - } - } else if ($coursenode->isexpandable === false) { - // Obviously the situation has changed, update the cache and adjust the node. - // This occurs if the user has been granted access to a course (one way or another) after initially - // logging in for this session. - $this->get_expand_course_cache()->set($course->id, 1); - $coursenode->isexpandable = true; - $coursenode->nodetype = self::NODETYPE_BRANCH; - } - - // Add the essentials such as reports etc... - $this->add_course_essentials($coursenode, $course); - // Extend course navigation with it's sections/activities - $this->load_course_sections($course, $coursenode); - if (!$coursenode->contains_active_node() && !$coursenode->search_for_active_node()) { - $coursenode->make_active(); - } - - break; - case CONTEXT_MODULE : - if ($issite) { - // If this is the site course then most information will have - // already been loaded. - // However we need to check if there is more content that can - // yet be loaded for the specific module instance. - $activitynode = $this->rootnodes['site']->find($this->page->cm->id, navigation_node::TYPE_ACTIVITY); - if ($activitynode) { - $this->load_activity($this->page->cm, $this->page->course, $activitynode); - } - break; - } - - $course = $this->page->course; - $cm = $this->page->cm; - - // Load the course associated with the page into the navigation - $coursenode = $this->add_course($course, false, self::COURSE_CURRENT); - - // If the course wasn't added then don't try going any further. - if (!$coursenode) { - $canviewcourseprofile = false; - break; - } - - // If the user is not enrolled then we only want to show the - // course node and not populate it. - if (!can_access_course($course, null, '', true)) { - $coursenode->make_active(); - $canviewcourseprofile = false; - break; - } - - $this->add_course_essentials($coursenode, $course); - - // Load the course sections into the page - $this->load_course_sections($course, $coursenode, null, $cm); - $activity = $coursenode->find($cm->id, navigation_node::TYPE_ACTIVITY); - if (!empty($activity)) { - // Finally load the cm specific navigaton information - $this->load_activity($cm, $course, $activity); - // Check if we have an active ndoe - if (!$activity->contains_active_node() && !$activity->search_for_active_node()) { - // And make the activity node active. - $activity->make_active(); - } - } - break; - case CONTEXT_USER : - if ($issite) { - // The users profile information etc is already loaded - // for the front page. - break; - } - $course = $this->page->course; - // Load the course associated with the user into the navigation - $coursenode = $this->add_course($course, false, self::COURSE_CURRENT); - - // If the course wasn't added then don't try going any further. - if (!$coursenode) { - $canviewcourseprofile = false; - break; - } - - // If the user is not enrolled then we only want to show the - // course node and not populate it. - if (!can_access_course($course, null, '', true)) { - $coursenode->make_active(); - $canviewcourseprofile = false; - break; - } - $this->add_course_essentials($coursenode, $course); - $this->load_course_sections($course, $coursenode); - break; - } - - // Load for the current user - $this->load_for_user(); - if ($this->page->context->contextlevel >= CONTEXT_COURSE && $this->page->context->instanceid != $SITE->id && $canviewcourseprofile) { - $this->load_for_user(null, true); - } - // Load each extending user into the navigation. - foreach ($this->extendforuser as $user) { - if ($user->id != $USER->id) { - $this->load_for_user($user); - } - } - - // Give the local plugins a chance to include some navigation if they want. - $this->load_local_plugin_navigation(); - - // Remove any empty root nodes - foreach ($this->rootnodes as $node) { - // Dont remove the home node - /** @var navigation_node $node */ - if (!in_array($node->key, ['home', 'mycourses', 'myhome']) && !$node->has_children() && !$node->isactive) { - $node->remove(); - } - } - - if (!$this->contains_active_node()) { - $this->search_for_active_node(); - } - - // If the user is not logged in modify the navigation structure. - if (!isloggedin()) { - $activities = clone($this->rootnodes['site']->children); - $this->rootnodes['site']->remove(); - $children = clone($this->children); - $this->children = new navigation_node_collection(); - foreach ($activities as $child) { - $this->children->add($child); - } - foreach ($children as $child) { - $this->children->add($child); - } - } - return true; - } - - /** - * This function gives local plugins an opportunity to modify navigation. - */ - protected function load_local_plugin_navigation() { - foreach (get_plugin_list_with_function('local', 'extend_navigation') as $function) { - $function($this); - } - } - - /** - * Returns true if the current user is a parent of the user being currently viewed. - * - * If the current user is not viewing another user, or if the current user does not hold any parent roles over the - * other user being viewed this function returns false. - * In order to set the user for whom we are checking against you must call {@link set_userid_for_parent_checks()} - * - * @since Moodle 2.4 - * @return bool - */ - protected function current_user_is_parent_role() { - global $USER, $DB; - if ($this->useridtouseforparentchecks && $this->useridtouseforparentchecks != $USER->id) { - $usercontext = context_user::instance($this->useridtouseforparentchecks, MUST_EXIST); - if (!has_capability('moodle/user:viewdetails', $usercontext)) { - return false; - } - if ($DB->record_exists('role_assignments', array('userid' => $USER->id, 'contextid' => $usercontext->id))) { - return true; - } - } - return false; - } - - /** - * Returns true if courses should be shown within categories on the navigation. - * - * @param bool $ismycourse Set to true if you are calculating this for a course. - * @return bool - */ - protected function show_categories($ismycourse = false) { - global $CFG, $DB; - if ($ismycourse) { - return $this->show_my_categories(); - } - if ($this->showcategories === null) { - $show = false; - if ($this->page->context->contextlevel == CONTEXT_COURSECAT) { - $show = true; - } else if (!empty($CFG->navshowcategories) && $DB->count_records('course_categories') > 1) { - $show = true; - } - $this->showcategories = $show; - } - return $this->showcategories; - } - - /** - * Returns true if we should show categories in the My Courses branch. - * @return bool - */ - protected function show_my_categories() { - global $CFG; - if ($this->showmycategories === null) { - $this->showmycategories = !empty($CFG->navshowmycoursecategories) && !core_course_category::is_simple_site(); - } - return $this->showmycategories; - } - - /** - * Loads the courses in Moodle into the navigation. - * - * @global moodle_database $DB - * @param string|array $categoryids An array containing categories to load courses - * for, OR null to load courses for all categories. - * @return array An array of navigation_nodes one for each course - */ - protected function load_all_courses($categoryids = null) { - global $CFG, $DB, $SITE; - - // Work out the limit of courses. - $limit = 20; - if (!empty($CFG->navcourselimit)) { - $limit = $CFG->navcourselimit; - } - - $toload = (empty($CFG->navshowallcourses))?self::LOAD_ROOT_CATEGORIES:self::LOAD_ALL_CATEGORIES; - - // If we are going to show all courses AND we are showing categories then - // to save us repeated DB calls load all of the categories now - if ($this->show_categories()) { - $this->load_all_categories($toload); - } - - // Will be the return of our efforts - $coursenodes = array(); - - // Check if we need to show categories. - if ($this->show_categories()) { - // Hmmm we need to show categories... this is going to be painful. - // We now need to fetch up to $limit courses for each category to - // be displayed. - if ($categoryids !== null) { - if (!is_array($categoryids)) { - $categoryids = array($categoryids); - } - list($categorywhere, $categoryparams) = $DB->get_in_or_equal($categoryids, SQL_PARAMS_NAMED, 'cc'); - $categorywhere = 'WHERE cc.id '.$categorywhere; - } else if ($toload == self::LOAD_ROOT_CATEGORIES) { - $categorywhere = 'WHERE cc.depth = 1 OR cc.depth = 2'; - $categoryparams = array(); - } else { - $categorywhere = ''; - $categoryparams = array(); - } - - // First up we are going to get the categories that we are going to - // need so that we can determine how best to load the courses from them. - $sql = "SELECT cc.id, COUNT(c.id) AS coursecount - FROM {course_categories} cc - LEFT JOIN {course} c ON c.category = cc.id - {$categorywhere} - GROUP BY cc.id"; - $categories = $DB->get_recordset_sql($sql, $categoryparams); - $fullfetch = array(); - $partfetch = array(); - foreach ($categories as $category) { - if (!$this->can_add_more_courses_to_category($category->id)) { - continue; - } - if ($category->coursecount > $limit * 5) { - $partfetch[] = $category->id; - } else if ($category->coursecount > 0) { - $fullfetch[] = $category->id; - } - } - $categories->close(); - - if (count($fullfetch)) { - // First up fetch all of the courses in categories where we know that we are going to - // need the majority of courses. - list($categoryids, $categoryparams) = $DB->get_in_or_equal($fullfetch, SQL_PARAMS_NAMED, 'lcategory'); - $ccselect = ', ' . context_helper::get_preload_record_columns_sql('ctx'); - $ccjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)"; - $categoryparams['contextlevel'] = CONTEXT_COURSE; - $sql = "SELECT c.id, c.sortorder, c.visible, c.fullname, c.shortname, c.category $ccselect - FROM {course} c - $ccjoin - WHERE c.category {$categoryids} - ORDER BY c.sortorder ASC"; - $coursesrs = $DB->get_recordset_sql($sql, $categoryparams); - foreach ($coursesrs as $course) { - if ($course->id == $SITE->id) { - // This should not be necessary, frontpage is not in any category. - continue; - } - if (array_key_exists($course->id, $this->addedcourses)) { - // It is probably better to not include the already loaded courses - // directly in SQL because inequalities may confuse query optimisers - // and may interfere with query caching. - continue; - } - if (!$this->can_add_more_courses_to_category($course->category)) { - continue; - } - context_helper::preload_from_record($course); - if (!$course->visible && !is_role_switched($course->id) && !has_capability('moodle/course:viewhiddencourses', context_course::instance($course->id))) { - continue; - } - $coursenodes[$course->id] = $this->add_course($course); - } - $coursesrs->close(); - } - - if (count($partfetch)) { - // Next we will work our way through the categories where we will likely only need a small - // proportion of the courses. - foreach ($partfetch as $categoryid) { - $ccselect = ', ' . context_helper::get_preload_record_columns_sql('ctx'); - $ccjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)"; - $sql = "SELECT c.id, c.sortorder, c.visible, c.fullname, c.shortname, c.category $ccselect - FROM {course} c - $ccjoin - WHERE c.category = :categoryid - ORDER BY c.sortorder ASC"; - $courseparams = array('categoryid' => $categoryid, 'contextlevel' => CONTEXT_COURSE); - $coursesrs = $DB->get_recordset_sql($sql, $courseparams, 0, $limit * 5); - foreach ($coursesrs as $course) { - if ($course->id == $SITE->id) { - // This should not be necessary, frontpage is not in any category. - continue; - } - if (array_key_exists($course->id, $this->addedcourses)) { - // It is probably better to not include the already loaded courses - // directly in SQL because inequalities may confuse query optimisers - // and may interfere with query caching. - // This also helps to respect expected $limit on repeated executions. - continue; - } - if (!$this->can_add_more_courses_to_category($course->category)) { - break; - } - context_helper::preload_from_record($course); - if (!$course->visible && !is_role_switched($course->id) && !has_capability('moodle/course:viewhiddencourses', context_course::instance($course->id))) { - continue; - } - $coursenodes[$course->id] = $this->add_course($course); - } - $coursesrs->close(); - } - } - } else { - // Prepare the SQL to load the courses and their contexts - list($courseids, $courseparams) = $DB->get_in_or_equal(array_keys($this->addedcourses), SQL_PARAMS_NAMED, 'lc', false); - $ccselect = ', ' . context_helper::get_preload_record_columns_sql('ctx'); - $ccjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)"; - $courseparams['contextlevel'] = CONTEXT_COURSE; - $sql = "SELECT c.id, c.sortorder, c.visible, c.fullname, c.shortname, c.category $ccselect - FROM {course} c - $ccjoin - WHERE c.id {$courseids} - ORDER BY c.sortorder ASC"; - $coursesrs = $DB->get_recordset_sql($sql, $courseparams); - foreach ($coursesrs as $course) { - if ($course->id == $SITE->id) { - // frotpage is not wanted here - continue; - } - if ($this->page->course && ($this->page->course->id == $course->id)) { - // Don't include the currentcourse in this nodelist - it's displayed in the Current course node - continue; - } - context_helper::preload_from_record($course); - if (!$course->visible && !is_role_switched($course->id) && !has_capability('moodle/course:viewhiddencourses', context_course::instance($course->id))) { - continue; - } - $coursenodes[$course->id] = $this->add_course($course); - if (count($coursenodes) >= $limit) { - break; - } - } - $coursesrs->close(); - } - - return $coursenodes; - } - - /** - * Returns true if more courses can be added to the provided category. - * - * @param int|navigation_node|stdClass $category - * @return bool - */ - protected function can_add_more_courses_to_category($category) { - global $CFG; - $limit = 20; - if (!empty($CFG->navcourselimit)) { - $limit = (int)$CFG->navcourselimit; - } - if (is_numeric($category)) { - if (!array_key_exists($category, $this->addedcategories)) { - return true; - } - $coursecount = count($this->addedcategories[$category]->children->type(self::TYPE_COURSE)); - } else if ($category instanceof navigation_node) { - if (($category->type != self::TYPE_CATEGORY) || ($category->type != self::TYPE_MY_CATEGORY)) { - return false; - } - $coursecount = count($category->children->type(self::TYPE_COURSE)); - } else if (is_object($category) && property_exists($category,'id')) { - $coursecount = count($this->addedcategories[$category->id]->children->type(self::TYPE_COURSE)); - } - return ($coursecount <= $limit); - } - - /** - * Loads all categories (top level or if an id is specified for that category) - * - * @param int $categoryid The category id to load or null/0 to load all base level categories - * @param bool $showbasecategories If set to true all base level categories will be loaded as well - * as the requested category and any parent categories. - * @return true|void - */ - protected function load_all_categories($categoryid = self::LOAD_ROOT_CATEGORIES, $showbasecategories = false) { - global $CFG, $DB; - - // Check if this category has already been loaded - if ($this->allcategoriesloaded || ($categoryid < 1 && $this->is_category_fully_loaded($categoryid))) { - return true; - } - - $catcontextsql = context_helper::get_preload_record_columns_sql('ctx'); - $sqlselect = "SELECT cc.*, $catcontextsql - FROM {course_categories} cc - JOIN {context} ctx ON cc.id = ctx.instanceid"; - $sqlwhere = "WHERE ctx.contextlevel = ".CONTEXT_COURSECAT; - $sqlorder = "ORDER BY cc.depth ASC, cc.sortorder ASC, cc.id ASC"; - $params = array(); - - $categoriestoload = array(); - if ($categoryid == self::LOAD_ALL_CATEGORIES) { - // We are going to load all categories regardless... prepare to fire - // on the database server! - } else if ($categoryid == self::LOAD_ROOT_CATEGORIES) { // can be 0 - // We are going to load all of the first level categories (categories without parents) - $sqlwhere .= " AND cc.parent = 0"; - } else if (array_key_exists($categoryid, $this->addedcategories)) { - // The category itself has been loaded already so we just need to ensure its subcategories - // have been loaded - $addedcategories = $this->addedcategories; - unset($addedcategories[$categoryid]); - if (count($addedcategories) > 0) { - list($sql, $params) = $DB->get_in_or_equal(array_keys($addedcategories), SQL_PARAMS_NAMED, 'parent', false); - if ($showbasecategories) { - // We need to include categories with parent = 0 as well - $sqlwhere .= " AND (cc.parent = :categoryid OR cc.parent = 0) AND cc.parent {$sql}"; - } else { - // All we need is categories that match the parent - $sqlwhere .= " AND cc.parent = :categoryid AND cc.parent {$sql}"; - } - } - $params['categoryid'] = $categoryid; - } else { - // This category hasn't been loaded yet so we need to fetch it, work out its category path - // and load this category plus all its parents and subcategories - $category = $DB->get_record('course_categories', array('id' => $categoryid), 'path', MUST_EXIST); - $categoriestoload = explode('/', trim($category->path, '/')); - list($select, $params) = $DB->get_in_or_equal($categoriestoload); - // We are going to use select twice so double the params - $params = array_merge($params, $params); - $basecategorysql = ($showbasecategories)?' OR cc.depth = 1':''; - $sqlwhere .= " AND (cc.id {$select} OR cc.parent {$select}{$basecategorysql})"; - } - - $categoriesrs = $DB->get_recordset_sql("$sqlselect $sqlwhere $sqlorder", $params); - $categories = array(); - foreach ($categoriesrs as $category) { - // Preload the context.. we'll need it when adding the category in order - // to format the category name. - context_helper::preload_from_record($category); - if (array_key_exists($category->id, $this->addedcategories)) { - // Do nothing, its already been added. - } else if ($category->parent == '0') { - // This is a root category lets add it immediately - $this->add_category($category, $this->rootnodes['courses']); - } else if (array_key_exists($category->parent, $this->addedcategories)) { - // This categories parent has already been added we can add this immediately - $this->add_category($category, $this->addedcategories[$category->parent]); - } else { - $categories[] = $category; - } - } - $categoriesrs->close(); - - // Now we have an array of categories we need to add them to the navigation. - while (!empty($categories)) { - $category = reset($categories); - if (array_key_exists($category->id, $this->addedcategories)) { - // Do nothing - } else if ($category->parent == '0') { - $this->add_category($category, $this->rootnodes['courses']); - } else if (array_key_exists($category->parent, $this->addedcategories)) { - $this->add_category($category, $this->addedcategories[$category->parent]); - } else { - // This category isn't in the navigation and niether is it's parent (yet). - // We need to go through the category path and add all of its components in order. - $path = explode('/', trim($category->path, '/')); - foreach ($path as $catid) { - if (!array_key_exists($catid, $this->addedcategories)) { - // This category isn't in the navigation yet so add it. - $subcategory = $categories[$catid]; - if ($subcategory->parent == '0') { - // Yay we have a root category - this likely means we will now be able - // to add categories without problems. - $this->add_category($subcategory, $this->rootnodes['courses']); - } else if (array_key_exists($subcategory->parent, $this->addedcategories)) { - // The parent is in the category (as we'd expect) so add it now. - $this->add_category($subcategory, $this->addedcategories[$subcategory->parent]); - // Remove the category from the categories array. - unset($categories[$catid]); - } else { - // We should never ever arrive here - if we have then there is a bigger - // problem at hand. - throw new coding_exception('Category path order is incorrect and/or there are missing categories'); - } - } - } - } - // Remove the category from the categories array now that we know it has been added. - unset($categories[$category->id]); - } - if ($categoryid === self::LOAD_ALL_CATEGORIES) { - $this->allcategoriesloaded = true; - } - // Check if there are any categories to load. - if (count($categoriestoload) > 0) { - $readytoloadcourses = array(); - foreach ($categoriestoload as $category) { - if ($this->can_add_more_courses_to_category($category)) { - $readytoloadcourses[] = $category; - } - } - if (count($readytoloadcourses)) { - $this->load_all_courses($readytoloadcourses); - } - } - - // Look for all categories which have been loaded - if (!empty($this->addedcategories)) { - $categoryids = array(); - foreach ($this->addedcategories as $category) { - if ($this->can_add_more_courses_to_category($category)) { - $categoryids[] = $category->key; - } - } - if ($categoryids) { - list($categoriessql, $params) = $DB->get_in_or_equal($categoryids, SQL_PARAMS_NAMED); - $params['limit'] = (!empty($CFG->navcourselimit))?$CFG->navcourselimit:20; - $sql = "SELECT cc.id, COUNT(c.id) AS coursecount - FROM {course_categories} cc - JOIN {course} c ON c.category = cc.id - WHERE cc.id {$categoriessql} - GROUP BY cc.id - HAVING COUNT(c.id) > :limit"; - $excessivecategories = $DB->get_records_sql($sql, $params); - foreach ($categories as &$category) { - if (array_key_exists($category->key, $excessivecategories) && !$this->can_add_more_courses_to_category($category)) { - $url = new moodle_url('/course/index.php', array('categoryid' => $category->key)); - $category->add(get_string('viewallcourses'), $url, self::TYPE_SETTING); - } - } - } - } - } - - /** - * Adds a structured category to the navigation in the correct order/place - * - * @param stdClass $category category to be added in navigation. - * @param navigation_node $parent parent navigation node - * @param int $nodetype type of node, if category is under MyHome then it's TYPE_MY_CATEGORY - * @return void. - */ - protected function add_category(stdClass $category, navigation_node $parent, $nodetype = self::TYPE_CATEGORY) { - global $CFG; - if (array_key_exists($category->id, $this->addedcategories)) { - return; - } - $canview = core_course_category::can_view_category($category); - $url = $canview ? new moodle_url('/course/index.php', array('categoryid' => $category->id)) : null; - $context = \context_helper::get_navigation_filter_context(context_coursecat::instance($category->id)); - $categoryname = $canview ? format_string($category->name, true, ['context' => $context]) : - get_string('categoryhidden'); - $categorynode = $parent->add($categoryname, $url, $nodetype, $categoryname, $category->id); - if (!$canview) { - // User does not have required capabilities to view category. - $categorynode->display = false; - } else if (!$category->visible) { - // Category is hidden but user has capability to view hidden categories. - $categorynode->hidden = true; - } - $this->addedcategories[$category->id] = $categorynode; - } - - /** - * Loads the given course into the navigation - * - * @param stdClass $course - * @return navigation_node - */ - protected function load_course(stdClass $course) { - global $SITE; - if ($course->id == $SITE->id) { - // This is always loaded during initialisation - return $this->rootnodes['site']; - } else if (array_key_exists($course->id, $this->addedcourses)) { - // The course has already been loaded so return a reference - return $this->addedcourses[$course->id]; - } else { - // Add the course - return $this->add_course($course); - } - } - - /** - * Loads all of the courses section into the navigation. - * - * This function calls method from current course format, see - * core_courseformat\base::extend_course_navigation() - * If course module ($cm) is specified but course format failed to create the node, - * the activity node is created anyway. - * - * By default course formats call the method global_navigation::load_generic_course_sections() - * - * @param stdClass $course Database record for the course - * @param navigation_node $coursenode The course node within the navigation - * @param null|int $sectionnum If specified load the contents of section with this relative number - * @param null|cm_info $cm If specified make sure that activity node is created (either - * in containg section or by calling load_stealth_activity() ) - */ - protected function load_course_sections(stdClass $course, navigation_node $coursenode, $sectionnum = null, $cm = null) { - global $CFG, $SITE; - require_once($CFG->dirroot.'/course/lib.php'); - if (isset($cm->sectionnum)) { - $sectionnum = $cm->sectionnum; - } - if ($sectionnum !== null) { - $this->includesectionnum = $sectionnum; - } - course_get_format($course)->extend_course_navigation($this, $coursenode, $sectionnum, $cm); - if (isset($cm->id)) { - $activity = $coursenode->find($cm->id, self::TYPE_ACTIVITY); - if (empty($activity)) { - $activity = $this->load_stealth_activity($coursenode, get_fast_modinfo($course)); - } - } - } - - /** - * Generates an array of sections and an array of activities for the given course. - * - * This method uses the cache to improve performance and avoid the get_fast_modinfo call - * - * @param stdClass $course - * @return array Array($sections, $activities) - */ - protected function generate_sections_and_activities(stdClass $course) { - global $CFG; - require_once($CFG->dirroot.'/course/lib.php'); - - $modinfo = get_fast_modinfo($course); - $sections = $modinfo->get_section_info_all(); - $format = course_get_format($course); - - // For course formats using 'numsections' trim the sections list - $courseformatoptions = $format->get_format_options(); - if (isset($courseformatoptions['numsections'])) { - $sections = array_slice($sections, 0, $courseformatoptions['numsections']+1, true); - } - - $activities = []; - - foreach ($sections as $key => $section) { - // Clone and unset summary to prevent $SESSION bloat (MDL-31802). - $sections[$key] = clone($section); - unset($sections[$key]->summary); - $sections[$key]->hasactivites = false; - if (!array_key_exists($section->sectionnum, $modinfo->sections)) { - continue; - } - foreach ($section->get_sequence_cm_infos() as $cm) { - $activity = new stdClass; - $activity->id = $cm->id; - $activity->course = $course->id; - $activity->section = $section->sectionnum; - $activity->name = $cm->name; - $activity->icon = $cm->icon; - $activity->iconcomponent = $cm->iconcomponent; - $activity->hidden = (!$cm->visible); - $activity->modname = $cm->modname; - $activity->nodetype = navigation_node::NODETYPE_LEAF; - $activity->onclick = $cm->onclick; - $url = $cm->url; - - // Activities witout url but with delegated section uses the section url. - $activity->delegatedsection = $cm->get_delegated_section_info(); - if (empty($cm->url) && $activity->delegatedsection) { - $url = $format->get_view_url( - $activity->delegatedsection->sectionnum, - ['navigation' => true] - ); - } - - if (!$url) { - $activity->url = null; - $activity->display = false; - } else { - $activity->url = $url->out(); - $activity->display = $cm->is_visible_on_course_page() ? true : false; - if (self::module_extends_navigation($cm->modname)) { - $activity->nodetype = navigation_node::NODETYPE_BRANCH; - } - } - $activities[$cm->id] = $activity; - if ($activity->display) { - $sections[$key]->hasactivites = true; - } - } - } - - return [$sections, $activities]; - } - - /** - * Generically loads the course sections into the course's navigation. - * - * @param stdClass $course - * @param navigation_node $coursenode - * @return array An array of course section nodes - */ - public function load_generic_course_sections(stdClass $course, navigation_node $coursenode) { - global $CFG, $DB, $USER, $SITE; - require_once($CFG->dirroot.'/course/lib.php'); - - list($sections, $activities) = $this->generate_sections_and_activities($course); - - $navigationsections = []; - foreach ($sections as $sectionid => $section) { - if ($course->id == $SITE->id) { - $this->load_section_activities_navigation($coursenode, $section, $activities); - continue; - } - - if ( - !$section->uservisible - || ( - !$this->showemptysections - && !$section->hasactivites - && $this->includesectionnum !== $section->section - ) - ) { - continue; - } - - // Delegated sections are added from the activity node. - if ($section->get_component_instance()) { - continue; - } - - $navigationsections[$sectionid] = $this->load_section_navigation( - parentnode: $coursenode, - section: $section, - activitiesdata: $activities, - ); - } - return $navigationsections; - } - - /** - * Returns true if the section is included in the breadcrumb. - * - * @param section_info $section - * @param moodle_url|null $sectionurl - * @return bool - */ - protected function is_section_in_breadcrumb(section_info $section, ?moodle_url $sectionurl): bool { - // Ajax requests uses includesectionnum as param. - if ($this->includesectionnum !== false && $this->includesectionnum == $section->sectionnum) { - return true; - } - - // If we are in a section page, we need to check for any child section. - $checkchildrenurls = false; - $format = null; - if ($sectionurl && $this->page->url->compare($sectionurl, URL_MATCH_BASE)) { - $checkchildrenurls = true; - $format = course_get_format($section->course); - } - - // Activities can have delegated sections that acts as a child section. - foreach ($section->get_sequence_cm_infos() as $cm) { - $delegatedsection = $cm->get_delegated_section_info(); - if (!$delegatedsection) { - continue; - } - // Check if the child node is requested via Ajax. - if ($this->includesectionnum == $delegatedsection->sectionnum) { - return true; - } - - if ($checkchildrenurls) { - $childurl = $format->get_view_url($delegatedsection, ['navigation' => true]); - if ($childurl && $this->page->url->compare($childurl, URL_MATCH_EXACT)) { - return true; - } - } - } - - return false; - } - - /** - * Loads a section into the navigation structure. - * - * @param navigation_node $parentnode - * @param section_info $section - * @param stdClass[] $activitiesdata Array of objects containing activities data indexed by cmid. - * @return navigation_node the section navigaiton node - */ - public function load_section_navigation($parentnode, $section, $activitiesdata): navigation_node { - $format = course_get_format($section->course); - $sectionname = $format->get_section_name($section); - $url = $format->get_view_url($section, ['navigation' => true]); - - $sectionnode = $parentnode->add( - text: $sectionname, - action: $url, - type: navigation_node::TYPE_SECTION, - key: $section->id, - icon: new pix_icon('i/section', ''), - ); - $sectionnode->nodetype = navigation_node::NODETYPE_BRANCH; - $sectionnode->hidden = (!$section->visible || !$section->available); - $sectionnode->add_attribute('data-section-name-for', $section->id); - - // Sections content are usually loaded via ajax but the sections from the requested breadcrumb. - if ($this->is_section_in_breadcrumb($section, $url)) { - $this->load_section_activities_navigation($sectionnode, $section, $activitiesdata); - } - return $sectionnode; - } - - /** - * Loads the activities for a section into the navigation structure. - * - * This method is called from global_navigation::load_section_navigation(), - * It is not intended to be called directly. - * - * @param navigation_node $sectionnode - * @param section_info $section - * @param stdClass[] $activitiesdata Array of objects containing activities data indexed by cmid. - */ - protected function load_section_activities_navigation( - navigation_node $sectionnode, - section_info $section, - array $activitiesdata - ): array { - global $CFG, $SITE; - - $activitynodes = []; - if (empty($activitiesdata)) { - return $activitynodes; - } - - foreach ($section->get_sequence_cm_infos() as $cm) { - $activitydata = $activitiesdata[$cm->id]; - - // If activity is a delegated section, load a section node instead of the activity one. - if ($activitydata->delegatedsection) { - $activitynodes[$activitydata->id] = $this->load_section_navigation( - parentnode: $sectionnode, - section: $activitydata->delegatedsection, - activitiesdata: $activitiesdata, - ); - continue; - } - - $activitynodes[$activitydata->id] = $this->load_activity_navigation($sectionnode, $activitydata); - } - - return $activitynodes; - } - - /** - * Loads an activity into the navigation structure. - * - * This method is called from global_navigation::load_section_activities_navigation(), - * It is not intended to be called directly. - * - * @param navigation_node $sectionnode - * @param stdClass $activitydata The acitivy navigation data generated from generate_sections_and_activities - * @return navigation_node - */ - protected function load_activity_navigation( - navigation_node $sectionnode, - stdClass $activitydata, - ): navigation_node { - global $SITE, $CFG; - - $showactivities = ($activitydata->course != $SITE->id || !empty($CFG->navshowfrontpagemods)); - - $icon = new pix_icon( - $activitydata->icon ?: 'monologo', - get_string('modulename', $activitydata->modname), - $activitydata->icon ? $activitydata->iconcomponent : $activitydata->modname, - ); - - // Prepare the default name and url for the node. - $displaycontext = \context_helper::get_navigation_filter_context(context_module::instance($activitydata->id)); - $activityname = format_string($activitydata->name, true, ['context' => $displaycontext]); - - $activitynode = $sectionnode->add( - text: $activityname, - action: $this->get_activity_action($activitydata, $activityname), - type: navigation_node::TYPE_ACTIVITY, - key: $activitydata->id, - icon: $icon, - ); - $activitynode->title(get_string('modulename', $activitydata->modname)); - $activitynode->hidden = $activitydata->hidden; - $activitynode->display = $showactivities && $activitydata->display; - $activitynode->nodetype = $activitydata->nodetype; - - return $activitynode; - } - - /** - * Returns the action for the activity. - * - * @param stdClass $activitydata The acitivy navigation data generated from generate_sections_and_activities - * @param string $activityname - * @return moodle_url|action_link - */ - protected function get_activity_action(stdClass $activitydata, string $activityname): moodle_url|action_link { - // A static counter for JS function naming. - static $legacyonclickcounter = 0; - - $action = new moodle_url($activitydata->url); - - // Check if the onclick property is set (puke!). - if (!empty($activitydata->onclick)) { - // Increment the counter so that we have a unique number. - $legacyonclickcounter++; - // Generate the function name we will use. - $functionname = 'legacy_activity_onclick_handler_' . $legacyonclickcounter; - $propogrationhandler = ''; - // Check if we need to cancel propogation. Remember inline onclick - // events would return false if they wanted to prevent propogation and the - // default action. - if (strpos($activitydata->onclick, 'return false')) { - $propogrationhandler = 'e.halt();'; - } - // Decode the onclick - it has already been encoded for display (puke). - $onclick = htmlspecialchars_decode($activitydata->onclick, ENT_QUOTES); - // Build the JS function the click event will call. - $jscode = "function {$functionname}(e) { $propogrationhandler $onclick }"; - $this->page->requires->js_amd_inline($jscode); - // Override the default url with the new action link. - $action = new action_link($action, $activityname, new component_action('click', $functionname)); - } - return $action; - } - - /** - * Loads all of the activities for a section into the navigation structure. - * - * @param navigation_node $sectionnode - * @param int $sectionnumber - * @param array $activities An array of activites as returned by {@link global_navigation::generate_sections_and_activities()} - * @param stdClass $course The course object the section and activities relate to. - * @return array Array of activity nodes - */ - #[\core\attribute\deprecated( - replacement: 'load_section_activities_navigation', - since: '4.5', - mdl: 'MDL-82845', - )] - protected function load_section_activities(navigation_node $sectionnode, $sectionnumber, array $activities, $course = null) { - \core\deprecation::emit_deprecation([self::class, __FUNCTION__]); - if (!is_object($course)) { - $activity = reset($activities); - $courseid = $activity->course; - } else { - $courseid = $course->id; - } - $sectionifo = get_fast_modinfo($courseid)->get_section_info($sectionnumber); - return $this->load_section_activities_navigation($sectionnode, $sectionifo, $activities); - } - /** - * Loads a stealth module from unavailable section - * @param navigation_node $coursenode - * @param stdClass|course_modinfo $modinfo - * @return navigation_node or null if not accessible - */ - protected function load_stealth_activity(navigation_node $coursenode, $modinfo) { - if (empty($modinfo->cms[$this->page->cm->id])) { - return null; - } - $cm = $modinfo->cms[$this->page->cm->id]; - if ($cm->icon) { - $icon = new pix_icon($cm->icon, get_string('modulename', $cm->modname), $cm->iconcomponent); - } else { - $icon = new pix_icon('monologo', get_string('modulename', $cm->modname), $cm->modname); - } - $url = $cm->url; - $activitynode = $coursenode->add(format_string($cm->name), $url, navigation_node::TYPE_ACTIVITY, null, $cm->id, $icon); - $activitynode->title(get_string('modulename', $cm->modname)); - $activitynode->hidden = (!$cm->visible); - if (!$cm->is_visible_on_course_page()) { - // Do not show any error here, let the page handle exception that activity is not visible for the current user. - // Also there may be no exception at all in case when teacher is logged in as student. - $activitynode->display = false; - } else if (!$url) { - // Don't show activities that don't have links! - $activitynode->display = false; - } else if (self::module_extends_navigation($cm->modname)) { - $activitynode->nodetype = navigation_node::NODETYPE_BRANCH; - } - return $activitynode; - } - /** - * Loads the navigation structure for the given activity into the activities node. - * - * This method utilises a callback within the modules lib.php file to load the - * content specific to activity given. - * - * The callback is a method: {modulename}_extend_navigation() - * Examples: - * * {@link forum_extend_navigation()} - * * {@link workshop_extend_navigation()} - * - * @param cm_info|stdClass $cm - * @param stdClass $course - * @param navigation_node $activity - * @return bool - */ - protected function load_activity($cm, stdClass $course, navigation_node $activity) { - global $CFG, $DB; - - // make sure we have a $cm from get_fast_modinfo as this contains activity access details - if (!($cm instanceof cm_info)) { - $modinfo = get_fast_modinfo($course); - $cm = $modinfo->get_cm($cm->id); - } - $activity->nodetype = navigation_node::NODETYPE_LEAF; - $activity->make_active(); - $file = $CFG->dirroot.'/mod/'.$cm->modname.'/lib.php'; - $function = $cm->modname.'_extend_navigation'; - - if (file_exists($file)) { - require_once($file); - if (function_exists($function)) { - $activtyrecord = $DB->get_record($cm->modname, array('id' => $cm->instance), '*', MUST_EXIST); - $function($activity, $course, $activtyrecord, $cm); - } - } - - // Allow the active advanced grading method plugin to append module navigation - $featuresfunc = $cm->modname.'_supports'; - if (function_exists($featuresfunc) && $featuresfunc(FEATURE_ADVANCED_GRADING)) { - require_once($CFG->dirroot.'/grade/grading/lib.php'); - $gradingman = get_grading_manager($cm->context, 'mod_'.$cm->modname); - $gradingman->extend_navigation($this, $activity); - } - - return $activity->has_children(); - } - /** - * Loads user specific information into the navigation in the appropriate place. - * - * If no user is provided the current user is assumed. - * - * @param stdClass $user - * @param bool $forceforcontext probably force something to be loaded somewhere (ask SamH if not sure what this means) - * @return bool - */ - protected function load_for_user($user=null, $forceforcontext=false) { - global $DB, $CFG, $USER, $SITE; - - require_once($CFG->dirroot . '/course/lib.php'); - - if ($user === null) { - // We can't require login here but if the user isn't logged in we don't - // want to show anything - if (!isloggedin() || isguestuser()) { - return false; - } - $user = $USER; - } else if (!is_object($user)) { - // If the user is not an object then get them from the database - $select = context_helper::get_preload_record_columns_sql('ctx'); - $sql = "SELECT u.*, $select - FROM {user} u - JOIN {context} ctx ON u.id = ctx.instanceid - WHERE u.id = :userid AND - ctx.contextlevel = :contextlevel"; - $user = $DB->get_record_sql($sql, array('userid' => (int)$user, 'contextlevel' => CONTEXT_USER), MUST_EXIST); - context_helper::preload_from_record($user); - } - - $iscurrentuser = ($user->id == $USER->id); - - $usercontext = context_user::instance($user->id); - - // Get the course set against the page, by default this will be the site - $course = $this->page->course; - $baseargs = array('id'=>$user->id); - if ($course->id != $SITE->id && (!$iscurrentuser || $forceforcontext)) { - $coursenode = $this->add_course($course, false, self::COURSE_CURRENT); - $baseargs['course'] = $course->id; - $coursecontext = context_course::instance($course->id); - $issitecourse = false; - } else { - // Load all categories and get the context for the system - $coursecontext = context_system::instance(); - $issitecourse = true; - } - - // Create a node to add user information under. - $usersnode = null; - if (!$issitecourse) { - // Not the current user so add it to the participants node for the current course. - $usersnode = $coursenode->get('participants', navigation_node::TYPE_CONTAINER); - $userviewurl = new moodle_url('/user/view.php', $baseargs); - } else if ($USER->id != $user->id) { - // This is the site so add a users node to the root branch. - $usersnode = $this->rootnodes['users']; - if (course_can_view_participants($coursecontext)) { - $usersnode->action = new moodle_url('/user/index.php', array('id' => $course->id)); - } - $userviewurl = new moodle_url('/user/profile.php', $baseargs); - } - if (!$usersnode) { - // We should NEVER get here, if the course hasn't been populated - // with a participants node then the navigaiton either wasn't generated - // for it (you are missing a require_login or set_context call) or - // you don't have access.... in the interests of no leaking informatin - // we simply quit... - return false; - } - // Add a branch for the current user. - // Only reveal user details if $user is the current user, or a user to which the current user has access. - $viewprofile = true; - if (!$iscurrentuser) { - require_once($CFG->dirroot . '/user/lib.php'); - if ($this->page->context->contextlevel == CONTEXT_USER && !has_capability('moodle/user:viewdetails', $usercontext) ) { - $viewprofile = false; - } else if ($this->page->context->contextlevel != CONTEXT_USER && !user_can_view_profile($user, $course, $usercontext)) { - $viewprofile = false; - } - if (!$viewprofile) { - $viewprofile = user_can_view_profile($user, null, $usercontext); - } - } - - // Now, conditionally add the user node. - if ($viewprofile) { - $canseefullname = has_capability('moodle/site:viewfullnames', $coursecontext); - $usernode = $usersnode->add(fullname($user, $canseefullname), $userviewurl, self::TYPE_USER, null, 'user' . $user->id); - } else { - $usernode = $usersnode->add(get_string('user')); - } - - if ($this->page->context->contextlevel == CONTEXT_USER && $user->id == $this->page->context->instanceid) { - $usernode->make_active(); - } - - // Add user information to the participants or user node. - if ($issitecourse) { - - // If the user is the current user or has permission to view the details of the requested - // user than add a view profile link. - if ($iscurrentuser || has_capability('moodle/user:viewdetails', $coursecontext) || - has_capability('moodle/user:viewdetails', $usercontext)) { - if ($issitecourse || ($iscurrentuser && !$forceforcontext)) { - $usernode->add(get_string('viewprofile'), new moodle_url('/user/profile.php', $baseargs)); - } else { - $usernode->add(get_string('viewprofile'), new moodle_url('/user/view.php', $baseargs)); - } - } - - // Add blog nodes. - if (!empty($CFG->enableblogs)) { - if (!$this->cache->cached('userblogoptions'.$user->id)) { - require_once($CFG->dirroot.'/blog/lib.php'); - // Get all options for the user. - $options = blog_get_options_for_user($user); - $this->cache->set('userblogoptions'.$user->id, $options); - } else { - $options = $this->cache->{'userblogoptions'.$user->id}; - } - - if (count($options) > 0) { - $blogs = $usernode->add(get_string('blogs', 'blog'), null, navigation_node::TYPE_CONTAINER); - foreach ($options as $type => $option) { - if ($type == "rss") { - $blogs->add($option['string'], $option['link'], settings_navigation::TYPE_SETTING, null, null, - new pix_icon('i/rss', '')); - } else { - $blogs->add($option['string'], $option['link']); - } - } - } - } - - // Add the messages link. - // It is context based so can appear in the user's profile and in course participants information. - if (!empty($CFG->messaging)) { - $messageargs = array('user1' => $USER->id); - if ($USER->id != $user->id) { - $messageargs['user2'] = $user->id; - } - $url = new moodle_url('/message/index.php', $messageargs); - $usernode->add(get_string('messages', 'message'), $url, self::TYPE_SETTING, null, 'messages'); - } - - // Add the "My private files" link. - // This link doesn't have a unique display for course context so only display it under the user's profile. - if ($issitecourse && $iscurrentuser && has_capability('moodle/user:manageownfiles', $usercontext)) { - $url = new moodle_url('/user/files.php'); - $usernode->add(get_string('privatefiles'), $url, self::TYPE_SETTING, null, 'privatefiles'); - } - - // Add a node to view the users notes if permitted. - if (!empty($CFG->enablenotes) && - has_any_capability(array('moodle/notes:manage', 'moodle/notes:view'), $coursecontext)) { - $url = new moodle_url('/notes/index.php', array('user' => $user->id)); - if ($coursecontext->instanceid != SITEID) { - $url->param('course', $coursecontext->instanceid); - } - $usernode->add(get_string('notes', 'notes'), $url); - } - - // Show the grades node. - if (($issitecourse && $iscurrentuser) || has_capability('moodle/user:viewdetails', $usercontext)) { - require_once($CFG->dirroot . '/user/lib.php'); - // Set the grades node to link to the "Grades" page. - if ($course->id == SITEID) { - $url = user_mygrades_url($user->id, $course->id); - } else { // Otherwise we are in a course and should redirect to the user grade report (Activity report version). - $url = new moodle_url('/course/user.php', array('mode' => 'grade', 'id' => $course->id, 'user' => $user->id)); - } - if ($USER->id != $user->id) { - $usernode->add(get_string('grades', 'grades'), $url, self::TYPE_SETTING, null, 'usergrades'); - } else { - $usernode->add(get_string('grades', 'grades'), $url); - } - } - - // If the user is the current user add the repositories for the current user. - $hiddenfields = array_flip(explode(',', $CFG->hiddenuserfields)); - if (!$iscurrentuser && - $course->id == $SITE->id && - has_capability('moodle/user:viewdetails', $usercontext) && - (!in_array('mycourses', $hiddenfields) || has_capability('moodle/user:viewhiddendetails', $coursecontext))) { - - // Add view grade report is permitted. - $reports = core_component::get_plugin_list('gradereport'); - arsort($reports); // User is last, we want to test it first. - - $userscourses = enrol_get_users_courses($user->id, false, '*'); - $userscoursesnode = $usernode->add(get_string('courses')); - - $count = 0; - foreach ($userscourses as $usercourse) { - if ($count === (int)$CFG->navcourselimit) { - $url = new moodle_url('/user/profile.php', array('id' => $user->id, 'showallcourses' => 1)); - $userscoursesnode->add(get_string('showallcourses'), $url); - break; - } - $count++; - $usercoursecontext = context_course::instance($usercourse->id); - $usercourseshortname = format_string($usercourse->shortname, true, array('context' => $usercoursecontext)); - $usercoursenode = $userscoursesnode->add($usercourseshortname, new moodle_url('/user/view.php', - array('id' => $user->id, 'course' => $usercourse->id)), self::TYPE_CONTAINER); - - $gradeavailable = has_capability('moodle/grade:view', $usercoursecontext); - if (!$gradeavailable && !empty($usercourse->showgrades) && is_array($reports) && !empty($reports)) { - foreach ($reports as $plugin => $plugindir) { - if (has_capability('gradereport/'.$plugin.':view', $usercoursecontext)) { - // Stop when the first visible plugin is found. - $gradeavailable = true; - break; - } - } - } - - if ($gradeavailable) { - $url = new moodle_url('/grade/report/index.php', array('id' => $usercourse->id)); - $usercoursenode->add(get_string('grades'), $url, self::TYPE_SETTING, null, null, - new pix_icon('i/grades', '')); - } - - // Add a node to view the users notes if permitted. - if (!empty($CFG->enablenotes) && - has_any_capability(array('moodle/notes:manage', 'moodle/notes:view'), $usercoursecontext)) { - $url = new moodle_url('/notes/index.php', array('user' => $user->id, 'course' => $usercourse->id)); - $usercoursenode->add(get_string('notes', 'notes'), $url, self::TYPE_SETTING); - } - - if (can_access_course($usercourse, $user->id, '', true)) { - $usercoursenode->add(get_string('entercourse'), new moodle_url('/course/view.php', - array('id' => $usercourse->id)), self::TYPE_SETTING, null, null, new pix_icon('i/course', '')); - } - - $reporttab = $usercoursenode->add(get_string('activityreports')); - - $reportfunctions = get_plugin_list_with_function('report', 'extend_navigation_user', 'lib.php'); - foreach ($reportfunctions as $reportfunction) { - $reportfunction($reporttab, $user, $usercourse); - } - - $reporttab->trim_if_empty(); - } - } - - // Let plugins hook into user navigation. - $pluginsfunction = get_plugins_with_function('extend_navigation_user', 'lib.php'); - foreach ($pluginsfunction as $plugintype => $plugins) { - if ($plugintype != 'report') { - foreach ($plugins as $pluginfunction) { - $pluginfunction($usernode, $user, $usercontext, $course, $coursecontext); - } - } - } - } - return true; - } - - /** - * This method simply checks to see if a given module can extend the navigation. - * - * @todo (MDL-25290) A shared caching solution should be used to save details on what extends navigation. - * - * @param string $modname - * @return bool - */ - public static function module_extends_navigation($modname) { - global $CFG; - static $extendingmodules = array(); - if (!array_key_exists($modname, $extendingmodules)) { - $extendingmodules[$modname] = false; - $file = $CFG->dirroot.'/mod/'.$modname.'/lib.php'; - if (file_exists($file)) { - $function = $modname.'_extend_navigation'; - require_once($file); - $extendingmodules[$modname] = (function_exists($function)); - } - } - return $extendingmodules[$modname]; - } - /** - * Extends the navigation for the given user. - * - * @param stdClass $user A user from the database - */ - public function extend_for_user($user) { - $this->extendforuser[] = $user; - } - - /** - * Returns all of the users the navigation is being extended for - * - * @return array An array of extending users. - */ - public function get_extending_users() { - return $this->extendforuser; - } - /** - * Adds the given course to the navigation structure. - * - * @param stdClass $course - * @param bool $forcegeneric - * @param bool $ismycourse - * @return navigation_node - */ - public function add_course(stdClass $course, $forcegeneric = false, $coursetype = self::COURSE_OTHER) { - global $CFG, $SITE; - - // We found the course... we can return it now :) - if (!$forcegeneric && array_key_exists($course->id, $this->addedcourses)) { - return $this->addedcourses[$course->id]; - } - - $coursecontext = context_course::instance($course->id); - - if ($coursetype != self::COURSE_MY && $coursetype != self::COURSE_CURRENT && $course->id != $SITE->id) { - if (is_role_switched($course->id)) { - // user has to be able to access course in order to switch, let's skip the visibility test here - } else if (!core_course_category::can_view_course_info($course)) { - return false; - } - } - - $issite = ($course->id == $SITE->id); - $displaycontext = \context_helper::get_navigation_filter_context($coursecontext); - $shortname = format_string($course->shortname, true, ['context' => $displaycontext]); - $fullname = format_string($course->fullname, true, ['context' => $displaycontext]); - // This is the name that will be shown for the course. - $coursename = empty($CFG->navshowfullcoursenames) ? $shortname : $fullname; - - if ($coursetype == self::COURSE_CURRENT) { - if ($coursenode = $this->rootnodes['mycourses']->find($course->id, self::TYPE_COURSE)) { - return $coursenode; - } else { - $coursetype = self::COURSE_OTHER; - } - } - - // Can the user expand the course to see its content. - $canexpandcourse = true; - if ($issite) { - $parent = $this; - $url = null; - if (empty($CFG->usesitenameforsitepages)) { - $coursename = get_string('sitepages'); - } - } else if ($coursetype == self::COURSE_CURRENT) { - $parent = $this->rootnodes['currentcourse']; - $url = new moodle_url('/course/view.php', array('id'=>$course->id)); - $canexpandcourse = $this->can_expand_course($course); - } else if ($coursetype == self::COURSE_MY && !$forcegeneric) { - if (!empty($CFG->navshowmycoursecategories) && ($parent = $this->rootnodes['mycourses']->find($course->category, self::TYPE_MY_CATEGORY))) { - // Nothing to do here the above statement set $parent to the category within mycourses. - } else { - $parent = $this->rootnodes['mycourses']; - } - $url = new moodle_url('/course/view.php', array('id'=>$course->id)); - } else { - $parent = $this->rootnodes['courses']; - $url = new moodle_url('/course/view.php', array('id'=>$course->id)); - // They can only expand the course if they can access it. - $canexpandcourse = $this->can_expand_course($course); - if (!empty($course->category) && $this->show_categories($coursetype == self::COURSE_MY)) { - if (!$this->is_category_fully_loaded($course->category)) { - // We need to load the category structure for this course - $this->load_all_categories($course->category, false); - } - if (array_key_exists($course->category, $this->addedcategories)) { - $parent = $this->addedcategories[$course->category]; - // This could lead to the course being created so we should check whether it is the case again - if (!$forcegeneric && array_key_exists($course->id, $this->addedcourses)) { - return $this->addedcourses[$course->id]; - } - } - } - } - - $coursenode = $parent->add($coursename, $url, self::TYPE_COURSE, $shortname, $course->id, new pix_icon('i/course', '')); - $coursenode->showinflatnavigation = $coursetype == self::COURSE_MY; - - $coursenode->hidden = (!$course->visible); - $coursenode->title(format_string($course->fullname, true, ['context' => $displaycontext, 'escape' => false])); - if ($canexpandcourse) { - // This course can be expanded by the user, make it a branch to make the system aware that its expandable by ajax. - $coursenode->nodetype = self::NODETYPE_BRANCH; - $coursenode->isexpandable = true; - } else { - $coursenode->nodetype = self::NODETYPE_LEAF; - $coursenode->isexpandable = false; - } - if (!$forcegeneric) { - $this->addedcourses[$course->id] = $coursenode; - } - - return $coursenode; - } - - /** - * Returns a cache instance to use for the expand course cache. - * @return cache_session - */ - protected function get_expand_course_cache() { - if ($this->cacheexpandcourse === null) { - $this->cacheexpandcourse = cache::make('core', 'navigation_expandcourse'); - } - return $this->cacheexpandcourse; - } - - /** - * Checks if a user can expand a course in the navigation. - * - * We use a cache here because in order to be accurate we need to call can_access_course which is a costly function. - * Because this functionality is basic + non-essential and because we lack good event triggering this cache - * permits stale data. - * In the situation the user is granted access to a course after we've initialised this session cache the cache - * will be stale. - * It is brought up to date in only one of two ways. - * 1. The user logs out and in again. - * 2. The user browses to the course they've just being given access to. - * - * Really all this controls is whether the node is shown as expandable or not. It is uber un-important. - * - * @param stdClass $course - * @return bool - */ - protected function can_expand_course($course) { - $cache = $this->get_expand_course_cache(); - $canexpand = $cache->get($course->id); - if ($canexpand === false) { - $canexpand = isloggedin() && can_access_course($course, null, '', true); - $canexpand = (int)$canexpand; - $cache->set($course->id, $canexpand); - } - return ($canexpand === 1); - } - - /** - * Returns true if the category has already been loaded as have any child categories - * - * @param int $categoryid - * @return bool - */ - protected function is_category_fully_loaded($categoryid) { - return (array_key_exists($categoryid, $this->addedcategories) && ($this->allcategoriesloaded || $this->addedcategories[$categoryid]->children->count() > 0)); - } - - /** - * Adds essential course nodes to the navigation for the given course. - * - * This method adds nodes such as reports, blogs and participants - * - * @param navigation_node $coursenode - * @param stdClass $course - * @return bool returns true on successful addition of a node. - */ - public function add_course_essentials($coursenode, stdClass $course) { - global $CFG, $SITE; - require_once($CFG->dirroot . '/course/lib.php'); - - if ($course->id == $SITE->id) { - return $this->add_front_page_course_essentials($coursenode, $course); - } - - if ($coursenode == false || !($coursenode instanceof navigation_node) || $coursenode->get('participants', navigation_node::TYPE_CONTAINER)) { - return true; - } - - $navoptions = course_get_user_navigation_options($this->page->context, $course); - - //Participants - if ($navoptions->participants) { - $participants = $coursenode->add(get_string('participants'), new moodle_url('/user/index.php?id='.$course->id), - self::TYPE_CONTAINER, get_string('participants'), 'participants', new pix_icon('i/users', '')); - - if ($navoptions->blogs) { - $blogsurls = new moodle_url('/blog/index.php'); - if ($currentgroup = groups_get_course_group($course, true)) { - $blogsurls->param('groupid', $currentgroup); - } else { - $blogsurls->param('courseid', $course->id); - } - $participants->add(get_string('blogscourse', 'blog'), $blogsurls->out(), self::TYPE_SETTING, null, 'courseblogs'); - } - - if ($navoptions->notes) { - $participants->add(get_string('notes', 'notes'), new moodle_url('/notes/index.php', array('filtertype' => 'course', 'filterselect' => $course->id)), self::TYPE_SETTING, null, 'currentcoursenotes'); - } - } else if (count($this->extendforuser) > 0) { - $coursenode->add(get_string('participants'), null, self::TYPE_CONTAINER, get_string('participants'), 'participants'); - } else if ($siteparticipantsnode = $this->rootnodes['site']->get('participants', self::TYPE_CUSTOM)) { - // The participants node was added for the site, but cannot be viewed inside the course itself, so remove. - $siteparticipantsnode->remove(); - } - - // Badges. - if ($navoptions->badges) { - $url = new moodle_url('/badges/index.php', ['type' => 2, 'id' => $course->id]); - - $coursenode->add(get_string('coursebadges', 'badges'), $url, - navigation_node::TYPE_SETTING, null, 'badgesview', - new pix_icon('i/badge', get_string('coursebadges', 'badges'))); - } - - // Check access to the course and competencies page. - if ($navoptions->competencies) { - // Just a link to course competency. - $title = get_string('competencies', 'core_competency'); - $path = new moodle_url("/admin/tool/lp/coursecompetencies.php", array('courseid' => $course->id)); - $coursenode->add($title, $path, navigation_node::TYPE_SETTING, null, 'competencies', - new pix_icon('i/competencies', '')); - } - if ($navoptions->grades) { - $url = new moodle_url('/grade/report/index.php', array('id'=>$course->id)); - $gradenode = $coursenode->add(get_string('grades'), $url, self::TYPE_SETTING, null, - 'grades', new pix_icon('i/grades', '')); - // If the page type matches the grade part, then make the nav drawer grade node (incl. all sub pages) active. - if ($this->page->context->contextlevel < CONTEXT_MODULE && strpos($this->page->pagetype, 'grade-') === 0) { - $gradenode->make_active(); - } - } - - // Add link for configuring communication. - if ($navoptions->communication) { - $url = new moodle_url('/communication/configure.php', [ - 'contextid' => \core\context\course::instance($course->id)->id, - 'instanceid' => $course->id, - 'instancetype' => 'coursecommunication', - 'component' => 'core_course', - ]); - $coursenode->add(get_string('communication', 'communication'), $url, - navigation_node::TYPE_SETTING, null, 'communication'); - } - - if ($navoptions->overview) { - $coursenode->add( - text: get_string('activities'), - action: new moodle_url('/course/overview.php', ['id' => $course->id]), - type: self::TYPE_CONTAINER, - key: 'courseoverview', - icon: new pix_icon('i/info', ''), - ); - } - - return true; - } - /** - * This generates the structure of the course that won't be generated when - * the modules and sections are added. - * - * Things such as the reports branch, the participants branch, blogs... get - * added to the course node by this method. - * - * @param navigation_node $coursenode - * @param stdClass $course - * @return bool True for successfull generation - */ - public function add_front_page_course_essentials(navigation_node $coursenode, stdClass $course) { - global $CFG, $USER, $COURSE, $SITE; - require_once($CFG->dirroot . '/course/lib.php'); - - if ($coursenode == false || $coursenode->get('frontpageloaded', navigation_node::TYPE_CUSTOM)) { - return true; - } - - $systemcontext = context_system::instance(); - $navoptions = course_get_user_navigation_options($systemcontext, $course); - - // Hidden node that we use to determine if the front page navigation is loaded. - // This required as there are not other guaranteed nodes that may be loaded. - $coursenode->add('frontpageloaded', null, self::TYPE_CUSTOM, null, 'frontpageloaded')->display = false; - - // Add My courses to the site pages within the navigation structure so the block can read it. - $coursenode->add(get_string('mycourses'), new moodle_url('/my/courses.php'), self::TYPE_CUSTOM, null, 'mycourses'); - - // Participants. - if ($navoptions->participants) { - $coursenode->add(get_string('participants'), new moodle_url('/user/index.php?id='.$course->id), - self::TYPE_CUSTOM, get_string('participants'), 'participants'); - } - - // Blogs. - if ($navoptions->blogs) { - $blogsurls = new moodle_url('/blog/index.php'); - $coursenode->add(get_string('blogssite', 'blog'), $blogsurls->out(), self::TYPE_SYSTEM, null, 'siteblog'); - } - - $filterselect = 0; - - // Badges. - if ($navoptions->badges) { - $url = new moodle_url($CFG->wwwroot . '/badges/index.php', ['type' => 1]); - $coursenode->add(get_string('sitebadges', 'badges'), $url, navigation_node::TYPE_CUSTOM); - } - - // Notes. - if ($navoptions->notes) { - $coursenode->add(get_string('notes', 'notes'), new moodle_url('/notes/index.php', - array('filtertype' => 'course', 'filterselect' => $filterselect)), self::TYPE_SETTING, null, 'notes'); - } - - // Tags - if ($navoptions->tags) { - $node = $coursenode->add(get_string('tags', 'tag'), new moodle_url('/tag/search.php'), - self::TYPE_SETTING, null, 'tags'); - } - - // Search. - if ($navoptions->search) { - $node = $coursenode->add(get_string('search', 'search'), new moodle_url('/search/index.php'), - self::TYPE_SETTING, null, 'search'); - } - - if (isloggedin()) { - $usercontext = context_user::instance($USER->id); - if (has_capability('moodle/user:manageownfiles', $usercontext)) { - $url = new moodle_url('/user/files.php'); - $node = $coursenode->add(get_string('privatefiles'), $url, - self::TYPE_SETTING, null, 'privatefiles', new pix_icon('i/privatefiles', '')); - $node->display = false; - $node->showinflatnavigation = true; - $node->mainnavonly = true; - } - } - - if (isloggedin()) { - $context = $this->page->context; - switch ($context->contextlevel) { - case CONTEXT_COURSECAT: - // OK, expected context level. - break; - case CONTEXT_COURSE: - // OK, expected context level if not on frontpage. - if ($COURSE->id != $SITE->id) { - break; - } - default: - // If this context is part of a course (excluding frontpage), use the course context. - // Otherwise, use the system context. - $coursecontext = $context->get_course_context(false); - if ($coursecontext && $coursecontext->instanceid !== $SITE->id) { - $context = $coursecontext; - } else { - $context = $systemcontext; - } - } - - $params = ['contextid' => $context->id]; - if (has_capability('moodle/contentbank:access', $context)) { - $url = new moodle_url('/contentbank/index.php', $params); - $node = $coursenode->add(get_string('contentbank'), $url, - self::TYPE_CUSTOM, null, 'contentbank', new pix_icon('i/contentbank', '')); - $node->showinflatnavigation = true; - } - } - - return true; - } - - /** - * Clears the navigation cache - */ - public function clear_cache() { - $this->cache->clear(); - } - - /** - * Sets an expansion limit for the navigation - * - * The expansion limit is used to prevent the display of content that has a type - * greater than the provided $type. - * - * Can be used to ensure things such as activities or activity content don't get - * shown on the navigation. - * They are still generated in order to ensure the navbar still makes sense. - * - * @param int $type One of navigation_node::TYPE_* - * @return bool true when complete. - */ - public function set_expansion_limit($type) { - global $SITE; - $nodes = $this->find_all_of_type($type); - - // We only want to hide specific types of nodes. - // Only nodes that represent "structure" in the navigation tree should be hidden. - // If we hide all nodes then we risk hiding vital information. - $typestohide = array( - self::TYPE_CATEGORY, - self::TYPE_COURSE, - self::TYPE_SECTION, - self::TYPE_ACTIVITY - ); - - foreach ($nodes as $node) { - // We need to generate the full site node - if ($type == self::TYPE_COURSE && $node->key == $SITE->id) { - continue; - } - foreach ($node->children as $child) { - $child->hide($typestohide); - } - } - return true; - } - /** - * Attempts to get the navigation with the given key from this nodes children. - * - * This function only looks at this nodes children, it does NOT look recursivily. - * If the node can't be found then false is returned. - * - * If you need to search recursivily then use the {@link global_navigation::find()} method. - * - * Note: If you are trying to set the active node {@link navigation_node::override_active_url()} - * may be of more use to you. - * - * @param string|int $key The key of the node you wish to receive. - * @param int $type One of navigation_node::TYPE_* - * @return navigation_node|false - */ - public function get($key, $type = null) { - if (!$this->initialised) { - $this->initialise(); - } - return parent::get($key, $type); - } - - /** - * Searches this nodes children and their children to find a navigation node - * with the matching key and type. - * - * This method is recursive and searches children so until either a node is - * found or there are no more nodes to search. - * - * If you know that the node being searched for is a child of this node - * then use the {@link global_navigation::get()} method instead. - * - * Note: If you are trying to set the active node {@link navigation_node::override_active_url()} - * may be of more use to you. - * - * @param string|int $key The key of the node you wish to receive. - * @param ?int $type One of navigation_node::TYPE_* - * @return navigation_node|false - */ - public function find($key, $type) { - if (!$this->initialised) { - $this->initialise(); - } - if ($type == self::TYPE_ROOTNODE && array_key_exists($key, $this->rootnodes)) { - return $this->rootnodes[$key]; - } - return parent::find($key, $type); - } - - /** - * They've expanded the 'my courses' branch. - */ - protected function load_courses_enrolled() { - global $CFG; - - $limit = (int) $CFG->navcourselimit; - - $courses = enrol_get_my_courses('*'); - $flatnavcourses = []; - - // Go through the courses and see which ones we want to display in the flatnav. - foreach ($courses as $course) { - $classify = course_classify_for_timeline($course); - - if ($classify == COURSE_TIMELINE_INPROGRESS) { - $flatnavcourses[$course->id] = $course; - } - } - - // Get the number of courses that can be displayed in the nav block and in the flatnav. - $numtotalcourses = count($courses); - $numtotalflatnavcourses = count($flatnavcourses); - - // Reduce the size of the arrays to abide by the 'navcourselimit' setting. - $courses = array_slice($courses, 0, $limit, true); - $flatnavcourses = array_slice($flatnavcourses, 0, $limit, true); - - // Get the number of courses we are going to show for each. - $numshowncourses = count($courses); - $numshownflatnavcourses = count($flatnavcourses); - if ($numshowncourses && $this->show_my_categories()) { - // Generate an array containing unique values of all the courses' categories. - $categoryids = array(); - foreach ($courses as $course) { - if (in_array($course->category, $categoryids)) { - continue; - } - $categoryids[] = $course->category; - } - - // Array of category IDs that include the categories of the user's courses and the related course categories. - $fullpathcategoryids = []; - // Get the course categories for the enrolled courses' category IDs. - $mycoursecategories = core_course_category::get_many($categoryids); - // Loop over each of these categories and build the category tree using each category's path. - foreach ($mycoursecategories as $mycoursecat) { - $pathcategoryids = explode('/', $mycoursecat->path); - // First element of the exploded path is empty since paths begin with '/'. - array_shift($pathcategoryids); - // Merge the exploded category IDs into the full list of category IDs that we will fetch. - $fullpathcategoryids = array_merge($fullpathcategoryids, $pathcategoryids); - } - - // Fetch all of the categories related to the user's courses. - $pathcategories = core_course_category::get_many($fullpathcategoryids); - // Loop over each of these categories and build the category tree. - foreach ($pathcategories as $coursecat) { - // No need to process categories that have already been added. - if (isset($this->addedcategories[$coursecat->id])) { - continue; - } - // Skip categories that are not visible. - if (!$coursecat->is_uservisible()) { - continue; - } - - // Get this course category's parent node. - $parent = null; - if ($coursecat->parent && isset($this->addedcategories[$coursecat->parent])) { - $parent = $this->addedcategories[$coursecat->parent]; - } - if (!$parent) { - // If it has no parent, then it should be right under the My courses node. - $parent = $this->rootnodes['mycourses']; - } - - // Build the category object based from the coursecat object. - $mycategory = new stdClass(); - $mycategory->id = $coursecat->id; - $mycategory->name = $coursecat->name; - $mycategory->visible = $coursecat->visible; - - // Add this category to the nav tree. - $this->add_category($mycategory, $parent, self::TYPE_MY_CATEGORY); - } - } - - // Go through each course now and add it to the nav block, and the flatnav if applicable. - foreach ($courses as $course) { - $node = $this->add_course($course, false, self::COURSE_MY); - if ($node) { - $node->showinflatnavigation = false; - // Check if we should also add this to the flat nav as well. - if (isset($flatnavcourses[$course->id])) { - $node->showinflatnavigation = true; - } - } - } - - // Go through each course in the flatnav now. - foreach ($flatnavcourses as $course) { - // Check if we haven't already added it. - if (!isset($courses[$course->id])) { - // Ok, add it to the flatnav only. - $node = $this->add_course($course, false, self::COURSE_MY); - $node->display = false; - $node->showinflatnavigation = true; - } - } - - $showmorelinkinnav = $numtotalcourses > $numshowncourses; - $showmorelinkinflatnav = $numtotalflatnavcourses > $numshownflatnavcourses; - // Show a link to the course page if there are more courses the user is enrolled in. - if ($showmorelinkinnav || $showmorelinkinflatnav) { - // Adding hash to URL so the link is not highlighted in the navigation when clicked. - $url = new moodle_url('/my/courses.php'); - $parent = $this->rootnodes['mycourses']; - $coursenode = $parent->add(get_string('morenavigationlinks'), $url, self::TYPE_CUSTOM, null, self::COURSE_INDEX_PAGE); - - if ($showmorelinkinnav) { - $coursenode->display = true; - } - - if ($showmorelinkinflatnav) { - $coursenode->showinflatnavigation = true; - } - } - } -} - -/** - * The global navigation class used especially for AJAX requests. - * - * The primary methods that are used in the global navigation class have been overriden - * to ensure that only the relevant branch is generated at the root of the tree. - * This can be done because AJAX is only used when the backwards structure for the - * requested branch exists. - * This has been done only because it shortens the amounts of information that is generated - * which of course will speed up the response time.. because no one likes laggy AJAX. - * - * @package core - * @category navigation - * @copyright 2009 Sam Hemelryk - * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later - */ -class global_navigation_for_ajax extends global_navigation { - - /** @var int used for determining what type of navigation_node::TYPE_* is being used */ - protected $branchtype; - - /** @var int the instance id */ - protected $instanceid; - - /** @var array Holds an array of expandable nodes */ - protected $expandable = array(); - - /** - * Constructs the navigation for use in an AJAX request - * - * @param moodle_page $page moodle_page object - * @param int $branchtype - * @param int $id - */ - public function __construct($page, $branchtype, $id) { - $this->page = $page; - $this->cache = new navigation_cache(NAVIGATION_CACHE_NAME); - $this->children = new navigation_node_collection(); - $this->branchtype = $branchtype; - $this->instanceid = $id; - $this->initialise(); - } - /** - * Initialise the navigation given the type and id for the branch to expand. - * - * @return array An array of the expandable nodes - */ - public function initialise() { - global $DB, $SITE; - - if ($this->initialised || during_initial_install()) { - return $this->expandable; - } - $this->initialised = true; - - $this->rootnodes = array(); - $this->rootnodes['site'] = $this->add_course($SITE); - $this->rootnodes['mycourses'] = $this->add( - get_string('mycourses'), - new moodle_url('/my/courses.php'), - self::TYPE_ROOTNODE, - null, - 'mycourses' - ); - $this->rootnodes['courses'] = $this->add(get_string('courses'), null, self::TYPE_ROOTNODE, null, 'courses'); - // The courses branch is always displayed, and is always expandable (although may be empty). - // This mimicks what is done during {@link global_navigation::initialise()}. - $this->rootnodes['courses']->isexpandable = true; - - // Branchtype will be one of navigation_node::TYPE_* - switch ($this->branchtype) { - case 0: - if ($this->instanceid === 'mycourses') { - $this->load_courses_enrolled(); - } else if ($this->instanceid === 'courses') { - $this->load_courses_other(); - } - break; - case self::TYPE_CATEGORY : - $this->load_category($this->instanceid); - break; - case self::TYPE_MY_CATEGORY : - $this->load_category($this->instanceid, self::TYPE_MY_CATEGORY); - break; - case self::TYPE_COURSE : - $course = $DB->get_record('course', array('id' => $this->instanceid), '*', MUST_EXIST); - if (!can_access_course($course, null, '', true)) { - // Thats OK all courses are expandable by default. We don't need to actually expand it we can just - // add the course node and break. This leads to an empty node. - $this->add_course($course); - break; - } - require_course_login($course, true, null, false, true); - $this->page->set_context(context_course::instance($course->id)); - $coursenode = $this->add_course($course, false, self::COURSE_CURRENT); - $this->add_course_essentials($coursenode, $course); - $this->load_course_sections($course, $coursenode); - break; - case self::TYPE_SECTION : - $sql = 'SELECT c.*, cs.section AS sectionnumber - FROM {course} c - LEFT JOIN {course_sections} cs ON cs.course = c.id - WHERE cs.id = ?'; - $course = $DB->get_record_sql($sql, array($this->instanceid), MUST_EXIST); - require_course_login($course, true, null, false, true); - $this->page->set_context(context_course::instance($course->id)); - $coursenode = $this->add_course($course, false, self::COURSE_CURRENT); - $this->add_course_essentials($coursenode, $course); - $this->load_course_sections($course, $coursenode, $course->sectionnumber); - break; - case self::TYPE_ACTIVITY : - $sql = "SELECT c.* - FROM {course} c - JOIN {course_modules} cm ON cm.course = c.id - WHERE cm.id = :cmid"; - $params = array('cmid' => $this->instanceid); - $course = $DB->get_record_sql($sql, $params, MUST_EXIST); - $modinfo = get_fast_modinfo($course); - $cm = $modinfo->get_cm($this->instanceid); - require_course_login($course, true, $cm, false, true); - $this->page->set_context(context_module::instance($cm->id)); - $coursenode = $this->add_course($course, false, self::COURSE_CURRENT); - $this->load_course_sections($course, $coursenode, null, $cm); - $activitynode = $coursenode->find($cm->id, self::TYPE_ACTIVITY); - if ($activitynode) { - $modulenode = $this->load_activity($cm, $course, $activitynode); - } - break; - default: - throw new Exception('Unknown type'); - return $this->expandable; - } - - if ($this->page->context->contextlevel == CONTEXT_COURSE && $this->page->context->instanceid != $SITE->id) { - $this->load_for_user(null, true); - } - - // Give the local plugins a chance to include some navigation if they want. - $this->load_local_plugin_navigation(); - - $this->find_expandable($this->expandable); - return $this->expandable; - } - - /** - * They've expanded the general 'courses' branch. - */ - protected function load_courses_other() { - $this->load_all_courses(); - } - - /** - * Loads a single category into the AJAX navigation. - * - * This function is special in that it doesn't concern itself with the parent of - * the requested category or its siblings. - * This is because with the AJAX navigation we know exactly what is wanted and only need to - * request that. - * - * @global moodle_database $DB - * @param int $categoryid id of category to load in navigation. - * @param int $nodetype type of node, if category is under MyHome then it's TYPE_MY_CATEGORY - * @return void. - */ - protected function load_category($categoryid, $nodetype = self::TYPE_CATEGORY) { - global $CFG, $DB; - - $limit = 20; - if (!empty($CFG->navcourselimit)) { - $limit = (int)$CFG->navcourselimit; - } - - $catcontextsql = context_helper::get_preload_record_columns_sql('ctx'); - $sql = "SELECT cc.*, $catcontextsql - FROM {course_categories} cc - JOIN {context} ctx ON cc.id = ctx.instanceid - WHERE ctx.contextlevel = ".CONTEXT_COURSECAT." AND - (cc.id = :categoryid1 OR cc.parent = :categoryid2) - ORDER BY cc.depth ASC, cc.sortorder ASC, cc.id ASC"; - $params = array('categoryid1' => $categoryid, 'categoryid2' => $categoryid); - $categories = $DB->get_recordset_sql($sql, $params, 0, $limit); - $categorylist = array(); - $subcategories = array(); - $basecategory = null; - foreach ($categories as $category) { - $categorylist[] = $category->id; - context_helper::preload_from_record($category); - if ($category->id == $categoryid) { - $this->add_category($category, $this, $nodetype); - $basecategory = $this->addedcategories[$category->id]; - } else { - $subcategories[$category->id] = $category; - } - } - $categories->close(); - - - // 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. - $coursesubcategories = array(); - $addedsubcategories = 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){ - $coursesubcategories = array_merge($coursesubcategories, explode('/', trim($category->path, "/"))); - } - $categories->close(); - $coursesubcategories = array_unique($coursesubcategories); - - // Only add a subcategory if it is part of the path to user's course and - // wasn't already added. - foreach ($subcategories as $subid => $subcategory) { - if (in_array($subid, $coursesubcategories) && - !in_array($subid, $addedsubcategories)) { - $this->add_category($subcategory, $basecategory, $nodetype); - $addedsubcategories[] = $subid; - } - } - } - - foreach ($courses as $course) { - // Add course if it's in category. - if (in_array($course->category, $categorylist)) { - $this->add_course($course, true, self::COURSE_MY); - } - } - } 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); - } - $courses->close(); - } - } - - /** - * Returns an array of expandable nodes - * @return array - */ - public function get_expandable() { - return $this->expandable; - } -} - -/** - * Navbar class - * - * This class is used to manage the navbar, which is initialised from the navigation - * object held by PAGE - * - * @package core - * @category navigation - * @copyright 2009 Sam Hemelryk - * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later - */ -class navbar extends navigation_node { - /** @var bool A switch for whether the navbar is initialised or not */ - protected $initialised = false; - /** @var mixed keys used to reference the nodes on the navbar */ - protected $keys = array(); - /** @var null|string content of the navbar */ - protected $content = null; - /** @var moodle_page object the moodle page that this navbar belongs to */ - protected $page; - /** @var bool A switch for whether to ignore the active navigation information */ - protected $ignoreactive = false; - /** @var bool A switch to let us know if we are in the middle of an install */ - protected $duringinstall = false; - /** @var bool A switch for whether the navbar has items */ - protected $hasitems = false; - /** @var array An array of navigation nodes for the navbar */ - protected $items; - /** @var array An array of child node objects */ - public $children = array(); - /** @var bool A switch for whether we want to include the root node in the navbar */ - public $includesettingsbase = false; - /** @var breadcrumb_navigation_node[] $prependchildren */ - protected $prependchildren = array(); - - /** - * The almighty constructor - * - * @param moodle_page $page - */ - public function __construct(moodle_page $page) { - global $CFG; - if (during_initial_install()) { - $this->duringinstall = true; - return; - } - $this->page = $page; - $this->text = get_string('home'); - $this->shorttext = get_string('home'); - $this->action = new moodle_url($CFG->wwwroot); - $this->nodetype = self::NODETYPE_BRANCH; - $this->type = self::TYPE_SYSTEM; - } - - /** - * Quick check to see if the navbar will have items in. - * - * @return bool Returns true if the navbar will have items, false otherwise - */ - public function has_items() { - if ($this->duringinstall) { - return false; - } else if ($this->hasitems !== false) { - return true; - } - $outcome = false; - if (count($this->children) > 0 || count($this->prependchildren) > 0) { - // There have been manually added items - there are definitely items. - $outcome = true; - } else if (!$this->ignoreactive) { - // We will need to initialise the navigation structure to check if there are active items. - $this->page->navigation->initialise($this->page); - $outcome = ($this->page->navigation->contains_active_node() || $this->page->settingsnav->contains_active_node()); - } - $this->hasitems = $outcome; - return $outcome; - } - - /** - * Turn on/off ignore active - * - * @param bool $setting - */ - public function ignore_active($setting=true) { - $this->ignoreactive = ($setting); - } - - /** - * Gets a navigation node - * - * @param string|int $key for referencing the navbar nodes - * @param int $type breadcrumb_navigation_node::TYPE_* - * @return breadcrumb_navigation_node|bool - */ - public function get($key, $type = null) { - foreach ($this->children as &$child) { - if ($child->key === $key && ($type == null || $type == $child->type)) { - return $child; - } - } - foreach ($this->prependchildren as &$child) { - if ($child->key === $key && ($type == null || $type == $child->type)) { - return $child; - } - } - return false; - } - /** - * Returns an array of breadcrumb_navigation_nodes that make up the navbar. - * - * @return array - */ - public function get_items() { - global $CFG; - $items = array(); - // Make sure that navigation is initialised - if (!$this->has_items()) { - return $items; - } - if ($this->items !== null) { - return $this->items; - } - - if (count($this->children) > 0) { - // Add the custom children. - $items = array_reverse($this->children); - } - - // Check if navigation contains the active node - if (!$this->ignoreactive) { - // We will need to ensure the navigation has been initialised. - $this->page->navigation->initialise($this->page); - // Now find the active nodes on both the navigation and settings. - $navigationactivenode = $this->page->navigation->find_active_node(); - $settingsactivenode = $this->page->settingsnav->find_active_node(); - - if ($navigationactivenode && $settingsactivenode) { - // Parse a combined navigation tree - while ($settingsactivenode && $settingsactivenode->parent !== null) { - if (!$settingsactivenode->mainnavonly) { - $items[] = new breadcrumb_navigation_node($settingsactivenode); - } - $settingsactivenode = $settingsactivenode->parent; - } - if (!$this->includesettingsbase) { - // Removes the first node from the settings (root node) from the list - array_pop($items); - } - while ($navigationactivenode && $navigationactivenode->parent !== null) { - if (!$navigationactivenode->mainnavonly) { - $items[] = new breadcrumb_navigation_node($navigationactivenode); - } - if (!empty($CFG->navshowcategories) && - $navigationactivenode->type === self::TYPE_COURSE && - $navigationactivenode->parent->key === 'currentcourse') { - foreach ($this->get_course_categories() as $item) { - $items[] = new breadcrumb_navigation_node($item); - } - } - $navigationactivenode = $navigationactivenode->parent; - } - } else if ($navigationactivenode) { - // Parse the navigation tree to get the active node - while ($navigationactivenode && $navigationactivenode->parent !== null) { - if (!$navigationactivenode->mainnavonly) { - $items[] = new breadcrumb_navigation_node($navigationactivenode); - } - if (!empty($CFG->navshowcategories) && - $navigationactivenode->type === self::TYPE_COURSE && - $navigationactivenode->parent->key === 'currentcourse') { - foreach ($this->get_course_categories() as $item) { - $items[] = new breadcrumb_navigation_node($item); - } - } - $navigationactivenode = $navigationactivenode->parent; - } - } else if ($settingsactivenode) { - // Parse the settings navigation to get the active node - while ($settingsactivenode && $settingsactivenode->parent !== null) { - if (!$settingsactivenode->mainnavonly) { - $items[] = new breadcrumb_navigation_node($settingsactivenode); - } - $settingsactivenode = $settingsactivenode->parent; - } - } - } - - $items[] = new breadcrumb_navigation_node(array( - 'text' => $this->page->navigation->text, - 'shorttext' => $this->page->navigation->shorttext, - 'key' => $this->page->navigation->key, - 'action' => $this->page->navigation->action - )); - - if (count($this->prependchildren) > 0) { - // Add the custom children - $items = array_merge($items, array_reverse($this->prependchildren)); - } - - $last = reset($items); - if ($last) { - $last->set_last(true); - } - $this->items = array_reverse($items); - return $this->items; - } - - /** - * Get the list of categories leading to this course. - * - * This function is used by {@link navbar::get_items()} to add back the "courses" - * node and category chain leading to the current course. Note that this is only ever - * called for the current course, so we don't need to bother taking in any parameters. - * - * @return array - */ - private function get_course_categories() { - global $CFG; - require_once($CFG->dirroot.'/course/lib.php'); - - $categories = array(); - $cap = 'moodle/category:viewhiddencategories'; - $showcategories = !core_course_category::is_simple_site(); - - if ($showcategories) { - foreach ($this->page->categories as $category) { - $context = context_coursecat::instance($category->id); - if (!core_course_category::can_view_category($category)) { - continue; - } - - $displaycontext = \context_helper::get_navigation_filter_context($context); - $url = new moodle_url('/course/index.php', ['categoryid' => $category->id]); - $name = format_string($category->name, true, ['context' => $displaycontext]); - $categorynode = breadcrumb_navigation_node::create($name, $url, self::TYPE_CATEGORY, null, $category->id); - if (!$category->visible) { - $categorynode->hidden = true; - } - $categories[] = $categorynode; - } - } - - // Don't show the 'course' node if enrolled in this course. - $coursecontext = context_course::instance($this->page->course->id); - if (!is_enrolled($coursecontext, null, '', true)) { - $courses = $this->page->navigation->get('courses'); - if (!$courses) { - // Courses node may not be present. - $courses = breadcrumb_navigation_node::create( - get_string('courses'), - new moodle_url('/course/index.php'), - self::TYPE_CONTAINER - ); - } - $categories[] = $courses; - } - - return $categories; - } - - /** - * Add a new breadcrumb_navigation_node to the navbar, overrides parent::add - * - * This function overrides {@link breadcrumb_navigation_node::add()} so that we can change - * the way nodes get added to allow us to simply call add and have the node added to the - * end of the navbar - * - * @param string $text - * @param string|moodle_url|action_link $action An action to associate with this node. - * @param int $type One of navigation_node::TYPE_* - * @param string $shorttext - * @param string|int $key A key to identify this node with. Key + type is unique to a parent. - * @param pix_icon $icon An optional icon to use for this node. - * @return navigation_node - */ - public function add($text, $action=null, $type=self::TYPE_CUSTOM, $shorttext=null, $key=null, ?pix_icon $icon=null) { - if ($this->content !== null) { - debugging('Nav bar items must be printed before $OUTPUT->header() has been called', DEBUG_DEVELOPER); - } - - // Properties array used when creating the new navigation node - $itemarray = array( - 'text' => $text, - 'type' => $type - ); - // Set the action if one was provided - if ($action!==null) { - $itemarray['action'] = $action; - } - // Set the shorttext if one was provided - if ($shorttext!==null) { - $itemarray['shorttext'] = $shorttext; - } - // Set the icon if one was provided - if ($icon!==null) { - $itemarray['icon'] = $icon; - } - // Default the key to the number of children if not provided - if ($key === null) { - $key = count($this->children); - } - // Set the key - $itemarray['key'] = $key; - // Set the parent to this node - $itemarray['parent'] = $this; - // Add the child using the navigation_node_collections add method - $this->children[] = new breadcrumb_navigation_node($itemarray); - return $this; - } - - /** - * Prepends a new navigation_node to the start of the navbar - * - * @param string $text - * @param string|moodle_url|action_link $action An action to associate with this node. - * @param int $type One of navigation_node::TYPE_* - * @param string $shorttext - * @param string|int $key A key to identify this node with. Key + type is unique to a parent. - * @param pix_icon $icon An optional icon to use for this node. - * @return navigation_node - */ - public function prepend($text, $action=null, $type=self::TYPE_CUSTOM, $shorttext=null, $key=null, ?pix_icon $icon=null) { - if ($this->content !== null) { - debugging('Nav bar items must be printed before $OUTPUT->header() has been called', DEBUG_DEVELOPER); - } - // Properties array used when creating the new navigation node. - $itemarray = array( - 'text' => $text, - 'type' => $type - ); - // Set the action if one was provided. - if ($action!==null) { - $itemarray['action'] = $action; - } - // Set the shorttext if one was provided. - if ($shorttext!==null) { - $itemarray['shorttext'] = $shorttext; - } - // Set the icon if one was provided. - if ($icon!==null) { - $itemarray['icon'] = $icon; - } - // Default the key to the number of children if not provided. - if ($key === null) { - $key = count($this->children); - } - // Set the key. - $itemarray['key'] = $key; - // Set the parent to this node. - $itemarray['parent'] = $this; - // Add the child node to the prepend list. - $this->prependchildren[] = new breadcrumb_navigation_node($itemarray); - return $this; - } -} - -/** - * Subclass of navigation_node allowing different rendering for the breadcrumbs - * in particular adding extra metadata for search engine robots to leverage. - * - * @package core - * @category navigation - * @copyright 2015 Brendan Heywood - * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later - */ -class breadcrumb_navigation_node extends navigation_node { - - /** @var $last boolean A flag indicating this is the last item in the list of breadcrumbs. */ - private $last = false; - - /** - * A proxy constructor - * - * @param mixed $navnode A navigation_node or an array - */ - public function __construct($navnode) { - if (is_array($navnode)) { - parent::__construct($navnode); - } else if ($navnode instanceof navigation_node) { - - // Just clone everything. - $objvalues = get_object_vars($navnode); - foreach ($objvalues as $key => $value) { - $this->$key = $value; - } - } else { - throw new coding_exception('Not a valid breadcrumb_navigation_node'); - } - } - - /** - * Getter for "last" - * @return boolean - */ - public function is_last() { - return $this->last; - } - - /** - * Setter for "last" - * @param $val boolean - */ - public function set_last($val) { - $this->last = $val; - } -} - -/** - * Subclass of navigation_node allowing different rendering for the flat navigation - * in particular allowing dividers and indents. - * - * @deprecated since Moodle 4.0 - do not use any more. Leverage secondary/tertiary navigation concepts - * @package core - * @category navigation - * @copyright 2016 Damyon Wiese - * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later - */ -class flat_navigation_node extends navigation_node { - - /** @var $indent integer The indent level */ - private $indent = 0; - - /** @var $showdivider bool Show a divider before this element */ - private $showdivider = false; - - /** @var $collectionlabel string Label for a group of nodes */ - private $collectionlabel = ''; - - /** - * A proxy constructor - * - * @param mixed $navnode A navigation_node or an array - */ - public function __construct($navnode, $indent) { - debugging("Flat nav has been deprecated in favour of primary/secondary navigation concepts"); - if (is_array($navnode)) { - parent::__construct($navnode); - } else if ($navnode instanceof navigation_node) { - - // Just clone everything. - $objvalues = get_object_vars($navnode); - foreach ($objvalues as $key => $value) { - $this->$key = $value; - } - } else { - throw new coding_exception('Not a valid flat_navigation_node'); - } - $this->indent = $indent; - } - - /** - * Setter, a label is required for a flat navigation node that shows a divider. - * - * @param string $label - */ - public function set_collectionlabel($label) { - $this->collectionlabel = $label; - } - - /** - * Getter, get the label for this flat_navigation node, or it's parent if it doesn't have one. - * - * @return string - */ - public function get_collectionlabel() { - if (!empty($this->collectionlabel)) { - return $this->collectionlabel; - } - if ($this->parent && ($this->parent instanceof flat_navigation_node || $this->parent instanceof flat_navigation)) { - return $this->parent->get_collectionlabel(); - } - debugging('Navigation region requires a label', DEBUG_DEVELOPER); - return ''; - } - - /** - * Does this node represent a course section link. - * @return boolean - */ - public function is_section() { - return $this->type == navigation_node::TYPE_SECTION; - } - - /** - * In flat navigation - sections are active if we are looking at activities in the section. - * @return boolean - */ - public function isactive() { - global $PAGE; - - if ($this->is_section()) { - $active = $PAGE->navigation->find_active_node(); - if ($active) { - while ($active = $active->parent) { - if ($active->key == $this->key && $active->type == $this->type) { - return true; - } - } - } - } - return $this->isactive; - } - - /** - * Getter for "showdivider" - * @return boolean - */ - public function showdivider() { - return $this->showdivider; - } - - /** - * Setter for "showdivider" - * @param $val boolean - * @param $label string Label for the group of nodes - */ - public function set_showdivider($val, $label = '') { - $this->showdivider = $val; - if ($this->showdivider && empty($label)) { - debugging('Navigation region requires a label', DEBUG_DEVELOPER); - } else { - $this->set_collectionlabel($label); - } - } - - /** - * Getter for "indent" - * @return boolean - */ - public function get_indent() { - return $this->indent; - } - - /** - * Setter for "indent" - * @param $val boolean - */ - public function set_indent($val) { - $this->indent = $val; - } -} - -/** - * Class used to generate a collection of navigation nodes most closely related - * to the current page. - * - * @deprecated since Moodle 4.0 - do not use any more. Leverage secondary/tertiary navigation concepts - * @package core - * @copyright 2016 Damyon Wiese - * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later - */ -class flat_navigation extends navigation_node_collection { - /** @var moodle_page the moodle page that the navigation belongs to */ - protected $page; - - /** - * Constructor. - * - * @param moodle_page $page - */ - public function __construct(moodle_page &$page) { - if (during_initial_install()) { - return; - } - debugging("Flat navigation has been deprecated in favour of primary/secondary navigation concepts"); - $this->page = $page; - } - - /** - * Build the list of navigation nodes based on the current navigation and settings trees. - * - */ - public function initialise() { - global $PAGE, $USER, $OUTPUT, $CFG; - if (during_initial_install()) { - return; - } - - $current = false; - - $course = $PAGE->course; - - $this->page->navigation->initialise(); - - // First walk the nav tree looking for "flat_navigation" nodes. - if ($course->id > 1) { - // It's a real course. - $url = new moodle_url('/course/view.php', array('id' => $course->id)); - - $coursecontext = context_course::instance($course->id, MUST_EXIST); - $displaycontext = \context_helper::get_navigation_filter_context($coursecontext); - // This is the name that will be shown for the course. - $coursename = empty($CFG->navshowfullcoursenames) ? - format_string($course->shortname, true, ['context' => $displaycontext]) : - format_string($course->fullname, true, ['context' => $displaycontext]); - - $flat = new flat_navigation_node(navigation_node::create($coursename, $url), 0); - $flat->set_collectionlabel($coursename); - $flat->key = 'coursehome'; - $flat->icon = new pix_icon('i/course', ''); - - $courseformat = course_get_format($course); - $coursenode = $PAGE->navigation->find_active_node(); - $targettype = navigation_node::TYPE_COURSE; - - // Single activity format has no course node - the course node is swapped for the activity node. - if (!$courseformat->has_view_page()) { - $targettype = navigation_node::TYPE_ACTIVITY; - } - - while (!empty($coursenode) && ($coursenode->type != $targettype)) { - $coursenode = $coursenode->parent; - } - // There is one very strange page in mod/feedback/view.php which thinks it is both site and course - // context at the same time. That page is broken but we need to handle it (hence the SITEID). - if ($coursenode && $coursenode->key != SITEID) { - $this->add($flat); - foreach ($coursenode->children as $child) { - if ($child->action) { - $flat = new flat_navigation_node($child, 0); - $this->add($flat); - } - } - } - - $this->page->navigation->build_flat_navigation_list($this, true, get_string('site')); - } else { - $this->page->navigation->build_flat_navigation_list($this, false, get_string('site')); - } - - $admin = $PAGE->settingsnav->find('siteadministration', navigation_node::TYPE_SITE_ADMIN); - if (!$admin) { - // Try again - crazy nav tree! - $admin = $PAGE->settingsnav->find('root', navigation_node::TYPE_SITE_ADMIN); - } - if ($admin) { - $flat = new flat_navigation_node($admin, 0); - $flat->set_showdivider(true, get_string('sitesettings')); - $flat->key = 'sitesettings'; - $flat->icon = new pix_icon('t/preferences', ''); - $this->add($flat); - } - - // Add-a-block in editing mode. - if (isset($this->page->theme->addblockposition) && - $this->page->theme->addblockposition == BLOCK_ADDBLOCK_POSITION_FLATNAV && - $PAGE->user_is_editing() && $PAGE->user_can_edit_blocks()) { - $url = new moodle_url($PAGE->url, ['bui_addblock' => '', 'sesskey' => sesskey()]); - $addablock = navigation_node::create(get_string('addblock'), $url); - $flat = new flat_navigation_node($addablock, 0); - $flat->set_showdivider(true, get_string('blocksaddedit')); - $flat->key = 'addblock'; - $flat->icon = new pix_icon('i/addblock', ''); - $this->add($flat); - - $addblockurl = "?{$url->get_query_string(false)}"; - - $PAGE->requires->js_call_amd('core_block/add_modal', 'init', - [$addblockurl, $this->page->get_edited_page_hash()]); - } - } - - /** - * Override the parent so we can set a label for this collection if it has not been set yet. - * - * @param navigation_node $node Node to add - * @param string $beforekey If specified, adds before a node with this key, - * otherwise adds at end - * @return navigation_node Added node - */ - public function add(navigation_node $node, $beforekey=null) { - $result = parent::add($node, $beforekey); - // Extend the parent to get a name for the collection of nodes if required. - if (empty($this->collectionlabel)) { - if ($node instanceof flat_navigation_node) { - $this->set_collectionlabel($node->get_collectionlabel()); - } - } - - return $result; - } -} - -/** - * Class used to manage the settings option for the current page - * - * This class is used to manage the settings options in a tree format (recursively) - * and was created initially for use with the settings blocks. - * - * @package core - * @category navigation - * @copyright 2009 Sam Hemelryk - * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later - */ -class settings_navigation extends navigation_node { - /** @var context the current context */ - protected $context; - /** @var moodle_page the moodle page that the navigation belongs to */ - protected $page; - /** @var string contains administration section navigation_nodes */ - protected $adminsection; - /** @var bool A switch to see if the navigation node is initialised */ - protected $initialised = false; - /** @var array An array of users that the nodes can extend for. */ - protected $userstoextendfor = array(); - /** @var navigation_cache **/ - protected $cache; - - /** - * Sets up the object with basic settings and preparse it for use - * - * @param moodle_page $page - */ - public function __construct(moodle_page &$page) { - if (during_initial_install()) { - return; - } - $this->page = $page; - // Initialise the main navigation. It is most important that this is done - // before we try anything - $this->page->navigation->initialise(); - // Initialise the navigation cache - $this->cache = new navigation_cache(NAVIGATION_CACHE_NAME); - $this->children = new navigation_node_collection(); - } - - /** - * Initialise the settings navigation based on the current context - * - * This function initialises the settings navigation tree for a given context - * by calling supporting functions to generate major parts of the tree. - * - */ - public function initialise() { - global $DB, $SESSION, $SITE; - - if (during_initial_install()) { - return false; - } else if ($this->initialised) { - return true; - } - $this->id = 'settingsnav'; - $this->context = $this->page->context; - - $context = $this->context; - if ($context->contextlevel == CONTEXT_BLOCK) { - $this->load_block_settings(); - $context = $context->get_parent_context(); - $this->context = $context; - } - switch ($context->contextlevel) { - case CONTEXT_SYSTEM: - if ($this->page->url->compare(new moodle_url('/admin/settings.php', array('section'=>'frontpagesettings')))) { - $this->load_front_page_settings(($context->id == $this->context->id)); - } - break; - case CONTEXT_COURSECAT: - $this->load_category_settings(); - break; - case CONTEXT_COURSE: - if ($this->page->course->id != $SITE->id) { - $this->load_course_settings(($context->id == $this->context->id)); - } else { - $this->load_front_page_settings(($context->id == $this->context->id)); - } - break; - case CONTEXT_MODULE: - $this->load_module_settings(); - $this->load_course_settings(); - break; - case CONTEXT_USER: - if ($this->page->course->id != $SITE->id) { - $this->load_course_settings(); - } - break; - } - - $usersettings = $this->load_user_settings($this->page->course->id); - - $adminsettings = false; - if (isloggedin() && !isguestuser() && (!isset($SESSION->load_navigation_admin) || $SESSION->load_navigation_admin)) { - $isadminpage = $this->is_admin_tree_needed(); - - if (has_capability('moodle/site:configview', context_system::instance())) { - if (has_capability('moodle/site:config', context_system::instance())) { - // Make sure this works even if config capability changes on the fly - // and also make it fast for admin right after login. - $SESSION->load_navigation_admin = 1; - if ($isadminpage) { - $adminsettings = $this->load_administration_settings(); - } - - } else if (!isset($SESSION->load_navigation_admin)) { - $adminsettings = $this->load_administration_settings(); - $SESSION->load_navigation_admin = (int)($adminsettings->children->count() > 0); - - } else if ($SESSION->load_navigation_admin) { - if ($isadminpage) { - $adminsettings = $this->load_administration_settings(); - } - } - - // Print empty navigation node, if needed. - if ($SESSION->load_navigation_admin && !$isadminpage) { - if ($adminsettings) { - // Do not print settings tree on pages that do not need it, this helps with performance. - $adminsettings->remove(); - $adminsettings = false; - } - $siteadminnode = $this->add(get_string('administrationsite'), new moodle_url('/admin/search.php'), - self::TYPE_SITE_ADMIN, null, 'siteadministration'); - $siteadminnode->id = 'expandable_branch_' . $siteadminnode->type . '_' . - clean_param($siteadminnode->key, PARAM_ALPHANUMEXT); - $siteadminnode->requiresajaxloading = 'true'; - } - } - } - - if ($context->contextlevel == CONTEXT_SYSTEM && $adminsettings) { - $adminsettings->force_open(); - } else if ($context->contextlevel == CONTEXT_USER && $usersettings) { - $usersettings->force_open(); - } - - // At this point we give any local plugins the ability to extend/tinker with the navigation settings. - $this->load_local_plugin_settings(); - - foreach ($this->children as $key=>$node) { - if ($node->nodetype == self::NODETYPE_BRANCH && $node->children->count() == 0) { - // Site administration is shown as link. - if (!empty($SESSION->load_navigation_admin) && ($node->type === self::TYPE_SITE_ADMIN)) { - continue; - } - $node->remove(); - } - } - $this->initialised = true; - } - /** - * Override the parent function so that we can add preceeding hr's and set a - * root node class against all first level element - * - * It does this by first calling the parent's add method {@link navigation_node::add()} - * and then proceeds to use the key to set class and hr - * - * @param string $text text to be used for the link. - * @param string|moodle_url $url url for the new node - * @param int $type the type of node navigation_node::TYPE_* - * @param string $shorttext - * @param string|int $key a key to access the node by. - * @param pix_icon $icon An icon that appears next to the node. - * @return navigation_node with the new node added to it. - */ - public function add($text, $url=null, $type=null, $shorttext=null, $key=null, ?pix_icon $icon=null) { - $node = parent::add($text, $url, $type, $shorttext, $key, $icon); - $node->add_class('root_node'); - return $node; - } - - /** - * This function allows the user to add something to the start of the settings - * navigation, which means it will be at the top of the settings navigation block - * - * @param string $text text to be used for the link. - * @param string|moodle_url $url url for the new node - * @param int $type the type of node navigation_node::TYPE_* - * @param string $shorttext - * @param string|int $key a key to access the node by. - * @param pix_icon $icon An icon that appears next to the node. - * @return navigation_node $node with the new node added to it. - */ - public function prepend($text, $url=null, $type=null, $shorttext=null, $key=null, ?pix_icon $icon=null) { - $children = $this->children; - $childrenclass = get_class($children); - $this->children = new $childrenclass; - $node = $this->add($text, $url, $type, $shorttext, $key, $icon); - foreach ($children as $child) { - $this->children->add($child); - } - return $node; - } - - /** - * Does this page require loading of full admin tree or is - * it enough rely on AJAX? - * - * @return bool - */ - protected function is_admin_tree_needed() { - if (self::$loadadmintree) { - // Usually external admin page or settings page. - return true; - } - - if ($this->page->pagelayout === 'admin' or strpos($this->page->pagetype, 'admin-') === 0) { - // Admin settings tree is intended for system level settings and management only, use navigation for the rest! - if ($this->page->context->contextlevel != CONTEXT_SYSTEM) { - return false; - } - return true; - } - - return false; - } - - /** - * Load the site administration tree - * - * This function loads the site administration tree by using the lib/adminlib library functions - * - * @param navigation_node $referencebranch A reference to a branch in the settings - * navigation tree - * @param part_of_admin_tree $adminbranch The branch to add, if null generate the admin - * tree and start at the beginning - * @return mixed A key to access the admin tree by - */ - protected function load_administration_settings(?navigation_node $referencebranch=null, ?part_of_admin_tree $adminbranch=null) { - global $CFG; - - // Check if we are just starting to generate this navigation. - if ($referencebranch === null) { - - // Require the admin lib then get an admin structure - if (!function_exists('admin_get_root')) { - require_once($CFG->dirroot.'/lib/adminlib.php'); - } - $adminroot = admin_get_root(false, false); - // This is the active section identifier - $this->adminsection = $this->page->url->param('section'); - - // Disable the navigation from automatically finding the active node - navigation_node::$autofindactive = false; - $referencebranch = $this->add(get_string('administrationsite'), '/admin/search.php', self::TYPE_SITE_ADMIN, null, 'root'); - foreach ($adminroot->children as $adminbranch) { - $this->load_administration_settings($referencebranch, $adminbranch); - } - navigation_node::$autofindactive = true; - - // Use the admin structure to locate the active page - if (!$this->contains_active_node() && $current = $adminroot->locate($this->adminsection, true)) { - $currentnode = $this; - while (($pathkey = array_pop($current->path))!==null && $currentnode) { - $currentnode = $currentnode->get($pathkey); - } - if ($currentnode) { - $currentnode->make_active(); - } - } else { - $this->scan_for_active_node($referencebranch); - } - return $referencebranch; - } else if ($adminbranch->check_access()) { - // We have a reference branch that we can access and is not hidden `hurrah` - // Now we need to display it and any children it may have - $url = null; - $icon = null; - - if ($adminbranch instanceof \core_admin\local\settings\linkable_settings_page) { - if (empty($CFG->linkadmincategories) && $adminbranch instanceof admin_category) { - $url = null; - } else { - $url = $adminbranch->get_settings_page_url(); - } - } - - // Add the branch - $reference = $referencebranch->add($adminbranch->visiblename, $url, self::TYPE_SETTING, null, $adminbranch->name, $icon); - - if ($adminbranch->is_hidden()) { - if (($adminbranch instanceof admin_externalpage || $adminbranch instanceof admin_settingpage) && $adminbranch->name == $this->adminsection) { - $reference->add_class('hidden'); - } else { - $reference->display = false; - } - } - - // Check if we are generating the admin notifications and whether notificiations exist - if ($adminbranch->name === 'adminnotifications' && admin_critical_warnings_present()) { - $reference->add_class('criticalnotification'); - } - // Check if this branch has children - if ($reference && isset($adminbranch->children) && is_array($adminbranch->children) && count($adminbranch->children)>0) { - foreach ($adminbranch->children as $branch) { - // Generate the child branches as well now using this branch as the reference - $this->load_administration_settings($reference, $branch); - } - } else { - $reference->icon = new pix_icon('i/settings', ''); - } - } - } - - /** - * This function recursivily scans nodes until it finds the active node or there - * are no more nodes. - * @param navigation_node $node - */ - protected function scan_for_active_node(navigation_node $node) { - if (!$node->check_if_active() && $node->children->count()>0) { - foreach ($node->children as &$child) { - $this->scan_for_active_node($child); - } - } - } - - /** - * Gets a navigation node given an array of keys that represent the path to - * the desired node. - * - * @param array $path - * @return navigation_node|false - */ - protected function get_by_path(array $path) { - $node = $this->get(array_shift($path)); - foreach ($path as $key) { - $node->get($key); - } - return $node; - } - - /** - * This function loads the course settings that are available for the user - * - * @param bool $forceopen If set to true the course node will be forced open - * @return navigation_node|false - */ - protected function load_course_settings($forceopen = false) { - global $CFG, $USER; - require_once($CFG->dirroot . '/course/lib.php'); - - $course = $this->page->course; - $coursecontext = context_course::instance($course->id); - $adminoptions = course_get_user_administration_options($course, $coursecontext); - - // note: do not test if enrolled or viewing here because we need the enrol link in Course administration section - - $coursenode = $this->add(get_string('courseadministration'), null, self::TYPE_COURSE, null, 'courseadmin'); - if ($forceopen) { - $coursenode->force_open(); - } - - // MoodleNet links. - if ($this->page->user_is_editing()) { - $this->page->requires->js_call_amd('core/moodlenet/mutations', 'init'); - } - $usercanshare = utilities::can_user_share($coursecontext, $USER->id, 'course'); - $issuerid = get_config('moodlenet', 'oauthservice'); - try { - $issuer = \core\oauth2\api::get_issuer($issuerid); - $isvalidinstance = utilities::is_valid_instance($issuer); - if ($usercanshare && $isvalidinstance) { - $this->page->requires->js_call_amd('core/moodlenet/send_resource', 'init'); - $action = new action_link(new moodle_url(''), '', null, [ - 'data-action' => 'sendtomoodlenet', - 'data-type' => 'course', - ]); - // Share course to MoodleNet link. - $coursenode->add(get_string('moodlenet:sharetomoodlenet', 'moodle'), - $action, self::TYPE_SETTING, null, 'exportcoursetomoodlenet')->set_force_into_more_menu(true); - // MoodleNet share progress link. - $url = new moodle_url('/moodlenet/shareprogress.php'); - $coursenode->add(get_string('moodlenet:shareprogress'), - $url, self::TYPE_SETTING, null, 'moodlenetshareprogress')->set_force_into_more_menu(true); - } - } catch (dml_missing_record_exception $e) { - debugging("Invalid MoodleNet OAuth 2 service set in site administration: 'moodlenet | oauthservice'. " . - "This must be a valid issuer."); - } - - if ($adminoptions->update) { - // Add the course settings link - $url = new moodle_url('/course/edit.php', array('id'=>$course->id)); - $coursenode->add(get_string('settings'), $url, self::TYPE_SETTING, null, - 'editsettings', new pix_icon('i/settings', '')); - } - - if ($adminoptions->editcompletion) { - // Add the course completion settings link - $url = new moodle_url('/course/completion.php', array('id' => $course->id)); - $coursenode->add(get_string('coursecompletion', 'completion'), $url, self::TYPE_SETTING, null, 'coursecompletion', - new pix_icon('i/settings', '')); - } - - if (!$adminoptions->update && $adminoptions->tags) { - $url = \core\router\util::get_path_for_callable([ - \core_course\route\controller\tags_controller::class, - 'administer_tags', - ], ['course' => $course->id]); - $coursenode->add(get_string('coursetags', 'tag'), $url, self::TYPE_SETTING, null, 'coursetags', new pix_icon('i/settings', '')); - $coursenode->get('coursetags')->set_force_into_more_menu(); - } - - // add enrol nodes - enrol_add_course_navigation($coursenode, $course); - - // Manage filters - if ($adminoptions->filters) { - $url = new moodle_url('/filter/manage.php', array('contextid'=>$coursecontext->id)); - $coursenode->add(get_string('filters', 'admin'), $url, self::TYPE_SETTING, - null, 'filtermanagement', new pix_icon('i/filter', '')); - } - - // View course reports. - if ($adminoptions->reports) { - $reportnav = $coursenode->add(get_string('reports'), - new moodle_url('/report/view.php', ['courseid' => $coursecontext->instanceid]), - self::TYPE_CONTAINER, null, 'coursereports', new pix_icon('i/stats', '')); - $coursereports = core_component::get_plugin_list('coursereport'); - foreach ($coursereports as $report => $dir) { - $libfile = $CFG->dirroot.'/course/report/'.$report.'/lib.php'; - if (file_exists($libfile)) { - require_once($libfile); - $reportfunction = $report.'_report_extend_navigation'; - if (function_exists($report.'_report_extend_navigation')) { - $reportfunction($reportnav, $course, $coursecontext); - } - } - } - - $reports = get_plugin_list_with_function('report', 'extend_navigation_course', 'lib.php'); - foreach ($reports as $reportfunction) { - $reportfunction($reportnav, $course, $coursecontext); - } - - if (!$reportnav->has_children()) { - $reportnav->remove(); - } - } - - // Grade penalty navigation. - \core_grades\penalty_manager::extend_navigation_course($coursenode, $course, $coursecontext); - - // Check if we can view the gradebook's setup page. - if ($adminoptions->gradebook) { - $url = new moodle_url('/grade/edit/tree/index.php', array('id' => $course->id)); - $coursenode->add(get_string('gradebooksetup', 'grades'), $url, self::TYPE_SETTING, - null, 'gradebooksetup', new pix_icon('i/settings', '')); - } - - // Add the context locking node. - $this->add_context_locking_node($coursenode, $coursecontext); - - // Add outcome if permitted - if ($adminoptions->outcomes) { - $url = new moodle_url('/grade/edit/outcome/course.php', array('id'=>$course->id)); - $coursenode->add(get_string('outcomes', 'grades'), $url, self::TYPE_SETTING, null, 'outcomes', new pix_icon('i/outcomes', '')); - } - - //Add badges navigation - if ($adminoptions->badges) { - require_once($CFG->libdir .'/badgeslib.php'); - badges_add_course_navigation($coursenode, $course); - } - - // Questions - require_once($CFG->libdir . '/questionlib.php'); - $baseurl = \core_question\local\bank\question_bank_helper::get_url_for_qbank_list($course->id); - question_extend_settings_navigation($coursenode, $coursecontext, $baseurl)->trim_if_empty(); - - if ($adminoptions->update) { - // Repository Instances - if (!$this->cache->cached('contexthasrepos'.$coursecontext->id)) { - require_once($CFG->dirroot . '/repository/lib.php'); - $editabletypes = repository::get_editable_types($coursecontext); - $haseditabletypes = !empty($editabletypes); - unset($editabletypes); - $this->cache->set('contexthasrepos'.$coursecontext->id, $haseditabletypes); - } else { - $haseditabletypes = $this->cache->{'contexthasrepos'.$coursecontext->id}; - } - if ($haseditabletypes) { - $url = new moodle_url('/repository/manage_instances.php', array('contextid' => $coursecontext->id)); - $coursenode->add(get_string('repositories'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/repository', '')); - } - } - - // Manage files - if ($adminoptions->files) { - // hidden in new courses and courses where legacy files were turned off - $url = new moodle_url('/files/index.php', array('contextid'=>$coursecontext->id)); - $coursenode->add(get_string('courselegacyfiles'), $url, self::TYPE_SETTING, null, 'coursefiles', new pix_icon('i/folder', '')); - - } - - // Let plugins hook into course navigation. - $pluginsfunction = get_plugins_with_function('extend_navigation_course', 'lib.php'); - foreach ($pluginsfunction as $plugintype => $plugins) { - // Ignore the report and gradepenalty plugins as they were already loaded above. - if ($plugintype == 'report' || $plugintype == 'gradepenalty') { - continue; - } - foreach ($plugins as $pluginfunction) { - $pluginfunction($coursenode, $course, $coursecontext); - } - } - - // Prepare data for course content download functionality if it is enabled. - if (\core\content::can_export_context($coursecontext, $USER)) { - $linkattr = \core_course\output\content_export_link::get_attributes($coursecontext); - $actionlink = new action_link($linkattr->url, $linkattr->displaystring, null, $linkattr->elementattributes); - - $coursenode->add($linkattr->displaystring, $actionlink, self::TYPE_SETTING, null, 'download', - new pix_icon('t/download', '')); - $coursenode->get('download')->set_force_into_more_menu(true); - } - - // Course reuse options. - if ($adminoptions->import - || $adminoptions->backup - || $adminoptions->restore - || $adminoptions->copy - || $adminoptions->reset) { - $coursereusenav = $coursenode->add( - get_string('coursereuse'), - new moodle_url('/backup/view.php', ['id' => $course->id]), - self::TYPE_CONTAINER, null, 'coursereuse', new pix_icon('t/edit', ''), - ); - - // Import data from other courses. - if ($adminoptions->import) { - $url = new moodle_url('/backup/import.php', ['id' => $course->id]); - $coursereusenav->add(get_string('import'), $url, self::TYPE_SETTING, null, 'import', new pix_icon('i/import', '')); - } - - // Backup this course. - if ($adminoptions->backup) { - $url = new moodle_url('/backup/backup.php', ['id' => $course->id]); - $coursereusenav->add(get_string('backup'), $url, self::TYPE_SETTING, null, 'backup', new pix_icon('i/backup', '')); - } - - // Restore to this course. - if ($adminoptions->restore) { - $url = new moodle_url('/backup/restorefile.php', ['contextid' => $coursecontext->id]); - $coursereusenav->add( - get_string('restore'), - $url, - self::TYPE_SETTING, - null, - 'restore', - new pix_icon('i/restore', ''), - ); - } - - // Copy this course. - if ($adminoptions->copy) { - $url = new moodle_url('/backup/copy.php', ['id' => $course->id]); - $coursereusenav->add(get_string('copycourse'), $url, self::TYPE_SETTING, null, 'copy', new pix_icon('t/copy', '')); - } - - // Reset this course. - if ($adminoptions->reset) { - $url = new moodle_url('/course/reset.php', ['id' => $course->id]); - $coursereusenav->add(get_string('reset'), $url, self::TYPE_SETTING, null, 'reset', new pix_icon('i/return', '')); - } - } - - // Return we are done - return $coursenode; - } - - /** - * Get the moodle_page object associated to the current settings navigation. - * - * @return moodle_page - */ - public function get_page(): moodle_page { - return $this->page; - } - - /** - * This function calls the module function to inject module settings into the - * settings navigation tree. - * - * This only gets called if there is a corrosponding function in the modules - * lib file. - * - * For examples mod/forum/lib.php {@link forum_extend_settings_navigation()} - * - * @return navigation_node|false - */ - protected function load_module_settings() { - global $CFG, $USER; - - if (!$this->page->cm && $this->context->contextlevel == CONTEXT_MODULE && $this->context->instanceid) { - $cm = get_coursemodule_from_id(false, $this->context->instanceid, 0, false, MUST_EXIST); - $this->page->set_cm($cm, $this->page->course); - } - - $file = $CFG->dirroot.'/mod/'.$this->page->activityname.'/lib.php'; - if (file_exists($file)) { - require_once($file); - } - - $modulenode = $this->add(get_string('pluginadministration', $this->page->activityname), null, self::TYPE_SETTING, null, 'modulesettings'); - $modulenode->nodetype = navigation_node::NODETYPE_BRANCH; - $modulenode->force_open(); - - // Settings for the module - if (has_capability('moodle/course:manageactivities', $this->page->cm->context)) { - $url = new moodle_url('/course/modedit.php', array('update' => $this->page->cm->id, 'return' => 1)); - $modulenode->add(get_string('settings'), $url, self::TYPE_SETTING, null, 'modedit', new pix_icon('i/settings', '')); - } - // Assign local roles - if (count(get_assignable_roles($this->page->cm->context))>0) { - $url = new moodle_url('/'.$CFG->admin.'/roles/assign.php', array('contextid'=>$this->page->cm->context->id)); - $modulenode->add(get_string('localroles', 'role'), $url, self::TYPE_SETTING, null, 'roleassign', - new pix_icon('i/role', '')); - } - // Override roles - if (has_capability('moodle/role:review', $this->page->cm->context) or count(get_overridable_roles($this->page->cm->context))>0) { - $url = new moodle_url('/'.$CFG->admin.'/roles/permissions.php', array('contextid'=>$this->page->cm->context->id)); - $modulenode->add(get_string('permissions', 'role'), $url, self::TYPE_SETTING, null, 'roleoverride', - new pix_icon('i/permissions', '')); - } - // Check role permissions - if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride','moodle/role:override', 'moodle/role:assign'), $this->page->cm->context)) { - $url = new moodle_url('/'.$CFG->admin.'/roles/check.php', array('contextid'=>$this->page->cm->context->id)); - $modulenode->add(get_string('checkpermissions', 'role'), $url, self::TYPE_SETTING, null, 'rolecheck', - new pix_icon('i/checkpermissions', '')); - } - - // Add the context locking node. - $this->add_context_locking_node($modulenode, $this->page->cm->context); - - // Manage filters - if (has_capability('moodle/filter:manage', $this->page->cm->context) && count(filter_get_available_in_context($this->page->cm->context))>0) { - $url = new moodle_url('/filter/manage.php', array('contextid'=>$this->page->cm->context->id)); - $modulenode->add(get_string('filters', 'admin'), $url, self::TYPE_SETTING, null, 'filtermanage', - new pix_icon('i/filter', '')); - } - // Add reports - $reports = get_plugin_list_with_function('report', 'extend_navigation_module', 'lib.php'); - foreach ($reports as $reportfunction) { - $reportfunction($modulenode, $this->page->cm); - } - // Add a backup link - $featuresfunc = $this->page->activityname.'_supports'; - if (function_exists($featuresfunc) && $featuresfunc(FEATURE_BACKUP_MOODLE2) && has_capability('moodle/backup:backupactivity', $this->page->cm->context)) { - $url = new moodle_url('/backup/backup.php', array('id'=>$this->page->cm->course, 'cm'=>$this->page->cm->id)); - $modulenode->add(get_string('backup'), $url, self::TYPE_SETTING, null, 'backup', new pix_icon('i/backup', '')); - } - - // Restore this activity - $featuresfunc = $this->page->activityname.'_supports'; - if (function_exists($featuresfunc) && $featuresfunc(FEATURE_BACKUP_MOODLE2) && has_capability('moodle/restore:restoreactivity', $this->page->cm->context)) { - $url = new moodle_url('/backup/restorefile.php', array('contextid'=>$this->page->cm->context->id)); - $modulenode->add(get_string('restore'), $url, self::TYPE_SETTING, null, 'restore', new pix_icon('i/restore', '')); - } - - // Allow the active advanced grading method plugin to append its settings - $featuresfunc = $this->page->activityname.'_supports'; - if (function_exists($featuresfunc) && $featuresfunc(FEATURE_ADVANCED_GRADING) && has_capability('moodle/grade:managegradingforms', $this->page->cm->context)) { - require_once($CFG->dirroot.'/grade/grading/lib.php'); - $gradingman = get_grading_manager($this->page->cm->context, 'mod_'.$this->page->activityname); - $gradingman->extend_settings_navigation($this, $modulenode); - } - - $function = $this->page->activityname.'_extend_settings_navigation'; - if (function_exists($function)) { - $function($this, $modulenode); - } - - // Send activity to MoodleNet. - $usercanshare = utilities::can_user_share($this->context->get_course_context(), $USER->id); - $issuerid = get_config('moodlenet', 'oauthservice'); - try { - $issuer = \core\oauth2\api::get_issuer($issuerid); - $isvalidinstance = utilities::is_valid_instance($issuer); - if ($usercanshare && $isvalidinstance) { - $this->page->requires->js_call_amd('core/moodlenet/send_resource', 'init'); - $action = new action_link(new moodle_url(''), '', null, [ - 'data-action' => 'sendtomoodlenet', - 'data-type' => 'activity', - ]); - $modulenode->add(get_string('moodlenet:sharetomoodlenet', 'moodle'), - $action, self::TYPE_SETTING, null, 'exportmoodlenet')->set_force_into_more_menu(true); - } - } catch (dml_missing_record_exception $e) { - debugging("Invalid MoodleNet OAuth 2 service set in site administration: 'moodlenet | oauthservice'. " . - "This must be a valid issuer."); - } - - // Remove the module node if there are no children. - if ($modulenode->children->count() <= 0) { - $modulenode->remove(); - } - - return $modulenode; - } - - /** - * Loads the user settings block of the settings nav - * - * This function is simply works out the userid and whether we need to load - * just the current users profile settings, or the current user and the user the - * current user is viewing. - * - * This function has some very ugly code to work out the user, if anyone has - * any bright ideas please feel free to intervene. - * - * @param int $courseid The course id of the current course - * @return navigation_node|false - */ - protected function load_user_settings($courseid = SITEID) { - global $USER, $CFG; - - if (isguestuser() || !isloggedin()) { - return false; - } - - $navusers = $this->page->navigation->get_extending_users(); - - if (count($this->userstoextendfor) > 0 || count($navusers) > 0) { - $usernode = null; - foreach ($this->userstoextendfor as $userid) { - if ($userid == $USER->id) { - continue; - } - $node = $this->generate_user_settings($courseid, $userid, 'userviewingsettings'); - if (is_null($usernode)) { - $usernode = $node; - } - } - foreach ($navusers as $user) { - if ($user->id == $USER->id) { - continue; - } - $node = $this->generate_user_settings($courseid, $user->id, 'userviewingsettings'); - if (is_null($usernode)) { - $usernode = $node; - } - } - $this->generate_user_settings($courseid, $USER->id); - } else { - $usernode = $this->generate_user_settings($courseid, $USER->id); - } - return $usernode; - } - - /** - * Extends the settings navigation for the given user. - * - * Note: This method gets called automatically if you call - * $PAGE->navigation->extend_for_user($userid) - * - * @param int $userid - */ - public function extend_for_user($userid) { - global $CFG; - - if (!in_array($userid, $this->userstoextendfor)) { - $this->userstoextendfor[] = $userid; - if ($this->initialised) { - $this->generate_user_settings($this->page->course->id, $userid, 'userviewingsettings'); - $children = array(); - foreach ($this->children as $child) { - $children[] = $child; - } - array_unshift($children, array_pop($children)); - $this->children = new navigation_node_collection(); - foreach ($children as $child) { - $this->children->add($child); - } - } - } - } - - /** - * This function gets called by {@link settings_navigation::load_user_settings()} and actually works out - * what can be shown/done - * - * @param int $courseid The current course' id - * @param int $userid The user id to load for - * @param string $gstitle The string to pass to get_string for the branch title - * @return navigation_node|false - */ - protected function generate_user_settings($courseid, $userid, $gstitle='usercurrentsettings') { - global $DB, $CFG, $USER, $SITE; - - if ($courseid != $SITE->id) { - if (!empty($this->page->course->id) && $this->page->course->id == $courseid) { - $course = $this->page->course; - } else { - $select = context_helper::get_preload_record_columns_sql('ctx'); - $sql = "SELECT c.*, $select - FROM {course} c - JOIN {context} ctx ON c.id = ctx.instanceid - WHERE c.id = :courseid AND ctx.contextlevel = :contextlevel"; - $params = array('courseid' => $courseid, 'contextlevel' => CONTEXT_COURSE); - $course = $DB->get_record_sql($sql, $params, MUST_EXIST); - context_helper::preload_from_record($course); - } - } else { - $course = $SITE; - } - - $coursecontext = context_course::instance($course->id); // Course context - $systemcontext = context_system::instance(); - $currentuser = ($USER->id == $userid); - - if ($currentuser) { - $user = $USER; - $usercontext = context_user::instance($user->id); // User context - } else { - $select = context_helper::get_preload_record_columns_sql('ctx'); - $sql = "SELECT u.*, $select - FROM {user} u - JOIN {context} ctx ON u.id = ctx.instanceid - WHERE u.id = :userid AND ctx.contextlevel = :contextlevel"; - $params = array('userid' => $userid, 'contextlevel' => CONTEXT_USER); - $user = $DB->get_record_sql($sql, $params, IGNORE_MISSING); - if (!$user) { - return false; - } - context_helper::preload_from_record($user); - - // Check that the user can view the profile - $usercontext = context_user::instance($user->id); // User context - $canviewuser = has_capability('moodle/user:viewdetails', $usercontext); - - if ($course->id == $SITE->id) { - if ($CFG->forceloginforprofiles && !has_coursecontact_role($user->id) && !$canviewuser) { // Reduce possibility of "browsing" userbase at site level - // Teachers can browse and be browsed at site level. If not forceloginforprofiles, allow access (bug #4366) - return false; - } - } else { - $canviewusercourse = has_capability('moodle/user:viewdetails', $coursecontext); - $userisenrolled = is_enrolled($coursecontext, $user->id, '', true); - if ((!$canviewusercourse && !$canviewuser) || !$userisenrolled) { - return false; - } - $canaccessallgroups = has_capability('moodle/site:accessallgroups', $coursecontext); - if (!$canaccessallgroups && groups_get_course_groupmode($course) == SEPARATEGROUPS && !$canviewuser) { - // If groups are in use, make sure we can see that group (MDL-45874). That does not apply to parents. - if ($courseid == $this->page->course->id) { - $mygroups = get_fast_modinfo($this->page->course)->groups; - } else { - $mygroups = groups_get_user_groups($courseid); - } - $usergroups = groups_get_user_groups($courseid, $userid); - if (!array_intersect_key($mygroups[0], $usergroups[0])) { - return false; - } - } - } - } - - $fullname = fullname($user, has_capability('moodle/site:viewfullnames', $this->page->context)); - - $key = $gstitle; - $prefurl = new moodle_url('/user/preferences.php'); - if ($gstitle != 'usercurrentsettings') { - $key .= $userid; - $prefurl->param('userid', $userid); - } - - // Add a user setting branch. - if ($gstitle == 'usercurrentsettings') { - $mainpage = $this->add(get_string('home'), new moodle_url('/'), self::TYPE_CONTAINER, null, 'site'); - - // This should be set to false as we don't want to show this to the user. It's only for generating the correct - // breadcrumb. - $mainpage->display = false; - $homepage = get_home_page(); - if (($homepage == HOMEPAGE_MY || $homepage == HOMEPAGE_MYCOURSES)) { - $mainpage->mainnavonly = true; - } - - $iscurrentuser = ($user->id == $USER->id); - - $baseargs = array('id' => $user->id); - if ($course->id != $SITE->id && !$iscurrentuser) { - $baseargs['course'] = $course->id; - $issitecourse = false; - } else { - // Load all categories and get the context for the system. - $issitecourse = true; - } - - // Add the user profile to the dashboard. - $profilenode = $mainpage->add(get_string('profile'), new moodle_url('/user/profile.php', - array('id' => $user->id)), self::TYPE_SETTING, null, 'myprofile'); - - // Add blog nodes. - if (!empty($CFG->enableblogs)) { - if (!$this->cache->cached('userblogoptions'.$user->id)) { - require_once($CFG->dirroot.'/blog/lib.php'); - // Get all options for the user. - $options = blog_get_options_for_user($user); - $this->cache->set('userblogoptions'.$user->id, $options); - } else { - $options = $this->cache->{'userblogoptions'.$user->id}; - } - - if (count($options) > 0) { - $blogs = $profilenode->add(get_string('blogs', 'blog'), null, navigation_node::TYPE_CONTAINER); - foreach ($options as $type => $option) { - if ($type == "rss") { - $blogs->add($option['string'], $option['link'], self::TYPE_SETTING, null, null, - new pix_icon('i/rss', '')); - } else { - $blogs->add($option['string'], $option['link'], self::TYPE_SETTING, null, 'blog' . $type); - } - } - } - } - - // Add the messages link. - // It is context based so can appear in the user's profile and in course participants information. - if (!empty($CFG->messaging)) { - $messageargs = array('user1' => $USER->id); - if ($USER->id != $user->id) { - $messageargs['user2'] = $user->id; - } - $url = new moodle_url('/message/index.php', $messageargs); - $mainpage->add(get_string('messages', 'message'), $url, self::TYPE_SETTING, null, 'messages'); - } - - // Add the "My private files" link. - // This link doesn't have a unique display for course context so only display it under the user's profile. - if ($issitecourse && $iscurrentuser && has_capability('moodle/user:manageownfiles', $usercontext)) { - $url = new moodle_url('/user/files.php'); - $mainpage->add(get_string('privatefiles'), $url, self::TYPE_SETTING, null, 'privatefiles'); - } - - // Add a node to view the users notes if permitted. - if (!empty($CFG->enablenotes) && - has_any_capability(array('moodle/notes:manage', 'moodle/notes:view'), $coursecontext)) { - $url = new moodle_url('/notes/index.php', array('user' => $user->id)); - if ($coursecontext->instanceid != SITEID) { - $url->param('course', $coursecontext->instanceid); - } - $profilenode->add(get_string('notes', 'notes'), $url); - } - - // Show the grades node. - if (($issitecourse && $iscurrentuser) || has_capability('moodle/user:viewdetails', $usercontext)) { - require_once($CFG->dirroot . '/user/lib.php'); - // Set the grades node to link to the "Grades" page. - if ($course->id == SITEID) { - $url = user_mygrades_url($user->id, $course->id); - } else { // Otherwise we are in a course and should redirect to the user grade report (Activity report version). - $url = new moodle_url('/course/user.php', array('mode' => 'grade', 'id' => $course->id, 'user' => $user->id)); - } - $mainpage->add(get_string('grades', 'grades'), $url, self::TYPE_SETTING, null, 'mygrades'); - } - - // Let plugins hook into user navigation. - $pluginsfunction = get_plugins_with_function('extend_navigation_user', 'lib.php'); - foreach ($pluginsfunction as $plugintype => $plugins) { - if ($plugintype != 'report') { - foreach ($plugins as $pluginfunction) { - $pluginfunction($profilenode, $user, $usercontext, $course, $coursecontext); - } - } - } - - $usersetting = navigation_node::create(get_string('preferences', 'moodle'), $prefurl, self::TYPE_CONTAINER, null, $key); - $mainpage->add_node($usersetting); - } else { - $usersetting = $this->add(get_string('preferences', 'moodle'), $prefurl, self::TYPE_CONTAINER, null, $key); - $usersetting->display = false; - } - $usersetting->id = 'usersettings'; - - // Check if the user has been deleted. - if ($user->deleted) { - if (!has_capability('moodle/user:update', $coursecontext)) { - // We can't edit the user so just show the user deleted message. - $usersetting->add(get_string('userdeleted'), null, self::TYPE_SETTING); - } else { - // We can edit the user so show the user deleted message and link it to the profile. - if ($course->id == $SITE->id) { - $profileurl = new moodle_url('/user/profile.php', array('id'=>$user->id)); - } else { - $profileurl = new moodle_url('/user/view.php', array('id'=>$user->id, 'course'=>$course->id)); - } - $usersetting->add(get_string('userdeleted'), $profileurl, self::TYPE_SETTING); - } - return true; - } - - $userauthplugin = false; - if (!empty($user->auth)) { - $userauthplugin = get_auth_plugin($user->auth); - } - - $useraccount = $usersetting->add(get_string('useraccount'), null, self::TYPE_CONTAINER, null, 'useraccount'); - - // Add the profile edit link. - if (isloggedin() && !isguestuser($user) && !is_mnet_remote_user($user)) { - if (($currentuser || is_siteadmin($USER) || !is_siteadmin($user)) && - has_capability('moodle/user:update', $systemcontext)) { - $url = new moodle_url('/user/editadvanced.php', array('id'=>$user->id, 'course'=>$course->id)); - $useraccount->add(get_string('editmyprofile'), $url, self::TYPE_SETTING, null, 'editprofile'); - } else if ((has_capability('moodle/user:editprofile', $usercontext) && !is_siteadmin($user)) || - ($currentuser && has_capability('moodle/user:editownprofile', $systemcontext))) { - if ($userauthplugin && $userauthplugin->can_edit_profile()) { - $url = $userauthplugin->edit_profile_url(); - if (empty($url)) { - $url = new moodle_url('/user/edit.php', array('id'=>$user->id, 'course'=>$course->id)); - } - $useraccount->add(get_string('editmyprofile'), $url, self::TYPE_SETTING, null, 'editprofile'); - } - } - } - - // Change password link. - if ($userauthplugin && $currentuser && !\core\session\manager::is_loggedinas() && !isguestuser() && - has_capability('moodle/user:changeownpassword', $systemcontext) && $userauthplugin->can_change_password()) { - $passwordchangeurl = $userauthplugin->change_password_url(); - if (empty($passwordchangeurl)) { - $passwordchangeurl = new moodle_url('/login/change_password.php', array('id'=>$course->id)); - } - $useraccount->add(get_string("changepassword"), $passwordchangeurl, self::TYPE_SETTING, null, 'changepassword'); - } - - // Default homepage. - $defaulthomepageuser = (!empty($CFG->defaulthomepage) && ($CFG->defaulthomepage == HOMEPAGE_USER)); - if (isloggedin() && !isguestuser($user) && $defaulthomepageuser) { - if ($currentuser && has_capability('moodle/user:editownprofile', $systemcontext) || - has_capability('moodle/user:editprofile', $usercontext)) { - $url = new moodle_url('/user/defaulthomepage.php', ['id' => $user->id]); - $useraccount->add(get_string('defaulthomepageuser'), $url, self::TYPE_SETTING, null, 'defaulthomepageuser'); - } - } - - if (isloggedin() && !isguestuser($user) && !is_mnet_remote_user($user)) { - if ($currentuser && has_capability('moodle/user:editownprofile', $systemcontext) || - has_capability('moodle/user:editprofile', $usercontext)) { - $url = new moodle_url('/user/language.php', array('id' => $user->id, 'course' => $course->id)); - $useraccount->add(get_string('preferredlanguage'), $url, self::TYPE_SETTING, null, 'preferredlanguage'); - } - } - $pluginmanager = core_plugin_manager::instance(); - $enabled = $pluginmanager->get_enabled_plugins('mod'); - if (isset($enabled['forum']) && isloggedin() && !isguestuser($user) && !is_mnet_remote_user($user)) { - if ($currentuser && has_capability('moodle/user:editownprofile', $systemcontext) || - has_capability('moodle/user:editprofile', $usercontext)) { - $url = new moodle_url('/user/forum.php', array('id' => $user->id, 'course' => $course->id)); - $useraccount->add(get_string('forumpreferences'), $url, self::TYPE_SETTING); - } - } - $editors = editors_get_enabled(); - if (count($editors) > 1) { - if (isloggedin() && !isguestuser($user) && !is_mnet_remote_user($user)) { - if ($currentuser && has_capability('moodle/user:editownprofile', $systemcontext) || - has_capability('moodle/user:editprofile', $usercontext)) { - $url = new moodle_url('/user/editor.php', array('id' => $user->id, 'course' => $course->id)); - $useraccount->add(get_string('editorpreferences'), $url, self::TYPE_SETTING); - } - } - } - - // Add "Calendar preferences" link. - if (isloggedin() && !isguestuser($user)) { - if ($currentuser && has_capability('moodle/user:editownprofile', $systemcontext) || - has_capability('moodle/user:editprofile', $usercontext)) { - $url = new moodle_url('/user/calendar.php', array('id' => $user->id)); - $useraccount->add(get_string('calendarpreferences', 'calendar'), $url, self::TYPE_SETTING, null, 'preferredcalendar'); - } - } - - // Add "Content bank preferences" link. - if (isloggedin() && !isguestuser($user)) { - if ($currentuser && has_capability('moodle/user:editownprofile', $systemcontext) || - has_capability('moodle/user:editprofile', $usercontext)) { - $url = new moodle_url('/user/contentbank.php', ['id' => $user->id]); - $useraccount->add(get_string('contentbankpreferences', 'core_contentbank'), $url, self::TYPE_SETTING, - null, 'contentbankpreferences'); - } - } - - // View the roles settings. - if (has_any_capability(['moodle/role:assign', 'moodle/role:safeoverride', 'moodle/role:override', - 'moodle/role:manage'], $usercontext)) { - $roles = $usersetting->add(get_string('roles'), null, self::TYPE_SETTING); - - $url = new moodle_url('/admin/roles/usersroles.php', ['userid' => $user->id, 'courseid' => $course->id]); - $roles->add(get_string('thisusersroles', 'role'), $url, self::TYPE_SETTING); - - $assignableroles = get_assignable_roles($usercontext, ROLENAME_BOTH); - - if (!empty($assignableroles)) { - $url = new moodle_url('/admin/roles/assign.php', - array('contextid' => $usercontext->id, 'userid' => $user->id, 'courseid' => $course->id)); - $roles->add(get_string('assignrolesrelativetothisuser', 'role'), $url, self::TYPE_SETTING); - } - - if (has_capability('moodle/role:review', $usercontext) || count(get_overridable_roles($usercontext, ROLENAME_BOTH))>0) { - $url = new moodle_url('/admin/roles/permissions.php', - array('contextid' => $usercontext->id, 'userid' => $user->id, 'courseid' => $course->id)); - $roles->add(get_string('permissions', 'role'), $url, self::TYPE_SETTING); - } - - $url = new moodle_url('/admin/roles/check.php', - array('contextid' => $usercontext->id, 'userid' => $user->id, 'courseid' => $course->id)); - $roles->add(get_string('checkpermissions', 'role'), $url, self::TYPE_SETTING); - } - - // Repositories. - if (!$this->cache->cached('contexthasrepos'.$usercontext->id)) { - require_once($CFG->dirroot . '/repository/lib.php'); - $editabletypes = repository::get_editable_types($usercontext); - $haseditabletypes = !empty($editabletypes); - unset($editabletypes); - $this->cache->set('contexthasrepos'.$usercontext->id, $haseditabletypes); - } else { - $haseditabletypes = $this->cache->{'contexthasrepos'.$usercontext->id}; - } - if ($haseditabletypes) { - $repositories = $usersetting->add(get_string('repositories', 'repository'), null, self::TYPE_SETTING); - $repositories->add(get_string('manageinstances', 'repository'), new moodle_url('/repository/manage_instances.php', - array('contextid' => $usercontext->id))); - } - - // Portfolio. - if ($currentuser && !empty($CFG->enableportfolios) && has_capability('moodle/portfolio:export', $systemcontext)) { - require_once($CFG->libdir . '/portfoliolib.php'); - if (portfolio_has_visible_instances()) { - $portfolio = $usersetting->add(get_string('portfolios', 'portfolio'), null, self::TYPE_SETTING); - - $url = new moodle_url('/user/portfolio.php', array('courseid'=>$course->id)); - $portfolio->add(get_string('configure', 'portfolio'), $url, self::TYPE_SETTING); - - $url = new moodle_url('/user/portfoliologs.php', array('courseid'=>$course->id)); - $portfolio->add(get_string('logs', 'portfolio'), $url, self::TYPE_SETTING); - } - } - - $enablemanagetokens = false; - if (!empty($CFG->enablerssfeeds)) { - $enablemanagetokens = true; - } else if (!is_siteadmin($USER->id) - && !empty($CFG->enablewebservices) - && has_capability('moodle/webservice:createtoken', context_system::instance()) ) { - $enablemanagetokens = true; - } - // Security keys. - if ($currentuser && $enablemanagetokens) { - $url = new moodle_url('/user/managetoken.php'); - $useraccount->add(get_string('securitykeys', 'webservice'), $url, self::TYPE_SETTING); - } - - // Messaging. - if (($currentuser && has_capability('moodle/user:editownmessageprofile', $systemcontext)) || (!isguestuser($user) && - has_capability('moodle/user:editmessageprofile', $usercontext) && !is_primary_admin($user->id))) { - $messagingurl = new moodle_url('/message/edit.php', array('id' => $user->id)); - $notificationsurl = new moodle_url('/message/notificationpreferences.php', array('userid' => $user->id)); - $useraccount->add(get_string('messagepreferences', 'message'), $messagingurl, self::TYPE_SETTING); - $useraccount->add(get_string('notificationpreferences', 'message'), $notificationsurl, self::TYPE_SETTING); - } - - // Blogs. - if ($currentuser && !empty($CFG->enableblogs)) { - $blog = $usersetting->add(get_string('blogs', 'blog'), null, navigation_node::TYPE_CONTAINER, null, 'blogs'); - if (has_capability('moodle/blog:view', $systemcontext)) { - $blog->add(get_string('preferences', 'blog'), new moodle_url('/blog/preferences.php'), - navigation_node::TYPE_SETTING); - } - if (!empty($CFG->useexternalblogs) && $CFG->maxexternalblogsperuser > 0 && - has_capability('moodle/blog:manageexternal', $systemcontext)) { - $blog->add(get_string('externalblogs', 'blog'), new moodle_url('/blog/external_blogs.php'), - navigation_node::TYPE_SETTING); - $blog->add(get_string('addnewexternalblog', 'blog'), new moodle_url('/blog/external_blog_edit.php'), - navigation_node::TYPE_SETTING); - } - // Remove the blog node if empty. - $blog->trim_if_empty(); - } - - // Badges. - if ($currentuser && !empty($CFG->enablebadges)) { - $badges = $usersetting->add(get_string('badges'), null, navigation_node::TYPE_CONTAINER, null, 'badges'); - if (has_capability('moodle/badges:manageownbadges', $usercontext)) { - $url = new moodle_url('/badges/mybadges.php'); - $badges->add(get_string('managebadges', 'badges'), $url, self::TYPE_SETTING); - } - $badges->add(get_string('preferences', 'badges'), new moodle_url('/badges/preferences.php'), - navigation_node::TYPE_SETTING); - if (!empty($CFG->badges_allowexternalbackpack)) { - $badges->add(get_string('backpackdetails', 'badges'), new moodle_url('/badges/mybackpack.php'), - navigation_node::TYPE_SETTING); - } - } - - // Let plugins hook into user settings navigation. - $pluginsfunction = get_plugins_with_function('extend_navigation_user_settings', 'lib.php'); - foreach ($pluginsfunction as $plugintype => $plugins) { - foreach ($plugins as $pluginfunction) { - $pluginfunction($usersetting, $user, $usercontext, $course, $coursecontext); - } - } - - return $usersetting; - } - - /** - * Loads block specific settings in the navigation - * - * @return navigation_node - */ - protected function load_block_settings() { - global $CFG; - - $blocknode = $this->add($this->context->get_context_name(), null, self::TYPE_SETTING, null, 'blocksettings'); - $blocknode->force_open(); - - // Assign local roles - if (get_assignable_roles($this->context, ROLENAME_ORIGINAL)) { - $assignurl = new moodle_url('/'.$CFG->admin.'/roles/assign.php', array('contextid' => $this->context->id)); - $blocknode->add(get_string('assignroles', 'role'), $assignurl, self::TYPE_SETTING, null, - 'roles', new pix_icon('i/assignroles', '')); - } - - // Override roles - if (has_capability('moodle/role:review', $this->context) or count(get_overridable_roles($this->context))>0) { - $url = new moodle_url('/'.$CFG->admin.'/roles/permissions.php', array('contextid'=>$this->context->id)); - $blocknode->add(get_string('permissions', 'role'), $url, self::TYPE_SETTING, null, - 'permissions', new pix_icon('i/permissions', '')); - } - // Check role permissions - if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride','moodle/role:override', 'moodle/role:assign'), $this->context)) { - $url = new moodle_url('/'.$CFG->admin.'/roles/check.php', array('contextid'=>$this->context->id)); - $blocknode->add(get_string('checkpermissions', 'role'), $url, self::TYPE_SETTING, null, - 'checkpermissions', new pix_icon('i/checkpermissions', '')); - } - - // Add the context locking node. - $this->add_context_locking_node($blocknode, $this->context); - - return $blocknode; - } - - /** - * Loads category specific settings in the navigation - * - * @return navigation_node - */ - protected function load_category_settings() { - global $CFG; - - // We can land here while being in the context of a block, in which case we - // should get the parent context which should be the category one. See self::initialise(). - if ($this->context->contextlevel == CONTEXT_BLOCK) { - $catcontext = $this->context->get_parent_context(); - } else { - $catcontext = $this->context; - } - - // Let's make sure that we always have the right context when getting here. - if ($catcontext->contextlevel != CONTEXT_COURSECAT) { - throw new coding_exception('Unexpected context while loading category settings.'); - } - - $categorynodetype = navigation_node::TYPE_CONTAINER; - $categorynode = $this->add($catcontext->get_context_name(), null, $categorynodetype, null, 'categorysettings'); - $categorynode->nodetype = navigation_node::NODETYPE_BRANCH; - $categorynode->force_open(); - - if (can_edit_in_category($catcontext->instanceid)) { - $url = new moodle_url('/course/management.php', array('categoryid' => $catcontext->instanceid)); - $editstring = get_string('managecategorythis'); - $node = $categorynode->add($editstring, $url, self::TYPE_SETTING, null, 'managecategory', new pix_icon('i/edit', '')); - $node->set_show_in_secondary_navigation(false); - } - - if (has_capability('moodle/category:manage', $catcontext)) { - $editurl = new moodle_url('/course/editcategory.php', array('id' => $catcontext->instanceid)); - $categorynode->add(get_string('settings'), $editurl, self::TYPE_SETTING, null, 'edit', new pix_icon('i/edit', '')); - - $addsubcaturl = new moodle_url('/course/editcategory.php', array('parent' => $catcontext->instanceid)); - $categorynode->add(get_string('addsubcategory'), $addsubcaturl, self::TYPE_SETTING, null, - 'addsubcat', new pix_icon('i/withsubcat', ''))->set_show_in_secondary_navigation(false); - } - - // Assign local roles - $assignableroles = get_assignable_roles($catcontext); - if (!empty($assignableroles)) { - $assignurl = new moodle_url('/'.$CFG->admin.'/roles/assign.php', array('contextid' => $catcontext->id)); - $categorynode->add(get_string('assignroles', 'role'), $assignurl, self::TYPE_SETTING, null, 'roles', new pix_icon('i/assignroles', '')); - } - - // Override roles - if (has_capability('moodle/role:review', $catcontext) or count(get_overridable_roles($catcontext)) > 0) { - $url = new moodle_url('/'.$CFG->admin.'/roles/permissions.php', array('contextid' => $catcontext->id)); - $categorynode->add(get_string('permissions', 'role'), $url, self::TYPE_SETTING, null, 'permissions', new pix_icon('i/permissions', '')); - } - // Check role permissions - if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride', - 'moodle/role:override', 'moodle/role:assign'), $catcontext)) { - $url = new moodle_url('/'.$CFG->admin.'/roles/check.php', array('contextid' => $catcontext->id)); - $categorynode->add(get_string('checkpermissions', 'role'), $url, self::TYPE_SETTING, null, 'rolecheck', new pix_icon('i/checkpermissions', '')); - } - - // Add the context locking node. - $this->add_context_locking_node($categorynode, $catcontext); - - // Cohorts - if (has_any_capability(array('moodle/cohort:view', 'moodle/cohort:manage'), $catcontext)) { - $categorynode->add(get_string('cohorts', 'cohort'), new moodle_url('/cohort/index.php', - array('contextid' => $catcontext->id)), self::TYPE_SETTING, null, 'cohort', new pix_icon('i/cohort', '')); - } - - // Manage filters - if (has_capability('moodle/filter:manage', $catcontext) && count(filter_get_available_in_context($catcontext)) > 0) { - $url = new moodle_url('/filter/manage.php', array('contextid' => $catcontext->id)); - $categorynode->add(get_string('filters', 'admin'), $url, self::TYPE_SETTING, null, 'filters', new pix_icon('i/filter', '')); - } - - // Restore. - if (has_capability('moodle/restore:restorecourse', $catcontext)) { - $url = new moodle_url('/backup/restorefile.php', array('contextid' => $catcontext->id)); - $categorynode->add(get_string('restorecourse', 'admin'), $url, self::TYPE_SETTING, null, 'restorecourse', new pix_icon('i/restore', '')); - } - - // Let plugins hook into category settings navigation. - $pluginsfunction = get_plugins_with_function('extend_navigation_category_settings', 'lib.php'); - foreach ($pluginsfunction as $plugintype => $plugins) { - foreach ($plugins as $pluginfunction) { - $pluginfunction($categorynode, $catcontext); - } - } - - $cb = new contentbank(); - if ($cb->is_context_allowed($catcontext) - && has_capability('moodle/contentbank:access', $catcontext)) { - $url = new \moodle_url('/contentbank/index.php', ['contextid' => $catcontext->id]); - $categorynode->add(get_string('contentbank'), $url, self::TYPE_CUSTOM, null, - 'contentbank', new \pix_icon('i/contentbank', '')); - } - - return $categorynode; - } - - /** - * Determine whether the user is assuming another role - * - * This function checks to see if the user is assuming another role by means of - * role switching. In doing this we compare each RSW key (context path) against - * the current context path. This ensures that we can provide the switching - * options against both the course and any page shown under the course. - * - * @return bool|int The role(int) if the user is in another role, false otherwise - */ - protected function in_alternative_role() { - global $USER; - if (!empty($USER->access['rsw']) && is_array($USER->access['rsw'])) { - if (!empty($this->page->context) && !empty($USER->access['rsw'][$this->page->context->path])) { - return $USER->access['rsw'][$this->page->context->path]; - } - foreach ($USER->access['rsw'] as $key=>$role) { - if (strpos($this->context->path,$key)===0) { - return $role; - } - } - } - return false; - } - - /** - * This function loads all of the front page settings into the settings navigation. - * This function is called when the user is on the front page, or $COURSE==$SITE - * @param bool $forceopen (optional) - * @return navigation_node - */ - protected function load_front_page_settings($forceopen = false) { - global $SITE, $CFG; - require_once($CFG->dirroot . '/course/lib.php'); - - $course = clone($SITE); - $coursecontext = context_course::instance($course->id); // Course context - $adminoptions = course_get_user_administration_options($course, $coursecontext); - - $frontpage = $this->add(get_string('frontpagesettings'), null, self::TYPE_SETTING, null, 'frontpage'); - if ($forceopen) { - $frontpage->force_open(); - } - $frontpage->id = 'frontpagesettings'; - - if ($this->page->user_allowed_editing() && !$this->page->theme->haseditswitch) { - - // Add the turn on/off settings - $url = new moodle_url('/course/view.php', array('id'=>$course->id, 'sesskey'=>sesskey())); - if ($this->page->user_is_editing()) { - $url->param('edit', 'off'); - $editstring = get_string('turneditingoff'); - } else { - $url->param('edit', 'on'); - $editstring = get_string('turneditingon'); - } - $frontpage->add($editstring, $url, self::TYPE_SETTING, null, null, new pix_icon('i/edit', '')); - } - - if ($adminoptions->update) { - // Add the course settings link - $url = new moodle_url('/admin/settings.php', array('section'=>'frontpagesettings')); - $frontpage->add(get_string('settings'), $url, self::TYPE_SETTING, null, - 'editsettings', new pix_icon('i/settings', '')); - } - - // add enrol nodes - enrol_add_course_navigation($frontpage, $course); - - // Manage filters - if ($adminoptions->filters) { - $url = new moodle_url('/filter/manage.php', array('contextid'=>$coursecontext->id)); - $frontpage->add(get_string('filters', 'admin'), $url, self::TYPE_SETTING, - null, 'filtermanagement', new pix_icon('i/filter', '')); - } - - // View course reports. - if ($adminoptions->reports) { - $frontpagenav = $frontpage->add(get_string('reports'), new moodle_url('/report/view.php', - ['courseid' => $coursecontext->instanceid]), - self::TYPE_CONTAINER, null, 'coursereports', - new pix_icon('i/stats', '')); - $coursereports = core_component::get_plugin_list('coursereport'); - foreach ($coursereports as $report=>$dir) { - $libfile = $CFG->dirroot.'/course/report/'.$report.'/lib.php'; - if (file_exists($libfile)) { - require_once($libfile); - $reportfunction = $report.'_report_extend_navigation'; - if (function_exists($report.'_report_extend_navigation')) { - $reportfunction($frontpagenav, $course, $coursecontext); - } - } - } - - $reports = get_plugin_list_with_function('report', 'extend_navigation_course', 'lib.php'); - foreach ($reports as $reportfunction) { - $reportfunction($frontpagenav, $course, $coursecontext); - } - - if (!$frontpagenav->has_children()) { - $frontpagenav->remove(); - } - } - - // Questions - require_once($CFG->libdir . '/questionlib.php'); - $baseurl = \core_question\local\bank\question_bank_helper::get_url_for_qbank_list($course->id); - question_extend_settings_navigation($frontpage, $coursecontext, $baseurl)->trim_if_empty(); - - // Manage files - if ($adminoptions->files) { - //hiden in new installs - $url = new moodle_url('/files/index.php', array('contextid'=>$coursecontext->id)); - $frontpage->add(get_string('sitelegacyfiles'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/folder', '')); - } - - // Let plugins hook into frontpage navigation. - $pluginsfunction = get_plugins_with_function('extend_navigation_frontpage', 'lib.php'); - foreach ($pluginsfunction as $plugintype => $plugins) { - foreach ($plugins as $pluginfunction) { - $pluginfunction($frontpage, $course, $coursecontext); - } - } - - // Course reuse options. - if ($adminoptions->backup || $adminoptions->restore) { - $coursereusenav = $frontpage->add( - get_string('coursereuse'), - new moodle_url('/backup/view.php', ['id' => $course->id]), - self::TYPE_CONTAINER, null, 'coursereuse', new pix_icon('t/edit', ''), - ); - - // Backup this course. - if ($adminoptions->backup) { - $url = new moodle_url('/backup/backup.php', ['id' => $course->id]); - $coursereusenav->add(get_string('backup'), $url, self::TYPE_SETTING, null, 'backup', new pix_icon('i/backup', '')); - } - - // Restore to this course. - if ($adminoptions->restore) { - $url = new moodle_url('/backup/restorefile.php', ['contextid' => $coursecontext->id]); - $coursereusenav->add( - get_string('restore'), - $url, - self::TYPE_SETTING, - null, - 'restore', - new pix_icon('i/restore', ''), - ); - } - } - - return $frontpage; - } - - /** - * This function gives local plugins an opportunity to modify the settings navigation. - */ - protected function load_local_plugin_settings() { - - foreach (get_plugin_list_with_function('local', 'extend_settings_navigation') as $function) { - $function($this, $this->context); - } - } - - /** - * This function marks the cache as volatile so it is cleared during shutdown - */ - public function clear_cache() { - $this->cache->volatile(); - } - - /** - * Checks to see if there are child nodes available in the specific user's preference node. - * If so, then they have the appropriate permissions view this user's preferences. - * - * @since Moodle 2.9.3 - * @param int $userid The user's ID. - * @return bool True if child nodes exist to view, otherwise false. - */ - public function can_view_user_preferences($userid) { - if (is_siteadmin()) { - return true; - } - // See if any nodes are present in the preferences section for this user. - $preferencenode = $this->find('userviewingsettings' . $userid, null); - if ($preferencenode && $preferencenode->has_children()) { - // Run through each child node. - foreach ($preferencenode->children as $childnode) { - // If the child node has children then this user has access to a link in the preferences page. - if ($childnode->has_children()) { - return true; - } - } - } - // No links found for the user to access on the preferences page. - return false; - } -} - -/** - * Class used to populate site admin navigation for ajax. - * - * @package core - * @category navigation - * @copyright 2013 Rajesh Taneja - * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later - */ -class settings_navigation_ajax extends settings_navigation { - /** - * Constructs the navigation for use in an AJAX request - * - * @param moodle_page $page - */ - public function __construct(moodle_page &$page) { - $this->page = $page; - $this->cache = new navigation_cache(NAVIGATION_CACHE_NAME); - $this->children = new navigation_node_collection(); - $this->initialise(); - } - - /** - * Initialise the site admin navigation. - */ - public function initialise() { - if ($this->initialised || during_initial_install()) { - return false; - } - $this->context = $this->page->context; - $this->load_administration_settings(); - - // Check if local plugins is adding node to site admin. - $this->load_local_plugin_settings(); - - $this->initialised = true; - } -} - -/** - * Simple class used to output a navigation branch in XML - * - * @package core - * @category navigation - * @copyright 2009 Sam Hemelryk - * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later - */ -class navigation_json { - /** @var array An array of different node types */ - protected $nodetype = array('node','branch'); - /** @var array An array of node keys and types */ - protected $expandable = array(); - /** - * Turns a branch and all of its children into XML - * - * @param navigation_node $branch - * @return string XML string - */ - public function convert($branch) { - $xml = $this->convert_child($branch); - return $xml; - } - /** - * Set the expandable items in the array so that we have enough information - * to attach AJAX events - * @param array $expandable - */ - public function set_expandable($expandable) { - foreach ($expandable as $node) { - $this->expandable[$node['key'].':'.$node['type']] = $node; - } - } - /** - * Recusively converts a child node and its children to XML for output - * - * @param navigation_node $child The child to convert - * @param int $depth Pointlessly used to track the depth of the XML structure - * @return string JSON - */ - protected function convert_child($child, $depth=1) { - if (!$child->display) { - return ''; - } - $attributes = array(); - $attributes['id'] = $child->id; - $attributes['name'] = (string)$child->text; // This can be lang_string object so typecast it. - $attributes['type'] = $child->type; - $attributes['key'] = $child->key; - $attributes['class'] = $child->get_css_type(); - $attributes['requiresajaxloading'] = $child->requiresajaxloading; - - if ($child->icon instanceof pix_icon) { - $attributes['icon'] = array( - 'component' => $child->icon->component, - 'pix' => $child->icon->pix, - ); - foreach ($child->icon->attributes as $key=>$value) { - if ($key == 'class') { - $attributes['icon']['classes'] = explode(' ', $value); - } else if (!array_key_exists($key, $attributes['icon'])) { - $attributes['icon'][$key] = $value; - } - - } - } else if (!empty($child->icon)) { - $attributes['icon'] = (string)$child->icon; - } - - if ($child->forcetitle || $child->title !== $child->text) { - $attributes['title'] = htmlentities($child->title ?? '', ENT_QUOTES, 'UTF-8'); - } - if (array_key_exists($child->key.':'.$child->type, $this->expandable)) { - $attributes['expandable'] = $child->key; - $child->add_class($this->expandable[$child->key.':'.$child->type]['id']); - } - - if (count($child->classes)>0) { - $attributes['class'] .= ' '.join(' ',$child->classes); - } - if (is_string($child->action)) { - $attributes['link'] = $child->action; - } else if ($child->action instanceof moodle_url) { - $attributes['link'] = $child->action->out(); - } else if ($child->action instanceof action_link) { - $attributes['link'] = $child->action->url->out(); - } - $attributes['hidden'] = ($child->hidden); - $attributes['haschildren'] = ($child->children->count()>0 || $child->type == navigation_node::TYPE_CATEGORY); - $attributes['haschildren'] = $attributes['haschildren'] || $child->type == navigation_node::TYPE_MY_CATEGORY; - - if ($child->children->count() > 0) { - $attributes['children'] = array(); - foreach ($child->children as $subchild) { - $attributes['children'][] = $this->convert_child($subchild, $depth+1); - } - } - - if ($depth > 1) { - return $attributes; - } else { - return json_encode($attributes); - } - } -} - -/** - * The navigation_cache class is used for global and settings navigation data. - * - * It provides an easy access to the session cache with TTL of 1800 seconds. - * - * Example use: - * - * if (!$cache->viewdiscussion()) { - * // Code to do stuff and produce cachable content - * $cache->viewdiscussion = has_capability('mod/forum:viewdiscussion', $coursecontext); - * } - * $content = $cache->viewdiscussion; - * - * - * @package core - * @category navigation - * @copyright 2009 Sam Hemelryk - * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later - */ -class navigation_cache { - /** @var cache_session The session cache instance */ - protected $cache; - /** @var array The current cache area data */ - protected $session = []; - - /** - * @var string A unique string to segregate this particular cache. - * It can either be unique to start a fresh cache or shared to use an existing cache. - */ - protected $area; - /** @var int cache time information */ - #[\core\attribute\deprecated(null, since: '4.5', reason: 'This constant is no longer needed.', mdl: 'MDL-79628')] - const CACHETIME = 0; - /** @var int cache user id */ - #[\core\attribute\deprecated(null, since: '4.5', reason: 'This constant is no longer needed.', mdl: 'MDL-79628')] - const CACHEUSERID = 1; - /** @var int cache value */ - const CACHEVALUE = 2; - /** @var null|array An array of cache areas to expire on shutdown */ - public static $volatilecaches = null; - - /** - * Contructor for the cache. Requires a area string be passed in. - * - * @param string $area The unique string to segregate this particular cache. - * @param int $timeout Deprecated since Moodle 4.5. The number of seconds to time the information out after - */ - public function __construct($area, $timeout = null) { - if ($timeout !== null) { - debugging( - 'The timeout argument has been deprecated. Please remove it from your method calls.', - DEBUG_DEVELOPER, - ); - } - global $USER; - $this->area = "user_{$USER->id}_{$area}"; - $this->cache = cache::make('core', 'navigation_cache'); - } - - /** - * Ensure the navigation cache is initialised - * - * This is called for each access and ensures that no data is put into the cache before it is required. - */ - protected function ensure_navigation_cache_initialised() { - if (empty($this->session)) { - $this->session = $this->cache->get($this->area); - if (!is_array($this->session)) { - $this->session = []; - } - } - } - - /** - * Magic Method to retrieve a cached item by simply calling using = cache->key - * - * @param mixed $key The identifier for the cached information - * @return mixed|void The cached information or void if not found - */ - public function __get($key) { - if (!$this->cached($key)) { - return; - } - return unserialize($this->session[$key][self::CACHEVALUE]); - } - - /** - * Magic method that simply uses {@see navigation_cache::set()} to store an item in the cache - * - * @param string|int $key The key to store the information against - * @param mixed $information The information to cache - */ - public function __set($key, $information) { - $this->set($key, $information); - } - - /** - * Sets some information in the session cache for later retrieval - * - * @param string|int $key - * @param mixed $information - */ - public function set($key, $information) { - $this->ensure_navigation_cache_initialised(); - $information = serialize($information); - $this->session[$key] = [self::CACHEVALUE => $information]; - $this->cache->set($this->area, $this->session); - } - /** - * Check the existence of the identifier in the cache - * - * @param string|int $key The identifier to check - * @return bool True if the item exists in the cache, false otherwise - */ - public function cached($key) { - $this->ensure_navigation_cache_initialised(); - return isset($this->session[$key]) && - is_array($this->session[$key]); - } - /** - * Compare something to it's equivilant in the cache - * - * @param string $key The key to check - * @param mixed $value The value to compare - * @param bool $serialise Whether to serialise the value before comparison - * this should only be set to false if the value is already - * serialised - * @return bool True if the value is the same as the cached one, false otherwise - */ - public function compare($key, $value, $serialise = true) { - if ($this->cached($key)) { - if ($serialise) { - $value = serialize($value); - } - return $this->session[$key][self::CACHEVALUE] === $value; - } - return false; - } - /** - * Deletes the entire cache area, forcing a fresh cache to be created - */ - public function clear() { - $this->cache->delete($this->area); - $this->session = []; - } - /** - * Marks the cache as volatile (likely to change) - * - * Any caches marked as volatile will be destroyed on shutdown by {@see navigation_node::destroy_volatile_caches()} - * - * @param bool $setting True to mark the cache as volatile, false to remove the volatile flag - */ - public function volatile($setting = true) { - if (self::$volatilecaches === null) { - self::$volatilecaches = []; - core_shutdown_manager::register_function(['navigation_cache', 'destroy_volatile_caches']); - } - - if ($setting) { - self::$volatilecaches[$this->area] = $this->area; - } else if (array_key_exists($this->area, self::$volatilecaches)) { - unset(self::$volatilecaches[$this->area]); - } - } - - /** - * Destroys all caches marked as volatile - * - * This function is static and works with the static volatilecaches property of navigation cache. - * It manually resets the cached areas back to an empty array. - */ - public static function destroy_volatile_caches() { - if (is_array(self::$volatilecaches) && count(self::$volatilecaches) > 0) { - $cache = cache::make('core', 'navigation_cache'); - foreach (self::$volatilecaches as $area) { - $cache->delete($area); - } - self::$volatilecaches = null; - } - } -} From 1b7682d536362ac9cec377de1549fd09665e9680 Mon Sep 17 00:00:00 2001 From: Andrew Nicols Date: Thu, 31 Jul 2025 06:47:28 +0800 Subject: [PATCH 2/4] MDL-82159 core: Update namespace of core navigation --- .upgradenotes/MDL-82159-2025073102000443.yml | 23 + public/lib/classes/component.php | 3 +- .../navigation/breadcrumb_navigation_node.php | 9 + .../classes/navigation/flat_navigation.php | 18 +- .../navigation/flat_navigation_node.php | 8 + .../classes/navigation/global_navigation.php | 139 +-- .../navigation/global_navigation_for_ajax.php | 19 +- public/lib/classes/navigation/navbar.php | 16 + .../classes/navigation/navigation_cache.php | 13 +- .../classes/navigation/navigation_json.php | 13 +- .../classes/navigation/navigation_node.php | 17 +- .../navigation/navigation_node_collection.php | 12 + .../navigation/settings_navigation.php | 197 +++-- .../navigation/settings_navigation_ajax.php | 8 + .../navigation/exposed_global_navigation.php | 47 + .../exposed_settings_navigation.php | 48 + .../navigation/navigation_testcase.php | 64 ++ .../navigation/global_navigation_test.php | 57 ++ public/lib/tests/navigation/navbar_test.php | 79 ++ .../navigation/navigation_cache_test.php | 73 ++ .../navigation_node_collection_test.php | 72 ++ .../tests/navigation/navigation_node_test.php | 431 +++++++++ .../tests/navigation/output/primary_test.php | 4 +- .../navigation/settings_navigation_test.php | 108 +++ public/lib/tests/navigationlib_test.php | 824 ------------------ 25 files changed, 1323 insertions(+), 979 deletions(-) create mode 100644 .upgradenotes/MDL-82159-2025073102000443.yml create mode 100644 public/lib/tests/classes/navigation/exposed_global_navigation.php create mode 100644 public/lib/tests/classes/navigation/exposed_settings_navigation.php create mode 100644 public/lib/tests/classes/navigation/navigation_testcase.php create mode 100644 public/lib/tests/navigation/global_navigation_test.php create mode 100644 public/lib/tests/navigation/navbar_test.php create mode 100644 public/lib/tests/navigation/navigation_cache_test.php create mode 100644 public/lib/tests/navigation/navigation_node_collection_test.php create mode 100644 public/lib/tests/navigation/navigation_node_test.php create mode 100644 public/lib/tests/navigation/settings_navigation_test.php delete mode 100644 public/lib/tests/navigationlib_test.php diff --git a/.upgradenotes/MDL-82159-2025073102000443.yml b/.upgradenotes/MDL-82159-2025073102000443.yml new file mode 100644 index 00000000000..65483be96a9 --- /dev/null +++ b/.upgradenotes/MDL-82159-2025073102000443.yml @@ -0,0 +1,23 @@ +issueNumber: MDL-82159 +notes: + core: + - message: |+ + The following classes have been renamed and now support autoloading. + Existing classes are currently unaffected. + + | Old class name | New class name | + | --- | --- | + | `\breadcrumb_navigation_node` | `\core\navigation\breadcrumb_navigation_node` | + | `\flat_navigation_node` | `\core\navigation\flat_navigation_node` | + | `\flat_navigation` | `\core\navigation\flat_navigation_node` | + | `\global_navigation_for_ajax` | `\core\navigation\global_navigation_for_ajax` | + | `\global_navigation` | `\core\navigation\global_navigation` | + | `\navbar` | `\core\navigation\navbar` | + | `\navigation_cache` | `\core\navigation\navigation_cache` | + | `\navigation_json` | `\core\navigation\navigation_json` | + | `\navigation_node_collection` | `\core\navigation\navigation_node_collection` | + | `\navigation_node` | `\core\navigation\navigation_node` | + | `\settings_navigation_for_ajax` | `\core\navigation\settings_navigation_for_ajax` | + | `\settings_navigation` | `\core\navigation\settings_navigation` | + + type: improved diff --git a/public/lib/classes/component.php b/public/lib/classes/component.php index 237e5f7bddc..ea38ed37fc3 100644 --- a/public/lib/classes/component.php +++ b/public/lib/classes/component.php @@ -548,7 +548,8 @@ class component { // Always keep moodle_exception in place. $keyclasses = [ \core\exception\moodle_exception::class, - \core_course\section_info::class, + \core\navigation\navbar::class, + \core\navigation\navigation_node::class, ]; foreach ($keyclasses as $classname) { if (!array_key_exists($classname, $cache['classmap'])) { diff --git a/public/lib/classes/navigation/breadcrumb_navigation_node.php b/public/lib/classes/navigation/breadcrumb_navigation_node.php index e688005e26b..7a20eee304b 100644 --- a/public/lib/classes/navigation/breadcrumb_navigation_node.php +++ b/public/lib/classes/navigation/breadcrumb_navigation_node.php @@ -14,6 +14,10 @@ // You should have received a copy of the GNU General Public License // along with Moodle. If not, see . +namespace core\navigation; + +use core\exception\coding_exception; + /** * Subclass of navigation_node allowing different rendering for the breadcrumbs * in particular adding extra metadata for search engine robots to leverage. @@ -64,3 +68,8 @@ class breadcrumb_navigation_node extends navigation_node { $this->last = $val; } } + +// Alias this class to the old name. +// This file will be autoloaded by the legacyclasses autoload system. +// In future all uses of this class will be corrected and the legacy references will be removed. +class_alias(breadcrumb_navigation_node::class, \breadcrumb_navigation_node::class); diff --git a/public/lib/classes/navigation/flat_navigation.php b/public/lib/classes/navigation/flat_navigation.php index 6cc053b8835..c97fbb533de 100644 --- a/public/lib/classes/navigation/flat_navigation.php +++ b/public/lib/classes/navigation/flat_navigation.php @@ -14,6 +14,13 @@ // You should have received a copy of the GNU General Public License // along with Moodle. If not, see . +namespace core\navigation; + +use core\context\course as context_course; +use core\context_helper; +use core\url; +use moodle_page; + /** * Class used to generate a collection of navigation nodes most closely related * to the current page. @@ -59,10 +66,10 @@ class flat_navigation extends navigation_node_collection { // First walk the nav tree looking for "flat_navigation" nodes. if ($course->id > 1) { // It's a real course. - $url = new moodle_url('/course/view.php', array('id' => $course->id)); + $url = new url('/course/view.php', array('id' => $course->id)); $coursecontext = context_course::instance($course->id, MUST_EXIST); - $displaycontext = \context_helper::get_navigation_filter_context($coursecontext); + $displaycontext = context_helper::get_navigation_filter_context($coursecontext); // This is the name that will be shown for the course. $coursename = empty($CFG->navshowfullcoursenames) ? format_string($course->shortname, true, ['context' => $displaycontext]) : @@ -119,7 +126,7 @@ class flat_navigation extends navigation_node_collection { if (isset($this->page->theme->addblockposition) && $this->page->theme->addblockposition == BLOCK_ADDBLOCK_POSITION_FLATNAV && $PAGE->user_is_editing() && $PAGE->user_can_edit_blocks()) { - $url = new moodle_url($PAGE->url, ['bui_addblock' => '', 'sesskey' => sesskey()]); + $url = new url($PAGE->url, ['bui_addblock' => '', 'sesskey' => sesskey()]); $addablock = navigation_node::create(get_string('addblock'), $url); $flat = new flat_navigation_node($addablock, 0); $flat->set_showdivider(true, get_string('blocksaddedit')); @@ -154,3 +161,8 @@ class flat_navigation extends navigation_node_collection { return $result; } } + +// Alias this class to the old name. +// This file will be autoloaded by the legacyclasses autoload system. +// In future all uses of this class will be corrected and the legacy references will be removed. +class_alias(flat_navigation::class, \flat_navigation::class); diff --git a/public/lib/classes/navigation/flat_navigation_node.php b/public/lib/classes/navigation/flat_navigation_node.php index da1ec134121..20f74daa52b 100644 --- a/public/lib/classes/navigation/flat_navigation_node.php +++ b/public/lib/classes/navigation/flat_navigation_node.php @@ -14,6 +14,9 @@ // You should have received a copy of the GNU General Public License // along with Moodle. If not, see . +namespace core\navigation; + +use core\exception\coding_exception; /** * Subclass of navigation_node allowing different rendering for the flat navigation @@ -149,3 +152,8 @@ class flat_navigation_node extends navigation_node { $this->indent = $val; } } + +// Alias this class to the old name. +// This file will be autoloaded by the legacyclasses autoload system. +// In future all uses of this class will be corrected and the legacy references will be removed. +class_alias(flat_navigation_node::class, \flat_navigation_node::class); diff --git a/public/lib/classes/navigation/global_navigation.php b/public/lib/classes/navigation/global_navigation.php index 97bd2a902ff..5804af2a79d 100644 --- a/public/lib/classes/navigation/global_navigation.php +++ b/public/lib/classes/navigation/global_navigation.php @@ -14,6 +14,29 @@ // You should have received a copy of the GNU General Public License // along with Moodle. If not, see . +namespace core\navigation; + +use cm_info; +use section_info; +use core\component; +use core\context\course as context_course; +use core\context\coursecat as context_coursecat; +use core\context\module as context_module; +use core\context\system as context_system; +use core\context\user as context_user; +use core\context_helper; +use core\exception\coding_exception; +use core\output\action_link; +use core\output\actions\component_action; +use core\output\pix_icon; +use core\url; +use core_cache\cache; +use core_cache\session_cache; +use core_course_category; +use course_modinfo; +use moodle_page; +use stdClass; + /** * The global navigation class used for... the global navigation * @@ -58,7 +81,7 @@ class global_navigation extends navigation_node { protected $expansionlimit = 0; /** @var int userid to allow parent to see child's profile page navigation */ protected $useridtouseforparentchecks = 0; - /** @var cache_session A cache that stores information on expanded courses */ + /** @var session_cache A cache that stores information on expanded courses */ protected $cacheexpandcourse = null; /** Used when loading categories to load all top level categories [parent = 0] **/ @@ -85,7 +108,7 @@ class global_navigation extends navigation_node { 'key' => 'myhome', 'type' => navigation_node::TYPE_SYSTEM, 'text' => get_string('myhome'), - 'action' => new moodle_url('/my/'), + 'action' => new url('/my/'), 'icon' => new pix_icon('i/dashboard', ''), ); } else if ($homepage == HOMEPAGE_MYCOURSES) { @@ -94,7 +117,7 @@ class global_navigation extends navigation_node { 'key' => 'mycourses', 'type' => navigation_node::TYPE_SYSTEM, 'text' => get_string('mycourses'), - 'action' => new moodle_url('/my/courses.php'), + 'action' => new url('/my/courses.php'), 'icon' => new pix_icon('i/course', '') ); } else { @@ -103,7 +126,7 @@ class global_navigation extends navigation_node { 'key' => 'home', 'type' => navigation_node::TYPE_SYSTEM, 'text' => get_string('home'), - 'action' => new moodle_url('/'), + 'action' => new url('/'), 'icon' => new pix_icon('i/home', ''), ); } @@ -166,14 +189,14 @@ class global_navigation extends navigation_node { if (isloggedin() && !isguestuser()) { // Makes no sense if you aren't logged in if (!empty($CFG->enabledashboard)) { // Only add dashboard to home if it's enabled. - $this->rootnodes['home'] = $this->add(get_string('myhome'), new moodle_url('/my/'), + $this->rootnodes['home'] = $this->add(get_string('myhome'), new url('/my/'), self::TYPE_SETTING, null, 'myhome', new pix_icon('i/dashboard', '')); $this->rootnodes['home']->showinflatnavigation = true; } } } else { // The home element should be the site because the root node is my moodle - $this->rootnodes['home'] = $this->add(get_string('sitehome'), new moodle_url('/'), + $this->rootnodes['home'] = $this->add(get_string('sitehome'), new url('/'), self::TYPE_SETTING, null, 'home', new pix_icon('i/home', '')); $this->rootnodes['home']->showinflatnavigation = true; if (!empty($CFG->defaulthomepage) && @@ -187,7 +210,7 @@ class global_navigation extends navigation_node { $this->rootnodes['currentcourse'] = $this->add(get_string('currentcourse'), null, self::TYPE_ROOTNODE, null, 'currentcourse'); $this->rootnodes['mycourses'] = $this->add( get_string('mycourses'), - new moodle_url('/my/courses.php'), + new url('/my/courses.php'), self::TYPE_ROOTNODE, null, 'mycourses', @@ -199,7 +222,7 @@ class global_navigation extends navigation_node { $this->rootnodes['mycourses']->mainnavonly = true; } - $this->rootnodes['courses'] = $this->add(get_string('courses'), new moodle_url('/course/index.php'), self::TYPE_ROOTNODE, null, 'courses'); + $this->rootnodes['courses'] = $this->add(get_string('courses'), new url('/course/index.php'), self::TYPE_ROOTNODE, null, 'courses'); if (!core_course_category::user_top()) { $this->rootnodes['courses']->hide(); } @@ -487,7 +510,6 @@ class global_navigation extends navigation_node { /** * Loads the courses in Moodle into the navigation. * - * @global moodle_database $DB * @param string|array $categoryids An array containing categories to load courses * for, OR null to load courses for all categories. * @return array An array of navigation_nodes one for each course @@ -842,7 +864,7 @@ class global_navigation extends navigation_node { $excessivecategories = $DB->get_records_sql($sql, $params); foreach ($categories as &$category) { if (array_key_exists($category->key, $excessivecategories) && !$this->can_add_more_courses_to_category($category)) { - $url = new moodle_url('/course/index.php', array('categoryid' => $category->key)); + $url = new url('/course/index.php', array('categoryid' => $category->key)); $category->add(get_string('viewallcourses'), $url, self::TYPE_SETTING); } } @@ -864,8 +886,8 @@ class global_navigation extends navigation_node { return; } $canview = core_course_category::can_view_category($category); - $url = $canview ? new moodle_url('/course/index.php', array('categoryid' => $category->id)) : null; - $context = \context_helper::get_navigation_filter_context(context_coursecat::instance($category->id)); + $url = $canview ? new url('/course/index.php', array('categoryid' => $category->id)) : null; + $context = context_helper::get_navigation_filter_context(context_coursecat::instance($category->id)); $categoryname = $canview ? format_string($category->name, true, ['context' => $context]) : get_string('categoryhidden'); $categorynode = $parent->add($categoryname, $url, $nodetype, $categoryname, $category->id); @@ -1057,10 +1079,10 @@ class global_navigation extends navigation_node { * Returns true if the section is included in the breadcrumb. * * @param section_info $section - * @param moodle_url|null $sectionurl + * @param url|null $sectionurl * @return bool */ - protected function is_section_in_breadcrumb(section_info $section, ?moodle_url $sectionurl): bool { + protected function is_section_in_breadcrumb(section_info $section, ?url $sectionurl): bool { // Ajax requests uses includesectionnum as param. if ($this->includesectionnum !== false && $this->includesectionnum == $section->sectionnum) { return true; @@ -1193,7 +1215,7 @@ class global_navigation extends navigation_node { ); // Prepare the default name and url for the node. - $displaycontext = \context_helper::get_navigation_filter_context(context_module::instance($activitydata->id)); + $displaycontext = context_helper::get_navigation_filter_context(context_module::instance($activitydata->id)); $activityname = format_string($activitydata->name, true, ['context' => $displaycontext]); $activitynode = $sectionnode->add( @@ -1216,13 +1238,13 @@ class global_navigation extends navigation_node { * * @param stdClass $activitydata The acitivy navigation data generated from generate_sections_and_activities * @param string $activityname - * @return moodle_url|action_link + * @return url|action_link */ - protected function get_activity_action(stdClass $activitydata, string $activityname): moodle_url|action_link { + protected function get_activity_action(stdClass $activitydata, string $activityname): url|action_link { // A static counter for JS function naming. static $legacyonclickcounter = 0; - $action = new moodle_url($activitydata->url); + $action = new url($activitydata->url); // Check if the onclick property is set (puke!). if (!empty($activitydata->onclick)) { @@ -1408,14 +1430,14 @@ class global_navigation extends navigation_node { if (!$issitecourse) { // Not the current user so add it to the participants node for the current course. $usersnode = $coursenode->get('participants', navigation_node::TYPE_CONTAINER); - $userviewurl = new moodle_url('/user/view.php', $baseargs); + $userviewurl = new url('/user/view.php', $baseargs); } else if ($USER->id != $user->id) { // This is the site so add a users node to the root branch. $usersnode = $this->rootnodes['users']; if (course_can_view_participants($coursecontext)) { - $usersnode->action = new moodle_url('/user/index.php', array('id' => $course->id)); + $usersnode->action = new url('/user/index.php', array('id' => $course->id)); } - $userviewurl = new moodle_url('/user/profile.php', $baseargs); + $userviewurl = new url('/user/profile.php', $baseargs); } if (!$usersnode) { // We should NEVER get here, if the course hasn't been populated @@ -1460,9 +1482,9 @@ class global_navigation extends navigation_node { if ($iscurrentuser || has_capability('moodle/user:viewdetails', $coursecontext) || has_capability('moodle/user:viewdetails', $usercontext)) { if ($issitecourse || ($iscurrentuser && !$forceforcontext)) { - $usernode->add(get_string('viewprofile'), new moodle_url('/user/profile.php', $baseargs)); + $usernode->add(get_string('viewprofile'), new url('/user/profile.php', $baseargs)); } else { - $usernode->add(get_string('viewprofile'), new moodle_url('/user/view.php', $baseargs)); + $usernode->add(get_string('viewprofile'), new url('/user/view.php', $baseargs)); } } @@ -1497,21 +1519,21 @@ class global_navigation extends navigation_node { if ($USER->id != $user->id) { $messageargs['user2'] = $user->id; } - $url = new moodle_url('/message/index.php', $messageargs); + $url = new url('/message/index.php', $messageargs); $usernode->add(get_string('messages', 'message'), $url, self::TYPE_SETTING, null, 'messages'); } // Add the "My private files" link. // This link doesn't have a unique display for course context so only display it under the user's profile. if ($issitecourse && $iscurrentuser && has_capability('moodle/user:manageownfiles', $usercontext)) { - $url = new moodle_url('/user/files.php'); + $url = new url('/user/files.php'); $usernode->add(get_string('privatefiles'), $url, self::TYPE_SETTING, null, 'privatefiles'); } // Add a node to view the users notes if permitted. if (!empty($CFG->enablenotes) && has_any_capability(array('moodle/notes:manage', 'moodle/notes:view'), $coursecontext)) { - $url = new moodle_url('/notes/index.php', array('user' => $user->id)); + $url = new url('/notes/index.php', array('user' => $user->id)); if ($coursecontext->instanceid != SITEID) { $url->param('course', $coursecontext->instanceid); } @@ -1525,7 +1547,7 @@ class global_navigation extends navigation_node { if ($course->id == SITEID) { $url = user_mygrades_url($user->id, $course->id); } else { // Otherwise we are in a course and should redirect to the user grade report (Activity report version). - $url = new moodle_url('/course/user.php', array('mode' => 'grade', 'id' => $course->id, 'user' => $user->id)); + $url = new url('/course/user.php', array('mode' => 'grade', 'id' => $course->id, 'user' => $user->id)); } if ($USER->id != $user->id) { $usernode->add(get_string('grades', 'grades'), $url, self::TYPE_SETTING, null, 'usergrades'); @@ -1542,7 +1564,7 @@ class global_navigation extends navigation_node { (!in_array('mycourses', $hiddenfields) || has_capability('moodle/user:viewhiddendetails', $coursecontext))) { // Add view grade report is permitted. - $reports = core_component::get_plugin_list('gradereport'); + $reports = component::get_plugin_list('gradereport'); arsort($reports); // User is last, we want to test it first. $userscourses = enrol_get_users_courses($user->id, false, '*'); @@ -1551,14 +1573,14 @@ class global_navigation extends navigation_node { $count = 0; foreach ($userscourses as $usercourse) { if ($count === (int)$CFG->navcourselimit) { - $url = new moodle_url('/user/profile.php', array('id' => $user->id, 'showallcourses' => 1)); + $url = new url('/user/profile.php', array('id' => $user->id, 'showallcourses' => 1)); $userscoursesnode->add(get_string('showallcourses'), $url); break; } $count++; $usercoursecontext = context_course::instance($usercourse->id); $usercourseshortname = format_string($usercourse->shortname, true, array('context' => $usercoursecontext)); - $usercoursenode = $userscoursesnode->add($usercourseshortname, new moodle_url('/user/view.php', + $usercoursenode = $userscoursesnode->add($usercourseshortname, new url('/user/view.php', array('id' => $user->id, 'course' => $usercourse->id)), self::TYPE_CONTAINER); $gradeavailable = has_capability('moodle/grade:view', $usercoursecontext); @@ -1573,7 +1595,7 @@ class global_navigation extends navigation_node { } if ($gradeavailable) { - $url = new moodle_url('/grade/report/index.php', array('id' => $usercourse->id)); + $url = new url('/grade/report/index.php', array('id' => $usercourse->id)); $usercoursenode->add(get_string('grades'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/grades', '')); } @@ -1581,12 +1603,12 @@ class global_navigation extends navigation_node { // Add a node to view the users notes if permitted. if (!empty($CFG->enablenotes) && has_any_capability(array('moodle/notes:manage', 'moodle/notes:view'), $usercoursecontext)) { - $url = new moodle_url('/notes/index.php', array('user' => $user->id, 'course' => $usercourse->id)); + $url = new url('/notes/index.php', array('user' => $user->id, 'course' => $usercourse->id)); $usercoursenode->add(get_string('notes', 'notes'), $url, self::TYPE_SETTING); } if (can_access_course($usercourse, $user->id, '', true)) { - $usercoursenode->add(get_string('entercourse'), new moodle_url('/course/view.php', + $usercoursenode->add(get_string('entercourse'), new url('/course/view.php', array('id' => $usercourse->id)), self::TYPE_SETTING, null, null, new pix_icon('i/course', '')); } @@ -1680,7 +1702,7 @@ class global_navigation extends navigation_node { } $issite = ($course->id == $SITE->id); - $displaycontext = \context_helper::get_navigation_filter_context($coursecontext); + $displaycontext = context_helper::get_navigation_filter_context($coursecontext); $shortname = format_string($course->shortname, true, ['context' => $displaycontext]); $fullname = format_string($course->fullname, true, ['context' => $displaycontext]); // This is the name that will be shown for the course. @@ -1704,7 +1726,7 @@ class global_navigation extends navigation_node { } } else if ($coursetype == self::COURSE_CURRENT) { $parent = $this->rootnodes['currentcourse']; - $url = new moodle_url('/course/view.php', array('id'=>$course->id)); + $url = new url('/course/view.php', array('id'=>$course->id)); $canexpandcourse = $this->can_expand_course($course); } else if ($coursetype == self::COURSE_MY && !$forcegeneric) { if (!empty($CFG->navshowmycoursecategories) && ($parent = $this->rootnodes['mycourses']->find($course->category, self::TYPE_MY_CATEGORY))) { @@ -1712,10 +1734,10 @@ class global_navigation extends navigation_node { } else { $parent = $this->rootnodes['mycourses']; } - $url = new moodle_url('/course/view.php', array('id'=>$course->id)); + $url = new url('/course/view.php', array('id'=>$course->id)); } else { $parent = $this->rootnodes['courses']; - $url = new moodle_url('/course/view.php', array('id'=>$course->id)); + $url = new url('/course/view.php', array('id'=>$course->id)); // They can only expand the course if they can access it. $canexpandcourse = $this->can_expand_course($course); if (!empty($course->category) && $this->show_categories($coursetype == self::COURSE_MY)) { @@ -1755,7 +1777,7 @@ class global_navigation extends navigation_node { /** * Returns a cache instance to use for the expand course cache. - * @return cache_session + * @return session_cache */ protected function get_expand_course_cache() { if ($this->cacheexpandcourse === null) { @@ -1827,11 +1849,11 @@ class global_navigation extends navigation_node { //Participants if ($navoptions->participants) { - $participants = $coursenode->add(get_string('participants'), new moodle_url('/user/index.php?id='.$course->id), + $participants = $coursenode->add(get_string('participants'), new url('/user/index.php?id='.$course->id), self::TYPE_CONTAINER, get_string('participants'), 'participants', new pix_icon('i/users', '')); if ($navoptions->blogs) { - $blogsurls = new moodle_url('/blog/index.php'); + $blogsurls = new url('/blog/index.php'); if ($currentgroup = groups_get_course_group($course, true)) { $blogsurls->param('groupid', $currentgroup); } else { @@ -1841,7 +1863,7 @@ class global_navigation extends navigation_node { } if ($navoptions->notes) { - $participants->add(get_string('notes', 'notes'), new moodle_url('/notes/index.php', array('filtertype' => 'course', 'filterselect' => $course->id)), self::TYPE_SETTING, null, 'currentcoursenotes'); + $participants->add(get_string('notes', 'notes'), new url('/notes/index.php', array('filtertype' => 'course', 'filterselect' => $course->id)), self::TYPE_SETTING, null, 'currentcoursenotes'); } } else if (count($this->extendforuser) > 0) { $coursenode->add(get_string('participants'), null, self::TYPE_CONTAINER, get_string('participants'), 'participants'); @@ -1852,7 +1874,7 @@ class global_navigation extends navigation_node { // Badges. if ($navoptions->badges) { - $url = new moodle_url('/badges/index.php', ['type' => 2, 'id' => $course->id]); + $url = new url('/badges/index.php', ['type' => 2, 'id' => $course->id]); $coursenode->add(get_string('coursebadges', 'badges'), $url, navigation_node::TYPE_SETTING, null, 'badgesview', @@ -1863,12 +1885,12 @@ class global_navigation extends navigation_node { if ($navoptions->competencies) { // Just a link to course competency. $title = get_string('competencies', 'core_competency'); - $path = new moodle_url("/admin/tool/lp/coursecompetencies.php", array('courseid' => $course->id)); + $path = new url("/admin/tool/lp/coursecompetencies.php", array('courseid' => $course->id)); $coursenode->add($title, $path, navigation_node::TYPE_SETTING, null, 'competencies', new pix_icon('i/competencies', '')); } if ($navoptions->grades) { - $url = new moodle_url('/grade/report/index.php', array('id'=>$course->id)); + $url = new url('/grade/report/index.php', array('id'=>$course->id)); $gradenode = $coursenode->add(get_string('grades'), $url, self::TYPE_SETTING, null, 'grades', new pix_icon('i/grades', '')); // If the page type matches the grade part, then make the nav drawer grade node (incl. all sub pages) active. @@ -1879,7 +1901,7 @@ class global_navigation extends navigation_node { // Add link for configuring communication. if ($navoptions->communication) { - $url = new moodle_url('/communication/configure.php', [ + $url = new url('/communication/configure.php', [ 'contextid' => \core\context\course::instance($course->id)->id, 'instanceid' => $course->id, 'instancetype' => 'coursecommunication', @@ -1892,7 +1914,7 @@ class global_navigation extends navigation_node { if ($navoptions->overview) { $coursenode->add( text: get_string('activities'), - action: new moodle_url('/course/overview.php', ['id' => $course->id]), + action: new url('/course/overview.php', ['id' => $course->id]), type: self::TYPE_CONTAINER, key: 'courseoverview', icon: new pix_icon('i/info', ''), @@ -1928,17 +1950,17 @@ class global_navigation extends navigation_node { $coursenode->add('frontpageloaded', null, self::TYPE_CUSTOM, null, 'frontpageloaded')->display = false; // Add My courses to the site pages within the navigation structure so the block can read it. - $coursenode->add(get_string('mycourses'), new moodle_url('/my/courses.php'), self::TYPE_CUSTOM, null, 'mycourses'); + $coursenode->add(get_string('mycourses'), new url('/my/courses.php'), self::TYPE_CUSTOM, null, 'mycourses'); // Participants. if ($navoptions->participants) { - $coursenode->add(get_string('participants'), new moodle_url('/user/index.php?id='.$course->id), + $coursenode->add(get_string('participants'), new url('/user/index.php?id='.$course->id), self::TYPE_CUSTOM, get_string('participants'), 'participants'); } // Blogs. if ($navoptions->blogs) { - $blogsurls = new moodle_url('/blog/index.php'); + $blogsurls = new url('/blog/index.php'); $coursenode->add(get_string('blogssite', 'blog'), $blogsurls->out(), self::TYPE_SYSTEM, null, 'siteblog'); } @@ -1946,32 +1968,32 @@ class global_navigation extends navigation_node { // Badges. if ($navoptions->badges) { - $url = new moodle_url($CFG->wwwroot . '/badges/index.php', ['type' => 1]); + $url = new url($CFG->wwwroot . '/badges/index.php', ['type' => 1]); $coursenode->add(get_string('sitebadges', 'badges'), $url, navigation_node::TYPE_CUSTOM); } // Notes. if ($navoptions->notes) { - $coursenode->add(get_string('notes', 'notes'), new moodle_url('/notes/index.php', + $coursenode->add(get_string('notes', 'notes'), new url('/notes/index.php', array('filtertype' => 'course', 'filterselect' => $filterselect)), self::TYPE_SETTING, null, 'notes'); } // Tags if ($navoptions->tags) { - $node = $coursenode->add(get_string('tags', 'tag'), new moodle_url('/tag/search.php'), + $node = $coursenode->add(get_string('tags', 'tag'), new url('/tag/search.php'), self::TYPE_SETTING, null, 'tags'); } // Search. if ($navoptions->search) { - $node = $coursenode->add(get_string('search', 'search'), new moodle_url('/search/index.php'), + $node = $coursenode->add(get_string('search', 'search'), new url('/search/index.php'), self::TYPE_SETTING, null, 'search'); } if (isloggedin()) { $usercontext = context_user::instance($USER->id); if (has_capability('moodle/user:manageownfiles', $usercontext)) { - $url = new moodle_url('/user/files.php'); + $url = new url('/user/files.php'); $node = $coursenode->add(get_string('privatefiles'), $url, self::TYPE_SETTING, null, 'privatefiles', new pix_icon('i/privatefiles', '')); $node->display = false; @@ -2004,7 +2026,7 @@ class global_navigation extends navigation_node { $params = ['contextid' => $context->id]; if (has_capability('moodle/contentbank:access', $context)) { - $url = new moodle_url('/contentbank/index.php', $params); + $url = new url('/contentbank/index.php', $params); $node = $coursenode->add(get_string('contentbank'), $url, self::TYPE_CUSTOM, null, 'contentbank', new pix_icon('i/contentbank', '')); $node->showinflatnavigation = true; @@ -2224,7 +2246,7 @@ class global_navigation extends navigation_node { // Show a link to the course page if there are more courses the user is enrolled in. if ($showmorelinkinnav || $showmorelinkinflatnav) { // Adding hash to URL so the link is not highlighted in the navigation when clicked. - $url = new moodle_url('/my/courses.php'); + $url = new url('/my/courses.php'); $parent = $this->rootnodes['mycourses']; $coursenode = $parent->add(get_string('morenavigationlinks'), $url, self::TYPE_CUSTOM, null, self::COURSE_INDEX_PAGE); @@ -2238,3 +2260,8 @@ class global_navigation extends navigation_node { } } } + +// Alias this class to the old name. +// This file will be autoloaded by the legacyclasses autoload system. +// In future all uses of this class will be corrected and the legacy references will be removed. +class_alias(global_navigation::class, \global_navigation::class); diff --git a/public/lib/classes/navigation/global_navigation_for_ajax.php b/public/lib/classes/navigation/global_navigation_for_ajax.php index b0fc9d27904..181762cf9af 100644 --- a/public/lib/classes/navigation/global_navigation_for_ajax.php +++ b/public/lib/classes/navigation/global_navigation_for_ajax.php @@ -14,6 +14,14 @@ // You should have received a copy of the GNU General Public License // along with Moodle. If not, see . +namespace core\navigation; + +use core\context\module as context_module; +use core\context\course as context_course; +use core\context_helper; +use core\url; +use moodle_page; + /** * The global navigation class used especially for AJAX requests. * @@ -72,7 +80,7 @@ class global_navigation_for_ajax extends global_navigation { $this->rootnodes['site'] = $this->add_course($SITE); $this->rootnodes['mycourses'] = $this->add( get_string('mycourses'), - new moodle_url('/my/courses.php'), + new url('/my/courses.php'), self::TYPE_ROOTNODE, null, 'mycourses' @@ -142,7 +150,7 @@ class global_navigation_for_ajax extends global_navigation { } break; default: - throw new Exception('Unknown type'); + throw new \Exception('Unknown type'); return $this->expandable; } @@ -172,10 +180,8 @@ class global_navigation_for_ajax extends global_navigation { * This is because with the AJAX navigation we know exactly what is wanted and only need to * request that. * - * @global moodle_database $DB * @param int $categoryid id of category to load in navigation. * @param int $nodetype type of node, if category is under MyHome then it's TYPE_MY_CATEGORY - * @return void. */ protected function load_category($categoryid, $nodetype = self::TYPE_CATEGORY) { global $CFG, $DB; @@ -276,3 +282,8 @@ class global_navigation_for_ajax extends global_navigation { return $this->expandable; } } + +// Alias this class to the old name. +// This file will be autoloaded by the legacyclasses autoload system. +// In future all uses of this class will be corrected and the legacy references will be removed. +class_alias(global_navigation_for_ajax::class, \global_navigation_for_ajax::class); diff --git a/public/lib/classes/navigation/navbar.php b/public/lib/classes/navigation/navbar.php index 9fec988e835..d747ae80ca3 100644 --- a/public/lib/classes/navigation/navbar.php +++ b/public/lib/classes/navigation/navbar.php @@ -14,6 +14,17 @@ // You should have received a copy of the GNU General Public License // along with Moodle. If not, see . +namespace core\navigation; + +use core\context\course as context_course; +use core\context_helper; +use core_course_category; +use core\context\coursecat as context_coursecat; +use core\output\action_link; +use core\output\pix_icon; +use core\url; +use moodle_page; + /** * Navbar class * @@ -369,3 +380,8 @@ class navbar extends navigation_node { return $this; } } + +// Alias this class to the old name. +// This file will be autoloaded by the legacyclasses autoload system. +// In future all uses of this class will be corrected and the legacy references will be removed. +class_alias(navbar::class, \navbar::class); diff --git a/public/lib/classes/navigation/navigation_cache.php b/public/lib/classes/navigation/navigation_cache.php index 4ce73eb36ce..dc9cec5244f 100644 --- a/public/lib/classes/navigation/navigation_cache.php +++ b/public/lib/classes/navigation/navigation_cache.php @@ -14,6 +14,12 @@ // You should have received a copy of the GNU General Public License // along with Moodle. If not, see . +namespace core\navigation; + +use core_cache\cache; +use core_cache\session_cache; +use core_shutdown_manager; + /** * Class navigation_cache * @@ -41,7 +47,7 @@ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ class navigation_cache { - /** @var cache_session The session cache instance */ + /** @var session_cache The session cache instance */ protected $cache; /** @var array The current cache area data */ protected $session = []; @@ -202,3 +208,8 @@ class navigation_cache { } } } + +// Alias this class to the old name. +// This file will be autoloaded by the legacyclasses autoload system. +// In future all uses of this class will be corrected and the legacy references will be removed. +class_alias(navigation_cache::class, \navigation_cache::class); diff --git a/public/lib/classes/navigation/navigation_json.php b/public/lib/classes/navigation/navigation_json.php index c576603faac..cd5b91000fa 100644 --- a/public/lib/classes/navigation/navigation_json.php +++ b/public/lib/classes/navigation/navigation_json.php @@ -14,6 +14,12 @@ // You should have received a copy of the GNU General Public License // along with Moodle. If not, see . +namespace core\navigation; + +use core\output\action_link; +use core\output\pix_icon; +use core\url; + /** * Simple class used to output a navigation branch in XML * @@ -96,7 +102,7 @@ class navigation_json { } if (is_string($child->action)) { $attributes['link'] = $child->action; - } else if ($child->action instanceof moodle_url) { + } else if ($child->action instanceof url) { $attributes['link'] = $child->action->out(); } else if ($child->action instanceof action_link) { $attributes['link'] = $child->action->url->out(); @@ -119,3 +125,8 @@ class navigation_json { } } } + +// Alias this class to the old name. +// This file will be autoloaded by the legacyclasses autoload system. +// In future all uses of this class will be corrected and the legacy references will be removed. +class_alias(navigation_json::class, \navigation_json::class); diff --git a/public/lib/classes/navigation/navigation_node.php b/public/lib/classes/navigation/navigation_node.php index fbb830583ba..63d949387e6 100644 --- a/public/lib/classes/navigation/navigation_node.php +++ b/public/lib/classes/navigation/navigation_node.php @@ -14,6 +14,16 @@ // You should have received a copy of the GNU General Public License // along with Moodle. If not, see . +namespace core\navigation; + +use core\context_helper; +use core\exception\coding_exception; +use core\output\action_link; +use core\output\pix_icon; +use core\output\renderable; +use core\output\tabobject; +use core\url; + /** * This class is used to represent a node in a navigation tree * @@ -730,7 +740,7 @@ class navigation_node implements renderable { global $CFG; if ($this->has_action()) { $url = $this->action(); - if ($this->action() instanceof \action_link) { + if ($this->action() instanceof action_link) { $url = $this->action()->url; } @@ -1015,3 +1025,8 @@ class navigation_node implements renderable { self::$loadadmintree = false; } } + +// Alias this class to the old name. +// This file will be autoloaded by the legacyclasses autoload system. +// In future all uses of this class will be corrected and the legacy references will be removed. +class_alias(navigation_node::class, \navigation_node::class); diff --git a/public/lib/classes/navigation/navigation_node_collection.php b/public/lib/classes/navigation/navigation_node_collection.php index 78e9698c532..dda0f843ec4 100644 --- a/public/lib/classes/navigation/navigation_node_collection.php +++ b/public/lib/classes/navigation/navigation_node_collection.php @@ -14,6 +14,13 @@ // You should have received a copy of the GNU General Public License // along with Moodle. If not, see . +namespace core\navigation; + +use ArrayIterator; +use Countable; +use IteratorAggregate; +use Traversable; + /** * Navigation node collection * @@ -279,3 +286,8 @@ class navigation_node_collection implements IteratorAggregate, Countable { return new ArrayIterator($this->collection); } } + +// Alias this class to the old name. +// This file will be autoloaded by the legacyclasses autoload system. +// In future all uses of this class will be corrected and the legacy references will be removed. +class_alias(navigation_node_collection::class, \navigation_node_collection::class); diff --git a/public/lib/classes/navigation/settings_navigation.php b/public/lib/classes/navigation/settings_navigation.php index a02831f3cbd..97ff006076f 100644 --- a/public/lib/classes/navigation/settings_navigation.php +++ b/public/lib/classes/navigation/settings_navigation.php @@ -14,8 +14,28 @@ // You should have received a copy of the GNU General Public License // along with Moodle. If not, see . +namespace core\navigation; + +use admin_category; +use admin_externalpage; +use admin_settingpage; +use core\component; +use core\context; +use core\context\course as context_course; +use core\context\system as context_system; +use core\context\user as context_user; +use core\context_helper; +use core\exception\coding_exception; +use core\output\action_link; +use core\output\pix_icon; +use core\url; use core\moodlenet\utilities; use core_contentbank\contentbank; +use core_plugin_manager; +use dml_missing_record_exception; +use moodle_page; +use part_of_admin_tree; +use repository; /** * Class used to manage the settings option for the current page @@ -86,7 +106,7 @@ class settings_navigation extends navigation_node { } switch ($context->contextlevel) { case CONTEXT_SYSTEM: - if ($this->page->url->compare(new moodle_url('/admin/settings.php', array('section'=>'frontpagesettings')))) { + if ($this->page->url->compare(new url('/admin/settings.php', array('section'=>'frontpagesettings')))) { $this->load_front_page_settings(($context->id == $this->context->id)); } break; @@ -143,7 +163,7 @@ class settings_navigation extends navigation_node { $adminsettings->remove(); $adminsettings = false; } - $siteadminnode = $this->add(get_string('administrationsite'), new moodle_url('/admin/search.php'), + $siteadminnode = $this->add(get_string('administrationsite'), new url('/admin/search.php'), self::TYPE_SITE_ADMIN, null, 'siteadministration'); $siteadminnode->id = 'expandable_branch_' . $siteadminnode->type . '_' . clean_param($siteadminnode->key, PARAM_ALPHANUMEXT); @@ -180,7 +200,7 @@ class settings_navigation extends navigation_node { * and then proceeds to use the key to set class and hr * * @param string $text text to be used for the link. - * @param string|moodle_url $url url for the new node + * @param string|url $url url for the new node * @param int $type the type of node navigation_node::TYPE_* * @param string $shorttext * @param string|int $key a key to access the node by. @@ -198,7 +218,7 @@ class settings_navigation extends navigation_node { * navigation, which means it will be at the top of the settings navigation block * * @param string $text text to be used for the link. - * @param string|moodle_url $url url for the new node + * @param string|url $url url for the new node * @param int $type the type of node navigation_node::TYPE_* * @param string $shorttext * @param string|int $key a key to access the node by. @@ -386,7 +406,7 @@ class settings_navigation extends navigation_node { $isvalidinstance = utilities::is_valid_instance($issuer); if ($usercanshare && $isvalidinstance) { $this->page->requires->js_call_amd('core/moodlenet/send_resource', 'init'); - $action = new action_link(new moodle_url(''), '', null, [ + $action = new action_link(new url(''), '', null, [ 'data-action' => 'sendtomoodlenet', 'data-type' => 'course', ]); @@ -394,7 +414,7 @@ class settings_navigation extends navigation_node { $coursenode->add(get_string('moodlenet:sharetomoodlenet', 'moodle'), $action, self::TYPE_SETTING, null, 'exportcoursetomoodlenet')->set_force_into_more_menu(true); // MoodleNet share progress link. - $url = new moodle_url('/moodlenet/shareprogress.php'); + $url = new url('/moodlenet/shareprogress.php'); $coursenode->add(get_string('moodlenet:shareprogress'), $url, self::TYPE_SETTING, null, 'moodlenetshareprogress')->set_force_into_more_menu(true); } @@ -405,14 +425,14 @@ class settings_navigation extends navigation_node { if ($adminoptions->update) { // Add the course settings link - $url = new moodle_url('/course/edit.php', array('id'=>$course->id)); + $url = new url('/course/edit.php', array('id'=>$course->id)); $coursenode->add(get_string('settings'), $url, self::TYPE_SETTING, null, 'editsettings', new pix_icon('i/settings', '')); } if ($adminoptions->editcompletion) { // Add the course completion settings link - $url = new moodle_url('/course/completion.php', array('id' => $course->id)); + $url = new url('/course/completion.php', array('id' => $course->id)); $coursenode->add(get_string('coursecompletion', 'completion'), $url, self::TYPE_SETTING, null, 'coursecompletion', new pix_icon('i/settings', '')); } @@ -431,7 +451,7 @@ class settings_navigation extends navigation_node { // Manage filters if ($adminoptions->filters) { - $url = new moodle_url('/filter/manage.php', array('contextid'=>$coursecontext->id)); + $url = new url('/filter/manage.php', array('contextid'=>$coursecontext->id)); $coursenode->add(get_string('filters', 'admin'), $url, self::TYPE_SETTING, null, 'filtermanagement', new pix_icon('i/filter', '')); } @@ -439,9 +459,9 @@ class settings_navigation extends navigation_node { // View course reports. if ($adminoptions->reports) { $reportnav = $coursenode->add(get_string('reports'), - new moodle_url('/report/view.php', ['courseid' => $coursecontext->instanceid]), + new url('/report/view.php', ['courseid' => $coursecontext->instanceid]), self::TYPE_CONTAINER, null, 'coursereports', new pix_icon('i/stats', '')); - $coursereports = core_component::get_plugin_list('coursereport'); + $coursereports = component::get_plugin_list('coursereport'); foreach ($coursereports as $report => $dir) { $libfile = $CFG->dirroot.'/course/report/'.$report.'/lib.php'; if (file_exists($libfile)) { @@ -468,7 +488,7 @@ class settings_navigation extends navigation_node { // Check if we can view the gradebook's setup page. if ($adminoptions->gradebook) { - $url = new moodle_url('/grade/edit/tree/index.php', array('id' => $course->id)); + $url = new url('/grade/edit/tree/index.php', array('id' => $course->id)); $coursenode->add(get_string('gradebooksetup', 'grades'), $url, self::TYPE_SETTING, null, 'gradebooksetup', new pix_icon('i/settings', '')); } @@ -478,7 +498,7 @@ class settings_navigation extends navigation_node { // Add outcome if permitted if ($adminoptions->outcomes) { - $url = new moodle_url('/grade/edit/outcome/course.php', array('id'=>$course->id)); + $url = new url('/grade/edit/outcome/course.php', array('id'=>$course->id)); $coursenode->add(get_string('outcomes', 'grades'), $url, self::TYPE_SETTING, null, 'outcomes', new pix_icon('i/outcomes', '')); } @@ -505,7 +525,7 @@ class settings_navigation extends navigation_node { $haseditabletypes = $this->cache->{'contexthasrepos'.$coursecontext->id}; } if ($haseditabletypes) { - $url = new moodle_url('/repository/manage_instances.php', array('contextid' => $coursecontext->id)); + $url = new url('/repository/manage_instances.php', array('contextid' => $coursecontext->id)); $coursenode->add(get_string('repositories'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/repository', '')); } } @@ -513,7 +533,7 @@ class settings_navigation extends navigation_node { // Manage files if ($adminoptions->files) { // hidden in new courses and courses where legacy files were turned off - $url = new moodle_url('/files/index.php', array('contextid'=>$coursecontext->id)); + $url = new url('/files/index.php', array('contextid'=>$coursecontext->id)); $coursenode->add(get_string('courselegacyfiles'), $url, self::TYPE_SETTING, null, 'coursefiles', new pix_icon('i/folder', '')); } @@ -548,25 +568,25 @@ class settings_navigation extends navigation_node { || $adminoptions->reset) { $coursereusenav = $coursenode->add( get_string('coursereuse'), - new moodle_url('/backup/view.php', ['id' => $course->id]), + new url('/backup/view.php', ['id' => $course->id]), self::TYPE_CONTAINER, null, 'coursereuse', new pix_icon('t/edit', ''), ); // Import data from other courses. if ($adminoptions->import) { - $url = new moodle_url('/backup/import.php', ['id' => $course->id]); + $url = new url('/backup/import.php', ['id' => $course->id]); $coursereusenav->add(get_string('import'), $url, self::TYPE_SETTING, null, 'import', new pix_icon('i/import', '')); } // Backup this course. if ($adminoptions->backup) { - $url = new moodle_url('/backup/backup.php', ['id' => $course->id]); + $url = new url('/backup/backup.php', ['id' => $course->id]); $coursereusenav->add(get_string('backup'), $url, self::TYPE_SETTING, null, 'backup', new pix_icon('i/backup', '')); } // Restore to this course. if ($adminoptions->restore) { - $url = new moodle_url('/backup/restorefile.php', ['contextid' => $coursecontext->id]); + $url = new url('/backup/restorefile.php', ['contextid' => $coursecontext->id]); $coursereusenav->add( get_string('restore'), $url, @@ -579,13 +599,13 @@ class settings_navigation extends navigation_node { // Copy this course. if ($adminoptions->copy) { - $url = new moodle_url('/backup/copy.php', ['id' => $course->id]); + $url = new url('/backup/copy.php', ['id' => $course->id]); $coursereusenav->add(get_string('copycourse'), $url, self::TYPE_SETTING, null, 'copy', new pix_icon('t/copy', '')); } // Reset this course. if ($adminoptions->reset) { - $url = new moodle_url('/course/reset.php', ['id' => $course->id]); + $url = new url('/course/reset.php', ['id' => $course->id]); $coursereusenav->add(get_string('reset'), $url, self::TYPE_SETTING, null, 'reset', new pix_icon('i/return', '')); } } @@ -633,24 +653,24 @@ class settings_navigation extends navigation_node { // Settings for the module if (has_capability('moodle/course:manageactivities', $this->page->cm->context)) { - $url = new moodle_url('/course/modedit.php', array('update' => $this->page->cm->id, 'return' => 1)); + $url = new url('/course/modedit.php', array('update' => $this->page->cm->id, 'return' => 1)); $modulenode->add(get_string('settings'), $url, self::TYPE_SETTING, null, 'modedit', new pix_icon('i/settings', '')); } // Assign local roles if (count(get_assignable_roles($this->page->cm->context))>0) { - $url = new moodle_url('/'.$CFG->admin.'/roles/assign.php', array('contextid'=>$this->page->cm->context->id)); + $url = new url('/'.$CFG->admin.'/roles/assign.php', array('contextid'=>$this->page->cm->context->id)); $modulenode->add(get_string('localroles', 'role'), $url, self::TYPE_SETTING, null, 'roleassign', new pix_icon('i/role', '')); } // Override roles if (has_capability('moodle/role:review', $this->page->cm->context) or count(get_overridable_roles($this->page->cm->context))>0) { - $url = new moodle_url('/'.$CFG->admin.'/roles/permissions.php', array('contextid'=>$this->page->cm->context->id)); + $url = new url('/'.$CFG->admin.'/roles/permissions.php', array('contextid'=>$this->page->cm->context->id)); $modulenode->add(get_string('permissions', 'role'), $url, self::TYPE_SETTING, null, 'roleoverride', new pix_icon('i/permissions', '')); } // Check role permissions if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride','moodle/role:override', 'moodle/role:assign'), $this->page->cm->context)) { - $url = new moodle_url('/'.$CFG->admin.'/roles/check.php', array('contextid'=>$this->page->cm->context->id)); + $url = new url('/'.$CFG->admin.'/roles/check.php', array('contextid'=>$this->page->cm->context->id)); $modulenode->add(get_string('checkpermissions', 'role'), $url, self::TYPE_SETTING, null, 'rolecheck', new pix_icon('i/checkpermissions', '')); } @@ -660,7 +680,7 @@ class settings_navigation extends navigation_node { // Manage filters if (has_capability('moodle/filter:manage', $this->page->cm->context) && count(filter_get_available_in_context($this->page->cm->context))>0) { - $url = new moodle_url('/filter/manage.php', array('contextid'=>$this->page->cm->context->id)); + $url = new url('/filter/manage.php', array('contextid'=>$this->page->cm->context->id)); $modulenode->add(get_string('filters', 'admin'), $url, self::TYPE_SETTING, null, 'filtermanage', new pix_icon('i/filter', '')); } @@ -672,14 +692,14 @@ class settings_navigation extends navigation_node { // Add a backup link $featuresfunc = $this->page->activityname.'_supports'; if (function_exists($featuresfunc) && $featuresfunc(FEATURE_BACKUP_MOODLE2) && has_capability('moodle/backup:backupactivity', $this->page->cm->context)) { - $url = new moodle_url('/backup/backup.php', array('id'=>$this->page->cm->course, 'cm'=>$this->page->cm->id)); + $url = new url('/backup/backup.php', array('id'=>$this->page->cm->course, 'cm'=>$this->page->cm->id)); $modulenode->add(get_string('backup'), $url, self::TYPE_SETTING, null, 'backup', new pix_icon('i/backup', '')); } // Restore this activity $featuresfunc = $this->page->activityname.'_supports'; if (function_exists($featuresfunc) && $featuresfunc(FEATURE_BACKUP_MOODLE2) && has_capability('moodle/restore:restoreactivity', $this->page->cm->context)) { - $url = new moodle_url('/backup/restorefile.php', array('contextid'=>$this->page->cm->context->id)); + $url = new url('/backup/restorefile.php', array('contextid'=>$this->page->cm->context->id)); $modulenode->add(get_string('restore'), $url, self::TYPE_SETTING, null, 'restore', new pix_icon('i/restore', '')); } @@ -704,7 +724,7 @@ class settings_navigation extends navigation_node { $isvalidinstance = utilities::is_valid_instance($issuer); if ($usercanshare && $isvalidinstance) { $this->page->requires->js_call_amd('core/moodlenet/send_resource', 'init'); - $action = new action_link(new moodle_url(''), '', null, [ + $action = new action_link(new url(''), '', null, [ 'data-action' => 'sendtomoodlenet', 'data-type' => 'activity', ]); @@ -884,7 +904,7 @@ class settings_navigation extends navigation_node { $fullname = fullname($user, has_capability('moodle/site:viewfullnames', $this->page->context)); $key = $gstitle; - $prefurl = new moodle_url('/user/preferences.php'); + $prefurl = new url('/user/preferences.php'); if ($gstitle != 'usercurrentsettings') { $key .= $userid; $prefurl->param('userid', $userid); @@ -892,7 +912,7 @@ class settings_navigation extends navigation_node { // Add a user setting branch. if ($gstitle == 'usercurrentsettings') { - $mainpage = $this->add(get_string('home'), new moodle_url('/'), self::TYPE_CONTAINER, null, 'site'); + $mainpage = $this->add(get_string('home'), new url('/'), self::TYPE_CONTAINER, null, 'site'); // This should be set to false as we don't want to show this to the user. It's only for generating the correct // breadcrumb. @@ -914,7 +934,7 @@ class settings_navigation extends navigation_node { } // Add the user profile to the dashboard. - $profilenode = $mainpage->add(get_string('profile'), new moodle_url('/user/profile.php', + $profilenode = $mainpage->add(get_string('profile'), new url('/user/profile.php', array('id' => $user->id)), self::TYPE_SETTING, null, 'myprofile'); // Add blog nodes. @@ -948,21 +968,21 @@ class settings_navigation extends navigation_node { if ($USER->id != $user->id) { $messageargs['user2'] = $user->id; } - $url = new moodle_url('/message/index.php', $messageargs); + $url = new url('/message/index.php', $messageargs); $mainpage->add(get_string('messages', 'message'), $url, self::TYPE_SETTING, null, 'messages'); } // Add the "My private files" link. // This link doesn't have a unique display for course context so only display it under the user's profile. if ($issitecourse && $iscurrentuser && has_capability('moodle/user:manageownfiles', $usercontext)) { - $url = new moodle_url('/user/files.php'); + $url = new url('/user/files.php'); $mainpage->add(get_string('privatefiles'), $url, self::TYPE_SETTING, null, 'privatefiles'); } // Add a node to view the users notes if permitted. if (!empty($CFG->enablenotes) && has_any_capability(array('moodle/notes:manage', 'moodle/notes:view'), $coursecontext)) { - $url = new moodle_url('/notes/index.php', array('user' => $user->id)); + $url = new url('/notes/index.php', array('user' => $user->id)); if ($coursecontext->instanceid != SITEID) { $url->param('course', $coursecontext->instanceid); } @@ -976,7 +996,7 @@ class settings_navigation extends navigation_node { if ($course->id == SITEID) { $url = user_mygrades_url($user->id, $course->id); } else { // Otherwise we are in a course and should redirect to the user grade report (Activity report version). - $url = new moodle_url('/course/user.php', array('mode' => 'grade', 'id' => $course->id, 'user' => $user->id)); + $url = new url('/course/user.php', array('mode' => 'grade', 'id' => $course->id, 'user' => $user->id)); } $mainpage->add(get_string('grades', 'grades'), $url, self::TYPE_SETTING, null, 'mygrades'); } @@ -1007,9 +1027,9 @@ class settings_navigation extends navigation_node { } else { // We can edit the user so show the user deleted message and link it to the profile. if ($course->id == $SITE->id) { - $profileurl = new moodle_url('/user/profile.php', array('id'=>$user->id)); + $profileurl = new url('/user/profile.php', array('id'=>$user->id)); } else { - $profileurl = new moodle_url('/user/view.php', array('id'=>$user->id, 'course'=>$course->id)); + $profileurl = new url('/user/view.php', array('id'=>$user->id, 'course'=>$course->id)); } $usersetting->add(get_string('userdeleted'), $profileurl, self::TYPE_SETTING); } @@ -1027,14 +1047,14 @@ class settings_navigation extends navigation_node { if (isloggedin() && !isguestuser($user) && !is_mnet_remote_user($user)) { if (($currentuser || is_siteadmin($USER) || !is_siteadmin($user)) && has_capability('moodle/user:update', $systemcontext)) { - $url = new moodle_url('/user/editadvanced.php', array('id'=>$user->id, 'course'=>$course->id)); + $url = new url('/user/editadvanced.php', array('id'=>$user->id, 'course'=>$course->id)); $useraccount->add(get_string('editmyprofile'), $url, self::TYPE_SETTING, null, 'editprofile'); } else if ((has_capability('moodle/user:editprofile', $usercontext) && !is_siteadmin($user)) || ($currentuser && has_capability('moodle/user:editownprofile', $systemcontext))) { if ($userauthplugin && $userauthplugin->can_edit_profile()) { $url = $userauthplugin->edit_profile_url(); if (empty($url)) { - $url = new moodle_url('/user/edit.php', array('id'=>$user->id, 'course'=>$course->id)); + $url = new url('/user/edit.php', array('id'=>$user->id, 'course'=>$course->id)); } $useraccount->add(get_string('editmyprofile'), $url, self::TYPE_SETTING, null, 'editprofile'); } @@ -1046,7 +1066,7 @@ class settings_navigation extends navigation_node { has_capability('moodle/user:changeownpassword', $systemcontext) && $userauthplugin->can_change_password()) { $passwordchangeurl = $userauthplugin->change_password_url(); if (empty($passwordchangeurl)) { - $passwordchangeurl = new moodle_url('/login/change_password.php', array('id'=>$course->id)); + $passwordchangeurl = new url('/login/change_password.php', array('id'=>$course->id)); } $useraccount->add(get_string("changepassword"), $passwordchangeurl, self::TYPE_SETTING, null, 'changepassword'); } @@ -1056,7 +1076,7 @@ class settings_navigation extends navigation_node { if (isloggedin() && !isguestuser($user) && $defaulthomepageuser) { if ($currentuser && has_capability('moodle/user:editownprofile', $systemcontext) || has_capability('moodle/user:editprofile', $usercontext)) { - $url = new moodle_url('/user/defaulthomepage.php', ['id' => $user->id]); + $url = new url('/user/defaulthomepage.php', ['id' => $user->id]); $useraccount->add(get_string('defaulthomepageuser'), $url, self::TYPE_SETTING, null, 'defaulthomepageuser'); } } @@ -1064,7 +1084,7 @@ class settings_navigation extends navigation_node { if (isloggedin() && !isguestuser($user) && !is_mnet_remote_user($user)) { if ($currentuser && has_capability('moodle/user:editownprofile', $systemcontext) || has_capability('moodle/user:editprofile', $usercontext)) { - $url = new moodle_url('/user/language.php', array('id' => $user->id, 'course' => $course->id)); + $url = new url('/user/language.php', array('id' => $user->id, 'course' => $course->id)); $useraccount->add(get_string('preferredlanguage'), $url, self::TYPE_SETTING, null, 'preferredlanguage'); } } @@ -1073,7 +1093,7 @@ class settings_navigation extends navigation_node { if (isset($enabled['forum']) && isloggedin() && !isguestuser($user) && !is_mnet_remote_user($user)) { if ($currentuser && has_capability('moodle/user:editownprofile', $systemcontext) || has_capability('moodle/user:editprofile', $usercontext)) { - $url = new moodle_url('/user/forum.php', array('id' => $user->id, 'course' => $course->id)); + $url = new url('/user/forum.php', array('id' => $user->id, 'course' => $course->id)); $useraccount->add(get_string('forumpreferences'), $url, self::TYPE_SETTING); } } @@ -1082,7 +1102,7 @@ class settings_navigation extends navigation_node { if (isloggedin() && !isguestuser($user) && !is_mnet_remote_user($user)) { if ($currentuser && has_capability('moodle/user:editownprofile', $systemcontext) || has_capability('moodle/user:editprofile', $usercontext)) { - $url = new moodle_url('/user/editor.php', array('id' => $user->id, 'course' => $course->id)); + $url = new url('/user/editor.php', array('id' => $user->id, 'course' => $course->id)); $useraccount->add(get_string('editorpreferences'), $url, self::TYPE_SETTING); } } @@ -1092,7 +1112,7 @@ class settings_navigation extends navigation_node { if (isloggedin() && !isguestuser($user)) { if ($currentuser && has_capability('moodle/user:editownprofile', $systemcontext) || has_capability('moodle/user:editprofile', $usercontext)) { - $url = new moodle_url('/user/calendar.php', array('id' => $user->id)); + $url = new url('/user/calendar.php', array('id' => $user->id)); $useraccount->add(get_string('calendarpreferences', 'calendar'), $url, self::TYPE_SETTING, null, 'preferredcalendar'); } } @@ -1101,7 +1121,7 @@ class settings_navigation extends navigation_node { if (isloggedin() && !isguestuser($user)) { if ($currentuser && has_capability('moodle/user:editownprofile', $systemcontext) || has_capability('moodle/user:editprofile', $usercontext)) { - $url = new moodle_url('/user/contentbank.php', ['id' => $user->id]); + $url = new url('/user/contentbank.php', ['id' => $user->id]); $useraccount->add(get_string('contentbankpreferences', 'core_contentbank'), $url, self::TYPE_SETTING, null, 'contentbankpreferences'); } @@ -1112,24 +1132,24 @@ class settings_navigation extends navigation_node { 'moodle/role:manage'], $usercontext)) { $roles = $usersetting->add(get_string('roles'), null, self::TYPE_SETTING); - $url = new moodle_url('/admin/roles/usersroles.php', ['userid' => $user->id, 'courseid' => $course->id]); + $url = new url('/admin/roles/usersroles.php', ['userid' => $user->id, 'courseid' => $course->id]); $roles->add(get_string('thisusersroles', 'role'), $url, self::TYPE_SETTING); $assignableroles = get_assignable_roles($usercontext, ROLENAME_BOTH); if (!empty($assignableroles)) { - $url = new moodle_url('/admin/roles/assign.php', + $url = new url('/admin/roles/assign.php', array('contextid' => $usercontext->id, 'userid' => $user->id, 'courseid' => $course->id)); $roles->add(get_string('assignrolesrelativetothisuser', 'role'), $url, self::TYPE_SETTING); } if (has_capability('moodle/role:review', $usercontext) || count(get_overridable_roles($usercontext, ROLENAME_BOTH))>0) { - $url = new moodle_url('/admin/roles/permissions.php', + $url = new url('/admin/roles/permissions.php', array('contextid' => $usercontext->id, 'userid' => $user->id, 'courseid' => $course->id)); $roles->add(get_string('permissions', 'role'), $url, self::TYPE_SETTING); } - $url = new moodle_url('/admin/roles/check.php', + $url = new url('/admin/roles/check.php', array('contextid' => $usercontext->id, 'userid' => $user->id, 'courseid' => $course->id)); $roles->add(get_string('checkpermissions', 'role'), $url, self::TYPE_SETTING); } @@ -1146,7 +1166,7 @@ class settings_navigation extends navigation_node { } if ($haseditabletypes) { $repositories = $usersetting->add(get_string('repositories', 'repository'), null, self::TYPE_SETTING); - $repositories->add(get_string('manageinstances', 'repository'), new moodle_url('/repository/manage_instances.php', + $repositories->add(get_string('manageinstances', 'repository'), new url('/repository/manage_instances.php', array('contextid' => $usercontext->id))); } @@ -1156,10 +1176,10 @@ class settings_navigation extends navigation_node { if (portfolio_has_visible_instances()) { $portfolio = $usersetting->add(get_string('portfolios', 'portfolio'), null, self::TYPE_SETTING); - $url = new moodle_url('/user/portfolio.php', array('courseid'=>$course->id)); + $url = new url('/user/portfolio.php', array('courseid'=>$course->id)); $portfolio->add(get_string('configure', 'portfolio'), $url, self::TYPE_SETTING); - $url = new moodle_url('/user/portfoliologs.php', array('courseid'=>$course->id)); + $url = new url('/user/portfoliologs.php', array('courseid'=>$course->id)); $portfolio->add(get_string('logs', 'portfolio'), $url, self::TYPE_SETTING); } } @@ -1174,15 +1194,15 @@ class settings_navigation extends navigation_node { } // Security keys. if ($currentuser && $enablemanagetokens) { - $url = new moodle_url('/user/managetoken.php'); + $url = new url('/user/managetoken.php'); $useraccount->add(get_string('securitykeys', 'webservice'), $url, self::TYPE_SETTING); } // Messaging. if (($currentuser && has_capability('moodle/user:editownmessageprofile', $systemcontext)) || (!isguestuser($user) && has_capability('moodle/user:editmessageprofile', $usercontext) && !is_primary_admin($user->id))) { - $messagingurl = new moodle_url('/message/edit.php', array('id' => $user->id)); - $notificationsurl = new moodle_url('/message/notificationpreferences.php', array('userid' => $user->id)); + $messagingurl = new url('/message/edit.php', array('id' => $user->id)); + $notificationsurl = new url('/message/notificationpreferences.php', array('userid' => $user->id)); $useraccount->add(get_string('messagepreferences', 'message'), $messagingurl, self::TYPE_SETTING); $useraccount->add(get_string('notificationpreferences', 'message'), $notificationsurl, self::TYPE_SETTING); } @@ -1191,14 +1211,14 @@ class settings_navigation extends navigation_node { if ($currentuser && !empty($CFG->enableblogs)) { $blog = $usersetting->add(get_string('blogs', 'blog'), null, navigation_node::TYPE_CONTAINER, null, 'blogs'); if (has_capability('moodle/blog:view', $systemcontext)) { - $blog->add(get_string('preferences', 'blog'), new moodle_url('/blog/preferences.php'), + $blog->add(get_string('preferences', 'blog'), new url('/blog/preferences.php'), navigation_node::TYPE_SETTING); } if (!empty($CFG->useexternalblogs) && $CFG->maxexternalblogsperuser > 0 && has_capability('moodle/blog:manageexternal', $systemcontext)) { - $blog->add(get_string('externalblogs', 'blog'), new moodle_url('/blog/external_blogs.php'), + $blog->add(get_string('externalblogs', 'blog'), new url('/blog/external_blogs.php'), navigation_node::TYPE_SETTING); - $blog->add(get_string('addnewexternalblog', 'blog'), new moodle_url('/blog/external_blog_edit.php'), + $blog->add(get_string('addnewexternalblog', 'blog'), new url('/blog/external_blog_edit.php'), navigation_node::TYPE_SETTING); } // Remove the blog node if empty. @@ -1209,13 +1229,13 @@ class settings_navigation extends navigation_node { if ($currentuser && !empty($CFG->enablebadges)) { $badges = $usersetting->add(get_string('badges'), null, navigation_node::TYPE_CONTAINER, null, 'badges'); if (has_capability('moodle/badges:manageownbadges', $usercontext)) { - $url = new moodle_url('/badges/mybadges.php'); + $url = new url('/badges/mybadges.php'); $badges->add(get_string('managebadges', 'badges'), $url, self::TYPE_SETTING); } - $badges->add(get_string('preferences', 'badges'), new moodle_url('/badges/preferences.php'), + $badges->add(get_string('preferences', 'badges'), new url('/badges/preferences.php'), navigation_node::TYPE_SETTING); if (!empty($CFG->badges_allowexternalbackpack)) { - $badges->add(get_string('backpackdetails', 'badges'), new moodle_url('/badges/mybackpack.php'), + $badges->add(get_string('backpackdetails', 'badges'), new url('/badges/mybackpack.php'), navigation_node::TYPE_SETTING); } } @@ -1244,20 +1264,20 @@ class settings_navigation extends navigation_node { // Assign local roles if (get_assignable_roles($this->context, ROLENAME_ORIGINAL)) { - $assignurl = new moodle_url('/'.$CFG->admin.'/roles/assign.php', array('contextid' => $this->context->id)); + $assignurl = new url('/'.$CFG->admin.'/roles/assign.php', array('contextid' => $this->context->id)); $blocknode->add(get_string('assignroles', 'role'), $assignurl, self::TYPE_SETTING, null, 'roles', new pix_icon('i/assignroles', '')); } // Override roles if (has_capability('moodle/role:review', $this->context) or count(get_overridable_roles($this->context))>0) { - $url = new moodle_url('/'.$CFG->admin.'/roles/permissions.php', array('contextid'=>$this->context->id)); + $url = new url('/'.$CFG->admin.'/roles/permissions.php', array('contextid'=>$this->context->id)); $blocknode->add(get_string('permissions', 'role'), $url, self::TYPE_SETTING, null, 'permissions', new pix_icon('i/permissions', '')); } // Check role permissions if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride','moodle/role:override', 'moodle/role:assign'), $this->context)) { - $url = new moodle_url('/'.$CFG->admin.'/roles/check.php', array('contextid'=>$this->context->id)); + $url = new url('/'.$CFG->admin.'/roles/check.php', array('contextid'=>$this->context->id)); $blocknode->add(get_string('checkpermissions', 'role'), $url, self::TYPE_SETTING, null, 'checkpermissions', new pix_icon('i/checkpermissions', '')); } @@ -1295,17 +1315,17 @@ class settings_navigation extends navigation_node { $categorynode->force_open(); if (can_edit_in_category($catcontext->instanceid)) { - $url = new moodle_url('/course/management.php', array('categoryid' => $catcontext->instanceid)); + $url = new url('/course/management.php', array('categoryid' => $catcontext->instanceid)); $editstring = get_string('managecategorythis'); $node = $categorynode->add($editstring, $url, self::TYPE_SETTING, null, 'managecategory', new pix_icon('i/edit', '')); $node->set_show_in_secondary_navigation(false); } if (has_capability('moodle/category:manage', $catcontext)) { - $editurl = new moodle_url('/course/editcategory.php', array('id' => $catcontext->instanceid)); + $editurl = new url('/course/editcategory.php', array('id' => $catcontext->instanceid)); $categorynode->add(get_string('settings'), $editurl, self::TYPE_SETTING, null, 'edit', new pix_icon('i/edit', '')); - $addsubcaturl = new moodle_url('/course/editcategory.php', array('parent' => $catcontext->instanceid)); + $addsubcaturl = new url('/course/editcategory.php', array('parent' => $catcontext->instanceid)); $categorynode->add(get_string('addsubcategory'), $addsubcaturl, self::TYPE_SETTING, null, 'addsubcat', new pix_icon('i/withsubcat', ''))->set_show_in_secondary_navigation(false); } @@ -1313,19 +1333,19 @@ class settings_navigation extends navigation_node { // Assign local roles $assignableroles = get_assignable_roles($catcontext); if (!empty($assignableroles)) { - $assignurl = new moodle_url('/'.$CFG->admin.'/roles/assign.php', array('contextid' => $catcontext->id)); + $assignurl = new url('/'.$CFG->admin.'/roles/assign.php', array('contextid' => $catcontext->id)); $categorynode->add(get_string('assignroles', 'role'), $assignurl, self::TYPE_SETTING, null, 'roles', new pix_icon('i/assignroles', '')); } // Override roles if (has_capability('moodle/role:review', $catcontext) or count(get_overridable_roles($catcontext)) > 0) { - $url = new moodle_url('/'.$CFG->admin.'/roles/permissions.php', array('contextid' => $catcontext->id)); + $url = new url('/'.$CFG->admin.'/roles/permissions.php', array('contextid' => $catcontext->id)); $categorynode->add(get_string('permissions', 'role'), $url, self::TYPE_SETTING, null, 'permissions', new pix_icon('i/permissions', '')); } // Check role permissions if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride', 'moodle/role:override', 'moodle/role:assign'), $catcontext)) { - $url = new moodle_url('/'.$CFG->admin.'/roles/check.php', array('contextid' => $catcontext->id)); + $url = new url('/'.$CFG->admin.'/roles/check.php', array('contextid' => $catcontext->id)); $categorynode->add(get_string('checkpermissions', 'role'), $url, self::TYPE_SETTING, null, 'rolecheck', new pix_icon('i/checkpermissions', '')); } @@ -1334,19 +1354,19 @@ class settings_navigation extends navigation_node { // Cohorts if (has_any_capability(array('moodle/cohort:view', 'moodle/cohort:manage'), $catcontext)) { - $categorynode->add(get_string('cohorts', 'cohort'), new moodle_url('/cohort/index.php', + $categorynode->add(get_string('cohorts', 'cohort'), new url('/cohort/index.php', array('contextid' => $catcontext->id)), self::TYPE_SETTING, null, 'cohort', new pix_icon('i/cohort', '')); } // Manage filters if (has_capability('moodle/filter:manage', $catcontext) && count(filter_get_available_in_context($catcontext)) > 0) { - $url = new moodle_url('/filter/manage.php', array('contextid' => $catcontext->id)); + $url = new url('/filter/manage.php', array('contextid' => $catcontext->id)); $categorynode->add(get_string('filters', 'admin'), $url, self::TYPE_SETTING, null, 'filters', new pix_icon('i/filter', '')); } // Restore. if (has_capability('moodle/restore:restorecourse', $catcontext)) { - $url = new moodle_url('/backup/restorefile.php', array('contextid' => $catcontext->id)); + $url = new url('/backup/restorefile.php', array('contextid' => $catcontext->id)); $categorynode->add(get_string('restorecourse', 'admin'), $url, self::TYPE_SETTING, null, 'restorecourse', new pix_icon('i/restore', '')); } @@ -1361,9 +1381,9 @@ class settings_navigation extends navigation_node { $cb = new contentbank(); if ($cb->is_context_allowed($catcontext) && has_capability('moodle/contentbank:access', $catcontext)) { - $url = new \moodle_url('/contentbank/index.php', ['contextid' => $catcontext->id]); + $url = new url('/contentbank/index.php', ['contextid' => $catcontext->id]); $categorynode->add(get_string('contentbank'), $url, self::TYPE_CUSTOM, null, - 'contentbank', new \pix_icon('i/contentbank', '')); + 'contentbank', new pix_icon('i/contentbank', '')); } return $categorynode; @@ -1417,7 +1437,7 @@ class settings_navigation extends navigation_node { if ($this->page->user_allowed_editing() && !$this->page->theme->haseditswitch) { // Add the turn on/off settings - $url = new moodle_url('/course/view.php', array('id'=>$course->id, 'sesskey'=>sesskey())); + $url = new url('/course/view.php', array('id'=>$course->id, 'sesskey'=>sesskey())); if ($this->page->user_is_editing()) { $url->param('edit', 'off'); $editstring = get_string('turneditingoff'); @@ -1430,7 +1450,7 @@ class settings_navigation extends navigation_node { if ($adminoptions->update) { // Add the course settings link - $url = new moodle_url('/admin/settings.php', array('section'=>'frontpagesettings')); + $url = new url('/admin/settings.php', array('section'=>'frontpagesettings')); $frontpage->add(get_string('settings'), $url, self::TYPE_SETTING, null, 'editsettings', new pix_icon('i/settings', '')); } @@ -1440,18 +1460,18 @@ class settings_navigation extends navigation_node { // Manage filters if ($adminoptions->filters) { - $url = new moodle_url('/filter/manage.php', array('contextid'=>$coursecontext->id)); + $url = new url('/filter/manage.php', array('contextid'=>$coursecontext->id)); $frontpage->add(get_string('filters', 'admin'), $url, self::TYPE_SETTING, null, 'filtermanagement', new pix_icon('i/filter', '')); } // View course reports. if ($adminoptions->reports) { - $frontpagenav = $frontpage->add(get_string('reports'), new moodle_url('/report/view.php', + $frontpagenav = $frontpage->add(get_string('reports'), new url('/report/view.php', ['courseid' => $coursecontext->instanceid]), self::TYPE_CONTAINER, null, 'coursereports', new pix_icon('i/stats', '')); - $coursereports = core_component::get_plugin_list('coursereport'); + $coursereports = component::get_plugin_list('coursereport'); foreach ($coursereports as $report=>$dir) { $libfile = $CFG->dirroot.'/course/report/'.$report.'/lib.php'; if (file_exists($libfile)) { @@ -1481,7 +1501,7 @@ class settings_navigation extends navigation_node { // Manage files if ($adminoptions->files) { //hiden in new installs - $url = new moodle_url('/files/index.php', array('contextid'=>$coursecontext->id)); + $url = new url('/files/index.php', array('contextid'=>$coursecontext->id)); $frontpage->add(get_string('sitelegacyfiles'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/folder', '')); } @@ -1497,19 +1517,19 @@ class settings_navigation extends navigation_node { if ($adminoptions->backup || $adminoptions->restore) { $coursereusenav = $frontpage->add( get_string('coursereuse'), - new moodle_url('/backup/view.php', ['id' => $course->id]), + new url('/backup/view.php', ['id' => $course->id]), self::TYPE_CONTAINER, null, 'coursereuse', new pix_icon('t/edit', ''), ); // Backup this course. if ($adminoptions->backup) { - $url = new moodle_url('/backup/backup.php', ['id' => $course->id]); + $url = new url('/backup/backup.php', ['id' => $course->id]); $coursereusenav->add(get_string('backup'), $url, self::TYPE_SETTING, null, 'backup', new pix_icon('i/backup', '')); } // Restore to this course. if ($adminoptions->restore) { - $url = new moodle_url('/backup/restorefile.php', ['contextid' => $coursecontext->id]); + $url = new url('/backup/restorefile.php', ['contextid' => $coursecontext->id]); $coursereusenav->add( get_string('restore'), $url, @@ -1568,3 +1588,8 @@ class settings_navigation extends navigation_node { return false; } } + +// Alias this class to the old name. +// This file will be autoloaded by the legacyclasses autoload system. +// In future all uses of this class will be corrected and the legacy references will be removed. +class_alias(settings_navigation::class, \settings_navigation::class); diff --git a/public/lib/classes/navigation/settings_navigation_ajax.php b/public/lib/classes/navigation/settings_navigation_ajax.php index 8b6970704ce..4ec4881f423 100644 --- a/public/lib/classes/navigation/settings_navigation_ajax.php +++ b/public/lib/classes/navigation/settings_navigation_ajax.php @@ -14,6 +14,9 @@ // You should have received a copy of the GNU General Public License // along with Moodle. If not, see . +namespace core\navigation; + +use moodle_page; /** * Class used to populate site admin navigation for ajax. @@ -52,3 +55,8 @@ class settings_navigation_ajax extends settings_navigation { $this->initialised = true; } } + +// Alias this class to the old name. +// This file will be autoloaded by the legacyclasses autoload system. +// In future all uses of this class will be corrected and the legacy references will be removed. +class_alias(settings_navigation_ajax::class, \settings_navigation_ajax::class); diff --git a/public/lib/tests/classes/navigation/exposed_global_navigation.php b/public/lib/tests/classes/navigation/exposed_global_navigation.php new file mode 100644 index 00000000000..b1152efe29b --- /dev/null +++ b/public/lib/tests/classes/navigation/exposed_global_navigation.php @@ -0,0 +1,47 @@ +. + +namespace core\tests\navigation; + +use core\exception\coding_exception; +use core\navigation\global_navigation; + +/** + * This is a dummy object that allows us to call protected methods within the + * global navigation class by prefixing the methods with `exposed_` + */ +class exposed_global_navigation extends global_navigation { + protected $exposedkey = 'exposed_'; + public function __construct(?\moodle_page $page=null) { + global $PAGE; + if ($page === null) { + $page = $PAGE; + } + parent::__construct($page); + } + public function __call($method, $arguments) { + if (strpos($method, $this->exposedkey) !== false) { + $method = substr($method, strlen($this->exposedkey)); + } + if (method_exists($this, $method)) { + return call_user_func_array(array($this, $method), $arguments); + } + throw new coding_exception('You have attempted to access a method that does not exist for the given object '.$method, DEBUG_DEVELOPER); + } + public function set_initialised() { + $this->initialised = true; + } +} diff --git a/public/lib/tests/classes/navigation/exposed_settings_navigation.php b/public/lib/tests/classes/navigation/exposed_settings_navigation.php new file mode 100644 index 00000000000..93d02738393 --- /dev/null +++ b/public/lib/tests/classes/navigation/exposed_settings_navigation.php @@ -0,0 +1,48 @@ +. + +namespace core\tests\navigation; + +use core\exception\coding_exception; +use core\navigation\settings_navigation; + +/** + * This is a dummy object that allows us to call protected methods within the + * global navigation class by prefixing the methods with `exposed_`. + * + * @package core + * @copyright Andrew Lyons + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +class exposed_settings_navigation extends settings_navigation { + protected string $exposedkey = 'exposed_'; + + public function __construct() { + global $PAGE; + parent::__construct($PAGE); + } + + public function __call($method, $arguments) { + if (strpos($method, $this->exposedkey) !== false) { + $method = substr($method, strlen($this->exposedkey)); + } + if (method_exists($this, $method)) { + return call_user_func_array(array($this, $method), $arguments); + } + throw new coding_exception('You have attempted to access a method that does not exist for the given object '.$method, DEBUG_DEVELOPER); + } +} diff --git a/public/lib/tests/classes/navigation/navigation_testcase.php b/public/lib/tests/classes/navigation/navigation_testcase.php new file mode 100644 index 00000000000..080519eaa2b --- /dev/null +++ b/public/lib/tests/classes/navigation/navigation_testcase.php @@ -0,0 +1,64 @@ +. + +namespace core\tests\navigation; + +use core\output\pix_icon; +use core\url; +use navigation_node; + +/** + * TODO describe file navigation_testcase + * + * @package core + * @copyright 2025 Andrew Lyons + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +abstract class navigation_testcase extends \advanced_testcase { + protected function setup_node(): navigation_node { + global $PAGE, $SITE; + + // Perform a reset between tests to reset the PAGE. + $this->resetAfterTest(); + + $PAGE->set_url('/'); + $PAGE->set_course($SITE); + + $activeurl = $PAGE->url; + $inactiveurl = new url('http://www.moodle.com/'); + + navigation_node::override_active_url($PAGE->url); + + $node = new navigation_node('Test Node'); + $node->type = navigation_node::TYPE_SYSTEM; + // We add the first child without key. This way we make sure all keys search by comparison is performed using ===. + $node->add('first child without key', null, navigation_node::TYPE_CUSTOM); + $demo1 = $node->add('demo1', $inactiveurl, navigation_node::TYPE_COURSE, null, 'demo1', new pix_icon('i/course', '')); + $demo2 = $node->add('demo2', $inactiveurl, navigation_node::TYPE_COURSE, null, 'demo2', new pix_icon('i/course', '')); + $demo3 = $node->add('demo3', $inactiveurl, navigation_node::TYPE_CATEGORY, null, 'demo3', new pix_icon('i/course', '')); + $demo4 = $demo3->add('demo4', $inactiveurl, navigation_node::TYPE_COURSE, null, 'demo4', new pix_icon('i/course', '')); + $demo5 = $demo3->add('demo5', $activeurl, navigation_node::TYPE_COURSE, null, 'demo5', new pix_icon('i/course', '')); + $demo5->add('activity1', null, navigation_node::TYPE_ACTIVITY, null, 'activity1')->make_active(); + $demo6 = $demo3->add('demo6', null, navigation_node::TYPE_CONTAINER, 'container node test', 'demo6'); + $hiddendemo1 = $node->add('hiddendemo1', $inactiveurl, navigation_node::TYPE_CATEGORY, null, 'hiddendemo1', new pix_icon('i/course', '')); + $hiddendemo1->hidden = true; + $hiddendemo1->add('hiddendemo2', $inactiveurl, navigation_node::TYPE_COURSE, null, 'hiddendemo2', new pix_icon('i/course', ''))->helpbutton = 'Here is a help button'; + $hiddendemo1->add('hiddendemo3', $inactiveurl, navigation_node::TYPE_COURSE, null, 'hiddendemo3', new pix_icon('i/course', ''))->display = false; + + return $node; + } + +} diff --git a/public/lib/tests/navigation/global_navigation_test.php b/public/lib/tests/navigation/global_navigation_test.php new file mode 100644 index 00000000000..408cf55426a --- /dev/null +++ b/public/lib/tests/navigation/global_navigation_test.php @@ -0,0 +1,57 @@ +. + +namespace core\navigation; + +use core\tests\navigation\exposed_global_navigation; +use core\tests\navigation\navigation_testcase; + +/** + * Tests for global_navigation. + * + * @package core + * @category test + * @copyright 2025 Andrew Lyons + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +#[\PHPUnit\Framework\Attributes\CoversClass(global_navigation::class)] +final class global_navigation_test extends navigation_testcase { + public function test_module_extends_navigation(): void { + $node = new exposed_global_navigation(); + // Create an initial tree structure to work with. + $cat1 = $node->add('category 1', null, navigation_node::TYPE_CATEGORY, null, 'cat1'); + $cat2 = $node->add('category 2', null, navigation_node::TYPE_CATEGORY, null, 'cat2'); + $cat3 = $node->add('category 3', null, navigation_node::TYPE_CATEGORY, null, 'cat3'); + $sub1 = $cat2->add('sub category 1', null, navigation_node::TYPE_CATEGORY, null, 'sub1'); + $sub2 = $cat2->add('sub category 2', null, navigation_node::TYPE_CATEGORY, null, 'sub2'); + $sub3 = $cat2->add('sub category 3', null, navigation_node::TYPE_CATEGORY, null, 'sub3'); + $course1 = $sub2->add('course 1', null, navigation_node::TYPE_COURSE, null, 'course1'); + $course2 = $sub2->add('course 2', null, navigation_node::TYPE_COURSE, null, 'course2'); + $course3 = $sub2->add('course 3', null, navigation_node::TYPE_COURSE, null, 'course3'); + $section1 = $course2->add('section 1', null, navigation_node::TYPE_SECTION, null, 'sec1'); + $section2 = $course2->add('section 2', null, navigation_node::TYPE_SECTION, null, 'sec2'); + $section3 = $course2->add('section 3', null, navigation_node::TYPE_SECTION, null, 'sec3'); + $act1 = $section2->add('activity 1', null, navigation_node::TYPE_ACTIVITY, null, 'act1'); + $act2 = $section2->add('activity 2', null, navigation_node::TYPE_ACTIVITY, null, 'act2'); + $act3 = $section2->add('activity 3', null, navigation_node::TYPE_ACTIVITY, null, 'act3'); + $res1 = $section2->add('resource 1', null, navigation_node::TYPE_RESOURCE, null, 'res1'); + $res2 = $section2->add('resource 2', null, navigation_node::TYPE_RESOURCE, null, 'res2'); + $res3 = $section2->add('resource 3', null, navigation_node::TYPE_RESOURCE, null, 'res3'); + + $this->assertTrue($node->exposed_module_extends_navigation('data')); + $this->assertFalse($node->exposed_module_extends_navigation('test1')); + } +} diff --git a/public/lib/tests/navigation/navbar_test.php b/public/lib/tests/navigation/navbar_test.php new file mode 100644 index 00000000000..d0e20536df6 --- /dev/null +++ b/public/lib/tests/navigation/navbar_test.php @@ -0,0 +1,79 @@ +. + +namespace core\navigation; + +/** + * Tests for navbar. + * + * @package core + * @category test + * @copyright 2025 Andrew Lyons + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +#[\PHPUnit\Framework\Attributes\CoversClass(navbar::class)] +final class navbar_test extends \advanced_testcase { + + public function test_navbar_prepend_and_add(): \moodle_page { + global $PAGE; + // Unfortunate hack needed because people use global $PAGE around the place. + $PAGE->set_url('/'); + + // We need to reset after this test because we using the generator. + $this->resetAfterTest(); + + $generator = self::getDataGenerator(); + $cat1 = $generator->create_category(); + $cat2 = $generator->create_category(array('parent' => $cat1->id)); + $course = $generator->create_course(array('category' => $cat2->id)); + + $page = new \moodle_page(); + $page->set_course($course); + $page->set_url(new \moodle_url('/course/view.php', array('id' => $course->id))); + $page->navbar->prepend('test 1'); + $page->navbar->prepend('test 2'); + $page->navbar->add('test 3'); + $page->navbar->add('test 4'); + + $items = $page->navbar->get_items(); + foreach ($items as $item) { + $this->assertInstanceOf(navigation_node::class, $item); + } + + $i = 0; + $this->assertSame('test 1', $items[$i++]->text); + $this->assertSame('test 2', $items[$i++]->text); + $this->assertSame('home', $items[$i++]->key); + $this->assertSame('courses', $items[$i++]->key); + $this->assertSame($cat1->id, $items[$i++]->key); + $this->assertSame($cat2->id, $items[$i++]->key); + $this->assertSame($course->id, $items[$i++]->key); + $this->assertSame('test 3', $items[$i++]->text); + $this->assertSame('test 4', $items[$i++]->text); + + return $page; + } + + /** + * @depends test_navbar_prepend_and_add + * @param $node + */ + public function test_navbar_has_items(\moodle_page $page): void { + $this->resetAfterTest(); + + $this->assertTrue($page->navbar->has_items()); + } +} diff --git a/public/lib/tests/navigation/navigation_cache_test.php b/public/lib/tests/navigation/navigation_cache_test.php new file mode 100644 index 00000000000..884b28aaeae --- /dev/null +++ b/public/lib/tests/navigation/navigation_cache_test.php @@ -0,0 +1,73 @@ +. + +namespace core\navigation; + +/** + * Tests for navigation_cache. + * + * @package core + * @category test + * @copyright 2025 Andrew Lyons + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +#[\PHPUnit\Framework\Attributes\CoversClass(navigation_cache::class)] +final class navigation_cache_test extends \advanced_testcase { + public function test_cache__get(): void { + $cache = new navigation_cache('unittest_nav'); + $cache->anysetvariable = true; + + $this->assertTrue($cache->anysetvariable); + $this->assertEquals($cache->notasetvariable, null); + } + + public function test_cache__set(): void { + $cache = new navigation_cache('unittest_nav'); + $cache->anysetvariable = true; + + $cache->myname = 'Sam Hemelryk'; + $this->assertTrue($cache->cached('myname')); + $this->assertSame('Sam Hemelryk', $cache->myname); + } + + public function test_cache_cached(): void { + $cache = new navigation_cache('unittest_nav'); + $cache->anysetvariable = true; + + $this->assertTrue($cache->cached('anysetvariable')); + $this->assertFalse($cache->cached('notasetvariable')); + } + + public function test_cache_clear(): void { + $cache = new navigation_cache('unittest_nav'); + $cache->anysetvariable = true; + + $cache = clone($cache); + $this->assertTrue($cache->cached('anysetvariable')); + $cache->clear(); + $this->assertFalse($cache->cached('anysetvariable')); + } + + public function test_cache_set(): void { + $cache = new navigation_cache('unittest_nav'); + $cache->anysetvariable = true; + + $cache->set('software', 'Moodle'); + $this->assertTrue($cache->cached('software')); + $this->assertEquals($cache->software, 'Moodle'); + } + +} diff --git a/public/lib/tests/navigation/navigation_node_collection_test.php b/public/lib/tests/navigation/navigation_node_collection_test.php new file mode 100644 index 00000000000..a5d190b0a8a --- /dev/null +++ b/public/lib/tests/navigation/navigation_node_collection_test.php @@ -0,0 +1,72 @@ +. + +namespace core\navigation; + +use core\tests\navigation\navigation_testcase; + +/** + * Tests for navigation_node_collection. + * + * @package core + * @category test + * @copyright 2025 Andrew Lyons + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +#[\PHPUnit\Framework\Attributes\CoversClass(navigation_node_collection::class)] +final class navigation_node_collection_test extends navigation_testcase { + public function test_navigation_node_collection_remove_with_no_type(): void { + $navigationnodecollection = new navigation_node_collection(); + $node = $this->setup_node(); + $node->key = 100; + + // Test it's empty. + $this->assertEquals(0, count($navigationnodecollection->get_key_list())); + + // Add a node. + $navigationnodecollection->add($node); + + // Test it's not empty. + $this->assertEquals(1, count($navigationnodecollection->get_key_list())); + + // Remove a node - passing key only! + $this->assertTrue($navigationnodecollection->remove(100)); + + // Test it's empty again! + $this->assertEquals(0, count($navigationnodecollection->get_key_list())); + } + + public function test_navigation_node_collection_remove_with_type(): void { + $navigationnodecollection = new navigation_node_collection(); + $node = $this->setup_node(); + $node->key = 100; + + // Test it's empty. + $this->assertEquals(0, count($navigationnodecollection->get_key_list())); + + // Add a node. + $navigationnodecollection->add($node); + + // Test it's not empty. + $this->assertEquals(1, count($navigationnodecollection->get_key_list())); + + // Remove a node - passing type. + $this->assertTrue($navigationnodecollection->remove(100, 1)); + + // Test it's empty again! + $this->assertEquals(0, count($navigationnodecollection->get_key_list())); + } +} diff --git a/public/lib/tests/navigation/navigation_node_test.php b/public/lib/tests/navigation/navigation_node_test.php new file mode 100644 index 00000000000..8d69a718c36 --- /dev/null +++ b/public/lib/tests/navigation/navigation_node_test.php @@ -0,0 +1,431 @@ +. + +namespace core\navigation; + +use core\output\action_link; +use core\output\actions\popup_action; +use core\output\pix_icon; +use core\tests\navigation\navigation_testcase; + +/** + * Tests for navigation_node. + * + * @package core + * @category test + * @copyright 2025 Andrew Lyons + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +#[\PHPUnit\Framework\Attributes\CoversClass(navigation_node::class)] +final class navigation_node_test extends navigation_testcase { + public function test_node__construct(): void { + $node = $this->setup_node(); + + $fakeproperties = array( + 'text' => 'text', + 'shorttext' => 'A very silly extra long short text string, more than 25 characters', + 'key' => 'key', + 'type' => 'navigation_node::TYPE_COURSE', + 'action' => new \moodle_url('http://www.moodle.org/')); + + $node = new navigation_node($fakeproperties); + $this->assertSame($fakeproperties['text'], $node->text); + $this->assertTrue(strpos($fakeproperties['shorttext'], substr($node->shorttext, 0, -3)) === 0); + $this->assertSame($fakeproperties['key'], $node->key); + $this->assertSame($fakeproperties['type'], $node->type); + $this->assertSame($fakeproperties['action'], $node->action); + } + + public function test_node_add(): void { + $node = $this->setup_node(); + + // Add a node with all args set. + $node1 = $node->add('test_add_1', 'http://www.moodle.org/', navigation_node::TYPE_COURSE, 'testadd1', 'key', new pix_icon('i/course', '')); + // Add a node with the minimum args required. + $node2 = $node->add('test_add_2', null, navigation_node::TYPE_CUSTOM, 'testadd2'); + $node3 = $node->add(str_repeat('moodle ', 15), str_repeat('moodle', 15)); + + $this->assertInstanceOf(navigation_node::class, $node1); + $this->assertInstanceOf(navigation_node::class, $node2); + $this->assertInstanceOf(navigation_node::class, $node3); + + $ref = $node->get('key'); + $this->assertSame($node1, $ref); + + $ref = $node->get($node2->key); + $this->assertSame($node2, $ref); + + $ref = $node->get($node2->key, $node2->type); + $this->assertSame($node2, $ref); + + $ref = $node->get($node3->key, $node3->type); + $this->assertSame($node3, $ref); + } + + public function test_node_add_before(): void { + $node = $this->setup_node(); + + // Create 3 nodes. + $node1 = navigation_node::create('test_add_1', null, navigation_node::TYPE_CUSTOM, + 'test 1', 'testadd1'); + $node2 = navigation_node::create('test_add_2', null, navigation_node::TYPE_CUSTOM, + 'test 2', 'testadd2'); + $node3 = navigation_node::create('test_add_3', null, navigation_node::TYPE_CUSTOM, + 'test 3', 'testadd3'); + // Add node 2, then node 1 before 2, then node 3 at end. + $node->add_node($node2); + $node->add_node($node1, 'testadd2'); + $node->add_node($node3); + // Check the last 3 nodes are in 1, 2, 3 order and have those indexes. + foreach ($node->children as $child) { + $keys[] = $child->key; + } + $this->assertSame('testadd1', $keys[count($keys)-3]); + $this->assertSame('testadd2', $keys[count($keys)-2]); + $this->assertSame('testadd3', $keys[count($keys)-1]); + } + + public function test_node_add_class(): void { + $node = $this->setup_node(); + + $node = $node->get('demo1'); + $this->assertInstanceOf(navigation_node::class, $node); + if ($node !== false) { + $node->add_class('myclass'); + $classes = $node->classes; + $this->assertContains('myclass', $classes); + } + } + + /** + * Test the add_attribute method. + * @covers \navigation_node::add_attribute + */ + public function test_node_add_attribute(): void { + $node = $this->setup_node(); + + $node = $node->get('demo1'); + $this->assertInstanceOf(navigation_node::class, $node); + if ($node !== false) { + $node->add_attribute('data-foo', 'bar'); + $attribute = reset($node->attributes); + $this->assertEqualsCanonicalizing(['name' => 'data-foo', 'value' => 'bar'], $attribute); + } + } + + public function test_node_check_if_active(): void { + $node = $this->setup_node(); + + // First test the string urls + // Demo1 -> action is http://www.moodle.org/, thus should be true. + $demo5 = $node->find('demo5', navigation_node::TYPE_COURSE); + if ($this->assertInstanceOf(navigation_node::class, $demo5)) { + $this->assertTrue($demo5->check_if_active()); + } + + // Demo2 -> action is http://www.moodle.com/, thus should be false. + $demo2 = $node->get('demo2'); + if ($this->assertInstanceOf(navigation_node::class, $demo2)) { + $this->assertFalse($demo2->check_if_active()); + } + } + + public function test_node_contains_active_node(): void { + $node = $this->setup_node(); + + // Demo5, and activity1 were set to active during setup. + // Should be true as it contains all nodes. + $this->assertTrue($node->contains_active_node()); + // Should be true as demo5 is a child of demo3. + $this->assertTrue($node->get('demo3')->contains_active_node()); + // Obviously duff. + $this->assertFalse($node->get('demo1')->contains_active_node()); + // Should be true as demo5 contains activity1. + $this->assertTrue($node->get('demo3')->get('demo5')->contains_active_node()); + // Should be true activity1 is the active node. + $this->assertTrue($node->get('demo3')->get('demo5')->get('activity1')->contains_active_node()); + // Obviously duff. + $this->assertFalse($node->get('demo3')->get('demo4')->contains_active_node()); + } + + public function test_node_find_active_node(): void { + $node = $this->setup_node(); + + $activenode1 = $node->find_active_node(); + $activenode2 = $node->get('demo1')->find_active_node(); + + if ($this->assertInstanceOf(navigation_node::class, $activenode1)) { + $ref = $node->get('demo3')->get('demo5')->get('activity1'); + $this->assertSame($activenode1, $ref); + } + + $this->assertNotInstanceOf(navigation_node::class, $activenode2); + } + + public function test_node_find(): void { + $node = $this->setup_node(); + + $node1 = $node->find('demo1', navigation_node::TYPE_COURSE); + $node2 = $node->find('demo5', navigation_node::TYPE_COURSE); + $node3 = $node->find('demo5', navigation_node::TYPE_CATEGORY); + $node4 = $node->find('demo0', navigation_node::TYPE_COURSE); + $this->assertInstanceOf(navigation_node::class, $node1); + $this->assertInstanceOf(navigation_node::class, $node2); + $this->assertNotInstanceOf(navigation_node::class, $node3); + $this->assertNotInstanceOf(navigation_node::class, $node4); + } + + public function test_node_find_expandable(): void { + $node = $this->setup_node(); + + $expandable = array(); + $node->find_expandable($expandable); + + $this->assertCount(0, $expandable); + if (count($expandable) === 4) { + $name = $expandable[0]['key']; + $name .= $expandable[1]['key']; + $name .= $expandable[2]['key']; + $name .= $expandable[3]['key']; + $this->assertSame('demo1demo2demo4hiddendemo2', $name); + } + } + + public function test_node_get(): void { + $node = $this->setup_node(); + + $node1 = $node->get('demo1'); // Exists. + $node2 = $node->get('demo4'); // Doesn't exist for this node. + $node3 = $node->get('demo0'); // Doesn't exist at all. + $node4 = $node->get(false); // Sometimes occurs in nature code. + $this->assertInstanceOf(navigation_node::class, $node1); + $this->assertFalse($node2); + $this->assertFalse($node3); + $this->assertFalse($node4); + } + + public function test_node_get_css_type(): void { + $node = $this->setup_node(); + + $csstype1 = $node->get('demo3')->get_css_type(); + $csstype2 = $node->get('demo3')->get('demo5')->get_css_type(); + $node->get('demo3')->get('demo5')->type = 1000; + $csstype3 = $node->get('demo3')->get('demo5')->get_css_type(); + $csstype4 = $node->get('demo3')->get('demo6')->get_css_type(); + $this->assertSame('type_category', $csstype1); + $this->assertSame('type_course', $csstype2); + $this->assertSame('type_unknown', $csstype3); + $this->assertSame('type_container', $csstype4); + } + + public function test_node_make_active(): void { + global $CFG; + $node = $this->setup_node(); + + $node1 = $node->add('active node 1', null, navigation_node::TYPE_CUSTOM, null, 'anode1'); + $node2 = $node->add('active node 2', new \moodle_url($CFG->wwwroot), navigation_node::TYPE_COURSE, null, 'anode2'); + $node1->make_active(); + $node->get('anode2')->make_active(); + $this->assertTrue($node1->isactive); + $this->assertTrue($node->get('anode2')->isactive); + } + + public function test_node_remove(): void { + $node = $this->setup_node(); + + $remove1 = $node->add('child to remove 1', null, navigation_node::TYPE_CUSTOM, null, 'remove1'); + $remove2 = $node->add('child to remove 2', null, navigation_node::TYPE_CUSTOM, null, 'remove2'); + $remove3 = $remove2->add('child to remove 3', null, navigation_node::TYPE_CUSTOM, null, 'remove3'); + + $this->assertInstanceOf(navigation_node::class, $remove1); + $this->assertInstanceOf(navigation_node::class, $remove2); + $this->assertInstanceOf(navigation_node::class, $remove3); + + $this->assertInstanceOf(navigation_node::class, $node->get('remove1')); + $this->assertInstanceOf(navigation_node::class, $node->get('remove2')); + $this->assertInstanceOf(navigation_node::class, $remove2->get('remove3')); + + // Remove element and make sure this is no longer a child. + $this->assertTrue($remove1->remove()); + $this->assertFalse($node->get('remove1')); + $this->assertFalse(in_array('remove1', $node->get_children_key_list(), true)); + + // Make sure that we can insert element after removal. + $insertelement = navigation_node::create('extra element 4', null, navigation_node::TYPE_CUSTOM, null, 'element4'); + $node->add_node($insertelement, 'remove2'); + $this->assertNotEmpty($node->get('element4')); + + // Remove more elements. + $this->assertTrue($node->get('remove2')->remove()); + $this->assertFalse($node->get('remove2')); + + // Make sure that we can add element after removal. + $node->add('extra element 5', null, navigation_node::TYPE_CUSTOM, null, 'element5'); + $this->assertNotEmpty($node->get('element5')); + + $this->assertTrue($remove2->get('remove3')->remove()); + + $this->assertFalse($node->get('remove1')); + $this->assertFalse($node->get('remove2')); + } + + public function test_node_remove_class(): void { + $node = $this->setup_node(); + + $node->add_class('testclass'); + $this->assertTrue($node->remove_class('testclass')); + $this->assertNotContains('testclass', $node->classes); + } + + + /** + * Test the set_force_into_more_menu method. + * + * @param bool $haschildren Whether the navigation node has children nodes + * @param bool $forceintomoremenu Whether to force the navigation node and its children into the "more" menu + */ + #[\PHPUnit\Framework\Attributes\DataProvider('set_force_into_more_menu_provider')] + public function test_set_force_into_more_menu(bool $haschildren, bool $forceintomoremenu): void { + // Create a navigation node. + $node = new navigation_node(['text' => 'Navigation node', 'key' => 'navnode']); + + // If required, add some children nodes to the navigation node. + if ($haschildren) { + for ($i = 1; $i <= 3; $i++) { + $node->add("Child navigation node {$i}"); + } + } + + $node->set_force_into_more_menu($forceintomoremenu); + // Assert that the expected value has been assigned to the 'forceintomoremenu' property + // in the navigation node and its children. + $this->assertEquals($forceintomoremenu, $node->forceintomoremenu); + foreach ($node->children as $child) { + $this->assertEquals($forceintomoremenu, $child->forceintomoremenu); + } + } + + /** + * Data provider for the test_set_force_into_more_menu function. + * + * @return array + */ + public static function set_force_into_more_menu_provider(): array { + return [ + 'Navigation node without any children nodes; Force into "more" menu => true.' => [ + false, + true, + ], + 'Navigation node with children nodes; Force into "more" menu => true.' => [ + true, + true, + ], + 'Navigation node with children nodes; Force into "more" menu => false.' => [ + true, + false, + ], + ]; + } + + /** + * Test the is_action_link method. + * + * @param navigation_node $node The sample navigation node + * @param bool $expected Whether the navigation node contains an action link + * @dataProvider is_action_link_provider + * @covers navigation_node::is_action_link + */ + public function test_is_action_link(navigation_node $node, bool $expected): void { + $this->assertEquals($node->is_action_link(), $expected); + } + + /** + * Data provider for the test_is_action_link function. + * + * @return array + */ + public static function is_action_link_provider(): array { + return [ + 'The navigation node has an action link.' => + [ + navigation_node::create('Node', new action_link(new \moodle_url('/'), '', + new popup_action('click', new \moodle_url('/'))), navigation_node::TYPE_SETTING), + true + ], + + 'The navigation node does not have an action link.' => + [ + navigation_node::create('Node', new \moodle_url('/'), navigation_node::TYPE_SETTING), + false + ], + ]; + } + + /** + * Test the action_link_actions method. + * + * @param navigation_node $node The sample navigation node + * @dataProvider action_link_actions_provider + * @covers navigation_node::action_link_actions + */ + public function test_action_link_actions(navigation_node $node): void { + // Get the formatted array of action link actions. + $data = $node->action_link_actions(); + // The navigation node has an action link. + if ($node->action instanceof action_link) { + if (!empty($node->action->actions)) { // There are actions added to the action link. + $this->assertArrayHasKey('actions', $data); + $this->assertCount(1, $data['actions']); + $expected = (object)[ + 'id' => $node->action->attributes['id'], + 'event' => $node->action->actions[0]->event, + 'jsfunction' => $node->action->actions[0]->jsfunction, + 'jsfunctionargs' => json_encode($node->action->actions[0]->jsfunctionargs) + ]; + $this->assertEquals($expected, $data['actions'][0]); + } else { // There are no actions added to the action link. + $this->assertArrayHasKey('actions', $data); + $this->assertEmpty($data['actions']); + } + } else { // The navigation node does not have an action link. + $this->assertEmpty($data); + } + } + + /** + * Data provider for the test_action_link_actions function. + * + * @return array + */ + public static function action_link_actions_provider(): array { + return [ + 'The navigation node has an action link with an action attached.' => + [ + navigation_node::create('Node', new action_link(new \moodle_url('/'), '', + new popup_action('click', new \moodle_url('/'))), navigation_node::TYPE_SETTING), + ], + 'The navigation node has an action link without an action.' => + [ + navigation_node::create('Node', new action_link(new \moodle_url('/'), '', null), + navigation_node::TYPE_SETTING), + ], + 'The navigation node does not have an action link.' => + [ + navigation_node::create('Node', new \moodle_url('/'), navigation_node::TYPE_SETTING), + ], + ]; + } +} diff --git a/public/lib/tests/navigation/output/primary_test.php b/public/lib/tests/navigation/output/primary_test.php index 75140428107..e5915dedc72 100644 --- a/public/lib/tests/navigation/output/primary_test.php +++ b/public/lib/tests/navigation/output/primary_test.php @@ -374,7 +374,7 @@ final class primary_test extends \advanced_testcase { } $primary = new primary($PAGE); - $method = new ReflectionMethod('core\navigation\output\primary', 'get_primary_nav'); + $method = new ReflectionMethod(primary::class, 'get_primary_nav'); $dataprimary = $method->invoke($primary); // Take this custom menu that would come from the setting custommenitems. @@ -393,7 +393,7 @@ final class primary_test extends \advanced_testcase { ENDMENU; $datacustom = $this->get_custom_menu($custommenuitems); - $method = new ReflectionMethod('core\navigation\output\primary', 'merge_primary_and_custom'); + $method = new ReflectionMethod(primary::class, 'merge_primary_and_custom'); $menucomplete = $method->invoke($primary, $dataprimary, $datacustom, $ismobile); return $menucomplete; } diff --git a/public/lib/tests/navigation/settings_navigation_test.php b/public/lib/tests/navigation/settings_navigation_test.php new file mode 100644 index 00000000000..bd087870cc3 --- /dev/null +++ b/public/lib/tests/navigation/settings_navigation_test.php @@ -0,0 +1,108 @@ +. + +namespace core\navigation; + +use core\tests\navigation\exposed_settings_navigation; + +/** + * Tests for + * + * @package core + * @category test + * @copyright 2025 Andrew Lyons + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +final class settings_navigation_test extends \advanced_testcase { + public function test_setting___construct(): settings_navigation { + global $PAGE, $SITE; + + $this->resetAfterTest(false); + + $PAGE->set_url('/'); + $PAGE->set_course($SITE); + + $node = new exposed_settings_navigation(); + + return $node; + } + + /** + * @depends test_setting___construct + * @param mixed $node + * @return mixed + */ + public function test_setting__initialise($node): settings_navigation { + $this->resetAfterTest(false); + + $node->initialise(); + $this->assertEquals($node->id, 'settingsnav'); + + return $node; + } + + + /** + * @depends test_setting__initialise + * @param mixed $node + * @return mixed + */ + public function test_setting_in_alternative_role($node): void { + $this->resetAfterTest(); + + $this->assertFalse($node->exposed_in_alternative_role()); + } + + /** + * Test that users with the correct permissions can view the preferences page. + */ + public function test_can_view_user_preferences(): void { + global $PAGE, $DB, $SITE; + $this->resetAfterTest(); + + $persontoview = $this->getDataGenerator()->create_user(); + $persondoingtheviewing = $this->getDataGenerator()->create_user(); + + $PAGE->set_url('/'); + $PAGE->set_course($SITE); + + // Check that a standard user can not view the preferences page. + $studentrole = $DB->get_record('role', array('shortname' => 'student')); + $this->getDataGenerator()->role_assign($studentrole->id, $persondoingtheviewing->id); + $this->setUser($persondoingtheviewing); + $settingsnav = new exposed_settings_navigation(); + $settingsnav->initialise(); + $settingsnav->extend_for_user($persontoview->id); + $this->assertFalse($settingsnav->can_view_user_preferences($persontoview->id)); + + // Set persondoingtheviewing as a manager. + $managerrole = $DB->get_record('role', array('shortname' => 'manager')); + $this->getDataGenerator()->role_assign($managerrole->id, $persondoingtheviewing->id); + $settingsnav = new exposed_settings_navigation(); + $settingsnav->initialise(); + $settingsnav->extend_for_user($persontoview->id); + $this->assertTrue($settingsnav->can_view_user_preferences($persontoview->id)); + + // Check that the admin can view the preferences page. + $this->setAdminUser(); + $settingsnav = new exposed_settings_navigation(); + $settingsnav->initialise(); + $settingsnav->extend_for_user($persontoview->id); + $preferencenode = $settingsnav->find('userviewingsettings' . $persontoview->id, null); + $this->assertTrue($settingsnav->can_view_user_preferences($persontoview->id)); + } + +} diff --git a/public/lib/tests/navigationlib_test.php b/public/lib/tests/navigationlib_test.php deleted file mode 100644 index a270dec0579..00000000000 --- a/public/lib/tests/navigationlib_test.php +++ /dev/null @@ -1,824 +0,0 @@ -. - -namespace core; - -use action_link; -use global_navigation; -use navbar; -use navigation_cache; -use navigation_node; -use navigation_node_collection; -use pix_icon; -use popup_action; -use settings_navigation; - -defined('MOODLE_INTERNAL') || die(); - -global $CFG; -require_once($CFG->libdir . '/navigationlib.php'); - -/** - * Unit tests for lib/navigationlib.php - * - * @package core - * @category test - * @copyright 2009 Sam Hemelryk - * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later (5) - */ -final class navigationlib_test extends \advanced_testcase { - /** - * @var navigation_node - */ - public $node; - - protected function setup_node() { - global $PAGE, $SITE; - - // Perform a reset between tests to reset the PAGE. - $this->resetAfterTest(); - - $PAGE->set_url('/'); - $PAGE->set_course($SITE); - - $activeurl = $PAGE->url; - $inactiveurl = new \moodle_url('http://www.moodle.com/'); - - navigation_node::override_active_url($PAGE->url); - - $this->node = new navigation_node('Test Node'); - $this->node->type = navigation_node::TYPE_SYSTEM; - // We add the first child without key. This way we make sure all keys search by comparison is performed using ===. - $this->node->add('first child without key', null, navigation_node::TYPE_CUSTOM); - $demo1 = $this->node->add('demo1', $inactiveurl, navigation_node::TYPE_COURSE, null, 'demo1', new pix_icon('i/course', '')); - $demo2 = $this->node->add('demo2', $inactiveurl, navigation_node::TYPE_COURSE, null, 'demo2', new pix_icon('i/course', '')); - $demo3 = $this->node->add('demo3', $inactiveurl, navigation_node::TYPE_CATEGORY, null, 'demo3', new pix_icon('i/course', '')); - $demo4 = $demo3->add('demo4', $inactiveurl, navigation_node::TYPE_COURSE, null, 'demo4', new pix_icon('i/course', '')); - $demo5 = $demo3->add('demo5', $activeurl, navigation_node::TYPE_COURSE, null, 'demo5', new pix_icon('i/course', '')); - $demo5->add('activity1', null, navigation_node::TYPE_ACTIVITY, null, 'activity1')->make_active(); - $demo6 = $demo3->add('demo6', null, navigation_node::TYPE_CONTAINER, 'container node test', 'demo6'); - $hiddendemo1 = $this->node->add('hiddendemo1', $inactiveurl, navigation_node::TYPE_CATEGORY, null, 'hiddendemo1', new pix_icon('i/course', '')); - $hiddendemo1->hidden = true; - $hiddendemo1->add('hiddendemo2', $inactiveurl, navigation_node::TYPE_COURSE, null, 'hiddendemo2', new pix_icon('i/course', ''))->helpbutton = 'Here is a help button'; - $hiddendemo1->add('hiddendemo3', $inactiveurl, navigation_node::TYPE_COURSE, null, 'hiddendemo3', new pix_icon('i/course', ''))->display = false; - } - - public function test_node__construct(): void { - $this->setup_node(); - - $fakeproperties = array( - 'text' => 'text', - 'shorttext' => 'A very silly extra long short text string, more than 25 characters', - 'key' => 'key', - 'type' => 'navigation_node::TYPE_COURSE', - 'action' => new \moodle_url('http://www.moodle.org/')); - - $node = new navigation_node($fakeproperties); - $this->assertSame($fakeproperties['text'], $node->text); - $this->assertTrue(strpos($fakeproperties['shorttext'], substr($node->shorttext, 0, -3)) === 0); - $this->assertSame($fakeproperties['key'], $node->key); - $this->assertSame($fakeproperties['type'], $node->type); - $this->assertSame($fakeproperties['action'], $node->action); - } - - public function test_node_add(): void { - $this->setup_node(); - - // Add a node with all args set. - $node1 = $this->node->add('test_add_1', 'http://www.moodle.org/', navigation_node::TYPE_COURSE, 'testadd1', 'key', new pix_icon('i/course', '')); - // Add a node with the minimum args required. - $node2 = $this->node->add('test_add_2', null, navigation_node::TYPE_CUSTOM, 'testadd2'); - $node3 = $this->node->add(str_repeat('moodle ', 15), str_repeat('moodle', 15)); - - $this->assertInstanceOf('navigation_node', $node1); - $this->assertInstanceOf('navigation_node', $node2); - $this->assertInstanceOf('navigation_node', $node3); - - $ref = $this->node->get('key'); - $this->assertSame($node1, $ref); - - $ref = $this->node->get($node2->key); - $this->assertSame($node2, $ref); - - $ref = $this->node->get($node2->key, $node2->type); - $this->assertSame($node2, $ref); - - $ref = $this->node->get($node3->key, $node3->type); - $this->assertSame($node3, $ref); - } - - public function test_node_add_before(): void { - $this->setup_node(); - - // Create 3 nodes. - $node1 = navigation_node::create('test_add_1', null, navigation_node::TYPE_CUSTOM, - 'test 1', 'testadd1'); - $node2 = navigation_node::create('test_add_2', null, navigation_node::TYPE_CUSTOM, - 'test 2', 'testadd2'); - $node3 = navigation_node::create('test_add_3', null, navigation_node::TYPE_CUSTOM, - 'test 3', 'testadd3'); - // Add node 2, then node 1 before 2, then node 3 at end. - $this->node->add_node($node2); - $this->node->add_node($node1, 'testadd2'); - $this->node->add_node($node3); - // Check the last 3 nodes are in 1, 2, 3 order and have those indexes. - foreach ($this->node->children as $child) { - $keys[] = $child->key; - } - $this->assertSame('testadd1', $keys[count($keys)-3]); - $this->assertSame('testadd2', $keys[count($keys)-2]); - $this->assertSame('testadd3', $keys[count($keys)-1]); - } - - public function test_node_add_class(): void { - $this->setup_node(); - - $node = $this->node->get('demo1'); - $this->assertInstanceOf('navigation_node', $node); - if ($node !== false) { - $node->add_class('myclass'); - $classes = $node->classes; - $this->assertContains('myclass', $classes); - } - } - - /** - * Test the add_attribute method. - * @covers \navigation_node::add_attribute - */ - public function test_node_add_attribute(): void { - $this->setup_node(); - - $node = $this->node->get('demo1'); - $this->assertInstanceOf('navigation_node', $node); - if ($node !== false) { - $node->add_attribute('data-foo', 'bar'); - $attribute = reset($node->attributes); - $this->assertEqualsCanonicalizing(['name' => 'data-foo', 'value' => 'bar'], $attribute); - } - } - - public function test_node_check_if_active(): void { - $this->setup_node(); - - // First test the string urls - // Demo1 -> action is http://www.moodle.org/, thus should be true. - $demo5 = $this->node->find('demo5', navigation_node::TYPE_COURSE); - if ($this->assertInstanceOf('navigation_node', $demo5)) { - $this->assertTrue($demo5->check_if_active()); - } - - // Demo2 -> action is http://www.moodle.com/, thus should be false. - $demo2 = $this->node->get('demo2'); - if ($this->assertInstanceOf('navigation_node', $demo2)) { - $this->assertFalse($demo2->check_if_active()); - } - } - - public function test_node_contains_active_node(): void { - $this->setup_node(); - - // Demo5, and activity1 were set to active during setup. - // Should be true as it contains all nodes. - $this->assertTrue($this->node->contains_active_node()); - // Should be true as demo5 is a child of demo3. - $this->assertTrue($this->node->get('demo3')->contains_active_node()); - // Obviously duff. - $this->assertFalse($this->node->get('demo1')->contains_active_node()); - // Should be true as demo5 contains activity1. - $this->assertTrue($this->node->get('demo3')->get('demo5')->contains_active_node()); - // Should be true activity1 is the active node. - $this->assertTrue($this->node->get('demo3')->get('demo5')->get('activity1')->contains_active_node()); - // Obviously duff. - $this->assertFalse($this->node->get('demo3')->get('demo4')->contains_active_node()); - } - - public function test_node_find_active_node(): void { - $this->setup_node(); - - $activenode1 = $this->node->find_active_node(); - $activenode2 = $this->node->get('demo1')->find_active_node(); - - if ($this->assertInstanceOf('navigation_node', $activenode1)) { - $ref = $this->node->get('demo3')->get('demo5')->get('activity1'); - $this->assertSame($activenode1, $ref); - } - - $this->assertNotInstanceOf('navigation_node', $activenode2); - } - - public function test_node_find(): void { - $this->setup_node(); - - $node1 = $this->node->find('demo1', navigation_node::TYPE_COURSE); - $node2 = $this->node->find('demo5', navigation_node::TYPE_COURSE); - $node3 = $this->node->find('demo5', navigation_node::TYPE_CATEGORY); - $node4 = $this->node->find('demo0', navigation_node::TYPE_COURSE); - $this->assertInstanceOf('navigation_node', $node1); - $this->assertInstanceOf('navigation_node', $node2); - $this->assertNotInstanceOf('navigation_node', $node3); - $this->assertNotInstanceOf('navigation_node', $node4); - } - - public function test_node_find_expandable(): void { - $this->setup_node(); - - $expandable = array(); - $this->node->find_expandable($expandable); - - $this->assertCount(0, $expandable); - if (count($expandable) === 4) { - $name = $expandable[0]['key']; - $name .= $expandable[1]['key']; - $name .= $expandable[2]['key']; - $name .= $expandable[3]['key']; - $this->assertSame('demo1demo2demo4hiddendemo2', $name); - } - } - - public function test_node_get(): void { - $this->setup_node(); - - $node1 = $this->node->get('demo1'); // Exists. - $node2 = $this->node->get('demo4'); // Doesn't exist for this node. - $node3 = $this->node->get('demo0'); // Doesn't exist at all. - $node4 = $this->node->get(false); // Sometimes occurs in nature code. - $this->assertInstanceOf('navigation_node', $node1); - $this->assertFalse($node2); - $this->assertFalse($node3); - $this->assertFalse($node4); - } - - public function test_node_get_css_type(): void { - $this->setup_node(); - - $csstype1 = $this->node->get('demo3')->get_css_type(); - $csstype2 = $this->node->get('demo3')->get('demo5')->get_css_type(); - $this->node->get('demo3')->get('demo5')->type = 1000; - $csstype3 = $this->node->get('demo3')->get('demo5')->get_css_type(); - $csstype4 = $this->node->get('demo3')->get('demo6')->get_css_type(); - $this->assertSame('type_category', $csstype1); - $this->assertSame('type_course', $csstype2); - $this->assertSame('type_unknown', $csstype3); - $this->assertSame('type_container', $csstype4); - } - - public function test_node_make_active(): void { - global $CFG; - $this->setup_node(); - - $node1 = $this->node->add('active node 1', null, navigation_node::TYPE_CUSTOM, null, 'anode1'); - $node2 = $this->node->add('active node 2', new \moodle_url($CFG->wwwroot), navigation_node::TYPE_COURSE, null, 'anode2'); - $node1->make_active(); - $this->node->get('anode2')->make_active(); - $this->assertTrue($node1->isactive); - $this->assertTrue($this->node->get('anode2')->isactive); - } - - public function test_node_remove(): void { - $this->setup_node(); - - $remove1 = $this->node->add('child to remove 1', null, navigation_node::TYPE_CUSTOM, null, 'remove1'); - $remove2 = $this->node->add('child to remove 2', null, navigation_node::TYPE_CUSTOM, null, 'remove2'); - $remove3 = $remove2->add('child to remove 3', null, navigation_node::TYPE_CUSTOM, null, 'remove3'); - - $this->assertInstanceOf('navigation_node', $remove1); - $this->assertInstanceOf('navigation_node', $remove2); - $this->assertInstanceOf('navigation_node', $remove3); - - $this->assertInstanceOf('navigation_node', $this->node->get('remove1')); - $this->assertInstanceOf('navigation_node', $this->node->get('remove2')); - $this->assertInstanceOf('navigation_node', $remove2->get('remove3')); - - // Remove element and make sure this is no longer a child. - $this->assertTrue($remove1->remove()); - $this->assertFalse($this->node->get('remove1')); - $this->assertFalse(in_array('remove1', $this->node->get_children_key_list(), true)); - - // Make sure that we can insert element after removal. - $insertelement = navigation_node::create('extra element 4', null, navigation_node::TYPE_CUSTOM, null, 'element4'); - $this->node->add_node($insertelement, 'remove2'); - $this->assertNotEmpty($this->node->get('element4')); - - // Remove more elements. - $this->assertTrue($this->node->get('remove2')->remove()); - $this->assertFalse($this->node->get('remove2')); - - // Make sure that we can add element after removal. - $this->node->add('extra element 5', null, navigation_node::TYPE_CUSTOM, null, 'element5'); - $this->assertNotEmpty($this->node->get('element5')); - - $this->assertTrue($remove2->get('remove3')->remove()); - - $this->assertFalse($this->node->get('remove1')); - $this->assertFalse($this->node->get('remove2')); - } - - public function test_node_remove_class(): void { - $this->setup_node(); - - $this->node->add_class('testclass'); - $this->assertTrue($this->node->remove_class('testclass')); - $this->assertNotContains('testclass', $this->node->classes); - } - - public function test_module_extends_navigation(): void { - $node = new exposed_global_navigation(); - // Create an initial tree structure to work with. - $cat1 = $node->add('category 1', null, navigation_node::TYPE_CATEGORY, null, 'cat1'); - $cat2 = $node->add('category 2', null, navigation_node::TYPE_CATEGORY, null, 'cat2'); - $cat3 = $node->add('category 3', null, navigation_node::TYPE_CATEGORY, null, 'cat3'); - $sub1 = $cat2->add('sub category 1', null, navigation_node::TYPE_CATEGORY, null, 'sub1'); - $sub2 = $cat2->add('sub category 2', null, navigation_node::TYPE_CATEGORY, null, 'sub2'); - $sub3 = $cat2->add('sub category 3', null, navigation_node::TYPE_CATEGORY, null, 'sub3'); - $course1 = $sub2->add('course 1', null, navigation_node::TYPE_COURSE, null, 'course1'); - $course2 = $sub2->add('course 2', null, navigation_node::TYPE_COURSE, null, 'course2'); - $course3 = $sub2->add('course 3', null, navigation_node::TYPE_COURSE, null, 'course3'); - $section1 = $course2->add('section 1', null, navigation_node::TYPE_SECTION, null, 'sec1'); - $section2 = $course2->add('section 2', null, navigation_node::TYPE_SECTION, null, 'sec2'); - $section3 = $course2->add('section 3', null, navigation_node::TYPE_SECTION, null, 'sec3'); - $act1 = $section2->add('activity 1', null, navigation_node::TYPE_ACTIVITY, null, 'act1'); - $act2 = $section2->add('activity 2', null, navigation_node::TYPE_ACTIVITY, null, 'act2'); - $act3 = $section2->add('activity 3', null, navigation_node::TYPE_ACTIVITY, null, 'act3'); - $res1 = $section2->add('resource 1', null, navigation_node::TYPE_RESOURCE, null, 'res1'); - $res2 = $section2->add('resource 2', null, navigation_node::TYPE_RESOURCE, null, 'res2'); - $res3 = $section2->add('resource 3', null, navigation_node::TYPE_RESOURCE, null, 'res3'); - - $this->assertTrue($node->exposed_module_extends_navigation('data')); - $this->assertFalse($node->exposed_module_extends_navigation('test1')); - } - - public function test_navbar_prepend_and_add(): \moodle_page { - global $PAGE; - // Unfortunate hack needed because people use global $PAGE around the place. - $PAGE->set_url('/'); - - // We need to reset after this test because we using the generator. - $this->resetAfterTest(); - - $generator = self::getDataGenerator(); - $cat1 = $generator->create_category(); - $cat2 = $generator->create_category(array('parent' => $cat1->id)); - $course = $generator->create_course(array('category' => $cat2->id)); - - $page = new \moodle_page(); - $page->set_course($course); - $page->set_url(new \moodle_url('/course/view.php', array('id' => $course->id))); - $page->navbar->prepend('test 1'); - $page->navbar->prepend('test 2'); - $page->navbar->add('test 3'); - $page->navbar->add('test 4'); - - $items = $page->navbar->get_items(); - foreach ($items as $item) { - $this->assertInstanceOf('navigation_node', $item); - } - - $i = 0; - $this->assertSame('test 1', $items[$i++]->text); - $this->assertSame('test 2', $items[$i++]->text); - $this->assertSame('home', $items[$i++]->key); - $this->assertSame('courses', $items[$i++]->key); - $this->assertSame($cat1->id, $items[$i++]->key); - $this->assertSame($cat2->id, $items[$i++]->key); - $this->assertSame($course->id, $items[$i++]->key); - $this->assertSame('test 3', $items[$i++]->text); - $this->assertSame('test 4', $items[$i++]->text); - - return $page; - } - - /** - * @depends test_navbar_prepend_and_add - * @param $node - */ - public function test_navbar_has_items(\moodle_page $page): void { - $this->resetAfterTest(); - - $this->assertTrue($page->navbar->has_items()); - } - - public function test_cache__get(): void { - $cache = new navigation_cache('unittest_nav'); - $cache->anysetvariable = true; - - $this->assertTrue($cache->anysetvariable); - $this->assertEquals($cache->notasetvariable, null); - } - - public function test_cache__set(): void { - $cache = new navigation_cache('unittest_nav'); - $cache->anysetvariable = true; - - $cache->myname = 'Sam Hemelryk'; - $this->assertTrue($cache->cached('myname')); - $this->assertSame('Sam Hemelryk', $cache->myname); - } - - public function test_cache_cached(): void { - $cache = new navigation_cache('unittest_nav'); - $cache->anysetvariable = true; - - $this->assertTrue($cache->cached('anysetvariable')); - $this->assertFalse($cache->cached('notasetvariable')); - } - - public function test_cache_clear(): void { - $cache = new navigation_cache('unittest_nav'); - $cache->anysetvariable = true; - - $cache = clone($cache); - $this->assertTrue($cache->cached('anysetvariable')); - $cache->clear(); - $this->assertFalse($cache->cached('anysetvariable')); - } - - public function test_cache_set(): void { - $cache = new navigation_cache('unittest_nav'); - $cache->anysetvariable = true; - - $cache->set('software', 'Moodle'); - $this->assertTrue($cache->cached('software')); - $this->assertEquals($cache->software, 'Moodle'); - } - - public function test_setting___construct(): settings_navigation { - global $PAGE, $SITE; - - $this->resetAfterTest(false); - - $PAGE->set_url('/'); - $PAGE->set_course($SITE); - - $node = new exposed_settings_navigation(); - - return $node; - } - - /** - * @depends test_setting___construct - * @param mixed $node - * @return mixed - */ - public function test_setting__initialise($node): settings_navigation { - $this->resetAfterTest(false); - - $node->initialise(); - $this->assertEquals($node->id, 'settingsnav'); - - return $node; - } - - /** - * Test that users with the correct permissions can view the preferences page. - */ - public function test_can_view_user_preferences(): void { - global $PAGE, $DB, $SITE; - $this->resetAfterTest(); - - $persontoview = $this->getDataGenerator()->create_user(); - $persondoingtheviewing = $this->getDataGenerator()->create_user(); - - $PAGE->set_url('/'); - $PAGE->set_course($SITE); - - // Check that a standard user can not view the preferences page. - $studentrole = $DB->get_record('role', array('shortname' => 'student')); - $this->getDataGenerator()->role_assign($studentrole->id, $persondoingtheviewing->id); - $this->setUser($persondoingtheviewing); - $settingsnav = new exposed_settings_navigation(); - $settingsnav->initialise(); - $settingsnav->extend_for_user($persontoview->id); - $this->assertFalse($settingsnav->can_view_user_preferences($persontoview->id)); - - // Set persondoingtheviewing as a manager. - $managerrole = $DB->get_record('role', array('shortname' => 'manager')); - $this->getDataGenerator()->role_assign($managerrole->id, $persondoingtheviewing->id); - $settingsnav = new exposed_settings_navigation(); - $settingsnav->initialise(); - $settingsnav->extend_for_user($persontoview->id); - $this->assertTrue($settingsnav->can_view_user_preferences($persontoview->id)); - - // Check that the admin can view the preferences page. - $this->setAdminUser(); - $settingsnav = new exposed_settings_navigation(); - $settingsnav->initialise(); - $settingsnav->extend_for_user($persontoview->id); - $preferencenode = $settingsnav->find('userviewingsettings' . $persontoview->id, null); - $this->assertTrue($settingsnav->can_view_user_preferences($persontoview->id)); - } - - /** - * @depends test_setting__initialise - * @param mixed $node - * @return mixed - */ - public function test_setting_in_alternative_role($node): void { - $this->resetAfterTest(); - - $this->assertFalse($node->exposed_in_alternative_role()); - } - - - public function test_navigation_node_collection_remove_with_no_type(): void { - $navigationnodecollection = new navigation_node_collection(); - $this->setup_node(); - $this->node->key = 100; - - // Test it's empty - $this->assertEquals(0, count($navigationnodecollection->get_key_list())); - - // Add a node - $navigationnodecollection->add($this->node); - - // Test it's not empty - $this->assertEquals(1, count($navigationnodecollection->get_key_list())); - - // Remove a node - passing key only! - $this->assertTrue($navigationnodecollection->remove(100)); - - // Test it's empty again! - $this->assertEquals(0, count($navigationnodecollection->get_key_list())); - } - - public function test_navigation_node_collection_remove_with_type(): void { - $navigationnodecollection = new navigation_node_collection(); - $this->setup_node(); - $this->node->key = 100; - - // Test it's empty - $this->assertEquals(0, count($navigationnodecollection->get_key_list())); - - // Add a node - $navigationnodecollection->add($this->node); - - // Test it's not empty - $this->assertEquals(1, count($navigationnodecollection->get_key_list())); - - // Remove a node - passing type - $this->assertTrue($navigationnodecollection->remove(100, 1)); - - // Test it's empty again! - $this->assertEquals(0, count($navigationnodecollection->get_key_list())); - } - - /** - * Test the set_force_into_more_menu method. - * - * @param bool $haschildren Whether the navigation node has children nodes - * @param bool $forceintomoremenu Whether to force the navigation node and its children into the "more" menu - * @dataProvider set_force_into_more_menu_provider - */ - public function test_set_force_into_more_menu(bool $haschildren, bool $forceintomoremenu): void { - // Create a navigation node. - $node = new navigation_node(['text' => 'Navigation node', 'key' => 'navnode']); - - // If required, add some children nodes to the navigation node. - if ($haschildren) { - for ($i = 1; $i <= 3; $i++) { - $node->add("Child navigation node {$i}"); - } - } - - $node->set_force_into_more_menu($forceintomoremenu); - // Assert that the expected value has been assigned to the 'forceintomoremenu' property - // in the navigation node and its children. - $this->assertEquals($forceintomoremenu, $node->forceintomoremenu); - foreach ($node->children as $child) { - $this->assertEquals($forceintomoremenu, $child->forceintomoremenu); - } - } - - /** - * Data provider for the test_set_force_into_more_menu function. - * - * @return array - */ - public static function set_force_into_more_menu_provider(): array { - return [ - 'Navigation node without any children nodes; Force into "more" menu => true.' => - [ - false, - true, - ], - 'Navigation node with children nodes; Force into "more" menu => true.' => - [ - true, - true, - ], - 'Navigation node with children nodes; Force into "more" menu => false.' => - [ - true, - false, - ], - ]; - } - - /** - * Test the is_action_link method. - * - * @param navigation_node $node The sample navigation node - * @param bool $expected Whether the navigation node contains an action link - * @dataProvider is_action_link_provider - * @covers navigation_node::is_action_link - */ - public function test_is_action_link(navigation_node $node, bool $expected): void { - $this->assertEquals($node->is_action_link(), $expected); - } - - /** - * Data provider for the test_is_action_link function. - * - * @return array - */ - public static function is_action_link_provider(): array { - return [ - 'The navigation node has an action link.' => - [ - navigation_node::create('Node', new action_link(new \moodle_url('/'), '', - new popup_action('click', new \moodle_url('/'))), navigation_node::TYPE_SETTING), - true - ], - - 'The navigation node does not have an action link.' => - [ - navigation_node::create('Node', new \moodle_url('/'), navigation_node::TYPE_SETTING), - false - ], - ]; - } - - /** - * Test the action_link_actions method. - * - * @param navigation_node $node The sample navigation node - * @dataProvider action_link_actions_provider - * @covers navigation_node::action_link_actions - */ - public function test_action_link_actions(navigation_node $node): void { - // Get the formatted array of action link actions. - $data = $node->action_link_actions(); - // The navigation node has an action link. - if ($node->action instanceof action_link) { - if (!empty($node->action->actions)) { // There are actions added to the action link. - $this->assertArrayHasKey('actions', $data); - $this->assertCount(1, $data['actions']); - $expected = (object)[ - 'id' => $node->action->attributes['id'], - 'event' => $node->action->actions[0]->event, - 'jsfunction' => $node->action->actions[0]->jsfunction, - 'jsfunctionargs' => json_encode($node->action->actions[0]->jsfunctionargs) - ]; - $this->assertEquals($expected, $data['actions'][0]); - } else { // There are no actions added to the action link. - $this->assertArrayHasKey('actions', $data); - $this->assertEmpty($data['actions']); - } - } else { // The navigation node does not have an action link. - $this->assertEmpty($data); - } - } - - /** - * Data provider for the test_action_link_actions function. - * - * @return array - */ - public static function action_link_actions_provider(): array { - return [ - 'The navigation node has an action link with an action attached.' => - [ - navigation_node::create('Node', new action_link(new \moodle_url('/'), '', - new popup_action('click', new \moodle_url('/'))), navigation_node::TYPE_SETTING), - ], - 'The navigation node has an action link without an action.' => - [ - navigation_node::create('Node', new action_link(new \moodle_url('/'), '', null), - navigation_node::TYPE_SETTING), - ], - 'The navigation node does not have an action link.' => - [ - navigation_node::create('Node', new \moodle_url('/'), navigation_node::TYPE_SETTING), - ], - ]; - } -} - - -/** - * This is a dummy object that allows us to call protected methods within the - * global navigation class by prefixing the methods with `exposed_` - */ -class exposed_global_navigation extends global_navigation { - protected $exposedkey = 'exposed_'; - public function __construct(?\moodle_page $page=null) { - global $PAGE; - if ($page === null) { - $page = $PAGE; - } - parent::__construct($page); - } - public function __call($method, $arguments) { - if (strpos($method, $this->exposedkey) !== false) { - $method = substr($method, strlen($this->exposedkey)); - } - if (method_exists($this, $method)) { - return call_user_func_array(array($this, $method), $arguments); - } - throw new \coding_exception('You have attempted to access a method that does not exist for the given object '.$method, DEBUG_DEVELOPER); - } - public function set_initialised() { - $this->initialised = true; - } -} - - -class mock_initialise_global_navigation extends global_navigation { - - protected static $count = 1; - - public function load_for_category() { - $this->add('load_for_category', null, null, null, 'initcall'.self::$count); - self::$count++; - return 0; - } - - public function load_for_course() { - $this->add('load_for_course', null, null, null, 'initcall'.self::$count); - self::$count++; - return 0; - } - - public function load_for_activity() { - $this->add('load_for_activity', null, null, null, 'initcall'.self::$count); - self::$count++; - return 0; - } - - public function load_for_user($user=null, $forceforcontext=false) { - $this->add('load_for_user', null, null, null, 'initcall'.self::$count); - self::$count++; - return 0; - } -} - -/** - * This is a dummy object that allows us to call protected methods within the - * global navigation class by prefixing the methods with `exposed_`. - */ -class exposed_navbar extends navbar { - protected $exposedkey = 'exposed_'; - - public function __construct(\moodle_page $page) { - parent::__construct($page); - } - public function __call($method, $arguments) { - if (strpos($method, $this->exposedkey) !== false) { - $method = substr($method, strlen($this->exposedkey)); - } - if (method_exists($this, $method)) { - return call_user_func_array(array($this, $method), $arguments); - } - throw new \coding_exception('You have attempted to access a method that does not exist for the given object '.$method, DEBUG_DEVELOPER); - } -} - -class navigation_exposed_moodle_page extends \moodle_page { - public function set_navigation(navigation_node $node) { - $this->_navigation = $node; - } -} - -/** - * This is a dummy object that allows us to call protected methods within the - * global navigation class by prefixing the methods with `exposed_`. - */ -class exposed_settings_navigation extends settings_navigation { - protected $exposedkey = 'exposed_'; - public function __construct() { - global $PAGE; - parent::__construct($PAGE); - } - public function __call($method, $arguments) { - if (strpos($method, $this->exposedkey) !== false) { - $method = substr($method, strlen($this->exposedkey)); - } - if (method_exists($this, $method)) { - return call_user_func_array(array($this, $method), $arguments); - } - throw new \coding_exception('You have attempted to access a method that does not exist for the given object '.$method, DEBUG_DEVELOPER); - } -} From 090926c281663f7ea7c641054ff2eedda1178268 Mon Sep 17 00:00:00 2001 From: Andrew Nicols Date: Wed, 30 Jul 2025 23:34:15 +0800 Subject: [PATCH 3/4] MDL-82159 core: Coding style fixes for navigation --- .../navigation/breadcrumb_navigation_node.php | 2 - .../classes/navigation/flat_navigation.php | 21 +- .../navigation/flat_navigation_node.php | 2 - .../classes/navigation/global_navigation.php | 645 +++++++----- .../navigation/global_navigation_for_ajax.php | 64 +- public/lib/classes/navigation/navbar.php | 110 ++- .../classes/navigation/navigation_cache.php | 13 +- .../classes/navigation/navigation_json.php | 31 +- .../classes/navigation/navigation_node.php | 234 ++--- .../navigation/navigation_node_collection.php | 74 +- .../navigation/settings_navigation.php | 915 ++++++++++++------ .../navigation/exposed_global_navigation.php | 10 +- .../exposed_settings_navigation.php | 10 +- .../navigation/navigation_testcase.php | 34 +- public/lib/tests/navigation/navbar_test.php | 12 +- .../navigation/navigation_cache_test.php | 1 - .../tests/navigation/navigation_node_test.php | 75 +- .../navigation/settings_navigation_test.php | 8 +- 18 files changed, 1392 insertions(+), 869 deletions(-) diff --git a/public/lib/classes/navigation/breadcrumb_navigation_node.php b/public/lib/classes/navigation/breadcrumb_navigation_node.php index 7a20eee304b..59e4c934cac 100644 --- a/public/lib/classes/navigation/breadcrumb_navigation_node.php +++ b/public/lib/classes/navigation/breadcrumb_navigation_node.php @@ -28,7 +28,6 @@ use core\exception\coding_exception; * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ class breadcrumb_navigation_node extends navigation_node { - /** @var $last boolean A flag indicating this is the last item in the list of breadcrumbs. */ private $last = false; @@ -41,7 +40,6 @@ class breadcrumb_navigation_node extends navigation_node { if (is_array($navnode)) { parent::__construct($navnode); } else if ($navnode instanceof navigation_node) { - // Just clone everything. $objvalues = get_object_vars($navnode); foreach ($objvalues as $key => $value) { diff --git a/public/lib/classes/navigation/flat_navigation.php b/public/lib/classes/navigation/flat_navigation.php index c97fbb533de..8690dd008e9 100644 --- a/public/lib/classes/navigation/flat_navigation.php +++ b/public/lib/classes/navigation/flat_navigation.php @@ -30,6 +30,10 @@ use moodle_page; * @copyright 2016 Damyon Wiese * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ +#[\core\attribute\deprecated( + since: '4.0', + reason: 'Do not use this class any more. Leverage secondary/tertiary navigation concepts.' +)] class flat_navigation extends navigation_node_collection { /** @var moodle_page the moodle page that the navigation belongs to */ protected $page; @@ -66,7 +70,7 @@ class flat_navigation extends navigation_node_collection { // First walk the nav tree looking for "flat_navigation" nodes. if ($course->id > 1) { // It's a real course. - $url = new url('/course/view.php', array('id' => $course->id)); + $url = new url('/course/view.php', ['id' => $course->id]); $coursecontext = context_course::instance($course->id, MUST_EXIST); $displaycontext = context_helper::get_navigation_filter_context($coursecontext); @@ -123,9 +127,11 @@ class flat_navigation extends navigation_node_collection { } // Add-a-block in editing mode. - if (isset($this->page->theme->addblockposition) && + if ( + isset($this->page->theme->addblockposition) && $this->page->theme->addblockposition == BLOCK_ADDBLOCK_POSITION_FLATNAV && - $PAGE->user_is_editing() && $PAGE->user_can_edit_blocks()) { + $PAGE->user_is_editing() && $PAGE->user_can_edit_blocks() + ) { $url = new url($PAGE->url, ['bui_addblock' => '', 'sesskey' => sesskey()]); $addablock = navigation_node::create(get_string('addblock'), $url); $flat = new flat_navigation_node($addablock, 0); @@ -136,8 +142,11 @@ class flat_navigation extends navigation_node_collection { $addblockurl = "?{$url->get_query_string(false)}"; - $PAGE->requires->js_call_amd('core_block/add_modal', 'init', - [$addblockurl, $this->page->get_edited_page_hash()]); + $PAGE->requires->js_call_amd( + 'core_block/add_modal', + 'init', + [$addblockurl, $this->page->get_edited_page_hash()] + ); } } @@ -149,7 +158,7 @@ class flat_navigation extends navigation_node_collection { * otherwise adds at end * @return navigation_node Added node */ - public function add(navigation_node $node, $beforekey=null) { + public function add(navigation_node $node, $beforekey = null) { $result = parent::add($node, $beforekey); // Extend the parent to get a name for the collection of nodes if required. if (empty($this->collectionlabel)) { diff --git a/public/lib/classes/navigation/flat_navigation_node.php b/public/lib/classes/navigation/flat_navigation_node.php index 20f74daa52b..4ddb924e63e 100644 --- a/public/lib/classes/navigation/flat_navigation_node.php +++ b/public/lib/classes/navigation/flat_navigation_node.php @@ -29,7 +29,6 @@ use core\exception\coding_exception; * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ class flat_navigation_node extends navigation_node { - /** @var $indent integer The indent level */ private $indent = 0; @@ -49,7 +48,6 @@ class flat_navigation_node extends navigation_node { if (is_array($navnode)) { parent::__construct($navnode); } else if ($navnode instanceof navigation_node) { - // Just clone everything. $objvalues = get_object_vars($navnode); foreach ($objvalues as $key => $value) { diff --git a/public/lib/classes/navigation/global_navigation.php b/public/lib/classes/navigation/global_navigation.php index 5804af2a79d..d111355b46d 100644 --- a/public/lib/classes/navigation/global_navigation.php +++ b/public/lib/classes/navigation/global_navigation.php @@ -58,25 +58,25 @@ class global_navigation extends navigation_node { /** @var bool switch to let us know if the navigation object is initialised*/ protected $initialised = false; /** @var array An array of course information */ - protected $mycourses = array(); + protected $mycourses = []; /** @var navigation_node[] An array for containing root navigation nodes */ - protected $rootnodes = array(); + protected $rootnodes = []; /** @var bool A switch for whether to show empty sections in the navigation */ protected $showemptysections = true; /** @var bool A switch for whether courses should be shown within categories on the navigation. */ protected $showcategories = null; - /** @var null@var bool A switch for whether or not to show categories in the my courses branch. */ + /** @var null|var bool A switch for whether or not to show categories in the my courses branch. */ protected $showmycategories = null; /** @var array An array of stdClasses for users that the navigation is extended for */ - protected $extendforuser = array(); + protected $extendforuser = []; /** @var navigation_cache */ protected $cache; /** @var array An array of course ids that are present in the navigation */ - protected $addedcourses = array(); + protected $addedcourses = []; /** @var bool */ protected $allcategoriesloaded = false; /** @var array An array of category ids that are included in the navigation */ - protected $addedcategories = array(); + protected $addedcategories = []; /** @var int expansion limit */ protected $expansionlimit = 0; /** @var int userid to allow parent to see child's profile page navigation */ @@ -85,9 +85,9 @@ class global_navigation extends navigation_node { protected $cacheexpandcourse = null; /** Used when loading categories to load all top level categories [parent = 0] **/ - const LOAD_ROOT_CATEGORIES = 0; + public const LOAD_ROOT_CATEGORIES = 0; /** Used when loading categories to load all categories **/ - const LOAD_ALL_CATEGORIES = -1; + public const LOAD_ALL_CATEGORIES = -1; /** * Constructs a new global navigation @@ -104,38 +104,38 @@ class global_navigation extends navigation_node { $homepage = get_home_page(); if ($homepage == HOMEPAGE_MY) { // We are using the users my moodle for the root element. - $properties = array( + $properties = [ 'key' => 'myhome', 'type' => navigation_node::TYPE_SYSTEM, 'text' => get_string('myhome'), 'action' => new url('/my/'), 'icon' => new pix_icon('i/dashboard', ''), - ); + ]; } else if ($homepage == HOMEPAGE_MYCOURSES) { // We are using the user's course summary page for the root element. - $properties = array( + $properties = [ 'key' => 'mycourses', 'type' => navigation_node::TYPE_SYSTEM, 'text' => get_string('mycourses'), 'action' => new url('/my/courses.php'), - 'icon' => new pix_icon('i/course', '') - ); + 'icon' => new pix_icon('i/course', ''), + ]; } else { // We are using the site home for the root element. - $properties = array( + $properties = [ 'key' => 'home', 'type' => navigation_node::TYPE_SYSTEM, 'text' => get_string('home'), 'action' => new url('/'), 'icon' => new pix_icon('i/home', ''), - ); + ]; } - // Use the parents constructor.... good good reuse + // Use the parents constructor.... good good reuse. parent::__construct($properties); $this->showinflatnavigation = true; - // Initalise and set defaults + // Initalise and set defaults. $this->page = $page; $this->forceopen = true; $this->cache = new navigation_cache(NAVIGATION_CACHE_NAME); @@ -168,53 +168,72 @@ class global_navigation extends navigation_node { */ public function initialise() { global $CFG, $SITE, $USER; - // Check if it has already been initialised + // Check if it has already been initialised. if ($this->initialised || during_initial_install()) { return true; } $this->initialised = true; - // Set up the five base root nodes. These are nodes where we will put our - // content and are as follows: - // site: Navigation for the front page. - // myprofile: User profile information goes here. - // currentcourse: The course being currently viewed. - // mycourses: The users courses get added here. - // courses: Additional courses are added here. - // users: Other users information loaded here. - $this->rootnodes = array(); + // Set up the five base root nodes. These are nodes where we will put our content and are as follows: + // - site: Navigation for the front page. + // - myprofile: User profile information goes here. + // - currentcourse: The course being currently viewed. + // - mycourses: The users courses get added here. + // - courses: Additional courses are added here. + // - users: Other users information loaded here. + $this->rootnodes = []; $defaulthomepage = get_home_page(); if ($defaulthomepage == HOMEPAGE_SITE) { - // The home element should be my moodle because the root element is the site - if (isloggedin() && !isguestuser()) { // Makes no sense if you aren't logged in + // The home element should be my moodle because the root element is the site. + if (isloggedin() && !isguestuser()) { // Makes no sense if you aren't logged in. if (!empty($CFG->enabledashboard)) { // Only add dashboard to home if it's enabled. - $this->rootnodes['home'] = $this->add(get_string('myhome'), new url('/my/'), - self::TYPE_SETTING, null, 'myhome', new pix_icon('i/dashboard', '')); + $this->rootnodes['home'] = $this->add( + get_string('myhome'), + new url('/my/'), + self::TYPE_SETTING, + null, + 'myhome', + new pix_icon('i/dashboard', '') + ); $this->rootnodes['home']->showinflatnavigation = true; } } } else { - // The home element should be the site because the root node is my moodle - $this->rootnodes['home'] = $this->add(get_string('sitehome'), new url('/'), - self::TYPE_SETTING, null, 'home', new pix_icon('i/home', '')); + // The home element should be the site because the root node is my moodle. + $this->rootnodes['home'] = $this->add( + get_string('sitehome'), + new url('/'), + self::TYPE_SETTING, + null, + 'home', + new pix_icon('i/home', '') + ); $this->rootnodes['home']->showinflatnavigation = true; - if (!empty($CFG->defaulthomepage) && - ($CFG->defaulthomepage == HOMEPAGE_MY || $CFG->defaulthomepage == HOMEPAGE_MYCOURSES)) { - // We need to stop automatic redirection + if ( + !empty($CFG->defaulthomepage) && + ($CFG->defaulthomepage == HOMEPAGE_MY || $CFG->defaulthomepage == HOMEPAGE_MYCOURSES) + ) { + // We need to stop automatic redirection. $this->rootnodes['home']->action->param('redirect', '0'); } } $this->rootnodes['site'] = $this->add_course($SITE); $this->rootnodes['myprofile'] = $this->add(get_string('profile'), null, self::TYPE_USER, null, 'myprofile'); - $this->rootnodes['currentcourse'] = $this->add(get_string('currentcourse'), null, self::TYPE_ROOTNODE, null, 'currentcourse'); + $this->rootnodes['currentcourse'] = $this->add( + get_string('currentcourse'), + null, + self::TYPE_ROOTNODE, + null, + 'currentcourse', + ); $this->rootnodes['mycourses'] = $this->add( get_string('mycourses'), new url('/my/courses.php'), self::TYPE_ROOTNODE, null, 'mycourses', - new pix_icon('i/course', '') + new pix_icon('i/course', ''), ); // We do not need to show this node in the breadcrumbs if the default homepage is mycourses. // It will be automatically handled by the breadcrumb generator. @@ -222,21 +241,26 @@ class global_navigation extends navigation_node { $this->rootnodes['mycourses']->mainnavonly = true; } - $this->rootnodes['courses'] = $this->add(get_string('courses'), new url('/course/index.php'), self::TYPE_ROOTNODE, null, 'courses'); + $this->rootnodes['courses'] = $this->add( + get_string('courses'), + new url('/course/index.php'), + self::TYPE_ROOTNODE, + null, + 'courses', + ); if (!core_course_category::user_top()) { $this->rootnodes['courses']->hide(); } $this->rootnodes['users'] = $this->add(get_string('users'), null, self::TYPE_ROOTNODE, null, 'users'); - // We always load the frontpage course to ensure it is available without - // JavaScript enabled. + // We always load the frontpage course to ensure it is available without JavaScript enabled. $this->add_front_page_course_essentials($this->rootnodes['site'], $SITE); $this->load_course_sections($SITE, $this->rootnodes['site']); $course = $this->page->course; $this->load_courses_enrolled(); - // $issite gets set to true if the current pages course is the sites frontpage course + // Note: $issite gets set to true if the current pages course is the sites frontpage course. $issite = ($this->page->course->id == $SITE->id); // Determine if the user is enrolled in any course. @@ -257,17 +281,17 @@ class global_navigation extends navigation_node { $canviewcourseprofile = true; - // Next load context specific content into the navigation + // Next load context specific content into the navigation. switch ($this->page->context->contextlevel) { - case CONTEXT_SYSTEM : + case CONTEXT_SYSTEM: // Nothing left to do here I feel. break; - case CONTEXT_COURSECAT : + case CONTEXT_COURSECAT: // This is essential, we must load categories. $this->load_all_categories($this->page->context->instanceid, true); break; - case CONTEXT_BLOCK : - case CONTEXT_COURSE : + case CONTEXT_BLOCK: + case CONTEXT_COURSE: if ($issite) { // Nothing left to do here. break; @@ -275,16 +299,16 @@ class global_navigation extends navigation_node { // Load the course associated with the current page into the navigation. $coursenode = $this->add_course($course, false, self::COURSE_CURRENT); + // If the course wasn't added then don't try going any further. if (!$coursenode) { $canviewcourseprofile = false; break; } - // If the user is not enrolled then we only want to show the - // course node and not populate it. + // If the user is not enrolled then we only want to show the course node and not populate it. - // Not enrolled, can't view, and hasn't switched roles + // Not enrolled, can't view, and hasn't switched roles. if (!can_access_course($course, null, '', true)) { if ($coursenode->isexpandable === true) { // Obviously the situation has changed, update the cache and adjust the node. @@ -294,8 +318,8 @@ class global_navigation extends navigation_node { $coursenode->isexpandable = true; $coursenode->nodetype = self::NODETYPE_BRANCH; } - // Very ugly hack - do not force "parents" to enrol into course their child is enrolled in, - // this hack has been propagated from user/view.php to display the navigation node. (MDL-25805) + // Very ugly hack - do not force "parents" to enrol into course their child is enrolled in. + // This hack has been propagated from user/view.php to display the navigation node. (MDL-25805). if (!$this->current_user_is_parent_role()) { $coursenode->make_active(); $canviewcourseprofile = false; @@ -312,19 +336,17 @@ class global_navigation extends navigation_node { // Add the essentials such as reports etc... $this->add_course_essentials($coursenode, $course); - // Extend course navigation with it's sections/activities + // Extend course navigation with it's sections/activities. $this->load_course_sections($course, $coursenode); if (!$coursenode->contains_active_node() && !$coursenode->search_for_active_node()) { $coursenode->make_active(); } break; - case CONTEXT_MODULE : + case CONTEXT_MODULE: if ($issite) { - // If this is the site course then most information will have - // already been loaded. - // However we need to check if there is more content that can - // yet be loaded for the specific module instance. + // If this is the site course then most information will have already been loaded. + // However we need to check if there is more content that can yet be loaded for the specific module instance. $activitynode = $this->rootnodes['site']->find($this->page->cm->id, navigation_node::TYPE_ACTIVITY); if ($activitynode) { $this->load_activity($this->page->cm, $this->page->course, $activitynode); @@ -335,7 +357,7 @@ class global_navigation extends navigation_node { $course = $this->page->course; $cm = $this->page->cm; - // Load the course associated with the page into the navigation + // Load the course associated with the page into the navigation. $coursenode = $this->add_course($course, false, self::COURSE_CURRENT); // If the course wasn't added then don't try going any further. @@ -344,8 +366,7 @@ class global_navigation extends navigation_node { break; } - // If the user is not enrolled then we only want to show the - // course node and not populate it. + // If the user is not enrolled then we only want to show the course node and not populate it. if (!can_access_course($course, null, '', true)) { $coursenode->make_active(); $canviewcourseprofile = false; @@ -354,27 +375,27 @@ class global_navigation extends navigation_node { $this->add_course_essentials($coursenode, $course); - // Load the course sections into the page + // Load the course sections into the page. $this->load_course_sections($course, $coursenode, null, $cm); $activity = $coursenode->find($cm->id, navigation_node::TYPE_ACTIVITY); if (!empty($activity)) { - // Finally load the cm specific navigaton information + // Finally load the cm specific navigaton information. $this->load_activity($cm, $course, $activity); - // Check if we have an active ndoe + + // Check if we have an active node. if (!$activity->contains_active_node() && !$activity->search_for_active_node()) { // And make the activity node active. $activity->make_active(); } } break; - case CONTEXT_USER : + case CONTEXT_USER: if ($issite) { - // The users profile information etc is already loaded - // for the front page. + // The users profile information etc is already loaded for the front page. break; } $course = $this->page->course; - // Load the course associated with the user into the navigation + // Load the course associated with the user into the navigation. $coursenode = $this->add_course($course, false, self::COURSE_CURRENT); // If the course wasn't added then don't try going any further. @@ -383,8 +404,7 @@ class global_navigation extends navigation_node { break; } - // If the user is not enrolled then we only want to show the - // course node and not populate it. + // If the user is not enrolled then we only want to show the course node and not populate it. if (!can_access_course($course, null, '', true)) { $coursenode->make_active(); $canviewcourseprofile = false; @@ -395,9 +415,13 @@ class global_navigation extends navigation_node { break; } - // Load for the current user + // Load for the current user. $this->load_for_user(); - if ($this->page->context->contextlevel >= CONTEXT_COURSE && $this->page->context->instanceid != $SITE->id && $canviewcourseprofile) { + if ( + $this->page->context->contextlevel >= CONTEXT_COURSE + && $this->page->context->instanceid != $SITE->id + && $canviewcourseprofile + ) { $this->load_for_user(null, true); } // Load each extending user into the navigation. @@ -410,10 +434,9 @@ class global_navigation extends navigation_node { // Give the local plugins a chance to include some navigation if they want. $this->load_local_plugin_navigation(); - // Remove any empty root nodes + // Remove any empty root nodes. foreach ($this->rootnodes as $node) { - // Dont remove the home node - /** @var navigation_node $node */ + // Dont remove the home node. if (!in_array($node->key, ['home', 'mycourses', 'myhome']) && !$node->has_children() && !$node->isactive) { $node->remove(); } @@ -465,7 +488,7 @@ class global_navigation extends navigation_node { if (!has_capability('moodle/user:viewdetails', $usercontext)) { return false; } - if ($DB->record_exists('role_assignments', array('userid' => $USER->id, 'contextid' => $usercontext->id))) { + if ($DB->record_exists('role_assignments', ['userid' => $USER->id, 'contextid' => $usercontext->id])) { return true; } } @@ -523,16 +546,16 @@ class global_navigation extends navigation_node { $limit = $CFG->navcourselimit; } - $toload = (empty($CFG->navshowallcourses))?self::LOAD_ROOT_CATEGORIES:self::LOAD_ALL_CATEGORIES; + $toload = (empty($CFG->navshowallcourses)) ? self::LOAD_ROOT_CATEGORIES : self::LOAD_ALL_CATEGORIES; // If we are going to show all courses AND we are showing categories then - // to save us repeated DB calls load all of the categories now + // to save us repeated DB calls load all of the categories now. if ($this->show_categories()) { $this->load_all_categories($toload); } - // Will be the return of our efforts - $coursenodes = array(); + // Will be the return of our efforts. + $coursenodes = []; // Check if we need to show categories. if ($this->show_categories()) { @@ -541,16 +564,16 @@ class global_navigation extends navigation_node { // be displayed. if ($categoryids !== null) { if (!is_array($categoryids)) { - $categoryids = array($categoryids); + $categoryids = [$categoryids]; } - list($categorywhere, $categoryparams) = $DB->get_in_or_equal($categoryids, SQL_PARAMS_NAMED, 'cc'); - $categorywhere = 'WHERE cc.id '.$categorywhere; + [$categorywhere, $categoryparams] = $DB->get_in_or_equal($categoryids, SQL_PARAMS_NAMED, 'cc'); + $categorywhere = 'WHERE cc.id ' . $categorywhere; } else if ($toload == self::LOAD_ROOT_CATEGORIES) { $categorywhere = 'WHERE cc.depth = 1 OR cc.depth = 2'; - $categoryparams = array(); + $categoryparams = []; } else { $categorywhere = ''; - $categoryparams = array(); + $categoryparams = []; } // First up we are going to get the categories that we are going to @@ -561,8 +584,8 @@ class global_navigation extends navigation_node { {$categorywhere} GROUP BY cc.id"; $categories = $DB->get_recordset_sql($sql, $categoryparams); - $fullfetch = array(); - $partfetch = array(); + $fullfetch = []; + $partfetch = []; foreach ($categories as $category) { if (!$this->can_add_more_courses_to_category($category->id)) { continue; @@ -578,7 +601,7 @@ class global_navigation extends navigation_node { if (count($fullfetch)) { // First up fetch all of the courses in categories where we know that we are going to // need the majority of courses. - list($categoryids, $categoryparams) = $DB->get_in_or_equal($fullfetch, SQL_PARAMS_NAMED, 'lcategory'); + [$categoryids, $categoryparams] = $DB->get_in_or_equal($fullfetch, SQL_PARAMS_NAMED, 'lcategory'); $ccselect = ', ' . context_helper::get_preload_record_columns_sql('ctx'); $ccjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)"; $categoryparams['contextlevel'] = CONTEXT_COURSE; @@ -603,7 +626,11 @@ class global_navigation extends navigation_node { continue; } context_helper::preload_from_record($course); - if (!$course->visible && !is_role_switched($course->id) && !has_capability('moodle/course:viewhiddencourses', context_course::instance($course->id))) { + if ( + !$course->visible + && !is_role_switched($course->id) + && !has_capability('moodle/course:viewhiddencourses', context_course::instance($course->id)) + ) { continue; } $coursenodes[$course->id] = $this->add_course($course); @@ -622,7 +649,7 @@ class global_navigation extends navigation_node { $ccjoin WHERE c.category = :categoryid ORDER BY c.sortorder ASC"; - $courseparams = array('categoryid' => $categoryid, 'contextlevel' => CONTEXT_COURSE); + $courseparams = ['categoryid' => $categoryid, 'contextlevel' => CONTEXT_COURSE]; $coursesrs = $DB->get_recordset_sql($sql, $courseparams, 0, $limit * 5); foreach ($coursesrs as $course) { if ($course->id == $SITE->id) { @@ -640,7 +667,11 @@ class global_navigation extends navigation_node { break; } context_helper::preload_from_record($course); - if (!$course->visible && !is_role_switched($course->id) && !has_capability('moodle/course:viewhiddencourses', context_course::instance($course->id))) { + if ( + !$course->visible + && !is_role_switched($course->id) + && !has_capability('moodle/course:viewhiddencourses', context_course::instance($course->id)) + ) { continue; } $coursenodes[$course->id] = $this->add_course($course); @@ -649,8 +680,11 @@ class global_navigation extends navigation_node { } } } else { - // Prepare the SQL to load the courses and their contexts - list($courseids, $courseparams) = $DB->get_in_or_equal(array_keys($this->addedcourses), SQL_PARAMS_NAMED, 'lc', false); + // Prepare the SQL to load the courses and their contexts. + [ + $courseids, + $courseparams, + ] = $DB->get_in_or_equal(array_keys($this->addedcourses), SQL_PARAMS_NAMED, 'lc', false); $ccselect = ', ' . context_helper::get_preload_record_columns_sql('ctx'); $ccjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)"; $courseparams['contextlevel'] = CONTEXT_COURSE; @@ -662,15 +696,19 @@ class global_navigation extends navigation_node { $coursesrs = $DB->get_recordset_sql($sql, $courseparams); foreach ($coursesrs as $course) { if ($course->id == $SITE->id) { - // frotpage is not wanted here + // Frontpage is not wanted here. continue; } if ($this->page->course && ($this->page->course->id == $course->id)) { - // Don't include the currentcourse in this nodelist - it's displayed in the Current course node + // Don't include the currentcourse in this nodelist - it's displayed in the Current course node. continue; } context_helper::preload_from_record($course); - if (!$course->visible && !is_role_switched($course->id) && !has_capability('moodle/course:viewhiddencourses', context_course::instance($course->id))) { + if ( + !$course->visible + && !is_role_switched($course->id) + && !has_capability('moodle/course:viewhiddencourses', context_course::instance($course->id)) + ) { continue; } $coursenodes[$course->id] = $this->add_course($course); @@ -706,7 +744,7 @@ class global_navigation extends navigation_node { return false; } $coursecount = count($category->children->type(self::TYPE_COURSE)); - } else if (is_object($category) && property_exists($category,'id')) { + } else if (is_object($category) && property_exists($category, 'id')) { $coursecount = count($this->addedcategories[$category->id]->children->type(self::TYPE_COURSE)); } return ($coursecount <= $limit); @@ -723,7 +761,7 @@ class global_navigation extends navigation_node { protected function load_all_categories($categoryid = self::LOAD_ROOT_CATEGORIES, $showbasecategories = false) { global $CFG, $DB; - // Check if this category has already been loaded + // Check if this category has already been loaded. if ($this->allcategoriesloaded || ($categoryid < 1 && $this->is_category_fully_loaded($categoryid))) { return true; } @@ -732,58 +770,58 @@ class global_navigation extends navigation_node { $sqlselect = "SELECT cc.*, $catcontextsql FROM {course_categories} cc JOIN {context} ctx ON cc.id = ctx.instanceid"; - $sqlwhere = "WHERE ctx.contextlevel = ".CONTEXT_COURSECAT; + $sqlwhere = "WHERE ctx.contextlevel = " . CONTEXT_COURSECAT; $sqlorder = "ORDER BY cc.depth ASC, cc.sortorder ASC, cc.id ASC"; - $params = array(); + $params = []; - $categoriestoload = array(); + $categoriestoload = []; + // phpcs:ignore Generic.CodeAnalysis.EmptyStatement.DetectedIf if ($categoryid == self::LOAD_ALL_CATEGORIES) { - // We are going to load all categories regardless... prepare to fire - // on the database server! - } else if ($categoryid == self::LOAD_ROOT_CATEGORIES) { // can be 0 - // We are going to load all of the first level categories (categories without parents) + // We are going to load all categories regardless. + } else if ($categoryid == self::LOAD_ROOT_CATEGORIES) { // Note: can be 0. + // We are going to load all of the first level categories (categories without parents). $sqlwhere .= " AND cc.parent = 0"; } else if (array_key_exists($categoryid, $this->addedcategories)) { - // The category itself has been loaded already so we just need to ensure its subcategories - // have been loaded + // The category itself has been loaded already so we just need to ensure its subcategories have been loaded. $addedcategories = $this->addedcategories; unset($addedcategories[$categoryid]); if (count($addedcategories) > 0) { - list($sql, $params) = $DB->get_in_or_equal(array_keys($addedcategories), SQL_PARAMS_NAMED, 'parent', false); + [$sql, $params] = $DB->get_in_or_equal(array_keys($addedcategories), SQL_PARAMS_NAMED, 'parent', false); if ($showbasecategories) { - // We need to include categories with parent = 0 as well + // We need to include categories with parent = 0 as well. $sqlwhere .= " AND (cc.parent = :categoryid OR cc.parent = 0) AND cc.parent {$sql}"; } else { - // All we need is categories that match the parent + // All we need is categories that match the parent. $sqlwhere .= " AND cc.parent = :categoryid AND cc.parent {$sql}"; } } $params['categoryid'] = $categoryid; } else { // This category hasn't been loaded yet so we need to fetch it, work out its category path - // and load this category plus all its parents and subcategories - $category = $DB->get_record('course_categories', array('id' => $categoryid), 'path', MUST_EXIST); + // and load this category plus all its parents and subcategories. + $category = $DB->get_record('course_categories', ['id' => $categoryid], 'path', MUST_EXIST); $categoriestoload = explode('/', trim($category->path, '/')); - list($select, $params) = $DB->get_in_or_equal($categoriestoload); - // We are going to use select twice so double the params + [$select, $params] = $DB->get_in_or_equal($categoriestoload); + // We are going to use select twice so double the param. $params = array_merge($params, $params); - $basecategorysql = ($showbasecategories)?' OR cc.depth = 1':''; + $basecategorysql = ($showbasecategories) ? ' OR cc.depth = 1' : ''; $sqlwhere .= " AND (cc.id {$select} OR cc.parent {$select}{$basecategorysql})"; } $categoriesrs = $DB->get_recordset_sql("$sqlselect $sqlwhere $sqlorder", $params); - $categories = array(); + $categories = []; foreach ($categoriesrs as $category) { - // Preload the context.. we'll need it when adding the category in order - // to format the category name. + // Preload the context.. we'll need it when adding the category in order to format the category name. context_helper::preload_from_record($category); + + // phpcs:ignore Generic.CodeAnalysis.EmptyStatement.DetectedIf if (array_key_exists($category->id, $this->addedcategories)) { // Do nothing, its already been added. } else if ($category->parent == '0') { - // This is a root category lets add it immediately + // This is a root category lets add it immediately. $this->add_category($category, $this->rootnodes['courses']); } else if (array_key_exists($category->parent, $this->addedcategories)) { - // This categories parent has already been added we can add this immediately + // This categories parent has already been added we can add this immediately. $this->add_category($category, $this->addedcategories[$category->parent]); } else { $categories[] = $category; @@ -794,8 +832,9 @@ class global_navigation extends navigation_node { // Now we have an array of categories we need to add them to the navigation. while (!empty($categories)) { $category = reset($categories); + // phpcs:ignore Generic.CodeAnalysis.EmptyStatement.DetectedIf if (array_key_exists($category->id, $this->addedcategories)) { - // Do nothing + // Do nothing. } else if ($category->parent == '0') { $this->add_category($category, $this->rootnodes['courses']); } else if (array_key_exists($category->parent, $this->addedcategories)) { @@ -833,7 +872,7 @@ class global_navigation extends navigation_node { } // Check if there are any categories to load. if (count($categoriestoload) > 0) { - $readytoloadcourses = array(); + $readytoloadcourses = []; foreach ($categoriestoload as $category) { if ($this->can_add_more_courses_to_category($category)) { $readytoloadcourses[] = $category; @@ -844,17 +883,17 @@ class global_navigation extends navigation_node { } } - // Look for all categories which have been loaded + // Look for all categories which have been loaded. if (!empty($this->addedcategories)) { - $categoryids = array(); + $categoryids = []; foreach ($this->addedcategories as $category) { if ($this->can_add_more_courses_to_category($category)) { $categoryids[] = $category->key; } } if ($categoryids) { - list($categoriessql, $params) = $DB->get_in_or_equal($categoryids, SQL_PARAMS_NAMED); - $params['limit'] = (!empty($CFG->navcourselimit))?$CFG->navcourselimit:20; + [$categoriessql, $params] = $DB->get_in_or_equal($categoryids, SQL_PARAMS_NAMED); + $params['limit'] = (!empty($CFG->navcourselimit)) ? $CFG->navcourselimit : 20; $sql = "SELECT cc.id, COUNT(c.id) AS coursecount FROM {course_categories} cc JOIN {course} c ON c.category = cc.id @@ -863,8 +902,11 @@ class global_navigation extends navigation_node { HAVING COUNT(c.id) > :limit"; $excessivecategories = $DB->get_records_sql($sql, $params); foreach ($categories as &$category) { - if (array_key_exists($category->key, $excessivecategories) && !$this->can_add_more_courses_to_category($category)) { - $url = new url('/course/index.php', array('categoryid' => $category->key)); + if ( + array_key_exists($category->key, $excessivecategories) + && !$this->can_add_more_courses_to_category($category) + ) { + $url = new url('/course/index.php', ['categoryid' => $category->key]); $category->add(get_string('viewallcourses'), $url, self::TYPE_SETTING); } } @@ -886,7 +928,7 @@ class global_navigation extends navigation_node { return; } $canview = core_course_category::can_view_category($category); - $url = $canview ? new url('/course/index.php', array('categoryid' => $category->id)) : null; + $url = $canview ? new url('/course/index.php', ['categoryid' => $category->id]) : null; $context = context_helper::get_navigation_filter_context(context_coursecat::instance($category->id)); $categoryname = $canview ? format_string($category->name, true, ['context' => $context]) : get_string('categoryhidden'); @@ -910,13 +952,13 @@ class global_navigation extends navigation_node { protected function load_course(stdClass $course) { global $SITE; if ($course->id == $SITE->id) { - // This is always loaded during initialisation + // This is always loaded during initialisation. return $this->rootnodes['site']; } else if (array_key_exists($course->id, $this->addedcourses)) { - // The course has already been loaded so return a reference + // The course has already been loaded so return a reference. return $this->addedcourses[$course->id]; } else { - // Add the course + // Add the course. return $this->add_course($course); } } @@ -939,7 +981,7 @@ class global_navigation extends navigation_node { */ protected function load_course_sections(stdClass $course, navigation_node $coursenode, $sectionnum = null, $cm = null) { global $CFG, $SITE; - require_once($CFG->dirroot.'/course/lib.php'); + require_once($CFG->dirroot . '/course/lib.php'); if (isset($cm->sectionnum)) { $sectionnum = $cm->sectionnum; } @@ -965,16 +1007,16 @@ class global_navigation extends navigation_node { */ protected function generate_sections_and_activities(stdClass $course) { global $CFG; - require_once($CFG->dirroot.'/course/lib.php'); + require_once($CFG->dirroot . '/course/lib.php'); $modinfo = get_fast_modinfo($course); $sections = $modinfo->get_section_info_all(); $format = course_get_format($course); - // For course formats using 'numsections' trim the sections list + // For course formats using 'numsections' trim the sections list. $courseformatoptions = $format->get_format_options(); if (isset($courseformatoptions['numsections'])) { - $sections = array_slice($sections, 0, $courseformatoptions['numsections']+1, true); + $sections = array_slice($sections, 0, $courseformatoptions['numsections'] + 1, true); } $activities = []; @@ -988,7 +1030,7 @@ class global_navigation extends navigation_node { continue; } foreach ($section->get_sequence_cm_infos() as $cm) { - $activity = new stdClass; + $activity = new stdClass(); $activity->id = $cm->id; $activity->course = $course->id; $activity->section = $section->sectionnum; @@ -1039,9 +1081,9 @@ class global_navigation extends navigation_node { */ public function load_generic_course_sections(stdClass $course, navigation_node $coursenode) { global $CFG, $DB, $USER, $SITE; - require_once($CFG->dirroot.'/course/lib.php'); + require_once($CFG->dirroot . '/course/lib.php'); - list($sections, $activities) = $this->generate_sections_and_activities($course); + [$sections, $activities] = $this->generate_sections_and_activities($course); $navigationsections = []; foreach ($sections as $sectionid => $section) { @@ -1346,29 +1388,29 @@ class global_navigation extends navigation_node { protected function load_activity($cm, stdClass $course, navigation_node $activity) { global $CFG, $DB; - // make sure we have a $cm from get_fast_modinfo as this contains activity access details + // Make sure we have a $cm from get_fast_modinfo as this contains activity access details. if (!($cm instanceof cm_info)) { $modinfo = get_fast_modinfo($course); $cm = $modinfo->get_cm($cm->id); } $activity->nodetype = navigation_node::NODETYPE_LEAF; $activity->make_active(); - $file = $CFG->dirroot.'/mod/'.$cm->modname.'/lib.php'; - $function = $cm->modname.'_extend_navigation'; + $file = $CFG->dirroot . '/mod/' . $cm->modname . '/lib.php'; + $function = $cm->modname . '_extend_navigation'; if (file_exists($file)) { require_once($file); if (function_exists($function)) { - $activtyrecord = $DB->get_record($cm->modname, array('id' => $cm->instance), '*', MUST_EXIST); + $activtyrecord = $DB->get_record($cm->modname, ['id' => $cm->instance], '*', MUST_EXIST); $function($activity, $course, $activtyrecord, $cm); } } - // Allow the active advanced grading method plugin to append module navigation - $featuresfunc = $cm->modname.'_supports'; + // Allow the active advanced grading method plugin to append module navigation. + $featuresfunc = $cm->modname . '_supports'; if (function_exists($featuresfunc) && $featuresfunc(FEATURE_ADVANCED_GRADING)) { - require_once($CFG->dirroot.'/grade/grading/lib.php'); - $gradingman = get_grading_manager($cm->context, 'mod_'.$cm->modname); + require_once($CFG->dirroot . '/grade/grading/lib.php'); + $gradingman = get_grading_manager($cm->context, 'mod_' . $cm->modname); $gradingman->extend_navigation($this, $activity); } @@ -1383,27 +1425,26 @@ class global_navigation extends navigation_node { * @param bool $forceforcontext probably force something to be loaded somewhere (ask SamH if not sure what this means) * @return bool */ - protected function load_for_user($user=null, $forceforcontext=false) { + protected function load_for_user($user = null, $forceforcontext = false) { global $DB, $CFG, $USER, $SITE; require_once($CFG->dirroot . '/course/lib.php'); if ($user === null) { - // We can't require login here but if the user isn't logged in we don't - // want to show anything + // We can't require login here but if the user isn't logged in we don't want to show anything. if (!isloggedin() || isguestuser()) { return false; } $user = $USER; } else if (!is_object($user)) { - // If the user is not an object then get them from the database + // If the user is not an object then get them from the database. $select = context_helper::get_preload_record_columns_sql('ctx'); $sql = "SELECT u.*, $select FROM {user} u JOIN {context} ctx ON u.id = ctx.instanceid WHERE u.id = :userid AND ctx.contextlevel = :contextlevel"; - $user = $DB->get_record_sql($sql, array('userid' => (int)$user, 'contextlevel' => CONTEXT_USER), MUST_EXIST); + $user = $DB->get_record_sql($sql, ['userid' => (int)$user, 'contextlevel' => CONTEXT_USER], MUST_EXIST); context_helper::preload_from_record($user); } @@ -1411,16 +1452,16 @@ class global_navigation extends navigation_node { $usercontext = context_user::instance($user->id); - // Get the course set against the page, by default this will be the site + // Get the course set against the page, by default this will be the site. $course = $this->page->course; - $baseargs = array('id'=>$user->id); + $baseargs = ['id' => $user->id]; if ($course->id != $SITE->id && (!$iscurrentuser || $forceforcontext)) { $coursenode = $this->add_course($course, false, self::COURSE_CURRENT); $baseargs['course'] = $course->id; $coursecontext = context_course::instance($course->id); $issitecourse = false; } else { - // Load all categories and get the context for the system + // Load all categories and get the context for the system. $coursecontext = context_system::instance(); $issitecourse = true; } @@ -1435,7 +1476,7 @@ class global_navigation extends navigation_node { // This is the site so add a users node to the root branch. $usersnode = $this->rootnodes['users']; if (course_can_view_participants($coursecontext)) { - $usersnode->action = new url('/user/index.php', array('id' => $course->id)); + $usersnode->action = new url('/user/index.php', ['id' => $course->id]); } $userviewurl = new url('/user/profile.php', $baseargs); } @@ -1452,7 +1493,7 @@ class global_navigation extends navigation_node { $viewprofile = true; if (!$iscurrentuser) { require_once($CFG->dirroot . '/user/lib.php'); - if ($this->page->context->contextlevel == CONTEXT_USER && !has_capability('moodle/user:viewdetails', $usercontext) ) { + if ($this->page->context->contextlevel == CONTEXT_USER && !has_capability('moodle/user:viewdetails', $usercontext)) { $viewprofile = false; } else if ($this->page->context->contextlevel != CONTEXT_USER && !user_can_view_profile($user, $course, $usercontext)) { $viewprofile = false; @@ -1476,11 +1517,12 @@ class global_navigation extends navigation_node { // Add user information to the participants or user node. if ($issitecourse) { - // If the user is the current user or has permission to view the details of the requested // user than add a view profile link. - if ($iscurrentuser || has_capability('moodle/user:viewdetails', $coursecontext) || - has_capability('moodle/user:viewdetails', $usercontext)) { + if ( + $iscurrentuser || has_capability('moodle/user:viewdetails', $coursecontext) || + has_capability('moodle/user:viewdetails', $usercontext) + ) { if ($issitecourse || ($iscurrentuser && !$forceforcontext)) { $usernode->add(get_string('viewprofile'), new url('/user/profile.php', $baseargs)); } else { @@ -1490,21 +1532,27 @@ class global_navigation extends navigation_node { // Add blog nodes. if (!empty($CFG->enableblogs)) { - if (!$this->cache->cached('userblogoptions'.$user->id)) { - require_once($CFG->dirroot.'/blog/lib.php'); + if (!$this->cache->cached('userblogoptions' . $user->id)) { + require_once($CFG->dirroot . '/blog/lib.php'); // Get all options for the user. $options = blog_get_options_for_user($user); - $this->cache->set('userblogoptions'.$user->id, $options); + $this->cache->set('userblogoptions' . $user->id, $options); } else { - $options = $this->cache->{'userblogoptions'.$user->id}; + $options = $this->cache->{'userblogoptions' . $user->id}; } if (count($options) > 0) { $blogs = $usernode->add(get_string('blogs', 'blog'), null, navigation_node::TYPE_CONTAINER); foreach ($options as $type => $option) { if ($type == "rss") { - $blogs->add($option['string'], $option['link'], settings_navigation::TYPE_SETTING, null, null, - new pix_icon('i/rss', '')); + $blogs->add( + $option['string'], + $option['link'], + settings_navigation::TYPE_SETTING, + null, + null, + new pix_icon('i/rss', '') + ); } else { $blogs->add($option['string'], $option['link']); } @@ -1515,7 +1563,7 @@ class global_navigation extends navigation_node { // Add the messages link. // It is context based so can appear in the user's profile and in course participants information. if (!empty($CFG->messaging)) { - $messageargs = array('user1' => $USER->id); + $messageargs = ['user1' => $USER->id]; if ($USER->id != $user->id) { $messageargs['user2'] = $user->id; } @@ -1531,9 +1579,11 @@ class global_navigation extends navigation_node { } // Add a node to view the users notes if permitted. - if (!empty($CFG->enablenotes) && - has_any_capability(array('moodle/notes:manage', 'moodle/notes:view'), $coursecontext)) { - $url = new url('/notes/index.php', array('user' => $user->id)); + if ( + !empty($CFG->enablenotes) && + has_any_capability(['moodle/notes:manage', 'moodle/notes:view'], $coursecontext) + ) { + $url = new url('/notes/index.php', ['user' => $user->id]); if ($coursecontext->instanceid != SITEID) { $url->param('course', $coursecontext->instanceid); } @@ -1547,7 +1597,7 @@ class global_navigation extends navigation_node { if ($course->id == SITEID) { $url = user_mygrades_url($user->id, $course->id); } else { // Otherwise we are in a course and should redirect to the user grade report (Activity report version). - $url = new url('/course/user.php', array('mode' => 'grade', 'id' => $course->id, 'user' => $user->id)); + $url = new url('/course/user.php', ['mode' => 'grade', 'id' => $course->id, 'user' => $user->id]); } if ($USER->id != $user->id) { $usernode->add(get_string('grades', 'grades'), $url, self::TYPE_SETTING, null, 'usergrades'); @@ -1558,11 +1608,12 @@ class global_navigation extends navigation_node { // If the user is the current user add the repositories for the current user. $hiddenfields = array_flip(explode(',', $CFG->hiddenuserfields)); - if (!$iscurrentuser && + if ( + !$iscurrentuser && $course->id == $SITE->id && has_capability('moodle/user:viewdetails', $usercontext) && - (!in_array('mycourses', $hiddenfields) || has_capability('moodle/user:viewhiddendetails', $coursecontext))) { - + (!in_array('mycourses', $hiddenfields) || has_capability('moodle/user:viewhiddendetails', $coursecontext)) + ) { // Add view grade report is permitted. $reports = component::get_plugin_list('gradereport'); arsort($reports); // User is last, we want to test it first. @@ -1573,20 +1624,22 @@ class global_navigation extends navigation_node { $count = 0; foreach ($userscourses as $usercourse) { if ($count === (int)$CFG->navcourselimit) { - $url = new url('/user/profile.php', array('id' => $user->id, 'showallcourses' => 1)); + $url = new url('/user/profile.php', ['id' => $user->id, 'showallcourses' => 1]); $userscoursesnode->add(get_string('showallcourses'), $url); break; } $count++; $usercoursecontext = context_course::instance($usercourse->id); - $usercourseshortname = format_string($usercourse->shortname, true, array('context' => $usercoursecontext)); - $usercoursenode = $userscoursesnode->add($usercourseshortname, new url('/user/view.php', - array('id' => $user->id, 'course' => $usercourse->id)), self::TYPE_CONTAINER); + $usercourseshortname = format_string($usercourse->shortname, true, ['context' => $usercoursecontext]); + $usercoursenode = $userscoursesnode->add($usercourseshortname, new url( + '/user/view.php', + ['id' => $user->id, 'course' => $usercourse->id] + ), self::TYPE_CONTAINER); $gradeavailable = has_capability('moodle/grade:view', $usercoursecontext); if (!$gradeavailable && !empty($usercourse->showgrades) && is_array($reports) && !empty($reports)) { foreach ($reports as $plugin => $plugindir) { - if (has_capability('gradereport/'.$plugin.':view', $usercoursecontext)) { + if (has_capability('gradereport/' . $plugin . ':view', $usercoursecontext)) { // Stop when the first visible plugin is found. $gradeavailable = true; break; @@ -1595,21 +1648,31 @@ class global_navigation extends navigation_node { } if ($gradeavailable) { - $url = new url('/grade/report/index.php', array('id' => $usercourse->id)); - $usercoursenode->add(get_string('grades'), $url, self::TYPE_SETTING, null, null, - new pix_icon('i/grades', '')); + $url = new url('/grade/report/index.php', ['id' => $usercourse->id]); + $usercoursenode->add( + get_string('grades'), + $url, + self::TYPE_SETTING, + null, + null, + new pix_icon('i/grades', '') + ); } // Add a node to view the users notes if permitted. - if (!empty($CFG->enablenotes) && - has_any_capability(array('moodle/notes:manage', 'moodle/notes:view'), $usercoursecontext)) { - $url = new url('/notes/index.php', array('user' => $user->id, 'course' => $usercourse->id)); + if ( + !empty($CFG->enablenotes) && + has_any_capability(['moodle/notes:manage', 'moodle/notes:view'], $usercoursecontext) + ) { + $url = new url('/notes/index.php', ['user' => $user->id, 'course' => $usercourse->id]); $usercoursenode->add(get_string('notes', 'notes'), $url, self::TYPE_SETTING); } if (can_access_course($usercourse, $user->id, '', true)) { - $usercoursenode->add(get_string('entercourse'), new url('/course/view.php', - array('id' => $usercourse->id)), self::TYPE_SETTING, null, null, new pix_icon('i/course', '')); + $usercoursenode->add(get_string('entercourse'), new url( + '/course/view.php', + ['id' => $usercourse->id] + ), self::TYPE_SETTING, null, null, new pix_icon('i/course', '')); } $reporttab = $usercoursenode->add(get_string('activityreports')); @@ -1646,12 +1709,12 @@ class global_navigation extends navigation_node { */ public static function module_extends_navigation($modname) { global $CFG; - static $extendingmodules = array(); + static $extendingmodules = []; if (!array_key_exists($modname, $extendingmodules)) { $extendingmodules[$modname] = false; - $file = $CFG->dirroot.'/mod/'.$modname.'/lib.php'; + $file = $CFG->dirroot . '/mod/' . $modname . '/lib.php'; if (file_exists($file)) { - $function = $modname.'_extend_navigation'; + $function = $modname . '_extend_navigation'; require_once($file); $extendingmodules[$modname] = (function_exists($function)); } @@ -1686,7 +1749,7 @@ class global_navigation extends navigation_node { public function add_course(stdClass $course, $forcegeneric = false, $coursetype = self::COURSE_OTHER) { global $CFG, $SITE; - // We found the course... we can return it now :) + // We found the course... we can return it now. if (!$forcegeneric && array_key_exists($course->id, $this->addedcourses)) { return $this->addedcourses[$course->id]; } @@ -1694,8 +1757,9 @@ class global_navigation extends navigation_node { $coursecontext = context_course::instance($course->id); if ($coursetype != self::COURSE_MY && $coursetype != self::COURSE_CURRENT && $course->id != $SITE->id) { + // phpcs:ignore Generic.CodeAnalysis.EmptyStatement.DetectedIf if (is_role_switched($course->id)) { - // user has to be able to access course in order to switch, let's skip the visibility test here + // User has to be able to access course in order to switch, let's skip the visibility test here. } else if (!core_course_category::can_view_course_info($course)) { return false; } @@ -1726,28 +1790,32 @@ class global_navigation extends navigation_node { } } else if ($coursetype == self::COURSE_CURRENT) { $parent = $this->rootnodes['currentcourse']; - $url = new url('/course/view.php', array('id'=>$course->id)); + $url = new url('/course/view.php', ['id' => $course->id]); $canexpandcourse = $this->can_expand_course($course); } else if ($coursetype == self::COURSE_MY && !$forcegeneric) { - if (!empty($CFG->navshowmycoursecategories) && ($parent = $this->rootnodes['mycourses']->find($course->category, self::TYPE_MY_CATEGORY))) { + // phpcs:ignore Generic.CodeAnalysis.EmptyStatement.DetectedIf + if ( + !empty($CFG->navshowmycoursecategories) + && ($parent = $this->rootnodes['mycourses']->find($course->category, self::TYPE_MY_CATEGORY)) + ) { // Nothing to do here the above statement set $parent to the category within mycourses. } else { $parent = $this->rootnodes['mycourses']; } - $url = new url('/course/view.php', array('id'=>$course->id)); + $url = new url('/course/view.php', ['id' => $course->id]); } else { $parent = $this->rootnodes['courses']; - $url = new url('/course/view.php', array('id'=>$course->id)); + $url = new url('/course/view.php', ['id' => $course->id]); // They can only expand the course if they can access it. $canexpandcourse = $this->can_expand_course($course); if (!empty($course->category) && $this->show_categories($coursetype == self::COURSE_MY)) { if (!$this->is_category_fully_loaded($course->category)) { - // We need to load the category structure for this course + // We need to load the category structure for this course. $this->load_all_categories($course->category, false); } if (array_key_exists($course->category, $this->addedcategories)) { $parent = $this->addedcategories[$course->category]; - // This could lead to the course being created so we should check whether it is the case again + // This could lead to the course being created so we should check whether it is the case again. if (!$forcegeneric && array_key_exists($course->id, $this->addedcourses)) { return $this->addedcourses[$course->id]; } @@ -1821,7 +1889,13 @@ class global_navigation extends navigation_node { * @return bool */ protected function is_category_fully_loaded($categoryid) { - return (array_key_exists($categoryid, $this->addedcategories) && ($this->allcategoriesloaded || $this->addedcategories[$categoryid]->children->count() > 0)); + return ( + array_key_exists($categoryid, $this->addedcategories) + && ( + $this->allcategoriesloaded + || $this->addedcategories[$categoryid]->children->count() > 0 + ) + ); } /** @@ -1841,16 +1915,26 @@ class global_navigation extends navigation_node { return $this->add_front_page_course_essentials($coursenode, $course); } - if ($coursenode == false || !($coursenode instanceof navigation_node) || $coursenode->get('participants', navigation_node::TYPE_CONTAINER)) { + if ( + $coursenode == false + || !($coursenode instanceof navigation_node) + || $coursenode->get('participants', navigation_node::TYPE_CONTAINER) + ) { return true; } $navoptions = course_get_user_navigation_options($this->page->context, $course); - //Participants + // Participants. if ($navoptions->participants) { - $participants = $coursenode->add(get_string('participants'), new url('/user/index.php?id='.$course->id), - self::TYPE_CONTAINER, get_string('participants'), 'participants', new pix_icon('i/users', '')); + $participants = $coursenode->add( + get_string('participants'), + new url('/user/index.php?id=' . $course->id), + self::TYPE_CONTAINER, + get_string('participants'), + 'participants', + new pix_icon('i/users', '') + ); if ($navoptions->blogs) { $blogsurls = new url('/blog/index.php'); @@ -1863,7 +1947,13 @@ class global_navigation extends navigation_node { } if ($navoptions->notes) { - $participants->add(get_string('notes', 'notes'), new url('/notes/index.php', array('filtertype' => 'course', 'filterselect' => $course->id)), self::TYPE_SETTING, null, 'currentcoursenotes'); + $participants->add( + get_string('notes', 'notes'), + new url('/notes/index.php', ['filtertype' => 'course', 'filterselect' => $course->id]), + self::TYPE_SETTING, + null, + 'currentcoursenotes', + ); } } else if (count($this->extendforuser) > 0) { $coursenode->add(get_string('participants'), null, self::TYPE_CONTAINER, get_string('participants'), 'participants'); @@ -1876,23 +1966,40 @@ class global_navigation extends navigation_node { if ($navoptions->badges) { $url = new url('/badges/index.php', ['type' => 2, 'id' => $course->id]); - $coursenode->add(get_string('coursebadges', 'badges'), $url, - navigation_node::TYPE_SETTING, null, 'badgesview', - new pix_icon('i/badge', get_string('coursebadges', 'badges'))); + $coursenode->add( + get_string('coursebadges', 'badges'), + $url, + navigation_node::TYPE_SETTING, + null, + 'badgesview', + new pix_icon('i/badge', get_string('coursebadges', 'badges')) + ); } // Check access to the course and competencies page. if ($navoptions->competencies) { // Just a link to course competency. $title = get_string('competencies', 'core_competency'); - $path = new url("/admin/tool/lp/coursecompetencies.php", array('courseid' => $course->id)); - $coursenode->add($title, $path, navigation_node::TYPE_SETTING, null, 'competencies', - new pix_icon('i/competencies', '')); + $path = new url("/admin/tool/lp/coursecompetencies.php", ['courseid' => $course->id]); + $coursenode->add( + $title, + $path, + navigation_node::TYPE_SETTING, + null, + 'competencies', + new pix_icon('i/competencies', '') + ); } if ($navoptions->grades) { - $url = new url('/grade/report/index.php', array('id'=>$course->id)); - $gradenode = $coursenode->add(get_string('grades'), $url, self::TYPE_SETTING, null, - 'grades', new pix_icon('i/grades', '')); + $url = new url('/grade/report/index.php', ['id' => $course->id]); + $gradenode = $coursenode->add( + get_string('grades'), + $url, + self::TYPE_SETTING, + null, + 'grades', + new pix_icon('i/grades', '') + ); // If the page type matches the grade part, then make the nav drawer grade node (incl. all sub pages) active. if ($this->page->context->contextlevel < CONTEXT_MODULE && strpos($this->page->pagetype, 'grade-') === 0) { $gradenode->make_active(); @@ -1907,8 +2014,13 @@ class global_navigation extends navigation_node { 'instancetype' => 'coursecommunication', 'component' => 'core_course', ]); - $coursenode->add(get_string('communication', 'communication'), $url, - navigation_node::TYPE_SETTING, null, 'communication'); + $coursenode->add( + get_string('communication', 'communication'), + $url, + navigation_node::TYPE_SETTING, + null, + 'communication' + ); } if ($navoptions->overview) { @@ -1954,8 +2066,13 @@ class global_navigation extends navigation_node { // Participants. if ($navoptions->participants) { - $coursenode->add(get_string('participants'), new url('/user/index.php?id='.$course->id), - self::TYPE_CUSTOM, get_string('participants'), 'participants'); + $coursenode->add( + get_string('participants'), + new url('/user/index.php?id=' . $course->id), + self::TYPE_CUSTOM, + get_string('participants'), + 'participants' + ); } // Blogs. @@ -1974,28 +2091,46 @@ class global_navigation extends navigation_node { // Notes. if ($navoptions->notes) { - $coursenode->add(get_string('notes', 'notes'), new url('/notes/index.php', - array('filtertype' => 'course', 'filterselect' => $filterselect)), self::TYPE_SETTING, null, 'notes'); + $coursenode->add(get_string('notes', 'notes'), new url( + '/notes/index.php', + ['filtertype' => 'course', 'filterselect' => $filterselect] + ), self::TYPE_SETTING, null, 'notes'); } - // Tags + // Tags. if ($navoptions->tags) { - $node = $coursenode->add(get_string('tags', 'tag'), new url('/tag/search.php'), - self::TYPE_SETTING, null, 'tags'); + $node = $coursenode->add( + get_string('tags', 'tag'), + new url('/tag/search.php'), + self::TYPE_SETTING, + null, + 'tags' + ); } // Search. if ($navoptions->search) { - $node = $coursenode->add(get_string('search', 'search'), new url('/search/index.php'), - self::TYPE_SETTING, null, 'search'); + $node = $coursenode->add( + get_string('search', 'search'), + new url('/search/index.php'), + self::TYPE_SETTING, + null, + 'search' + ); } if (isloggedin()) { $usercontext = context_user::instance($USER->id); if (has_capability('moodle/user:manageownfiles', $usercontext)) { $url = new url('/user/files.php'); - $node = $coursenode->add(get_string('privatefiles'), $url, - self::TYPE_SETTING, null, 'privatefiles', new pix_icon('i/privatefiles', '')); + $node = $coursenode->add( + get_string('privatefiles'), + $url, + self::TYPE_SETTING, + null, + 'privatefiles', + new pix_icon('i/privatefiles', '') + ); $node->display = false; $node->showinflatnavigation = true; $node->mainnavonly = true; @@ -2013,6 +2148,7 @@ class global_navigation extends navigation_node { if ($COURSE->id != $SITE->id) { break; } + // Not the site. Fall through to default. default: // If this context is part of a course (excluding frontpage), use the course context. // Otherwise, use the system context. @@ -2027,8 +2163,14 @@ class global_navigation extends navigation_node { $params = ['contextid' => $context->id]; if (has_capability('moodle/contentbank:access', $context)) { $url = new url('/contentbank/index.php', $params); - $node = $coursenode->add(get_string('contentbank'), $url, - self::TYPE_CUSTOM, null, 'contentbank', new pix_icon('i/contentbank', '')); + $node = $coursenode->add( + get_string('contentbank'), + $url, + self::TYPE_CUSTOM, + null, + 'contentbank', + new pix_icon('i/contentbank', '') + ); $node->showinflatnavigation = true; } } @@ -2063,15 +2205,15 @@ class global_navigation extends navigation_node { // We only want to hide specific types of nodes. // Only nodes that represent "structure" in the navigation tree should be hidden. // If we hide all nodes then we risk hiding vital information. - $typestohide = array( + $typestohide = [ self::TYPE_CATEGORY, self::TYPE_COURSE, self::TYPE_SECTION, - self::TYPE_ACTIVITY - ); + self::TYPE_ACTIVITY, + ]; foreach ($nodes as $node) { - // We need to generate the full site node + // We need to generate the full site node. if ($type == self::TYPE_COURSE && $node->key == $SITE->id) { continue; } @@ -2081,21 +2223,8 @@ class global_navigation extends navigation_node { } return true; } - /** - * Attempts to get the navigation with the given key from this nodes children. - * - * This function only looks at this nodes children, it does NOT look recursivily. - * If the node can't be found then false is returned. - * - * If you need to search recursivily then use the {@link global_navigation::find()} method. - * - * Note: If you are trying to set the active node {@link navigation_node::override_active_url()} - * may be of more use to you. - * - * @param string|int $key The key of the node you wish to receive. - * @param int $type One of navigation_node::TYPE_* - * @return navigation_node|false - */ + + #[\Override] public function get($key, $type = null) { if (!$this->initialised) { $this->initialise(); @@ -2103,23 +2232,7 @@ class global_navigation extends navigation_node { return parent::get($key, $type); } - /** - * Searches this nodes children and their children to find a navigation node - * with the matching key and type. - * - * This method is recursive and searches children so until either a node is - * found or there are no more nodes to search. - * - * If you know that the node being searched for is a child of this node - * then use the {@link global_navigation::get()} method instead. - * - * Note: If you are trying to set the active node {@link navigation_node::override_active_url()} - * may be of more use to you. - * - * @param string|int $key The key of the node you wish to receive. - * @param ?int $type One of navigation_node::TYPE_* - * @return navigation_node|false - */ + #[\Override] public function find($key, $type) { if (!$this->initialised) { $this->initialise(); @@ -2163,7 +2276,7 @@ class global_navigation extends navigation_node { $numshownflatnavcourses = count($flatnavcourses); if ($numshowncourses && $this->show_my_categories()) { // Generate an array containing unique values of all the courses' categories. - $categoryids = array(); + $categoryids = []; foreach ($courses as $course) { if (in_array($course->category, $categoryids)) { continue; diff --git a/public/lib/classes/navigation/global_navigation_for_ajax.php b/public/lib/classes/navigation/global_navigation_for_ajax.php index 181762cf9af..2e4b9430eae 100644 --- a/public/lib/classes/navigation/global_navigation_for_ajax.php +++ b/public/lib/classes/navigation/global_navigation_for_ajax.php @@ -38,7 +38,6 @@ use moodle_page; * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ class global_navigation_for_ajax extends global_navigation { - /** @var int used for determining what type of navigation_node::TYPE_* is being used */ protected $branchtype; @@ -46,7 +45,7 @@ class global_navigation_for_ajax extends global_navigation { protected $instanceid; /** @var array Holds an array of expandable nodes */ - protected $expandable = array(); + protected $expandable = []; /** * Constructs the navigation for use in an AJAX request @@ -63,11 +62,8 @@ class global_navigation_for_ajax extends global_navigation { $this->instanceid = $id; $this->initialise(); } - /** - * Initialise the navigation given the type and id for the branch to expand. - * - * @return array An array of the expandable nodes - */ + + #[\Override] public function initialise() { global $DB, $SITE; @@ -76,7 +72,7 @@ class global_navigation_for_ajax extends global_navigation { } $this->initialised = true; - $this->rootnodes = array(); + $this->rootnodes = []; $this->rootnodes['site'] = $this->add_course($SITE); $this->rootnodes['mycourses'] = $this->add( get_string('mycourses'), @@ -90,7 +86,7 @@ class global_navigation_for_ajax extends global_navigation { // This mimicks what is done during {@link global_navigation::initialise()}. $this->rootnodes['courses']->isexpandable = true; - // Branchtype will be one of navigation_node::TYPE_* + // Branchtype will be one of navigation_node::TYPE_*. switch ($this->branchtype) { case 0: if ($this->instanceid === 'mycourses') { @@ -99,14 +95,14 @@ class global_navigation_for_ajax extends global_navigation { $this->load_courses_other(); } break; - case self::TYPE_CATEGORY : + case self::TYPE_CATEGORY: $this->load_category($this->instanceid); break; - case self::TYPE_MY_CATEGORY : + case self::TYPE_MY_CATEGORY: $this->load_category($this->instanceid, self::TYPE_MY_CATEGORY); break; - case self::TYPE_COURSE : - $course = $DB->get_record('course', array('id' => $this->instanceid), '*', MUST_EXIST); + case self::TYPE_COURSE: + $course = $DB->get_record('course', ['id' => $this->instanceid], '*', MUST_EXIST); if (!can_access_course($course, null, '', true)) { // Thats OK all courses are expandable by default. We don't need to actually expand it we can just // add the course node and break. This leads to an empty node. @@ -119,24 +115,24 @@ class global_navigation_for_ajax extends global_navigation { $this->add_course_essentials($coursenode, $course); $this->load_course_sections($course, $coursenode); break; - case self::TYPE_SECTION : + case self::TYPE_SECTION: $sql = 'SELECT c.*, cs.section AS sectionnumber FROM {course} c LEFT JOIN {course_sections} cs ON cs.course = c.id WHERE cs.id = ?'; - $course = $DB->get_record_sql($sql, array($this->instanceid), MUST_EXIST); + $course = $DB->get_record_sql($sql, [$this->instanceid], MUST_EXIST); require_course_login($course, true, null, false, true); $this->page->set_context(context_course::instance($course->id)); $coursenode = $this->add_course($course, false, self::COURSE_CURRENT); $this->add_course_essentials($coursenode, $course); $this->load_course_sections($course, $coursenode, $course->sectionnumber); break; - case self::TYPE_ACTIVITY : + case self::TYPE_ACTIVITY: $sql = "SELECT c.* FROM {course} c JOIN {course_modules} cm ON cm.course = c.id WHERE cm.id = :cmid"; - $params = array('cmid' => $this->instanceid); + $params = ['cmid' => $this->instanceid]; $course = $DB->get_record_sql($sql, $params, MUST_EXIST); $modinfo = get_fast_modinfo($course); $cm = $modinfo->get_cm($this->instanceid); @@ -195,13 +191,13 @@ class global_navigation_for_ajax extends global_navigation { $sql = "SELECT cc.*, $catcontextsql FROM {course_categories} cc JOIN {context} ctx ON cc.id = ctx.instanceid - WHERE ctx.contextlevel = ".CONTEXT_COURSECAT." AND + WHERE ctx.contextlevel = " . CONTEXT_COURSECAT . " AND (cc.id = :categoryid1 OR cc.parent = :categoryid2) ORDER BY cc.depth ASC, cc.sortorder ASC, cc.id ASC"; - $params = array('categoryid1' => $categoryid, 'categoryid2' => $categoryid); + $params = ['categoryid1' => $categoryid, 'categoryid2' => $categoryid]; $categories = $DB->get_recordset_sql($sql, $params, 0, $limit); - $categorylist = array(); - $subcategories = array(); + $categorylist = []; + $subcategories = []; $basecategory = null; foreach ($categories as $category) { $categorylist[] = $category->id; @@ -215,12 +211,11 @@ class global_navigation_for_ajax extends global_navigation { } $categories->close(); - // 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(); + $categoryids = []; // Only search for categories if basecategory was found. if (!is_null($basecategory)) { @@ -231,13 +226,13 @@ class global_navigation_for_ajax extends global_navigation { // Get a unique list of category ids which a part of the path // to user's courses. - $coursesubcategories = array(); - $addedsubcategories = array(); + $coursesubcategories = []; + $addedsubcategories = []; - list($sql, $params) = $DB->get_in_or_equal($categoryids); - $categories = $DB->get_recordset_select('course_categories', 'id '.$sql, $params, 'sortorder, id', 'id, path'); + [$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){ + foreach ($categories as $category) { $coursesubcategories = array_merge($coursesubcategories, explode('/', trim($category->path, "/"))); } $categories->close(); @@ -246,8 +241,10 @@ class global_navigation_for_ajax extends global_navigation { // Only add a subcategory if it is part of the path to user's course and // wasn't already added. foreach ($subcategories as $subid => $subcategory) { - if (in_array($subid, $coursesubcategories) && - !in_array($subid, $addedsubcategories)) { + if ( + in_array($subid, $coursesubcategories) && + !in_array($subid, $addedsubcategories) + ) { $this->add_category($subcategory, $basecategory, $nodetype); $addedsubcategories[] = $subid; } @@ -262,11 +259,11 @@ class global_navigation_for_ajax extends global_navigation { } } else { if (!is_null($basecategory)) { - foreach ($subcategories as $key=>$category) { + foreach ($subcategories as $key => $category) { $this->add_category($category, $basecategory, $nodetype); } } - $courses = $DB->get_recordset('course', array('category' => $categoryid), 'sortorder', '*' , 0, $limit); + $courses = $DB->get_recordset('course', ['category' => $categoryid], 'sortorder', '*', 0, $limit); foreach ($courses as $course) { $this->add_course($course); } @@ -275,7 +272,8 @@ class global_navigation_for_ajax extends global_navigation { } /** - * Returns an array of expandable nodes + * Returns an array of expandable nodes. + * * @return array */ public function get_expandable() { diff --git a/public/lib/classes/navigation/navbar.php b/public/lib/classes/navigation/navbar.php index d747ae80ca3..a7fe67179d7 100644 --- a/public/lib/classes/navigation/navbar.php +++ b/public/lib/classes/navigation/navbar.php @@ -40,7 +40,7 @@ class navbar extends navigation_node { /** @var bool A switch for whether the navbar is initialised or not */ protected $initialised = false; /** @var mixed keys used to reference the nodes on the navbar */ - protected $keys = array(); + protected $keys = []; /** @var null|string content of the navbar */ protected $content = null; /** @var moodle_page object the moodle page that this navbar belongs to */ @@ -54,11 +54,11 @@ class navbar extends navigation_node { /** @var array An array of navigation nodes for the navbar */ protected $items; /** @var array An array of child node objects */ - public $children = array(); + public $children = []; /** @var bool A switch for whether we want to include the root node in the navbar */ public $includesettingsbase = false; /** @var breadcrumb_navigation_node[] $prependchildren */ - protected $prependchildren = array(); + protected $prependchildren = []; /** * The almighty constructor @@ -71,10 +71,11 @@ class navbar extends navigation_node { $this->duringinstall = true; return; } + $this->page = $page; $this->text = get_string('home'); $this->shorttext = get_string('home'); - $this->action = new moodle_url($CFG->wwwroot); + $this->action = new url($CFG->wwwroot); $this->nodetype = self::NODETYPE_BRANCH; $this->type = self::TYPE_SYSTEM; } @@ -108,7 +109,7 @@ class navbar extends navigation_node { * * @param bool $setting */ - public function ignore_active($setting=true) { + public function ignore_active($setting = true) { $this->ignoreactive = ($setting); } @@ -139,8 +140,8 @@ class navbar extends navigation_node { */ public function get_items() { global $CFG; - $items = array(); - // Make sure that navigation is initialised + $items = []; + // Make sure that navigation is initialised. if (!$this->has_items()) { return $items; } @@ -153,7 +154,7 @@ class navbar extends navigation_node { $items = array_reverse($this->children); } - // Check if navigation contains the active node + // Check if navigation contains the active node. if (!$this->ignoreactive) { // We will need to ensure the navigation has been initialised. $this->page->navigation->initialise($this->page); @@ -162,7 +163,7 @@ class navbar extends navigation_node { $settingsactivenode = $this->page->settingsnav->find_active_node(); if ($navigationactivenode && $settingsactivenode) { - // Parse a combined navigation tree + // Parse a combined navigation tree. while ($settingsactivenode && $settingsactivenode->parent !== null) { if (!$settingsactivenode->mainnavonly) { $items[] = new breadcrumb_navigation_node($settingsactivenode); @@ -170,16 +171,18 @@ class navbar extends navigation_node { $settingsactivenode = $settingsactivenode->parent; } if (!$this->includesettingsbase) { - // Removes the first node from the settings (root node) from the list + // Removes the first node from the settings (root node) from the list. array_pop($items); } while ($navigationactivenode && $navigationactivenode->parent !== null) { if (!$navigationactivenode->mainnavonly) { $items[] = new breadcrumb_navigation_node($navigationactivenode); } - if (!empty($CFG->navshowcategories) && + if ( + !empty($CFG->navshowcategories) && $navigationactivenode->type === self::TYPE_COURSE && - $navigationactivenode->parent->key === 'currentcourse') { + $navigationactivenode->parent->key === 'currentcourse' + ) { foreach ($this->get_course_categories() as $item) { $items[] = new breadcrumb_navigation_node($item); } @@ -187,14 +190,16 @@ class navbar extends navigation_node { $navigationactivenode = $navigationactivenode->parent; } } else if ($navigationactivenode) { - // Parse the navigation tree to get the active node + // Parse the navigation tree to get the active node. while ($navigationactivenode && $navigationactivenode->parent !== null) { if (!$navigationactivenode->mainnavonly) { $items[] = new breadcrumb_navigation_node($navigationactivenode); } - if (!empty($CFG->navshowcategories) && + if ( + !empty($CFG->navshowcategories) && $navigationactivenode->type === self::TYPE_COURSE && - $navigationactivenode->parent->key === 'currentcourse') { + $navigationactivenode->parent->key === 'currentcourse' + ) { foreach ($this->get_course_categories() as $item) { $items[] = new breadcrumb_navigation_node($item); } @@ -202,7 +207,7 @@ class navbar extends navigation_node { $navigationactivenode = $navigationactivenode->parent; } } else if ($settingsactivenode) { - // Parse the settings navigation to get the active node + // Parse the settings navigation to get the active node. while ($settingsactivenode && $settingsactivenode->parent !== null) { if (!$settingsactivenode->mainnavonly) { $items[] = new breadcrumb_navigation_node($settingsactivenode); @@ -212,15 +217,15 @@ class navbar extends navigation_node { } } - $items[] = new breadcrumb_navigation_node(array( + $items[] = new breadcrumb_navigation_node([ 'text' => $this->page->navigation->text, 'shorttext' => $this->page->navigation->shorttext, 'key' => $this->page->navigation->key, - 'action' => $this->page->navigation->action - )); + 'action' => $this->page->navigation->action, + ]); if (count($this->prependchildren) > 0) { - // Add the custom children + // Add the custom children. $items = array_merge($items, array_reverse($this->prependchildren)); } @@ -243,9 +248,9 @@ class navbar extends navigation_node { */ private function get_course_categories() { global $CFG; - require_once($CFG->dirroot.'/course/lib.php'); + require_once($CFG->dirroot . '/course/lib.php'); - $categories = array(); + $categories = []; $cap = 'moodle/category:viewhiddencategories'; $showcategories = !core_course_category::is_simple_site(); @@ -256,8 +261,8 @@ class navbar extends navigation_node { continue; } - $displaycontext = \context_helper::get_navigation_filter_context($context); - $url = new moodle_url('/course/index.php', ['categoryid' => $category->id]); + $displaycontext = context_helper::get_navigation_filter_context($context); + $url = new url('/course/index.php', ['categoryid' => $category->id]); $name = format_string($category->name, true, ['context' => $displaycontext]); $categorynode = breadcrumb_navigation_node::create($name, $url, self::TYPE_CATEGORY, null, $category->id); if (!$category->visible) { @@ -275,7 +280,7 @@ class navbar extends navigation_node { // Courses node may not be present. $courses = breadcrumb_navigation_node::create( get_string('courses'), - new moodle_url('/course/index.php'), + new url('/course/index.php'), self::TYPE_CONTAINER ); } @@ -293,44 +298,44 @@ class navbar extends navigation_node { * end of the navbar * * @param string $text - * @param string|moodle_url|action_link $action An action to associate with this node. + * @param string|url|action_link $action An action to associate with this node. * @param int $type One of navigation_node::TYPE_* * @param string $shorttext * @param string|int $key A key to identify this node with. Key + type is unique to a parent. * @param pix_icon $icon An optional icon to use for this node. * @return navigation_node */ - public function add($text, $action=null, $type=self::TYPE_CUSTOM, $shorttext=null, $key=null, ?pix_icon $icon=null) { + public function add($text, $action = null, $type = self::TYPE_CUSTOM, $shorttext = null, $key = null, ?pix_icon $icon = null) { if ($this->content !== null) { debugging('Nav bar items must be printed before $OUTPUT->header() has been called', DEBUG_DEVELOPER); } - // Properties array used when creating the new navigation node - $itemarray = array( + // Properties array used when creating the new navigation node. + $itemarray = [ 'text' => $text, - 'type' => $type - ); - // Set the action if one was provided - if ($action!==null) { + 'type' => $type, + ]; + // Set the action if one was provided. + if ($action !== null) { $itemarray['action'] = $action; } - // Set the shorttext if one was provided - if ($shorttext!==null) { + // Set the shorttext if one was provided. + if ($shorttext !== null) { $itemarray['shorttext'] = $shorttext; } - // Set the icon if one was provided - if ($icon!==null) { + // Set the icon if one was provided. + if ($icon !== null) { $itemarray['icon'] = $icon; } - // Default the key to the number of children if not provided + // Default the key to the number of children if not provided. if ($key === null) { $key = count($this->children); } - // Set the key + // Set the key. $itemarray['key'] = $key; - // Set the parent to this node + // Set the parent to this node. $itemarray['parent'] = $this; - // Add the child using the navigation_node_collections add method + // Add the child using the navigation_node_collections add method. $this->children[] = new breadcrumb_navigation_node($itemarray); return $this; } @@ -339,32 +344,39 @@ class navbar extends navigation_node { * Prepends a new navigation_node to the start of the navbar * * @param string $text - * @param string|moodle_url|action_link $action An action to associate with this node. + * @param string|url|action_link $action An action to associate with this node. * @param int $type One of navigation_node::TYPE_* * @param string $shorttext * @param string|int $key A key to identify this node with. Key + type is unique to a parent. * @param pix_icon $icon An optional icon to use for this node. * @return navigation_node */ - public function prepend($text, $action=null, $type=self::TYPE_CUSTOM, $shorttext=null, $key=null, ?pix_icon $icon=null) { + public function prepend( + $text, + $action = null, + $type = self::TYPE_CUSTOM, + $shorttext = null, + $key = null, + ?pix_icon $icon = null, + ) { if ($this->content !== null) { debugging('Nav bar items must be printed before $OUTPUT->header() has been called', DEBUG_DEVELOPER); } // Properties array used when creating the new navigation node. - $itemarray = array( + $itemarray = [ 'text' => $text, - 'type' => $type - ); + 'type' => $type, + ]; // Set the action if one was provided. - if ($action!==null) { + if ($action !== null) { $itemarray['action'] = $action; } // Set the shorttext if one was provided. - if ($shorttext!==null) { + if ($shorttext !== null) { $itemarray['shorttext'] = $shorttext; } // Set the icon if one was provided. - if ($icon!==null) { + if ($icon !== null) { $itemarray['icon'] = $icon; } // Default the key to the number of children if not provided. diff --git a/public/lib/classes/navigation/navigation_cache.php b/public/lib/classes/navigation/navigation_cache.php index dc9cec5244f..db69ecbda12 100644 --- a/public/lib/classes/navigation/navigation_cache.php +++ b/public/lib/classes/navigation/navigation_cache.php @@ -20,13 +20,6 @@ use core_cache\cache; use core_cache\session_cache; use core_shutdown_manager; -/** - * Class navigation_cache - * - * @package core - * @copyright 2025 Andrew Lyons - * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later - */ /** * The navigation_cache class is used for global and settings navigation data. * @@ -59,12 +52,12 @@ class navigation_cache { protected $area; /** @var int cache time information */ #[\core\attribute\deprecated(null, since: '4.5', reason: 'This constant is no longer needed.', mdl: 'MDL-79628')] - const CACHETIME = 0; + public const CACHETIME = 0; /** @var int cache user id */ #[\core\attribute\deprecated(null, since: '4.5', reason: 'This constant is no longer needed.', mdl: 'MDL-79628')] - const CACHEUSERID = 1; + public const CACHEUSERID = 1; /** @var int cache value */ - const CACHEVALUE = 2; + public const CACHEVALUE = 2; /** @var null|array An array of cache areas to expire on shutdown */ public static $volatilecaches = null; diff --git a/public/lib/classes/navigation/navigation_json.php b/public/lib/classes/navigation/navigation_json.php index cd5b91000fa..74bbcfffac1 100644 --- a/public/lib/classes/navigation/navigation_json.php +++ b/public/lib/classes/navigation/navigation_json.php @@ -30,9 +30,9 @@ use core\url; */ class navigation_json { /** @var array An array of different node types */ - protected $nodetype = array('node','branch'); + protected $nodetype = ['node', 'branch']; /** @var array An array of node keys and types */ - protected $expandable = array(); + protected $expandable = []; /** * Turns a branch and all of its children into XML * @@ -50,7 +50,7 @@ class navigation_json { */ public function set_expandable($expandable) { foreach ($expandable as $node) { - $this->expandable[$node['key'].':'.$node['type']] = $node; + $this->expandable[$node['key'] . ':' . $node['type']] = $node; } } /** @@ -60,11 +60,11 @@ class navigation_json { * @param int $depth Pointlessly used to track the depth of the XML structure * @return string JSON */ - protected function convert_child($child, $depth=1) { + protected function convert_child($child, $depth = 1) { if (!$child->display) { return ''; } - $attributes = array(); + $attributes = []; $attributes['id'] = $child->id; $attributes['name'] = (string)$child->text; // This can be lang_string object so typecast it. $attributes['type'] = $child->type; @@ -73,17 +73,16 @@ class navigation_json { $attributes['requiresajaxloading'] = $child->requiresajaxloading; if ($child->icon instanceof pix_icon) { - $attributes['icon'] = array( + $attributes['icon'] = [ 'component' => $child->icon->component, 'pix' => $child->icon->pix, - ); - foreach ($child->icon->attributes as $key=>$value) { + ]; + foreach ($child->icon->attributes as $key => $value) { if ($key == 'class') { $attributes['icon']['classes'] = explode(' ', $value); } else if (!array_key_exists($key, $attributes['icon'])) { $attributes['icon'][$key] = $value; } - } } else if (!empty($child->icon)) { $attributes['icon'] = (string)$child->icon; @@ -92,13 +91,13 @@ class navigation_json { if ($child->forcetitle || $child->title !== $child->text) { $attributes['title'] = htmlentities($child->title ?? '', ENT_QUOTES, 'UTF-8'); } - if (array_key_exists($child->key.':'.$child->type, $this->expandable)) { + if (array_key_exists($child->key . ':' . $child->type, $this->expandable)) { $attributes['expandable'] = $child->key; - $child->add_class($this->expandable[$child->key.':'.$child->type]['id']); + $child->add_class($this->expandable[$child->key . ':' . $child->type]['id']); } - if (count($child->classes)>0) { - $attributes['class'] .= ' '.join(' ',$child->classes); + if (count($child->classes) > 0) { + $attributes['class'] .= ' ' . join(' ', $child->classes); } if (is_string($child->action)) { $attributes['link'] = $child->action; @@ -108,13 +107,13 @@ class navigation_json { $attributes['link'] = $child->action->url->out(); } $attributes['hidden'] = ($child->hidden); - $attributes['haschildren'] = ($child->children->count()>0 || $child->type == navigation_node::TYPE_CATEGORY); + $attributes['haschildren'] = ($child->children->count() > 0 || $child->type == navigation_node::TYPE_CATEGORY); $attributes['haschildren'] = $attributes['haschildren'] || $child->type == navigation_node::TYPE_MY_CATEGORY; if ($child->children->count() > 0) { - $attributes['children'] = array(); + $attributes['children'] = []; foreach ($child->children as $subchild) { - $attributes['children'][] = $this->convert_child($subchild, $depth+1); + $attributes['children'][] = $this->convert_child($subchild, $depth + 1); } } diff --git a/public/lib/classes/navigation/navigation_node.php b/public/lib/classes/navigation/navigation_node.php index 63d949387e6..f72b3319c86 100644 --- a/public/lib/classes/navigation/navigation_node.php +++ b/public/lib/classes/navigation/navigation_node.php @@ -40,45 +40,45 @@ use core\url; */ class navigation_node implements renderable { /** @var int Used to identify this node a leaf (default) 0 */ - const NODETYPE_LEAF = 0; + public const NODETYPE_LEAF = 0; /** @var int Used to identify this node a branch, happens with children 1 */ - const NODETYPE_BRANCH = 1; + public const NODETYPE_BRANCH = 1; /** @var null Unknown node type null */ - const TYPE_UNKNOWN = null; + public const TYPE_UNKNOWN = null; /** @var int System node type 0 */ - const TYPE_ROOTNODE = 0; + public const TYPE_ROOTNODE = 0; /** @var int System node type 1 */ - const TYPE_SYSTEM = 1; + public const TYPE_SYSTEM = 1; /** @var int Category node type 10 */ - const TYPE_CATEGORY = 10; + public const TYPE_CATEGORY = 10; /** var int Category displayed in MyHome navigation node */ - const TYPE_MY_CATEGORY = 11; + public const TYPE_MY_CATEGORY = 11; /** @var int Course node type 20 */ - const TYPE_COURSE = 20; + public const TYPE_COURSE = 20; /** @var int Course Structure node type 30 */ - const TYPE_SECTION = 30; + public const TYPE_SECTION = 30; /** @var int Activity node type, e.g. Forum, Quiz 40 */ - const TYPE_ACTIVITY = 40; + public const TYPE_ACTIVITY = 40; /** @var int Resource node type, e.g. Link to a file, or label 50 */ - const TYPE_RESOURCE = 50; + public const TYPE_RESOURCE = 50; /** @var int A custom node type, default when adding without specifing type 60 */ - const TYPE_CUSTOM = 60; + public const TYPE_CUSTOM = 60; /** @var int Setting node type, used only within settings nav 70 */ - const TYPE_SETTING = 70; + public const TYPE_SETTING = 70; /** @var int site admin branch node type, used only within settings nav 71 */ - const TYPE_SITE_ADMIN = 71; + public const TYPE_SITE_ADMIN = 71; /** @var int Setting node type, used only within settings nav 80 */ - const TYPE_USER = 80; + public const TYPE_USER = 80; /** @var int Setting node type, used for containers of no importance 90 */ - const TYPE_CONTAINER = 90; + public const TYPE_CONTAINER = 90; /** var int Course the current user is not enrolled in */ - const COURSE_OTHER = 0; + public const COURSE_OTHER = 0; /** var int Course the current user is enrolled in but not viewing */ - const COURSE_MY = 1; + public const COURSE_MY = 1; /** var int Course the current user is currently viewing */ - const COURSE_CURRENT = 2; + public const COURSE_CURRENT = 2; /** var string The course index page navigation node */ - const COURSE_INDEX_PAGE = 'courseindexpage'; + public const COURSE_INDEX_PAGE = 'courseindexpage'; /** @var int Parameter to aid the coder in tracking [optional] */ public $id = null; @@ -92,7 +92,7 @@ class navigation_node implements renderable { public $title = null; /** @var string A string that can be used to build a help button */ public $helpbutton = null; - /** @var moodle_url|action_link|null An action for the node (link) */ + /** @var url|action_link|null An action for the node (link) */ public $action = null; /** @var pix_icon The path to an icon to use for this node */ public $icon = null; @@ -105,11 +105,11 @@ class navigation_node implements renderable { /** @var bool If set to true the node will be expanded by default */ public $forceopen = false; /** @var array An array of CSS classes for the node */ - public $classes = array(); + public $classes = []; /** @var array An array of HTML attributes for the node */ public $attributes = []; /** @var navigation_node_collection An array of child nodes */ - public $children = array(); + public $children = []; /** @var bool If set to true the node will be recognised as active */ public $isactive = false; /** @var bool If set to true the node will be dimmed */ @@ -129,10 +129,10 @@ class navigation_node implements renderable { /** @var bool Set to true if we KNOW that this node can be expanded. */ public $isexpandable = false; /** @var array */ - protected $namedtypes = array(0 => 'system', 10 => 'category', 20 => 'course', 30 => 'structure', 40 => 'activity', + protected $namedtypes = [0 => 'system', 10 => 'category', 20 => 'course', 30 => 'structure', 40 => 'activity', 50 => 'resource', 60 => 'custom', 70 => 'setting', 71 => 'siteadmin', 80 => 'user', - 90 => 'container'); - /** @var moodle_url */ + 90 => 'container']; + /** @var url */ protected static $fullmeurl = null; /** @var bool toogles auto matching of active node */ public static $autofindactive = true; @@ -166,13 +166,13 @@ class navigation_node implements renderable { public function __construct($properties) { if (is_array($properties)) { // Check the array for each property that we allow to set at construction. - // text - The main content for the node - // shorttext - A short text if required for the node - // icon - The icon to display for the node - // type - The type of the node - // key - The key to use to identify the node - // parent - A reference to the nodes parent - // action - The action to attribute to this node, usually a URL to link to + // text - The main content for the node. + // shorttext - A short text if required for the node. + // icon - The icon to display for the node. + // type - The type of the node. + // key - The key to use to identify the node. + // parent - A reference to the nodes parent. + // action - The action to attribute to this node, usually a URL to link to. if (array_key_exists('text', $properties)) { $this->text = $properties['text']; } @@ -198,11 +198,12 @@ class navigation_node implements renderable { if (array_key_exists('key', $properties)) { $this->key = $properties['key']; } - // This needs to happen last because of the check_if_active call that occurs + + // This needs to happen last because of the check_if_active call that occurs. if (array_key_exists('action', $properties)) { $this->action = $properties['action']; if (is_string($this->action)) { - $this->action = new moodle_url($this->action); + $this->action = new url($this->action); } if (self::$autofindactive) { $this->check_if_active(); @@ -217,7 +218,7 @@ class navigation_node implements renderable { if ($this->text === null) { throw new coding_exception('You must set the text for the node when you create it.'); } - // Instantiate a new navigation node collection for this nodes children + // Instantiate a new navigation node collection for this nodes children. $this->children = new navigation_node_collection(); } @@ -230,19 +231,20 @@ class navigation_node implements renderable { * @param int $strength One of URL_MATCH_EXACT, URL_MATCH_PARAMS, or URL_MATCH_BASE * @return bool */ - public function check_if_active($strength=URL_MATCH_EXACT) { + public function check_if_active($strength = URL_MATCH_EXACT) { global $FULLME, $PAGE; - // Set fullmeurl if it hasn't already been set + + // Set fullmeurl if it hasn't already been set. if (self::$fullmeurl == null) { if ($PAGE->has_set_url()) { - self::override_active_url(new moodle_url($PAGE->url)); + self::override_active_url(new url($PAGE->url)); } else { - self::override_active_url(new moodle_url($FULLME)); + self::override_active_url(new url($FULLME)); } } - // Compare the action of this node against the fullmeurl - if ($this->action instanceof moodle_url && $this->action->compare(self::$fullmeurl, $strength)) { + // Compare the action of this node against the fullmeurl. + if ($this->action instanceof url && $this->action->compare(self::$fullmeurl, $strength)) { $this->make_active(); return true; } @@ -288,18 +290,17 @@ class navigation_node implements renderable { } /** - * This sets the URL that the URL of new nodes get compared to when locating - * the active node. + * This sets the URL that the URL of new nodes get compared to when locating the active node. * * The active node is the node that matches the URL set here. By default this * is either $PAGE->url or if that hasn't been set $FULLME. * - * @param moodle_url $url The url to use for the fullmeurl. + * @param url $url The url to use for the fullmeurl. * @param bool $loadadmintree use true if the URL point to administration tree */ - public static function override_active_url(moodle_url $url, $loadadmintree = false) { + public static function override_active_url(url $url, $loadadmintree = false) { // Clone the URL, in case the calling script changes their URL later. - self::$fullmeurl = new moodle_url($url); + self::$fullmeurl = new url($url); // True means we do not want AJAX loaded admin tree, required for all admin pages. if ($loadadmintree) { // Do not change back to false if already set. @@ -308,6 +309,8 @@ class navigation_node implements renderable { } /** + * Require the admin tree. + * * Use when page is linked from the admin tree, * if not used navigation could not find the page using current URL * because the tree is not fully loaded. @@ -317,43 +320,53 @@ class navigation_node implements renderable { } /** - * Creates a navigation node, ready to add it as a child using add_node - * function. (The created node needs to be added before you can use it.) + * Creates a navigation node, ready to add it as a child using add_node function. + * + * The created node needs to be added before you can use it. + * * @param string $text - * @param moodle_url|action_link $action + * @param url|action_link $action * @param int $type * @param string $shorttext * @param string|int $key * @param pix_icon $icon * @return navigation_node */ - public static function create($text, $action=null, $type=self::TYPE_CUSTOM, - $shorttext=null, $key=null, ?pix_icon $icon=null) { - if ($action && !($action instanceof moodle_url || $action instanceof action_link)) { + public static function create( + $text, + $action = null, + $type = self::TYPE_CUSTOM, + $shorttext = null, + $key = null, + ?pix_icon $icon = null + ) { + if ($action && !($action instanceof url || $action instanceof action_link)) { debugging( - "It is required that the action provided be either an action_url|moodle_url." . - " Please update your definition.", E_NOTICE); + "It is required that the action provided be either an action_url|url." . + " Please update your definition.", + E_NOTICE + ); } - // Properties array used when creating the new navigation node - $itemarray = array( + // Properties array used when creating the new navigation node. + $itemarray = [ 'text' => $text, - 'type' => $type - ); - // Set the action if one was provided - if ($action!==null) { + 'type' => $type, + ]; + // Set the action if one was provided. + if ($action !== null) { $itemarray['action'] = $action; } - // Set the shorttext if one was provided - if ($shorttext!==null) { + // Set the shorttext if one was provided. + if ($shorttext !== null) { $itemarray['shorttext'] = $shorttext; } - // Set the icon if one was provided - if ($icon!==null) { + // Set the icon if one was provided. + if ($icon !== null) { $itemarray['icon'] = $icon; } - // Set the key + // Set the key. $itemarray['key'] = $key; - // Construct and return + // Construct and return. return new navigation_node($itemarray); } @@ -361,21 +374,21 @@ class navigation_node implements renderable { * Adds a navigation node as a child of this node. * * @param string $text - * @param moodle_url|action_link|string $action + * @param url|action_link|string $action * @param ?int $type * @param string $shorttext * @param string|int $key * @param pix_icon $icon * @return navigation_node */ - public function add($text, $action=null, $type=self::TYPE_CUSTOM, $shorttext=null, $key=null, ?pix_icon $icon=null) { + public function add($text, $action = null, $type = self::TYPE_CUSTOM, $shorttext = null, $key = null, ?pix_icon $icon = null) { if ($action && is_string($action)) { - $action = new moodle_url($action); + $action = new url($action); } - // Create child node + // Create child node. $childnode = self::create($text, $action, $type, $shorttext, $key, $icon); - // Add the child to end and return + // Add the child to end and return. return $this->add_node($childnode); } @@ -386,34 +399,36 @@ class navigation_node implements renderable { * @param string $beforekey * @return navigation_node The added node */ - public function add_node(navigation_node $childnode, $beforekey=null) { - // First convert the nodetype for this node to a branch as it will now have children + public function add_node(navigation_node $childnode, $beforekey = null) { + // First convert the nodetype for this node to a branch as it will now have children. if ($this->nodetype !== self::NODETYPE_BRANCH) { $this->nodetype = self::NODETYPE_BRANCH; } - // Set the parent to this node + // Set the parent to this node. $childnode->set_parent($this); - // Default the key to the number of children if not provided + // Default the key to the number of children if not provided. if ($childnode->key === null) { $childnode->key = $this->children->count(); } - // Add the child using the navigation_node_collections add method + // Add the child using the navigation_node_collections add method. $node = $this->children->add($childnode, $beforekey); // If added node is a category node or the user is logged in and it's a course - // then mark added node as a branch (makes it expandable by AJAX) + // then mark added node as a branch (makes it expandable by AJAX). $type = $childnode->type; - if (($type == self::TYPE_CATEGORY) || (isloggedin() && ($type == self::TYPE_COURSE)) || ($type == self::TYPE_MY_CATEGORY) || - ($type === self::TYPE_SITE_ADMIN)) { + if ( + ($type == self::TYPE_CATEGORY) || (isloggedin() && ($type == self::TYPE_COURSE)) || ($type == self::TYPE_MY_CATEGORY) || + ($type === self::TYPE_SITE_ADMIN) + ) { $node->nodetype = self::NODETYPE_BRANCH; } - // If this node is hidden mark it's children as hidden also + // If this node is hidden mark it's children as hidden also. if ($this->hidden) { $node->hidden = true; } - // Return added node (reference returned by $this->children->add() + // Return added node (reference returned by $this->children->add(). return $node; } @@ -474,7 +489,7 @@ class navigation_node implements renderable { * @param int $type One of navigation_node::TYPE_* * @return navigation_node|false */ - public function get($key, $type=null) { + public function get($key, $type = null) { return $this->children->get($key, $type); } @@ -493,7 +508,7 @@ class navigation_node implements renderable { * @return bool Returns true if it has children or could have (by AJAX expansion) */ public function has_children() { - return ($this->nodetype === navigation_node::NODETYPE_BRANCH || $this->children->count()>0 || $this->isexpandable); + return ($this->nodetype === self::NODETYPE_BRANCH || $this->children->count() > 0 || $this->isexpandable); } /** @@ -569,8 +584,8 @@ class navigation_node implements renderable { */ public function remove_class($class) { if (in_array($class, $this->classes)) { - $key = array_search($class,$this->classes); - if ($key!==false) { + $key = array_search($class, $this->classes); + if ($key !== false) { // Remove the class' array element. unset($this->classes[$key]); // Reindex the array to avoid failures when the classes array is iterated later in mustache templates. @@ -603,7 +618,7 @@ class navigation_node implements renderable { /** * Resets the page specific information on this node if it is being unserialised. */ - public function __wakeup(){ + public function __wakeup() { $this->forceopen = false; $this->isactive = false; $this->remove_class('active_tree_node'); @@ -698,11 +713,11 @@ class navigation_node implements renderable { * @param bool $shorttext If true shorttext is used rather than the normal text * @return string */ - public function get_content($shorttext=false) { - $navcontext = \context_helper::get_navigation_filter_context(null); + public function get_content($shorttext = false) { + $navcontext = context_helper::get_navigation_filter_context(null); $options = !empty($navcontext) ? ['context' => $navcontext] : null; - if ($shorttext && $this->shorttext!==null) { + if ($shorttext && $this->shorttext !== null) { return format_string($this->shorttext, null, $options); } else { return format_string($this->text, null, $options); @@ -715,7 +730,7 @@ class navigation_node implements renderable { * @return string */ public function get_title() { - if ($this->forcetitle || $this->action != null){ + if ($this->forcetitle || $this->action != null) { return $this->title; } else { return ''; @@ -744,7 +759,7 @@ class navigation_node implements renderable { $url = $this->action()->url; } - if (($url->out() === $CFG->wwwroot) || (strpos($url->out(), $CFG->wwwroot.'/') === 0)) { + if (($url->out() === $CFG->wwwroot) || (strpos($url->out(), $CFG->wwwroot . '/') === 0)) { return true; } } @@ -767,7 +782,7 @@ class navigation_node implements renderable { */ public function get_css_type() { if (array_key_exists($this->type, $this->namedtypes)) { - return 'type_'.$this->namedtypes[$this->type]; + return 'type_' . $this->namedtypes[$this->type]; } return 'type_unknown'; } @@ -780,10 +795,10 @@ class navigation_node implements renderable { public function find_expandable(array &$expandable) { foreach ($this->children as &$child) { if ($child->display && $child->has_children() && $child->children->count() == 0) { - $child->id = 'expandable_branch_'.$child->type.'_'.clean_param($child->key, PARAM_ALPHANUMEXT); + $child->id = 'expandable_branch_' . $child->type . '_' . clean_param($child->key, PARAM_ALPHANUMEXT); $this->add_class('canexpand'); $child->requiresajaxloading = true; - $expandable[] = array('id' => $child->id, 'key' => $child->key, 'type' => $child->type); + $expandable[] = ['id' => $child->id, 'key' => $child->key, 'type' => $child->type]; } $child->find_expandable($expandable); } @@ -823,11 +838,11 @@ class navigation_node implements renderable { * @param bool $return * @return array Array (tabs, selected, inactive, activated, return) */ - public function get_tabs_array(array $inactive=array(), $return=false) { - $tabs = array(); - $rows = array(); + public function get_tabs_array(array $inactive = [], $return = false) { + $tabs = []; + $rows = []; $selected = null; - $activated = array(); + $activated = []; foreach ($this->children as $node) { $tabs[] = new tabobject($node->key, $node->action, $node->get_content(), $node->get_title()); if ($node->contains_active_node()) { @@ -844,7 +859,7 @@ class navigation_node implements renderable { } } } - return array(array($tabs, $rows), $selected, $inactive, $activated, $return); + return [[$tabs, $rows], $selected, $inactive, $activated, $return]; } /** @@ -854,11 +869,11 @@ class navigation_node implements renderable { * @param navigation_node $parent */ public function set_parent(navigation_node $parent) { - // Set the parent (thats the easy part) + // Set the parent (thats the easy part). $this->parent = $parent; - // Check if this node is active (this is checked during construction) + // Check if this node is active (this is checked during construction). if ($this->isactive) { - // Force all of the parent nodes open so you can see this node + // Force all of the parent nodes open so you can see this node. $this->parent->force_open(); // Make all parents inactive so that its clear where we are. $this->parent->make_inactive(); @@ -892,7 +907,7 @@ class navigation_node implements renderable { * @since Moodle 3.2 */ public function action() { - if ($this->action instanceof moodle_url) { + if ($this->action instanceof url) { return $this->action; } else if ($this->action instanceof action_link) { return $this->action->url; @@ -907,10 +922,10 @@ class navigation_node implements renderable { */ public function actionattributes() { if ($this->action instanceof action_link) { - return array_map(function($key, $value) { + return array_map(function ($key, $value) { return [ 'name' => $key, - 'value' => $value + 'value' => $value, ]; }, array_keys($this->action->attributes), $this->action->attributes); } @@ -940,7 +955,7 @@ class navigation_node implements renderable { } $actionid = $this->action->attributes['id']; - $actionsdata = array_map(function($action) use ($PAGE, $actionid) { + $actionsdata = array_map(function ($action) use ($PAGE, $actionid) { $data = $action->export_for_template($PAGE->get_renderer('core')); $data->id = $actionid; return $data; @@ -994,7 +1009,7 @@ class navigation_node implements renderable { } $node->add( $lockstring, - new moodle_url( + new url( '/admin/lock.php', [ 'id' => $context->id, @@ -1003,11 +1018,10 @@ class navigation_node implements renderable { self::TYPE_SETTING, null, 'contextlocking', - new pix_icon($lockicon, '') + new pix_icon($lockicon, '') ); } } - } /** diff --git a/public/lib/classes/navigation/navigation_node_collection.php b/public/lib/classes/navigation/navigation_node_collection.php index dda0f843ec4..27d80a22480 100644 --- a/public/lib/classes/navigation/navigation_node_collection.php +++ b/public/lib/classes/navigation/navigation_node_collection.php @@ -37,19 +37,19 @@ use Traversable; * @copyright 2010 Sam Hemelryk * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ -class navigation_node_collection implements IteratorAggregate, Countable { +class navigation_node_collection implements Countable, IteratorAggregate { /** * A multidimensional array to where the first key is the type and the second * key is the nodes key. * @var array */ - protected $collection = array(); + protected $collection = []; /** * An array that contains references to nodes in the same order they were added. * This is maintained as a progressive array. * @var array */ - protected $orderedcollection = array(); + protected $orderedcollection = []; /** * A reference to the last node that was added to the collection * @var navigation_node @@ -68,28 +68,28 @@ class navigation_node_collection implements IteratorAggregate, Countable { protected $collectionlabel = ''; /** - * Adds a navigation node to the collection + * Adds a navigation node to the collection. * * @param navigation_node $node Node to add * @param string $beforekey If specified, adds before a node with this key, * otherwise adds at end * @return navigation_node Added node */ - public function add(navigation_node $node, $beforekey=null) { + public function add(navigation_node $node, $beforekey = null) { global $CFG; $key = $node->key; $type = $node->type; - // First check we have a 2nd dimension for this type + // First check we have a 2nd dimension for this type. if (!array_key_exists($type, $this->orderedcollection)) { - $this->orderedcollection[$type] = array(); + $this->orderedcollection[$type] = []; } - // Check for a collision and report if debugging is turned on + // Check for a collision and report if debugging is turned on. if ($CFG->debug && array_key_exists($key, $this->orderedcollection[$type])) { - debugging('Navigation node intersect: Adding a node that already exists '.$key, DEBUG_DEVELOPER); + debugging('Navigation node intersect: Adding a node that already exists ' . $key, DEBUG_DEVELOPER); } - // Find the key to add before + // Find the key to add before. $newindex = $this->count; $last = true; if ($beforekey !== null) { @@ -107,11 +107,11 @@ class navigation_node_collection implements IteratorAggregate, Countable { } // Add the node to the appropriate place in the by-type structure (which - // is not ordered, despite the variable name) + // is not ordered, despite the variable name). $this->orderedcollection[$type][$key] = $node; if (!$last) { // Update existing references in the ordered collection (which is the - // one that isn't called 'ordered') to shuffle them along if required + // one that isn't called 'ordered') to shuffle them along if required. for ($oldindex = $this->count; $oldindex > $newindex; $oldindex--) { $this->collection[$oldindex] = $this->collection[$oldindex - 1]; } @@ -121,21 +121,22 @@ class navigation_node_collection implements IteratorAggregate, Countable { // Update the last property to a reference to this new node. $this->last = $this->orderedcollection[$type][$key]; - // Reorder the array by index if needed + // Reorder the array by index if needed. if (!$last) { ksort($this->collection); } $this->count++; - // Return the reference to the now added node + // Return the reference to the now added node. return $node; } /** * Return a list of all the keys of all the nodes. + * * @return array the keys. */ public function get_key_list() { - $keys = array(); + $keys = []; foreach ($this->collection as $node) { $keys[] = $node->key; } @@ -167,14 +168,14 @@ class navigation_node_collection implements IteratorAggregate, Countable { * @param int $type One of navigation_node::TYPE_*. * @return navigation_node|null|false */ - public function get($key, $type=null) { + public function get($key, $type = null) { if ($type !== null) { - // If the type is known then we can simply check and fetch + // If the type is known then we can simply check and fetch. if (!empty($this->orderedcollection[$type][$key])) { return $this->orderedcollection[$type][$key]; } } else { - // Because we don't know the type we look in the progressive array + // Because we don't know the type we look in the progressive array. foreach ($this->collection as $node) { if ($node->key === $key) { return $node; @@ -196,18 +197,24 @@ class navigation_node_collection implements IteratorAggregate, Countable { * @param int $type One of navigation_node::TYPE_*. * @return navigation_node|false */ - public function find($key, $type=null) { - if ($type !== null && array_key_exists($type, $this->orderedcollection) && array_key_exists($key, $this->orderedcollection[$type])) { + public function find($key, $type = null) { + if ( + $type !== null + && array_key_exists($type, $this->orderedcollection) + && array_key_exists($key, $this->orderedcollection[$type]) + ) { return $this->orderedcollection[$type][$key]; } else { $nodes = $this->getIterator(); - // Search immediate children first + + // Search immediate children first. foreach ($nodes as &$node) { if ($node->key === $key && ($type === null || $type === $node->type)) { return $node; } } - // Now search each childs children + + // Now search each childs children. foreach ($nodes as &$node) { $result = $node->children->find($key, $type); if ($result !== false) { @@ -235,7 +242,7 @@ class navigation_node_collection implements IteratorAggregate, Countable { */ public function type($type) { if (!array_key_exists($type, $this->orderedcollection)) { - $this->orderedcollection[$type] = array(); + $this->orderedcollection[$type] = []; } return $this->orderedcollection[$type]; } @@ -246,7 +253,7 @@ class navigation_node_collection implements IteratorAggregate, Countable { * @param int $type * @return bool */ - public function remove($key, $type=null) { + public function remove($key, $type = null) { $child = $this->get($key, $type); if ($child !== false) { foreach ($this->collection as $colkey => $node) { @@ -263,25 +270,12 @@ class navigation_node_collection implements IteratorAggregate, Countable { return false; } - /** - * Gets the number of nodes in this collection - * - * This option uses an internal count rather than counting the actual options to avoid - * a performance hit through the count function. - * - * @return int - */ + #[\Override] public function count(): int { return $this->count; } - /** - * Gets an array iterator for the collection. - * - * This is required by the IteratorAggregator interface and is used by routines - * such as the foreach loop. - * - * @return ArrayIterator - */ + + #[\Override] public function getIterator(): Traversable { return new ArrayIterator($this->collection); } diff --git a/public/lib/classes/navigation/settings_navigation.php b/public/lib/classes/navigation/settings_navigation.php index 97ff006076f..45b9df4b2b3 100644 --- a/public/lib/classes/navigation/settings_navigation.php +++ b/public/lib/classes/navigation/settings_navigation.php @@ -58,7 +58,7 @@ class settings_navigation extends navigation_node { /** @var bool A switch to see if the navigation node is initialised */ protected $initialised = false; /** @var array An array of users that the nodes can extend for. */ - protected $userstoextendfor = array(); + protected $userstoextendfor = []; /** @var navigation_cache **/ protected $cache; @@ -72,10 +72,10 @@ class settings_navigation extends navigation_node { return; } $this->page = $page; - // Initialise the main navigation. It is most important that this is done - // before we try anything + // Initialise the main navigation. It is most important that this is done before we try anything. $this->page->navigation->initialise(); - // Initialise the navigation cache + + // Initialise the navigation cache. $this->cache = new navigation_cache(NAVIGATION_CACHE_NAME); $this->children = new navigation_node_collection(); } @@ -106,7 +106,7 @@ class settings_navigation extends navigation_node { } switch ($context->contextlevel) { case CONTEXT_SYSTEM: - if ($this->page->url->compare(new url('/admin/settings.php', array('section'=>'frontpagesettings')))) { + if ($this->page->url->compare(new url('/admin/settings.php', ['section' => 'frontpagesettings']))) { $this->load_front_page_settings(($context->id == $this->context->id)); } break; @@ -145,11 +145,9 @@ class settings_navigation extends navigation_node { if ($isadminpage) { $adminsettings = $this->load_administration_settings(); } - } else if (!isset($SESSION->load_navigation_admin)) { $adminsettings = $this->load_administration_settings(); $SESSION->load_navigation_admin = (int)($adminsettings->children->count() > 0); - } else if ($SESSION->load_navigation_admin) { if ($isadminpage) { $adminsettings = $this->load_administration_settings(); @@ -163,8 +161,13 @@ class settings_navigation extends navigation_node { $adminsettings->remove(); $adminsettings = false; } - $siteadminnode = $this->add(get_string('administrationsite'), new url('/admin/search.php'), - self::TYPE_SITE_ADMIN, null, 'siteadministration'); + $siteadminnode = $this->add( + get_string('administrationsite'), + new url('/admin/search.php'), + self::TYPE_SITE_ADMIN, + null, + 'siteadministration' + ); $siteadminnode->id = 'expandable_branch_' . $siteadminnode->type . '_' . clean_param($siteadminnode->key, PARAM_ALPHANUMEXT); $siteadminnode->requiresajaxloading = 'true'; @@ -181,7 +184,7 @@ class settings_navigation extends navigation_node { // At this point we give any local plugins the ability to extend/tinker with the navigation settings. $this->load_local_plugin_settings(); - foreach ($this->children as $key=>$node) { + foreach ($this->children as $key => $node) { if ($node->nodetype == self::NODETYPE_BRANCH && $node->children->count() == 0) { // Site administration is shown as link. if (!empty($SESSION->load_navigation_admin) && ($node->type === self::TYPE_SITE_ADMIN)) { @@ -192,6 +195,7 @@ class settings_navigation extends navigation_node { } $this->initialised = true; } + /** * Override the parent function so that we can add preceeding hr's and set a * root node class against all first level element @@ -207,7 +211,8 @@ class settings_navigation extends navigation_node { * @param pix_icon $icon An icon that appears next to the node. * @return navigation_node with the new node added to it. */ - public function add($text, $url=null, $type=null, $shorttext=null, $key=null, ?pix_icon $icon=null) { + #[\Override] + public function add($text, $url = null, $type = null, $shorttext = null, $key = null, ?pix_icon $icon = null) { $node = parent::add($text, $url, $type, $shorttext, $key, $icon); $node->add_class('root_node'); return $node; @@ -225,10 +230,10 @@ class settings_navigation extends navigation_node { * @param pix_icon $icon An icon that appears next to the node. * @return navigation_node $node with the new node added to it. */ - public function prepend($text, $url=null, $type=null, $shorttext=null, $key=null, ?pix_icon $icon=null) { + public function prepend($text, $url = null, $type = null, $shorttext = null, $key = null, ?pix_icon $icon = null) { $children = $this->children; $childrenclass = get_class($children); - $this->children = new $childrenclass; + $this->children = new $childrenclass(); $node = $this->add($text, $url, $type, $shorttext, $key, $icon); foreach ($children as $child) { $this->children->add($child); @@ -248,7 +253,7 @@ class settings_navigation extends navigation_node { return true; } - if ($this->page->pagelayout === 'admin' or strpos($this->page->pagetype, 'admin-') === 0) { + if ($this->page->pagelayout === 'admin' || strpos($this->page->pagetype, 'admin-') === 0) { // Admin settings tree is intended for system level settings and management only, use navigation for the rest! if ($this->page->context->contextlevel != CONTEXT_SYSTEM) { return false; @@ -270,32 +275,40 @@ class settings_navigation extends navigation_node { * tree and start at the beginning * @return mixed A key to access the admin tree by */ - protected function load_administration_settings(?navigation_node $referencebranch=null, ?part_of_admin_tree $adminbranch=null) { + protected function load_administration_settings( + ?navigation_node $referencebranch = null, + ?part_of_admin_tree $adminbranch = null, + ) { global $CFG; // Check if we are just starting to generate this navigation. if ($referencebranch === null) { - - // Require the admin lib then get an admin structure + // Require the admin lib then get an admin structure. if (!function_exists('admin_get_root')) { - require_once($CFG->dirroot.'/lib/adminlib.php'); + require_once($CFG->dirroot . '/lib/adminlib.php'); } $adminroot = admin_get_root(false, false); - // This is the active section identifier + // This is the active section identifier. $this->adminsection = $this->page->url->param('section'); - // Disable the navigation from automatically finding the active node + // Disable the navigation from automatically finding the active node. navigation_node::$autofindactive = false; - $referencebranch = $this->add(get_string('administrationsite'), '/admin/search.php', self::TYPE_SITE_ADMIN, null, 'root'); + $referencebranch = $this->add( + get_string('administrationsite'), + '/admin/search.php', + self::TYPE_SITE_ADMIN, + null, + 'root', + ); foreach ($adminroot->children as $adminbranch) { $this->load_administration_settings($referencebranch, $adminbranch); } navigation_node::$autofindactive = true; - // Use the admin structure to locate the active page + // Use the admin structure to locate the active page. if (!$this->contains_active_node() && $current = $adminroot->locate($this->adminsection, true)) { $currentnode = $this; - while (($pathkey = array_pop($current->path))!==null && $currentnode) { + while (($pathkey = array_pop($current->path)) !== null && $currentnode) { $currentnode = $currentnode->get($pathkey); } if ($currentnode) { @@ -307,7 +320,7 @@ class settings_navigation extends navigation_node { return $referencebranch; } else if ($adminbranch->check_access()) { // We have a reference branch that we can access and is not hidden `hurrah` - // Now we need to display it and any children it may have + // Now we need to display it and any children it may have. $url = null; $icon = null; @@ -319,25 +332,43 @@ class settings_navigation extends navigation_node { } } - // Add the branch - $reference = $referencebranch->add($adminbranch->visiblename, $url, self::TYPE_SETTING, null, $adminbranch->name, $icon); + // Add the branch. + $reference = $referencebranch->add( + $adminbranch->visiblename, + $url, + self::TYPE_SETTING, + null, + $adminbranch->name, + $icon, + ); if ($adminbranch->is_hidden()) { - if (($adminbranch instanceof admin_externalpage || $adminbranch instanceof admin_settingpage) && $adminbranch->name == $this->adminsection) { + if ( + ( + $adminbranch instanceof admin_externalpage + || $adminbranch instanceof admin_settingpage + ) + && $adminbranch->name == $this->adminsection + ) { $reference->add_class('hidden'); } else { $reference->display = false; } } - // Check if we are generating the admin notifications and whether notificiations exist + // Check if we are generating the admin notifications and whether notificiations exist. if ($adminbranch->name === 'adminnotifications' && admin_critical_warnings_present()) { $reference->add_class('criticalnotification'); } - // Check if this branch has children - if ($reference && isset($adminbranch->children) && is_array($adminbranch->children) && count($adminbranch->children)>0) { + // Check if this branch has children. + if ( + $reference + && isset($adminbranch->children) + && is_array($adminbranch->children) + && count($adminbranch->children) > 0 + ) { foreach ($adminbranch->children as $branch) { - // Generate the child branches as well now using this branch as the reference + // Generate the child branches as well now using this branch as the reference. $this->load_administration_settings($reference, $branch); } } else { @@ -352,7 +383,7 @@ class settings_navigation extends navigation_node { * @param navigation_node $node */ protected function scan_for_active_node(navigation_node $node) { - if (!$node->check_if_active() && $node->children->count()>0) { + if (!$node->check_if_active() && $node->children->count() > 0) { foreach ($node->children as &$child) { $this->scan_for_active_node($child); } @@ -388,8 +419,7 @@ class settings_navigation extends navigation_node { $coursecontext = context_course::instance($course->id); $adminoptions = course_get_user_administration_options($course, $coursecontext); - // note: do not test if enrolled or viewing here because we need the enrol link in Course administration section - + // Note: Do not test if enrolled or viewing here because we need the enrol link in Course administration section. $coursenode = $this->add(get_string('courseadministration'), null, self::TYPE_COURSE, null, 'courseadmin'); if ($forceopen) { $coursenode->force_open(); @@ -411,30 +441,54 @@ class settings_navigation extends navigation_node { 'data-type' => 'course', ]); // Share course to MoodleNet link. - $coursenode->add(get_string('moodlenet:sharetomoodlenet', 'moodle'), - $action, self::TYPE_SETTING, null, 'exportcoursetomoodlenet')->set_force_into_more_menu(true); + $coursenode->add( + get_string('moodlenet:sharetomoodlenet', 'moodle'), + $action, + self::TYPE_SETTING, + null, + 'exportcoursetomoodlenet' + )->set_force_into_more_menu(true); // MoodleNet share progress link. $url = new url('/moodlenet/shareprogress.php'); - $coursenode->add(get_string('moodlenet:shareprogress'), - $url, self::TYPE_SETTING, null, 'moodlenetshareprogress')->set_force_into_more_menu(true); + $coursenode->add( + get_string('moodlenet:shareprogress'), + $url, + self::TYPE_SETTING, + null, + 'moodlenetshareprogress' + )->set_force_into_more_menu(true); } } catch (dml_missing_record_exception $e) { - debugging("Invalid MoodleNet OAuth 2 service set in site administration: 'moodlenet | oauthservice'. " . - "This must be a valid issuer."); + debugging( + "Invalid MoodleNet OAuth 2 service set in site administration: 'moodlenet | oauthservice'. " . + "This must be a valid issuer." + ); } if ($adminoptions->update) { - // Add the course settings link - $url = new url('/course/edit.php', array('id'=>$course->id)); - $coursenode->add(get_string('settings'), $url, self::TYPE_SETTING, null, - 'editsettings', new pix_icon('i/settings', '')); + // Add the course settings link. + $url = new url('/course/edit.php', ['id' => $course->id]); + $coursenode->add( + get_string('settings'), + $url, + self::TYPE_SETTING, + null, + 'editsettings', + new pix_icon('i/settings', '') + ); } if ($adminoptions->editcompletion) { - // Add the course completion settings link - $url = new url('/course/completion.php', array('id' => $course->id)); - $coursenode->add(get_string('coursecompletion', 'completion'), $url, self::TYPE_SETTING, null, 'coursecompletion', - new pix_icon('i/settings', '')); + // Add the course completion settings link. + $url = new url('/course/completion.php', ['id' => $course->id]); + $coursenode->add( + get_string('coursecompletion', 'completion'), + $url, + self::TYPE_SETTING, + null, + 'coursecompletion', + new pix_icon('i/settings', '') + ); } if (!$adminoptions->update && $adminoptions->tags) { @@ -442,32 +496,50 @@ class settings_navigation extends navigation_node { \core_course\route\controller\tags_controller::class, 'administer_tags', ], ['course' => $course->id]); - $coursenode->add(get_string('coursetags', 'tag'), $url, self::TYPE_SETTING, null, 'coursetags', new pix_icon('i/settings', '')); + $coursenode->add( + get_string('coursetags', 'tag'), + $url, + self::TYPE_SETTING, + null, + 'coursetags', + new pix_icon('i/settings', ''), + ); $coursenode->get('coursetags')->set_force_into_more_menu(); } - // add enrol nodes + // Add enrol nodes. enrol_add_course_navigation($coursenode, $course); - // Manage filters + // Manage filters. if ($adminoptions->filters) { - $url = new url('/filter/manage.php', array('contextid'=>$coursecontext->id)); - $coursenode->add(get_string('filters', 'admin'), $url, self::TYPE_SETTING, - null, 'filtermanagement', new pix_icon('i/filter', '')); + $url = new url('/filter/manage.php', ['contextid' => $coursecontext->id]); + $coursenode->add( + get_string('filters', 'admin'), + $url, + self::TYPE_SETTING, + null, + 'filtermanagement', + new pix_icon('i/filter', '') + ); } // View course reports. if ($adminoptions->reports) { - $reportnav = $coursenode->add(get_string('reports'), + $reportnav = $coursenode->add( + get_string('reports'), new url('/report/view.php', ['courseid' => $coursecontext->instanceid]), - self::TYPE_CONTAINER, null, 'coursereports', new pix_icon('i/stats', '')); + self::TYPE_CONTAINER, + null, + 'coursereports', + new pix_icon('i/stats', '') + ); $coursereports = component::get_plugin_list('coursereport'); foreach ($coursereports as $report => $dir) { - $libfile = $CFG->dirroot.'/course/report/'.$report.'/lib.php'; + $libfile = $CFG->dirroot . '/course/report/' . $report . '/lib.php'; if (file_exists($libfile)) { require_once($libfile); - $reportfunction = $report.'_report_extend_navigation'; - if (function_exists($report.'_report_extend_navigation')) { + $reportfunction = $report . '_report_extend_navigation'; + if (function_exists($report . '_report_extend_navigation')) { $reportfunction($reportnav, $course, $coursecontext); } } @@ -488,54 +560,80 @@ class settings_navigation extends navigation_node { // Check if we can view the gradebook's setup page. if ($adminoptions->gradebook) { - $url = new url('/grade/edit/tree/index.php', array('id' => $course->id)); - $coursenode->add(get_string('gradebooksetup', 'grades'), $url, self::TYPE_SETTING, - null, 'gradebooksetup', new pix_icon('i/settings', '')); + $url = new url('/grade/edit/tree/index.php', ['id' => $course->id]); + $coursenode->add( + get_string('gradebooksetup', 'grades'), + $url, + self::TYPE_SETTING, + null, + 'gradebooksetup', + new pix_icon('i/settings', '') + ); } // Add the context locking node. $this->add_context_locking_node($coursenode, $coursecontext); - // Add outcome if permitted + // Add outcome if permitted. if ($adminoptions->outcomes) { - $url = new url('/grade/edit/outcome/course.php', array('id'=>$course->id)); - $coursenode->add(get_string('outcomes', 'grades'), $url, self::TYPE_SETTING, null, 'outcomes', new pix_icon('i/outcomes', '')); + $url = new url('/grade/edit/outcome/course.php', ['id' => $course->id]); + $coursenode->add( + get_string('outcomes', 'grades'), + $url, + self::TYPE_SETTING, + null, + 'outcomes', + new pix_icon('i/outcomes', ''), + ); } - //Add badges navigation + // Add badges navigation. if ($adminoptions->badges) { - require_once($CFG->libdir .'/badgeslib.php'); + require_once($CFG->libdir . '/badgeslib.php'); badges_add_course_navigation($coursenode, $course); } - // Questions + // Questions. require_once($CFG->libdir . '/questionlib.php'); $baseurl = \core_question\local\bank\question_bank_helper::get_url_for_qbank_list($course->id); question_extend_settings_navigation($coursenode, $coursecontext, $baseurl)->trim_if_empty(); if ($adminoptions->update) { - // Repository Instances - if (!$this->cache->cached('contexthasrepos'.$coursecontext->id)) { + // Repository Instances. + if (!$this->cache->cached('contexthasrepos' . $coursecontext->id)) { require_once($CFG->dirroot . '/repository/lib.php'); $editabletypes = repository::get_editable_types($coursecontext); $haseditabletypes = !empty($editabletypes); unset($editabletypes); - $this->cache->set('contexthasrepos'.$coursecontext->id, $haseditabletypes); + $this->cache->set('contexthasrepos' . $coursecontext->id, $haseditabletypes); } else { - $haseditabletypes = $this->cache->{'contexthasrepos'.$coursecontext->id}; + $haseditabletypes = $this->cache->{'contexthasrepos' . $coursecontext->id}; } if ($haseditabletypes) { - $url = new url('/repository/manage_instances.php', array('contextid' => $coursecontext->id)); - $coursenode->add(get_string('repositories'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/repository', '')); + $url = new url('/repository/manage_instances.php', ['contextid' => $coursecontext->id]); + $coursenode->add( + get_string('repositories'), + $url, + self::TYPE_SETTING, + null, + null, + new pix_icon('i/repository', ''), + ); } } - // Manage files + // Manage files. if ($adminoptions->files) { - // hidden in new courses and courses where legacy files were turned off - $url = new url('/files/index.php', array('contextid'=>$coursecontext->id)); - $coursenode->add(get_string('courselegacyfiles'), $url, self::TYPE_SETTING, null, 'coursefiles', new pix_icon('i/folder', '')); - + // Hidden in new courses and courses where legacy files were turned off. + $url = new url('/files/index.php', ['contextid' => $coursecontext->id]); + $coursenode->add( + get_string('courselegacyfiles'), + $url, + self::TYPE_SETTING, + null, + 'coursefiles', + new pix_icon('i/folder', ''), + ); } // Let plugins hook into course navigation. @@ -555,21 +653,32 @@ class settings_navigation extends navigation_node { $linkattr = \core_course\output\content_export_link::get_attributes($coursecontext); $actionlink = new action_link($linkattr->url, $linkattr->displaystring, null, $linkattr->elementattributes); - $coursenode->add($linkattr->displaystring, $actionlink, self::TYPE_SETTING, null, 'download', - new pix_icon('t/download', '')); + $coursenode->add( + $linkattr->displaystring, + $actionlink, + self::TYPE_SETTING, + null, + 'download', + new pix_icon('t/download', '') + ); $coursenode->get('download')->set_force_into_more_menu(true); } // Course reuse options. - if ($adminoptions->import + if ( + $adminoptions->import || $adminoptions->backup || $adminoptions->restore || $adminoptions->copy - || $adminoptions->reset) { + || $adminoptions->reset + ) { $coursereusenav = $coursenode->add( get_string('coursereuse'), new url('/backup/view.php', ['id' => $course->id]), - self::TYPE_CONTAINER, null, 'coursereuse', new pix_icon('t/edit', ''), + self::TYPE_CONTAINER, + null, + 'coursereuse', + new pix_icon('t/edit', ''), ); // Import data from other courses. @@ -610,7 +719,7 @@ class settings_navigation extends navigation_node { } } - // Return we are done + // Return we are done. return $coursenode; } @@ -642,76 +751,129 @@ class settings_navigation extends navigation_node { $this->page->set_cm($cm, $this->page->course); } - $file = $CFG->dirroot.'/mod/'.$this->page->activityname.'/lib.php'; + $file = $CFG->dirroot . '/mod/' . $this->page->activityname . '/lib.php'; if (file_exists($file)) { require_once($file); } - $modulenode = $this->add(get_string('pluginadministration', $this->page->activityname), null, self::TYPE_SETTING, null, 'modulesettings'); + $modulenode = $this->add( + get_string('pluginadministration', $this->page->activityname), + null, + self::TYPE_SETTING, + null, + 'modulesettings', + ); $modulenode->nodetype = navigation_node::NODETYPE_BRANCH; $modulenode->force_open(); - // Settings for the module + // Settings for the module. if (has_capability('moodle/course:manageactivities', $this->page->cm->context)) { - $url = new url('/course/modedit.php', array('update' => $this->page->cm->id, 'return' => 1)); + $url = new url('/course/modedit.php', ['update' => $this->page->cm->id, 'return' => 1]); $modulenode->add(get_string('settings'), $url, self::TYPE_SETTING, null, 'modedit', new pix_icon('i/settings', '')); } - // Assign local roles - if (count(get_assignable_roles($this->page->cm->context))>0) { - $url = new url('/'.$CFG->admin.'/roles/assign.php', array('contextid'=>$this->page->cm->context->id)); - $modulenode->add(get_string('localroles', 'role'), $url, self::TYPE_SETTING, null, 'roleassign', - new pix_icon('i/role', '')); + // Assign local roles. + if (count(get_assignable_roles($this->page->cm->context)) > 0) { + $url = new url('/' . $CFG->admin . '/roles/assign.php', ['contextid' => $this->page->cm->context->id]); + $modulenode->add( + get_string('localroles', 'role'), + $url, + self::TYPE_SETTING, + null, + 'roleassign', + new pix_icon('i/role', '') + ); } - // Override roles - if (has_capability('moodle/role:review', $this->page->cm->context) or count(get_overridable_roles($this->page->cm->context))>0) { - $url = new url('/'.$CFG->admin.'/roles/permissions.php', array('contextid'=>$this->page->cm->context->id)); - $modulenode->add(get_string('permissions', 'role'), $url, self::TYPE_SETTING, null, 'roleoverride', - new pix_icon('i/permissions', '')); + // Override roles. + if ( + has_capability('moodle/role:review', $this->page->cm->context) + || count(get_overridable_roles($this->page->cm->context)) > 0 + ) { + $url = new url('/admin/roles/permissions.php', ['contextid' => $this->page->cm->context->id]); + $modulenode->add( + get_string('permissions', 'role'), + $url, + self::TYPE_SETTING, + null, + 'roleoverride', + new pix_icon('i/permissions', '') + ); } - // Check role permissions - if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride','moodle/role:override', 'moodle/role:assign'), $this->page->cm->context)) { - $url = new url('/'.$CFG->admin.'/roles/check.php', array('contextid'=>$this->page->cm->context->id)); - $modulenode->add(get_string('checkpermissions', 'role'), $url, self::TYPE_SETTING, null, 'rolecheck', - new pix_icon('i/checkpermissions', '')); + // Check role permissions. + if ( + has_any_capability( + ['moodle/role:assign', 'moodle/role:safeoverride', 'moodle/role:override', 'moodle/role:assign'], + $this->page->cm->context, + ) + ) { + $url = new url('/' . $CFG->admin . '/roles/check.php', ['contextid' => $this->page->cm->context->id]); + $modulenode->add( + get_string('checkpermissions', 'role'), + $url, + self::TYPE_SETTING, + null, + 'rolecheck', + new pix_icon('i/checkpermissions', ''), + ); } // Add the context locking node. $this->add_context_locking_node($modulenode, $this->page->cm->context); - // Manage filters - if (has_capability('moodle/filter:manage', $this->page->cm->context) && count(filter_get_available_in_context($this->page->cm->context))>0) { - $url = new url('/filter/manage.php', array('contextid'=>$this->page->cm->context->id)); - $modulenode->add(get_string('filters', 'admin'), $url, self::TYPE_SETTING, null, 'filtermanage', - new pix_icon('i/filter', '')); + // Manage filters. + if ( + has_capability('moodle/filter:manage', $this->page->cm->context) && + count(filter_get_available_in_context($this->page->cm->context)) > 0 + ) { + $url = new url('/filter/manage.php', ['contextid' => $this->page->cm->context->id]); + $modulenode->add( + get_string('filters', 'admin'), + $url, + self::TYPE_SETTING, + null, + 'filtermanage', + new pix_icon('i/filter', '') + ); } - // Add reports + // Add reports. $reports = get_plugin_list_with_function('report', 'extend_navigation_module', 'lib.php'); foreach ($reports as $reportfunction) { $reportfunction($modulenode, $this->page->cm); } - // Add a backup link - $featuresfunc = $this->page->activityname.'_supports'; - if (function_exists($featuresfunc) && $featuresfunc(FEATURE_BACKUP_MOODLE2) && has_capability('moodle/backup:backupactivity', $this->page->cm->context)) { - $url = new url('/backup/backup.php', array('id'=>$this->page->cm->course, 'cm'=>$this->page->cm->id)); + // Add a backup link. + $featuresfunc = $this->page->activityname . '_supports'; + if ( + function_exists($featuresfunc) + && $featuresfunc(FEATURE_BACKUP_MOODLE2) + && has_capability('moodle/backup:backupactivity', $this->page->cm->context) + ) { + $url = new url('/backup/backup.php', ['id' => $this->page->cm->course, 'cm' => $this->page->cm->id]); $modulenode->add(get_string('backup'), $url, self::TYPE_SETTING, null, 'backup', new pix_icon('i/backup', '')); } - // Restore this activity - $featuresfunc = $this->page->activityname.'_supports'; - if (function_exists($featuresfunc) && $featuresfunc(FEATURE_BACKUP_MOODLE2) && has_capability('moodle/restore:restoreactivity', $this->page->cm->context)) { - $url = new url('/backup/restorefile.php', array('contextid'=>$this->page->cm->context->id)); + // Restore this activity. + $featuresfunc = $this->page->activityname . '_supports'; + if ( + function_exists($featuresfunc) && + $featuresfunc(FEATURE_BACKUP_MOODLE2) && + has_capability('moodle/restore:restoreactivity', $this->page->cm->context) + ) { + $url = new url('/backup/restorefile.php', ['contextid' => $this->page->cm->context->id]); $modulenode->add(get_string('restore'), $url, self::TYPE_SETTING, null, 'restore', new pix_icon('i/restore', '')); } - // Allow the active advanced grading method plugin to append its settings - $featuresfunc = $this->page->activityname.'_supports'; - if (function_exists($featuresfunc) && $featuresfunc(FEATURE_ADVANCED_GRADING) && has_capability('moodle/grade:managegradingforms', $this->page->cm->context)) { - require_once($CFG->dirroot.'/grade/grading/lib.php'); - $gradingman = get_grading_manager($this->page->cm->context, 'mod_'.$this->page->activityname); + // Allow the active advanced grading method plugin to append its settings. + $featuresfunc = $this->page->activityname . '_supports'; + if ( + function_exists($featuresfunc) + && $featuresfunc(FEATURE_ADVANCED_GRADING) + && has_capability('moodle/grade:managegradingforms', $this->page->cm->context) + ) { + require_once($CFG->dirroot . '/grade/grading/lib.php'); + $gradingman = get_grading_manager($this->page->cm->context, 'mod_' . $this->page->activityname); $gradingman->extend_settings_navigation($this, $modulenode); } - $function = $this->page->activityname.'_extend_settings_navigation'; + $function = $this->page->activityname . '_extend_settings_navigation'; if (function_exists($function)) { $function($this, $modulenode); } @@ -728,8 +890,13 @@ class settings_navigation extends navigation_node { 'data-action' => 'sendtomoodlenet', 'data-type' => 'activity', ]); - $modulenode->add(get_string('moodlenet:sharetomoodlenet', 'moodle'), - $action, self::TYPE_SETTING, null, 'exportmoodlenet')->set_force_into_more_menu(true); + $modulenode->add( + get_string('moodlenet:sharetomoodlenet', 'moodle'), + $action, + self::TYPE_SETTING, + null, + 'exportmoodlenet' + )->set_force_into_more_menu(true); } } catch (dml_missing_record_exception $e) { debugging("Invalid MoodleNet OAuth 2 service set in site administration: 'moodlenet | oauthservice'. " . @@ -808,7 +975,7 @@ class settings_navigation extends navigation_node { $this->userstoextendfor[] = $userid; if ($this->initialised) { $this->generate_user_settings($this->page->course->id, $userid, 'userviewingsettings'); - $children = array(); + $children = []; foreach ($this->children as $child) { $children[] = $child; } @@ -830,7 +997,7 @@ class settings_navigation extends navigation_node { * @param string $gstitle The string to pass to get_string for the branch title * @return navigation_node|false */ - protected function generate_user_settings($courseid, $userid, $gstitle='usercurrentsettings') { + protected function generate_user_settings($courseid, $userid, $gstitle = 'usercurrentsettings') { global $DB, $CFG, $USER, $SITE; if ($courseid != $SITE->id) { @@ -842,7 +1009,7 @@ class settings_navigation extends navigation_node { FROM {course} c JOIN {context} ctx ON c.id = ctx.instanceid WHERE c.id = :courseid AND ctx.contextlevel = :contextlevel"; - $params = array('courseid' => $courseid, 'contextlevel' => CONTEXT_COURSE); + $params = ['courseid' => $courseid, 'contextlevel' => CONTEXT_COURSE]; $course = $DB->get_record_sql($sql, $params, MUST_EXIST); context_helper::preload_from_record($course); } @@ -850,33 +1017,35 @@ class settings_navigation extends navigation_node { $course = $SITE; } - $coursecontext = context_course::instance($course->id); // Course context + $coursecontext = context_course::instance($course->id); $systemcontext = context_system::instance(); $currentuser = ($USER->id == $userid); if ($currentuser) { $user = $USER; - $usercontext = context_user::instance($user->id); // User context + $usercontext = context_user::instance($user->id); } else { $select = context_helper::get_preload_record_columns_sql('ctx'); $sql = "SELECT u.*, $select FROM {user} u JOIN {context} ctx ON u.id = ctx.instanceid WHERE u.id = :userid AND ctx.contextlevel = :contextlevel"; - $params = array('userid' => $userid, 'contextlevel' => CONTEXT_USER); + $params = ['userid' => $userid, 'contextlevel' => CONTEXT_USER]; $user = $DB->get_record_sql($sql, $params, IGNORE_MISSING); if (!$user) { return false; } context_helper::preload_from_record($user); - // Check that the user can view the profile - $usercontext = context_user::instance($user->id); // User context + // Check that the user can view the profile. + $usercontext = context_user::instance($user->id); // User context. $canviewuser = has_capability('moodle/user:viewdetails', $usercontext); if ($course->id == $SITE->id) { - if ($CFG->forceloginforprofiles && !has_coursecontact_role($user->id) && !$canviewuser) { // Reduce possibility of "browsing" userbase at site level - // Teachers can browse and be browsed at site level. If not forceloginforprofiles, allow access (bug #4366) + // Reduce possibility of "browsing" userbase at site level. + if ($CFG->forceloginforprofiles && !has_coursecontact_role($user->id) && !$canviewuser) { + // Teachers can browse and be browsed at site level. + // If not forceloginforprofiles, allow access (See MDL-4366). return false; } } else { @@ -924,7 +1093,7 @@ class settings_navigation extends navigation_node { $iscurrentuser = ($user->id == $USER->id); - $baseargs = array('id' => $user->id); + $baseargs = ['id' => $user->id]; if ($course->id != $SITE->id && !$iscurrentuser) { $baseargs['course'] = $course->id; $issitecourse = false; @@ -934,26 +1103,34 @@ class settings_navigation extends navigation_node { } // Add the user profile to the dashboard. - $profilenode = $mainpage->add(get_string('profile'), new url('/user/profile.php', - array('id' => $user->id)), self::TYPE_SETTING, null, 'myprofile'); + $profilenode = $mainpage->add(get_string('profile'), new url( + '/user/profile.php', + ['id' => $user->id] + ), self::TYPE_SETTING, null, 'myprofile'); // Add blog nodes. if (!empty($CFG->enableblogs)) { - if (!$this->cache->cached('userblogoptions'.$user->id)) { - require_once($CFG->dirroot.'/blog/lib.php'); + if (!$this->cache->cached('userblogoptions' . $user->id)) { + require_once($CFG->dirroot . '/blog/lib.php'); // Get all options for the user. $options = blog_get_options_for_user($user); - $this->cache->set('userblogoptions'.$user->id, $options); + $this->cache->set('userblogoptions' . $user->id, $options); } else { - $options = $this->cache->{'userblogoptions'.$user->id}; + $options = $this->cache->{'userblogoptions' . $user->id}; } if (count($options) > 0) { $blogs = $profilenode->add(get_string('blogs', 'blog'), null, navigation_node::TYPE_CONTAINER); foreach ($options as $type => $option) { if ($type == "rss") { - $blogs->add($option['string'], $option['link'], self::TYPE_SETTING, null, null, - new pix_icon('i/rss', '')); + $blogs->add( + $option['string'], + $option['link'], + self::TYPE_SETTING, + null, + null, + new pix_icon('i/rss', '') + ); } else { $blogs->add($option['string'], $option['link'], self::TYPE_SETTING, null, 'blog' . $type); } @@ -964,7 +1141,7 @@ class settings_navigation extends navigation_node { // Add the messages link. // It is context based so can appear in the user's profile and in course participants information. if (!empty($CFG->messaging)) { - $messageargs = array('user1' => $USER->id); + $messageargs = ['user1' => $USER->id]; if ($USER->id != $user->id) { $messageargs['user2'] = $user->id; } @@ -980,9 +1157,11 @@ class settings_navigation extends navigation_node { } // Add a node to view the users notes if permitted. - if (!empty($CFG->enablenotes) && - has_any_capability(array('moodle/notes:manage', 'moodle/notes:view'), $coursecontext)) { - $url = new url('/notes/index.php', array('user' => $user->id)); + if ( + !empty($CFG->enablenotes) && + has_any_capability(['moodle/notes:manage', 'moodle/notes:view'], $coursecontext) + ) { + $url = new url('/notes/index.php', ['user' => $user->id]); if ($coursecontext->instanceid != SITEID) { $url->param('course', $coursecontext->instanceid); } @@ -996,7 +1175,7 @@ class settings_navigation extends navigation_node { if ($course->id == SITEID) { $url = user_mygrades_url($user->id, $course->id); } else { // Otherwise we are in a course and should redirect to the user grade report (Activity report version). - $url = new url('/course/user.php', array('mode' => 'grade', 'id' => $course->id, 'user' => $user->id)); + $url = new url('/course/user.php', ['mode' => 'grade', 'id' => $course->id, 'user' => $user->id]); } $mainpage->add(get_string('grades', 'grades'), $url, self::TYPE_SETTING, null, 'mygrades'); } @@ -1027,9 +1206,9 @@ class settings_navigation extends navigation_node { } else { // We can edit the user so show the user deleted message and link it to the profile. if ($course->id == $SITE->id) { - $profileurl = new url('/user/profile.php', array('id'=>$user->id)); + $profileurl = new url('/user/profile.php', ['id' => $user->id]); } else { - $profileurl = new url('/user/view.php', array('id'=>$user->id, 'course'=>$course->id)); + $profileurl = new url('/user/view.php', ['id' => $user->id, 'course' => $course->id]); } $usersetting->add(get_string('userdeleted'), $profileurl, self::TYPE_SETTING); } @@ -1045,16 +1224,20 @@ class settings_navigation extends navigation_node { // Add the profile edit link. if (isloggedin() && !isguestuser($user) && !is_mnet_remote_user($user)) { - if (($currentuser || is_siteadmin($USER) || !is_siteadmin($user)) && - has_capability('moodle/user:update', $systemcontext)) { - $url = new url('/user/editadvanced.php', array('id'=>$user->id, 'course'=>$course->id)); + if ( + ($currentuser || is_siteadmin($USER) || !is_siteadmin($user)) && + has_capability('moodle/user:update', $systemcontext) + ) { + $url = new url('/user/editadvanced.php', ['id' => $user->id, 'course' => $course->id]); $useraccount->add(get_string('editmyprofile'), $url, self::TYPE_SETTING, null, 'editprofile'); - } else if ((has_capability('moodle/user:editprofile', $usercontext) && !is_siteadmin($user)) || - ($currentuser && has_capability('moodle/user:editownprofile', $systemcontext))) { + } else if ( + (has_capability('moodle/user:editprofile', $usercontext) && !is_siteadmin($user)) || + ($currentuser && has_capability('moodle/user:editownprofile', $systemcontext)) + ) { if ($userauthplugin && $userauthplugin->can_edit_profile()) { $url = $userauthplugin->edit_profile_url(); if (empty($url)) { - $url = new url('/user/edit.php', array('id'=>$user->id, 'course'=>$course->id)); + $url = new url('/user/edit.php', ['id' => $user->id, 'course' => $course->id]); } $useraccount->add(get_string('editmyprofile'), $url, self::TYPE_SETTING, null, 'editprofile'); } @@ -1062,11 +1245,13 @@ class settings_navigation extends navigation_node { } // Change password link. - if ($userauthplugin && $currentuser && !\core\session\manager::is_loggedinas() && !isguestuser() && - has_capability('moodle/user:changeownpassword', $systemcontext) && $userauthplugin->can_change_password()) { + if ( + $userauthplugin && $currentuser && !\core\session\manager::is_loggedinas() && !isguestuser() && + has_capability('moodle/user:changeownpassword', $systemcontext) && $userauthplugin->can_change_password() + ) { $passwordchangeurl = $userauthplugin->change_password_url(); if (empty($passwordchangeurl)) { - $passwordchangeurl = new url('/login/change_password.php', array('id'=>$course->id)); + $passwordchangeurl = new url('/login/change_password.php', ['id' => $course->id]); } $useraccount->add(get_string("changepassword"), $passwordchangeurl, self::TYPE_SETTING, null, 'changepassword'); } @@ -1074,35 +1259,43 @@ class settings_navigation extends navigation_node { // Default homepage. $defaulthomepageuser = (!empty($CFG->defaulthomepage) && ($CFG->defaulthomepage == HOMEPAGE_USER)); if (isloggedin() && !isguestuser($user) && $defaulthomepageuser) { - if ($currentuser && has_capability('moodle/user:editownprofile', $systemcontext) || - has_capability('moodle/user:editprofile', $usercontext)) { + if ( + $currentuser && has_capability('moodle/user:editownprofile', $systemcontext) || + has_capability('moodle/user:editprofile', $usercontext) + ) { $url = new url('/user/defaulthomepage.php', ['id' => $user->id]); $useraccount->add(get_string('defaulthomepageuser'), $url, self::TYPE_SETTING, null, 'defaulthomepageuser'); } } if (isloggedin() && !isguestuser($user) && !is_mnet_remote_user($user)) { - if ($currentuser && has_capability('moodle/user:editownprofile', $systemcontext) || - has_capability('moodle/user:editprofile', $usercontext)) { - $url = new url('/user/language.php', array('id' => $user->id, 'course' => $course->id)); + if ( + $currentuser && has_capability('moodle/user:editownprofile', $systemcontext) || + has_capability('moodle/user:editprofile', $usercontext) + ) { + $url = new url('/user/language.php', ['id' => $user->id, 'course' => $course->id]); $useraccount->add(get_string('preferredlanguage'), $url, self::TYPE_SETTING, null, 'preferredlanguage'); } } $pluginmanager = core_plugin_manager::instance(); $enabled = $pluginmanager->get_enabled_plugins('mod'); if (isset($enabled['forum']) && isloggedin() && !isguestuser($user) && !is_mnet_remote_user($user)) { - if ($currentuser && has_capability('moodle/user:editownprofile', $systemcontext) || - has_capability('moodle/user:editprofile', $usercontext)) { - $url = new url('/user/forum.php', array('id' => $user->id, 'course' => $course->id)); + if ( + $currentuser && has_capability('moodle/user:editownprofile', $systemcontext) || + has_capability('moodle/user:editprofile', $usercontext) + ) { + $url = new url('/user/forum.php', ['id' => $user->id, 'course' => $course->id]); $useraccount->add(get_string('forumpreferences'), $url, self::TYPE_SETTING); } } $editors = editors_get_enabled(); if (count($editors) > 1) { if (isloggedin() && !isguestuser($user) && !is_mnet_remote_user($user)) { - if ($currentuser && has_capability('moodle/user:editownprofile', $systemcontext) || - has_capability('moodle/user:editprofile', $usercontext)) { - $url = new url('/user/editor.php', array('id' => $user->id, 'course' => $course->id)); + if ( + $currentuser && has_capability('moodle/user:editownprofile', $systemcontext) || + has_capability('moodle/user:editprofile', $usercontext) + ) { + $url = new url('/user/editor.php', ['id' => $user->id, 'course' => $course->id]); $useraccount->add(get_string('editorpreferences'), $url, self::TYPE_SETTING); } } @@ -1110,26 +1303,45 @@ class settings_navigation extends navigation_node { // Add "Calendar preferences" link. if (isloggedin() && !isguestuser($user)) { - if ($currentuser && has_capability('moodle/user:editownprofile', $systemcontext) || - has_capability('moodle/user:editprofile', $usercontext)) { - $url = new url('/user/calendar.php', array('id' => $user->id)); - $useraccount->add(get_string('calendarpreferences', 'calendar'), $url, self::TYPE_SETTING, null, 'preferredcalendar'); + if ( + $currentuser && has_capability('moodle/user:editownprofile', $systemcontext) || + has_capability('moodle/user:editprofile', $usercontext) + ) { + $url = new url('/user/calendar.php', ['id' => $user->id]); + $useraccount->add( + get_string('calendarpreferences', 'calendar'), + $url, + self::TYPE_SETTING, + null, + 'preferredcalendar', + ); } } // Add "Content bank preferences" link. if (isloggedin() && !isguestuser($user)) { - if ($currentuser && has_capability('moodle/user:editownprofile', $systemcontext) || - has_capability('moodle/user:editprofile', $usercontext)) { + if ( + $currentuser && has_capability('moodle/user:editownprofile', $systemcontext) || + has_capability('moodle/user:editprofile', $usercontext) + ) { $url = new url('/user/contentbank.php', ['id' => $user->id]); - $useraccount->add(get_string('contentbankpreferences', 'core_contentbank'), $url, self::TYPE_SETTING, - null, 'contentbankpreferences'); + $useraccount->add( + get_string('contentbankpreferences', 'core_contentbank'), + $url, + self::TYPE_SETTING, + null, + 'contentbankpreferences' + ); } } // View the roles settings. - if (has_any_capability(['moodle/role:assign', 'moodle/role:safeoverride', 'moodle/role:override', - 'moodle/role:manage'], $usercontext)) { + if ( + has_any_capability( + ['moodle/role:assign', 'moodle/role:safeoverride', 'moodle/role:override', 'moodle/role:manage'], + $usercontext, + ) + ) { $roles = $usersetting->add(get_string('roles'), null, self::TYPE_SETTING); $url = new url('/admin/roles/usersroles.php', ['userid' => $user->id, 'courseid' => $course->id]); @@ -1138,36 +1350,47 @@ class settings_navigation extends navigation_node { $assignableroles = get_assignable_roles($usercontext, ROLENAME_BOTH); if (!empty($assignableroles)) { - $url = new url('/admin/roles/assign.php', - array('contextid' => $usercontext->id, 'userid' => $user->id, 'courseid' => $course->id)); + $url = new url( + '/admin/roles/assign.php', + ['contextid' => $usercontext->id, 'userid' => $user->id, 'courseid' => $course->id] + ); $roles->add(get_string('assignrolesrelativetothisuser', 'role'), $url, self::TYPE_SETTING); } - if (has_capability('moodle/role:review', $usercontext) || count(get_overridable_roles($usercontext, ROLENAME_BOTH))>0) { - $url = new url('/admin/roles/permissions.php', - array('contextid' => $usercontext->id, 'userid' => $user->id, 'courseid' => $course->id)); + if ( + has_capability('moodle/role:review', $usercontext) + || count(get_overridable_roles($usercontext, ROLENAME_BOTH)) > 0 + ) { + $url = new url( + '/admin/roles/permissions.php', + ['contextid' => $usercontext->id, 'userid' => $user->id, 'courseid' => $course->id] + ); $roles->add(get_string('permissions', 'role'), $url, self::TYPE_SETTING); } - $url = new url('/admin/roles/check.php', - array('contextid' => $usercontext->id, 'userid' => $user->id, 'courseid' => $course->id)); + $url = new url( + '/admin/roles/check.php', + ['contextid' => $usercontext->id, 'userid' => $user->id, 'courseid' => $course->id] + ); $roles->add(get_string('checkpermissions', 'role'), $url, self::TYPE_SETTING); } // Repositories. - if (!$this->cache->cached('contexthasrepos'.$usercontext->id)) { + if (!$this->cache->cached('contexthasrepos' . $usercontext->id)) { require_once($CFG->dirroot . '/repository/lib.php'); $editabletypes = repository::get_editable_types($usercontext); $haseditabletypes = !empty($editabletypes); unset($editabletypes); - $this->cache->set('contexthasrepos'.$usercontext->id, $haseditabletypes); + $this->cache->set('contexthasrepos' . $usercontext->id, $haseditabletypes); } else { - $haseditabletypes = $this->cache->{'contexthasrepos'.$usercontext->id}; + $haseditabletypes = $this->cache->{'contexthasrepos' . $usercontext->id}; } if ($haseditabletypes) { $repositories = $usersetting->add(get_string('repositories', 'repository'), null, self::TYPE_SETTING); - $repositories->add(get_string('manageinstances', 'repository'), new url('/repository/manage_instances.php', - array('contextid' => $usercontext->id))); + $repositories->add(get_string('manageinstances', 'repository'), new url( + '/repository/manage_instances.php', + ['contextid' => $usercontext->id] + )); } // Portfolio. @@ -1176,10 +1399,10 @@ class settings_navigation extends navigation_node { if (portfolio_has_visible_instances()) { $portfolio = $usersetting->add(get_string('portfolios', 'portfolio'), null, self::TYPE_SETTING); - $url = new url('/user/portfolio.php', array('courseid'=>$course->id)); + $url = new url('/user/portfolio.php', ['courseid' => $course->id]); $portfolio->add(get_string('configure', 'portfolio'), $url, self::TYPE_SETTING); - $url = new url('/user/portfoliologs.php', array('courseid'=>$course->id)); + $url = new url('/user/portfoliologs.php', ['courseid' => $course->id]); $portfolio->add(get_string('logs', 'portfolio'), $url, self::TYPE_SETTING); } } @@ -1187,9 +1410,11 @@ class settings_navigation extends navigation_node { $enablemanagetokens = false; if (!empty($CFG->enablerssfeeds)) { $enablemanagetokens = true; - } else if (!is_siteadmin($USER->id) + } else if ( + !is_siteadmin($USER->id) && !empty($CFG->enablewebservices) - && has_capability('moodle/webservice:createtoken', context_system::instance()) ) { + && has_capability('moodle/webservice:createtoken', context_system::instance()) + ) { $enablemanagetokens = true; } // Security keys. @@ -1199,10 +1424,12 @@ class settings_navigation extends navigation_node { } // Messaging. - if (($currentuser && has_capability('moodle/user:editownmessageprofile', $systemcontext)) || (!isguestuser($user) && - has_capability('moodle/user:editmessageprofile', $usercontext) && !is_primary_admin($user->id))) { - $messagingurl = new url('/message/edit.php', array('id' => $user->id)); - $notificationsurl = new url('/message/notificationpreferences.php', array('userid' => $user->id)); + if ( + ($currentuser && has_capability('moodle/user:editownmessageprofile', $systemcontext)) || (!isguestuser($user) && + has_capability('moodle/user:editmessageprofile', $usercontext) && !is_primary_admin($user->id)) + ) { + $messagingurl = new url('/message/edit.php', ['id' => $user->id]); + $notificationsurl = new url('/message/notificationpreferences.php', ['userid' => $user->id]); $useraccount->add(get_string('messagepreferences', 'message'), $messagingurl, self::TYPE_SETTING); $useraccount->add(get_string('notificationpreferences', 'message'), $notificationsurl, self::TYPE_SETTING); } @@ -1211,15 +1438,26 @@ class settings_navigation extends navigation_node { if ($currentuser && !empty($CFG->enableblogs)) { $blog = $usersetting->add(get_string('blogs', 'blog'), null, navigation_node::TYPE_CONTAINER, null, 'blogs'); if (has_capability('moodle/blog:view', $systemcontext)) { - $blog->add(get_string('preferences', 'blog'), new url('/blog/preferences.php'), - navigation_node::TYPE_SETTING); + $blog->add( + get_string('preferences', 'blog'), + new url('/blog/preferences.php'), + navigation_node::TYPE_SETTING + ); } - if (!empty($CFG->useexternalblogs) && $CFG->maxexternalblogsperuser > 0 && - has_capability('moodle/blog:manageexternal', $systemcontext)) { - $blog->add(get_string('externalblogs', 'blog'), new url('/blog/external_blogs.php'), - navigation_node::TYPE_SETTING); - $blog->add(get_string('addnewexternalblog', 'blog'), new url('/blog/external_blog_edit.php'), - navigation_node::TYPE_SETTING); + if ( + !empty($CFG->useexternalblogs) && $CFG->maxexternalblogsperuser > 0 && + has_capability('moodle/blog:manageexternal', $systemcontext) + ) { + $blog->add( + get_string('externalblogs', 'blog'), + new url('/blog/external_blogs.php'), + navigation_node::TYPE_SETTING + ); + $blog->add( + get_string('addnewexternalblog', 'blog'), + new url('/blog/external_blog_edit.php'), + navigation_node::TYPE_SETTING + ); } // Remove the blog node if empty. $blog->trim_if_empty(); @@ -1232,11 +1470,17 @@ class settings_navigation extends navigation_node { $url = new url('/badges/mybadges.php'); $badges->add(get_string('managebadges', 'badges'), $url, self::TYPE_SETTING); } - $badges->add(get_string('preferences', 'badges'), new url('/badges/preferences.php'), - navigation_node::TYPE_SETTING); + $badges->add( + get_string('preferences', 'badges'), + new url('/badges/preferences.php'), + navigation_node::TYPE_SETTING + ); if (!empty($CFG->badges_allowexternalbackpack)) { - $badges->add(get_string('backpackdetails', 'badges'), new url('/badges/mybackpack.php'), - navigation_node::TYPE_SETTING); + $badges->add( + get_string('backpackdetails', 'badges'), + new url('/badges/mybackpack.php'), + navigation_node::TYPE_SETTING + ); } } @@ -1252,7 +1496,7 @@ class settings_navigation extends navigation_node { } /** - * Loads block specific settings in the navigation + * Loads block specific settings in the navigation. * * @return navigation_node */ @@ -1262,24 +1506,47 @@ class settings_navigation extends navigation_node { $blocknode = $this->add($this->context->get_context_name(), null, self::TYPE_SETTING, null, 'blocksettings'); $blocknode->force_open(); - // Assign local roles + // Assign local roles. if (get_assignable_roles($this->context, ROLENAME_ORIGINAL)) { - $assignurl = new url('/'.$CFG->admin.'/roles/assign.php', array('contextid' => $this->context->id)); - $blocknode->add(get_string('assignroles', 'role'), $assignurl, self::TYPE_SETTING, null, - 'roles', new pix_icon('i/assignroles', '')); + $assignurl = new url('/' . $CFG->admin . '/roles/assign.php', ['contextid' => $this->context->id]); + $blocknode->add( + get_string('assignroles', 'role'), + $assignurl, + self::TYPE_SETTING, + null, + 'roles', + new pix_icon('i/assignroles', '') + ); } - // Override roles - if (has_capability('moodle/role:review', $this->context) or count(get_overridable_roles($this->context))>0) { - $url = new url('/'.$CFG->admin.'/roles/permissions.php', array('contextid'=>$this->context->id)); - $blocknode->add(get_string('permissions', 'role'), $url, self::TYPE_SETTING, null, - 'permissions', new pix_icon('i/permissions', '')); + // Override roles. + if (has_capability('moodle/role:review', $this->context) || count(get_overridable_roles($this->context)) > 0) { + $url = new url('/admin/roles/permissions.php', ['contextid' => $this->context->id]); + $blocknode->add( + get_string('permissions', 'role'), + $url, + self::TYPE_SETTING, + null, + 'permissions', + new pix_icon('i/permissions', '') + ); } - // Check role permissions - if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride','moodle/role:override', 'moodle/role:assign'), $this->context)) { - $url = new url('/'.$CFG->admin.'/roles/check.php', array('contextid'=>$this->context->id)); - $blocknode->add(get_string('checkpermissions', 'role'), $url, self::TYPE_SETTING, null, - 'checkpermissions', new pix_icon('i/checkpermissions', '')); + // Check role permissions. + if ( + has_any_capability( + ['moodle/role:assign', 'moodle/role:safeoverride', 'moodle/role:override', 'moodle/role:assign'], + $this->context, + ) + ) { + $url = new url('/' . $CFG->admin . '/roles/check.php', ['contextid' => $this->context->id]); + $blocknode->add( + get_string('checkpermissions', 'role'), + $url, + self::TYPE_SETTING, + null, + 'checkpermissions', + new pix_icon('i/checkpermissions', '') + ); } // Add the context locking node. @@ -1315,59 +1582,104 @@ class settings_navigation extends navigation_node { $categorynode->force_open(); if (can_edit_in_category($catcontext->instanceid)) { - $url = new url('/course/management.php', array('categoryid' => $catcontext->instanceid)); + $url = new url('/course/management.php', ['categoryid' => $catcontext->instanceid]); $editstring = get_string('managecategorythis'); $node = $categorynode->add($editstring, $url, self::TYPE_SETTING, null, 'managecategory', new pix_icon('i/edit', '')); $node->set_show_in_secondary_navigation(false); } if (has_capability('moodle/category:manage', $catcontext)) { - $editurl = new url('/course/editcategory.php', array('id' => $catcontext->instanceid)); + $editurl = new url('/course/editcategory.php', ['id' => $catcontext->instanceid]); $categorynode->add(get_string('settings'), $editurl, self::TYPE_SETTING, null, 'edit', new pix_icon('i/edit', '')); - $addsubcaturl = new url('/course/editcategory.php', array('parent' => $catcontext->instanceid)); - $categorynode->add(get_string('addsubcategory'), $addsubcaturl, self::TYPE_SETTING, null, - 'addsubcat', new pix_icon('i/withsubcat', ''))->set_show_in_secondary_navigation(false); + $addsubcaturl = new url('/course/editcategory.php', ['parent' => $catcontext->instanceid]); + $categorynode->add( + get_string('addsubcategory'), + $addsubcaturl, + self::TYPE_SETTING, + null, + 'addsubcat', + new pix_icon('i/withsubcat', '') + )->set_show_in_secondary_navigation(false); } - // Assign local roles + // Assign local roles. $assignableroles = get_assignable_roles($catcontext); if (!empty($assignableroles)) { - $assignurl = new url('/'.$CFG->admin.'/roles/assign.php', array('contextid' => $catcontext->id)); - $categorynode->add(get_string('assignroles', 'role'), $assignurl, self::TYPE_SETTING, null, 'roles', new pix_icon('i/assignroles', '')); + $assignurl = new url('/' . $CFG->admin . '/roles/assign.php', ['contextid' => $catcontext->id]); + $categorynode->add( + get_string('assignroles', 'role'), + $assignurl, + self::TYPE_SETTING, + null, + 'roles', + new pix_icon('i/assignroles', ''), + ); } - // Override roles - if (has_capability('moodle/role:review', $catcontext) or count(get_overridable_roles($catcontext)) > 0) { - $url = new url('/'.$CFG->admin.'/roles/permissions.php', array('contextid' => $catcontext->id)); - $categorynode->add(get_string('permissions', 'role'), $url, self::TYPE_SETTING, null, 'permissions', new pix_icon('i/permissions', '')); + // Override roles. + if (has_capability('moodle/role:review', $catcontext) || count(get_overridable_roles($catcontext)) > 0) { + $url = new url('/' . $CFG->admin . '/roles/permissions.php', ['contextid' => $catcontext->id]); + $categorynode->add( + get_string('permissions', 'role'), + $url, + self::TYPE_SETTING, + null, + 'permissions', + new pix_icon('i/permissions', ''), + ); } - // Check role permissions - if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride', - 'moodle/role:override', 'moodle/role:assign'), $catcontext)) { - $url = new url('/'.$CFG->admin.'/roles/check.php', array('contextid' => $catcontext->id)); - $categorynode->add(get_string('checkpermissions', 'role'), $url, self::TYPE_SETTING, null, 'rolecheck', new pix_icon('i/checkpermissions', '')); + // Check role permissions. + if ( + has_any_capability(['moodle/role:assign', 'moodle/role:safeoverride', + 'moodle/role:override', 'moodle/role:assign'], $catcontext) + ) { + $url = new url('/' . $CFG->admin . '/roles/check.php', ['contextid' => $catcontext->id]); + $categorynode->add( + get_string('checkpermissions', 'role'), + $url, + self::TYPE_SETTING, + null, + 'rolecheck', + new pix_icon('i/checkpermissions', ''), + ); } // Add the context locking node. $this->add_context_locking_node($categorynode, $catcontext); - // Cohorts - if (has_any_capability(array('moodle/cohort:view', 'moodle/cohort:manage'), $catcontext)) { - $categorynode->add(get_string('cohorts', 'cohort'), new url('/cohort/index.php', - array('contextid' => $catcontext->id)), self::TYPE_SETTING, null, 'cohort', new pix_icon('i/cohort', '')); + // Cohorts. + if (has_any_capability(['moodle/cohort:view', 'moodle/cohort:manage'], $catcontext)) { + $categorynode->add(get_string('cohorts', 'cohort'), new url( + '/cohort/index.php', + ['contextid' => $catcontext->id] + ), self::TYPE_SETTING, null, 'cohort', new pix_icon('i/cohort', '')); } - // Manage filters + // Manage filters. if (has_capability('moodle/filter:manage', $catcontext) && count(filter_get_available_in_context($catcontext)) > 0) { - $url = new url('/filter/manage.php', array('contextid' => $catcontext->id)); - $categorynode->add(get_string('filters', 'admin'), $url, self::TYPE_SETTING, null, 'filters', new pix_icon('i/filter', '')); + $url = new url('/filter/manage.php', ['contextid' => $catcontext->id]); + $categorynode->add( + get_string('filters', 'admin'), + $url, + self::TYPE_SETTING, + null, + 'filters', + new pix_icon('i/filter', ''), + ); } // Restore. if (has_capability('moodle/restore:restorecourse', $catcontext)) { - $url = new url('/backup/restorefile.php', array('contextid' => $catcontext->id)); - $categorynode->add(get_string('restorecourse', 'admin'), $url, self::TYPE_SETTING, null, 'restorecourse', new pix_icon('i/restore', '')); + $url = new url('/backup/restorefile.php', ['contextid' => $catcontext->id]); + $categorynode->add( + get_string('restorecourse', 'admin'), + $url, + self::TYPE_SETTING, + null, + 'restorecourse', + new pix_icon('i/restore', ''), + ); } // Let plugins hook into category settings navigation. @@ -1379,11 +1691,19 @@ class settings_navigation extends navigation_node { } $cb = new contentbank(); - if ($cb->is_context_allowed($catcontext) - && has_capability('moodle/contentbank:access', $catcontext)) { + if ( + $cb->is_context_allowed($catcontext) + && has_capability('moodle/contentbank:access', $catcontext) + ) { $url = new url('/contentbank/index.php', ['contextid' => $catcontext->id]); - $categorynode->add(get_string('contentbank'), $url, self::TYPE_CUSTOM, null, - 'contentbank', new pix_icon('i/contentbank', '')); + $categorynode->add( + get_string('contentbank'), + $url, + self::TYPE_CUSTOM, + null, + 'contentbank', + new pix_icon('i/contentbank', '') + ); } return $categorynode; @@ -1405,8 +1725,8 @@ class settings_navigation extends navigation_node { if (!empty($this->page->context) && !empty($USER->access['rsw'][$this->page->context->path])) { return $USER->access['rsw'][$this->page->context->path]; } - foreach ($USER->access['rsw'] as $key=>$role) { - if (strpos($this->context->path,$key)===0) { + foreach ($USER->access['rsw'] as $key => $role) { + if (strpos($this->context->path, $key) === 0) { return $role; } } @@ -1425,7 +1745,7 @@ class settings_navigation extends navigation_node { require_once($CFG->dirroot . '/course/lib.php'); $course = clone($SITE); - $coursecontext = context_course::instance($course->id); // Course context + $coursecontext = context_course::instance($course->id); // Course context. $adminoptions = course_get_user_administration_options($course, $coursecontext); $frontpage = $this->add(get_string('frontpagesettings'), null, self::TYPE_SETTING, null, 'frontpage'); @@ -1435,9 +1755,8 @@ class settings_navigation extends navigation_node { $frontpage->id = 'frontpagesettings'; if ($this->page->user_allowed_editing() && !$this->page->theme->haseditswitch) { - - // Add the turn on/off settings - $url = new url('/course/view.php', array('id'=>$course->id, 'sesskey'=>sesskey())); + // Add the turn on/off settings. + $url = new url('/course/view.php', ['id' => $course->id, 'sesskey' => sesskey()]); if ($this->page->user_is_editing()) { $url->param('edit', 'off'); $editstring = get_string('turneditingoff'); @@ -1449,35 +1768,54 @@ class settings_navigation extends navigation_node { } if ($adminoptions->update) { - // Add the course settings link - $url = new url('/admin/settings.php', array('section'=>'frontpagesettings')); - $frontpage->add(get_string('settings'), $url, self::TYPE_SETTING, null, - 'editsettings', new pix_icon('i/settings', '')); + // Add the course settings link. + $url = new url('/admin/settings.php', ['section' => 'frontpagesettings']); + $frontpage->add( + get_string('settings'), + $url, + self::TYPE_SETTING, + null, + 'editsettings', + new pix_icon('i/settings', '') + ); } - // add enrol nodes + // Add enrol nodes. enrol_add_course_navigation($frontpage, $course); - // Manage filters + // Manage filters. if ($adminoptions->filters) { - $url = new url('/filter/manage.php', array('contextid'=>$coursecontext->id)); - $frontpage->add(get_string('filters', 'admin'), $url, self::TYPE_SETTING, - null, 'filtermanagement', new pix_icon('i/filter', '')); + $url = new url('/filter/manage.php', ['contextid' => $coursecontext->id]); + $frontpage->add( + get_string('filters', 'admin'), + $url, + self::TYPE_SETTING, + null, + 'filtermanagement', + new pix_icon('i/filter', '') + ); } // View course reports. if ($adminoptions->reports) { - $frontpagenav = $frontpage->add(get_string('reports'), new url('/report/view.php', - ['courseid' => $coursecontext->instanceid]), - self::TYPE_CONTAINER, null, 'coursereports', - new pix_icon('i/stats', '')); + $frontpagenav = $frontpage->add( + get_string('reports'), + new url( + '/report/view.php', + ['courseid' => $coursecontext->instanceid] + ), + self::TYPE_CONTAINER, + null, + 'coursereports', + new pix_icon('i/stats', '') + ); $coursereports = component::get_plugin_list('coursereport'); - foreach ($coursereports as $report=>$dir) { - $libfile = $CFG->dirroot.'/course/report/'.$report.'/lib.php'; + foreach ($coursereports as $report => $dir) { + $libfile = $CFG->dirroot . '/course/report/' . $report . '/lib.php'; if (file_exists($libfile)) { require_once($libfile); - $reportfunction = $report.'_report_extend_navigation'; - if (function_exists($report.'_report_extend_navigation')) { + $reportfunction = $report . '_report_extend_navigation'; + if (function_exists($report . '_report_extend_navigation')) { $reportfunction($frontpagenav, $course, $coursecontext); } } @@ -1493,15 +1831,15 @@ class settings_navigation extends navigation_node { } } - // Questions + // Questions. require_once($CFG->libdir . '/questionlib.php'); $baseurl = \core_question\local\bank\question_bank_helper::get_url_for_qbank_list($course->id); question_extend_settings_navigation($frontpage, $coursecontext, $baseurl)->trim_if_empty(); - // Manage files + // Manage files. if ($adminoptions->files) { - //hiden in new installs - $url = new url('/files/index.php', array('contextid'=>$coursecontext->id)); + // Hide in new installs. + $url = new url('/files/index.php', ['contextid' => $coursecontext->id]); $frontpage->add(get_string('sitelegacyfiles'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/folder', '')); } @@ -1518,7 +1856,10 @@ class settings_navigation extends navigation_node { $coursereusenav = $frontpage->add( get_string('coursereuse'), new url('/backup/view.php', ['id' => $course->id]), - self::TYPE_CONTAINER, null, 'coursereuse', new pix_icon('t/edit', ''), + self::TYPE_CONTAINER, + null, + 'coursereuse', + new pix_icon('t/edit', ''), ); // Backup this course. diff --git a/public/lib/tests/classes/navigation/exposed_global_navigation.php b/public/lib/tests/classes/navigation/exposed_global_navigation.php index b1152efe29b..f6b3a8b03bf 100644 --- a/public/lib/tests/classes/navigation/exposed_global_navigation.php +++ b/public/lib/tests/classes/navigation/exposed_global_navigation.php @@ -19,13 +19,14 @@ namespace core\tests\navigation; use core\exception\coding_exception; use core\navigation\global_navigation; +// phpcs:disable /** * This is a dummy object that allows us to call protected methods within the * global navigation class by prefixing the methods with `exposed_` */ class exposed_global_navigation extends global_navigation { protected $exposedkey = 'exposed_'; - public function __construct(?\moodle_page $page=null) { + public function __construct(?\moodle_page $page = null) { global $PAGE; if ($page === null) { $page = $PAGE; @@ -37,9 +38,12 @@ class exposed_global_navigation extends global_navigation { $method = substr($method, strlen($this->exposedkey)); } if (method_exists($this, $method)) { - return call_user_func_array(array($this, $method), $arguments); + return call_user_func_array([$this, $method], $arguments); } - throw new coding_exception('You have attempted to access a method that does not exist for the given object '.$method, DEBUG_DEVELOPER); + throw new coding_exception( + 'You have attempted to access a method that does not exist for the given object ' . $method, + DEBUG_DEVELOPER, + ); } public function set_initialised() { $this->initialised = true; diff --git a/public/lib/tests/classes/navigation/exposed_settings_navigation.php b/public/lib/tests/classes/navigation/exposed_settings_navigation.php index 93d02738393..3bbe45ba2f4 100644 --- a/public/lib/tests/classes/navigation/exposed_settings_navigation.php +++ b/public/lib/tests/classes/navigation/exposed_settings_navigation.php @@ -19,6 +19,8 @@ namespace core\tests\navigation; use core\exception\coding_exception; use core\navigation\settings_navigation; +// phpcs:disable + /** * This is a dummy object that allows us to call protected methods within the * global navigation class by prefixing the methods with `exposed_`. @@ -27,7 +29,6 @@ use core\navigation\settings_navigation; * @copyright Andrew Lyons * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ - class exposed_settings_navigation extends settings_navigation { protected string $exposedkey = 'exposed_'; @@ -41,8 +42,11 @@ class exposed_settings_navigation extends settings_navigation { $method = substr($method, strlen($this->exposedkey)); } if (method_exists($this, $method)) { - return call_user_func_array(array($this, $method), $arguments); + return call_user_func_array([$this, $method], $arguments); } - throw new coding_exception('You have attempted to access a method that does not exist for the given object '.$method, DEBUG_DEVELOPER); + throw new coding_exception( + 'You have attempted to access a method that does not exist for the given object ' . $method, + DEBUG_DEVELOPER, + ); } } diff --git a/public/lib/tests/classes/navigation/navigation_testcase.php b/public/lib/tests/classes/navigation/navigation_testcase.php index 080519eaa2b..9f023100da5 100644 --- a/public/lib/tests/classes/navigation/navigation_testcase.php +++ b/public/lib/tests/classes/navigation/navigation_testcase.php @@ -16,9 +16,9 @@ namespace core\tests\navigation; +use core\navigation\navigation_node; use core\output\pix_icon; use core\url; -use navigation_node; /** * TODO describe file navigation_testcase @@ -28,7 +28,7 @@ use navigation_node; * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ abstract class navigation_testcase extends \advanced_testcase { - protected function setup_node(): navigation_node { + protected function setup_node(): navigation_node { // phpcs:ignore global $PAGE, $SITE; // Perform a reset between tests to reset the PAGE. @@ -49,16 +49,36 @@ abstract class navigation_testcase extends \advanced_testcase { $demo1 = $node->add('demo1', $inactiveurl, navigation_node::TYPE_COURSE, null, 'demo1', new pix_icon('i/course', '')); $demo2 = $node->add('demo2', $inactiveurl, navigation_node::TYPE_COURSE, null, 'demo2', new pix_icon('i/course', '')); $demo3 = $node->add('demo3', $inactiveurl, navigation_node::TYPE_CATEGORY, null, 'demo3', new pix_icon('i/course', '')); - $demo4 = $demo3->add('demo4', $inactiveurl, navigation_node::TYPE_COURSE, null, 'demo4', new pix_icon('i/course', '')); + $demo4 = $demo3->add('demo4', $inactiveurl, navigation_node::TYPE_COURSE, null, 'demo4', new pix_icon('i/course', '')); $demo5 = $demo3->add('demo5', $activeurl, navigation_node::TYPE_COURSE, null, 'demo5', new pix_icon('i/course', '')); $demo5->add('activity1', null, navigation_node::TYPE_ACTIVITY, null, 'activity1')->make_active(); $demo6 = $demo3->add('demo6', null, navigation_node::TYPE_CONTAINER, 'container node test', 'demo6'); - $hiddendemo1 = $node->add('hiddendemo1', $inactiveurl, navigation_node::TYPE_CATEGORY, null, 'hiddendemo1', new pix_icon('i/course', '')); + $hiddendemo1 = $node->add( + 'hiddendemo1', + $inactiveurl, + navigation_node::TYPE_CATEGORY, + null, + 'hiddendemo1', + new pix_icon('i/course', '') + ); $hiddendemo1->hidden = true; - $hiddendemo1->add('hiddendemo2', $inactiveurl, navigation_node::TYPE_COURSE, null, 'hiddendemo2', new pix_icon('i/course', ''))->helpbutton = 'Here is a help button'; - $hiddendemo1->add('hiddendemo3', $inactiveurl, navigation_node::TYPE_COURSE, null, 'hiddendemo3', new pix_icon('i/course', ''))->display = false; + $hiddendemo1->add( + 'hiddendemo2', + $inactiveurl, + navigation_node::TYPE_COURSE, + null, + 'hiddendemo2', + new pix_icon('i/course', '') + )->helpbutton = 'Here is a help button'; + $hiddendemo1->add( + 'hiddendemo3', + $inactiveurl, + navigation_node::TYPE_COURSE, + null, + 'hiddendemo3', + new pix_icon('i/course', '') + )->display = false; return $node; } - } diff --git a/public/lib/tests/navigation/navbar_test.php b/public/lib/tests/navigation/navbar_test.php index d0e20536df6..6385d4a90ca 100644 --- a/public/lib/tests/navigation/navbar_test.php +++ b/public/lib/tests/navigation/navbar_test.php @@ -26,7 +26,6 @@ namespace core\navigation; */ #[\PHPUnit\Framework\Attributes\CoversClass(navbar::class)] final class navbar_test extends \advanced_testcase { - public function test_navbar_prepend_and_add(): \moodle_page { global $PAGE; // Unfortunate hack needed because people use global $PAGE around the place. @@ -37,12 +36,12 @@ final class navbar_test extends \advanced_testcase { $generator = self::getDataGenerator(); $cat1 = $generator->create_category(); - $cat2 = $generator->create_category(array('parent' => $cat1->id)); - $course = $generator->create_course(array('category' => $cat2->id)); + $cat2 = $generator->create_category(['parent' => $cat1->id]); + $course = $generator->create_course(['category' => $cat2->id]); $page = new \moodle_page(); $page->set_course($course); - $page->set_url(new \moodle_url('/course/view.php', array('id' => $course->id))); + $page->set_url(new \moodle_url('/course/view.php', ['id' => $course->id])); $page->navbar->prepend('test 1'); $page->navbar->prepend('test 2'); $page->navbar->add('test 3'); @@ -67,10 +66,7 @@ final class navbar_test extends \advanced_testcase { return $page; } - /** - * @depends test_navbar_prepend_and_add - * @param $node - */ + #[\PHPUnit\Framework\Attributes\Depends('test_navbar_prepend_and_add')] public function test_navbar_has_items(\moodle_page $page): void { $this->resetAfterTest(); diff --git a/public/lib/tests/navigation/navigation_cache_test.php b/public/lib/tests/navigation/navigation_cache_test.php index 884b28aaeae..4644284de77 100644 --- a/public/lib/tests/navigation/navigation_cache_test.php +++ b/public/lib/tests/navigation/navigation_cache_test.php @@ -69,5 +69,4 @@ final class navigation_cache_test extends \advanced_testcase { $this->assertTrue($cache->cached('software')); $this->assertEquals($cache->software, 'Moodle'); } - } diff --git a/public/lib/tests/navigation/navigation_node_test.php b/public/lib/tests/navigation/navigation_node_test.php index 8d69a718c36..f45ccc3f1d0 100644 --- a/public/lib/tests/navigation/navigation_node_test.php +++ b/public/lib/tests/navigation/navigation_node_test.php @@ -34,12 +34,12 @@ final class navigation_node_test extends navigation_testcase { public function test_node__construct(): void { $node = $this->setup_node(); - $fakeproperties = array( + $fakeproperties = [ 'text' => 'text', 'shorttext' => 'A very silly extra long short text string, more than 25 characters', 'key' => 'key', 'type' => 'navigation_node::TYPE_COURSE', - 'action' => new \moodle_url('http://www.moodle.org/')); + 'action' => new \moodle_url('http://www.moodle.org/')]; $node = new navigation_node($fakeproperties); $this->assertSame($fakeproperties['text'], $node->text); @@ -53,7 +53,14 @@ final class navigation_node_test extends navigation_testcase { $node = $this->setup_node(); // Add a node with all args set. - $node1 = $node->add('test_add_1', 'http://www.moodle.org/', navigation_node::TYPE_COURSE, 'testadd1', 'key', new pix_icon('i/course', '')); + $node1 = $node->add( + 'test_add_1', + 'http://www.moodle.org/', + navigation_node::TYPE_COURSE, + 'testadd1', + 'key', + new pix_icon('i/course', ''), + ); // Add a node with the minimum args required. $node2 = $node->add('test_add_2', null, navigation_node::TYPE_CUSTOM, 'testadd2'); $node3 = $node->add(str_repeat('moodle ', 15), str_repeat('moodle', 15)); @@ -79,12 +86,27 @@ final class navigation_node_test extends navigation_testcase { $node = $this->setup_node(); // Create 3 nodes. - $node1 = navigation_node::create('test_add_1', null, navigation_node::TYPE_CUSTOM, - 'test 1', 'testadd1'); - $node2 = navigation_node::create('test_add_2', null, navigation_node::TYPE_CUSTOM, - 'test 2', 'testadd2'); - $node3 = navigation_node::create('test_add_3', null, navigation_node::TYPE_CUSTOM, - 'test 3', 'testadd3'); + $node1 = navigation_node::create( + 'test_add_1', + null, + navigation_node::TYPE_CUSTOM, + 'test 1', + 'testadd1' + ); + $node2 = navigation_node::create( + 'test_add_2', + null, + navigation_node::TYPE_CUSTOM, + 'test 2', + 'testadd2' + ); + $node3 = navigation_node::create( + 'test_add_3', + null, + navigation_node::TYPE_CUSTOM, + 'test 3', + 'testadd3' + ); // Add node 2, then node 1 before 2, then node 3 at end. $node->add_node($node2); $node->add_node($node1, 'testadd2'); @@ -93,9 +115,9 @@ final class navigation_node_test extends navigation_testcase { foreach ($node->children as $child) { $keys[] = $child->key; } - $this->assertSame('testadd1', $keys[count($keys)-3]); - $this->assertSame('testadd2', $keys[count($keys)-2]); - $this->assertSame('testadd3', $keys[count($keys)-1]); + $this->assertSame('testadd1', $keys[count($keys) - 3]); + $this->assertSame('testadd2', $keys[count($keys) - 2]); + $this->assertSame('testadd3', $keys[count($keys) - 1]); } public function test_node_add_class(): void { @@ -191,7 +213,7 @@ final class navigation_node_test extends navigation_testcase { public function test_node_find_expandable(): void { $node = $this->setup_node(); - $expandable = array(); + $expandable = []; $node->find_expandable($expandable); $this->assertCount(0, $expandable); @@ -361,15 +383,18 @@ final class navigation_node_test extends navigation_testcase { return [ 'The navigation node has an action link.' => [ - navigation_node::create('Node', new action_link(new \moodle_url('/'), '', - new popup_action('click', new \moodle_url('/'))), navigation_node::TYPE_SETTING), - true + navigation_node::create('Node', new action_link( + new \moodle_url('/'), + '', + new popup_action('click', new \moodle_url('/')) + ), navigation_node::TYPE_SETTING), + true, ], 'The navigation node does not have an action link.' => [ navigation_node::create('Node', new \moodle_url('/'), navigation_node::TYPE_SETTING), - false + false, ], ]; } @@ -393,7 +418,7 @@ final class navigation_node_test extends navigation_testcase { 'id' => $node->action->attributes['id'], 'event' => $node->action->actions[0]->event, 'jsfunction' => $node->action->actions[0]->jsfunction, - 'jsfunctionargs' => json_encode($node->action->actions[0]->jsfunctionargs) + 'jsfunctionargs' => json_encode($node->action->actions[0]->jsfunctionargs), ]; $this->assertEquals($expected, $data['actions'][0]); } else { // There are no actions added to the action link. @@ -414,13 +439,19 @@ final class navigation_node_test extends navigation_testcase { return [ 'The navigation node has an action link with an action attached.' => [ - navigation_node::create('Node', new action_link(new \moodle_url('/'), '', - new popup_action('click', new \moodle_url('/'))), navigation_node::TYPE_SETTING), + navigation_node::create('Node', new action_link( + new \moodle_url('/'), + '', + new popup_action('click', new \moodle_url('/')) + ), navigation_node::TYPE_SETTING), ], 'The navigation node has an action link without an action.' => [ - navigation_node::create('Node', new action_link(new \moodle_url('/'), '', null), - navigation_node::TYPE_SETTING), + navigation_node::create( + 'Node', + new action_link(new \moodle_url('/'), '', null), + navigation_node::TYPE_SETTING + ), ], 'The navigation node does not have an action link.' => [ diff --git a/public/lib/tests/navigation/settings_navigation_test.php b/public/lib/tests/navigation/settings_navigation_test.php index bd087870cc3..125ae19ae84 100644 --- a/public/lib/tests/navigation/settings_navigation_test.php +++ b/public/lib/tests/navigation/settings_navigation_test.php @@ -19,13 +19,14 @@ namespace core\navigation; use core\tests\navigation\exposed_settings_navigation; /** - * Tests for + * Tests for * * @package core * @category test * @copyright 2025 Andrew Lyons * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ +#[\PHPUnit\Framework\Attributes\CoversClass(settings_navigation::class)] final class settings_navigation_test extends \advanced_testcase { public function test_setting___construct(): settings_navigation { global $PAGE, $SITE; @@ -80,7 +81,7 @@ final class settings_navigation_test extends \advanced_testcase { $PAGE->set_course($SITE); // Check that a standard user can not view the preferences page. - $studentrole = $DB->get_record('role', array('shortname' => 'student')); + $studentrole = $DB->get_record('role', ['shortname' => 'student']); $this->getDataGenerator()->role_assign($studentrole->id, $persondoingtheviewing->id); $this->setUser($persondoingtheviewing); $settingsnav = new exposed_settings_navigation(); @@ -89,7 +90,7 @@ final class settings_navigation_test extends \advanced_testcase { $this->assertFalse($settingsnav->can_view_user_preferences($persontoview->id)); // Set persondoingtheviewing as a manager. - $managerrole = $DB->get_record('role', array('shortname' => 'manager')); + $managerrole = $DB->get_record('role', ['shortname' => 'manager']); $this->getDataGenerator()->role_assign($managerrole->id, $persondoingtheviewing->id); $settingsnav = new exposed_settings_navigation(); $settingsnav->initialise(); @@ -104,5 +105,4 @@ final class settings_navigation_test extends \advanced_testcase { $preferencenode = $settingsnav->find('userviewingsettings' . $persontoview->id, null); $this->assertTrue($settingsnav->can_view_user_preferences($persontoview->id)); } - } From 3fe065bdf49c5cdba07eeaff2133045af21e93e8 Mon Sep 17 00:00:00 2001 From: Andrew Nicols Date: Thu, 31 Jul 2025 16:18:12 +0800 Subject: [PATCH 4/4] MDL-82159 core: Deprecate lib/navigationlib.php --- .upgradenotes/MDL-82159-2025080707392534.yml | 12 ++++++++++++ .../classes/navigation/global_navigation.php | 2 +- .../navigation/global_navigation_for_ajax.php | 2 +- .../lib/classes/navigation/navigation_node.php | 6 ++++++ .../classes/navigation/settings_navigation.php | 2 +- .../navigation/settings_navigation_ajax.php | 2 +- public/lib/navigationlib.php | 17 ++++++++++++++++- public/lib/setup.php | 1 - public/lib/tests/coverage.php | 1 - public/r.php | 1 - public/user/preferences.php | 1 - 11 files changed, 38 insertions(+), 9 deletions(-) create mode 100644 .upgradenotes/MDL-82159-2025080707392534.yml diff --git a/.upgradenotes/MDL-82159-2025080707392534.yml b/.upgradenotes/MDL-82159-2025080707392534.yml new file mode 100644 index 00000000000..b03423cc3d2 --- /dev/null +++ b/.upgradenotes/MDL-82159-2025080707392534.yml @@ -0,0 +1,12 @@ +issueNumber: MDL-82159 +notes: + core: + - message: | + The following global constants have been deprecated in favour of class + constants: + + | Old constant | New constant | + | --- | --- | + | `NAVIGATION_CACHE_NAME` | `\core\navigation\navigation_node::CACHE_NAME` | + | `NAVIGATION_SITE_ADMIN_CACHE_NAME` | `\core\navigation\navigation_node::SITE_ADMIN_CACHE_NAME` | + type: deprecated diff --git a/public/lib/classes/navigation/global_navigation.php b/public/lib/classes/navigation/global_navigation.php index d111355b46d..909affaa5d6 100644 --- a/public/lib/classes/navigation/global_navigation.php +++ b/public/lib/classes/navigation/global_navigation.php @@ -138,7 +138,7 @@ class global_navigation extends navigation_node { // Initalise and set defaults. $this->page = $page; $this->forceopen = true; - $this->cache = new navigation_cache(NAVIGATION_CACHE_NAME); + $this->cache = new navigation_cache(self::CACHE_NAME); } /** diff --git a/public/lib/classes/navigation/global_navigation_for_ajax.php b/public/lib/classes/navigation/global_navigation_for_ajax.php index 2e4b9430eae..1e551b8a186 100644 --- a/public/lib/classes/navigation/global_navigation_for_ajax.php +++ b/public/lib/classes/navigation/global_navigation_for_ajax.php @@ -56,7 +56,7 @@ class global_navigation_for_ajax extends global_navigation { */ public function __construct($page, $branchtype, $id) { $this->page = $page; - $this->cache = new navigation_cache(NAVIGATION_CACHE_NAME); + $this->cache = new navigation_cache(self::CACHE_NAME); $this->children = new navigation_node_collection(); $this->branchtype = $branchtype; $this->instanceid = $id; diff --git a/public/lib/classes/navigation/navigation_node.php b/public/lib/classes/navigation/navigation_node.php index f72b3319c86..890b7d25df5 100644 --- a/public/lib/classes/navigation/navigation_node.php +++ b/public/lib/classes/navigation/navigation_node.php @@ -80,6 +80,12 @@ class navigation_node implements renderable { /** var string The course index page navigation node */ public const COURSE_INDEX_PAGE = 'courseindexpage'; + /** @var string The name that will be used for the navigation cache */ + protected const CACHE_NAME = 'navigation'; + + /** @var string The name that will be used for the site admin navigation cache */ + protected const SITE_ADMIN_CACHE_NAME = 'navigationsiteadmin'; + /** @var int Parameter to aid the coder in tracking [optional] */ public $id = null; /** @var string|int The identifier for the node, used to retrieve the node */ diff --git a/public/lib/classes/navigation/settings_navigation.php b/public/lib/classes/navigation/settings_navigation.php index 45b9df4b2b3..a943b34d120 100644 --- a/public/lib/classes/navigation/settings_navigation.php +++ b/public/lib/classes/navigation/settings_navigation.php @@ -76,7 +76,7 @@ class settings_navigation extends navigation_node { $this->page->navigation->initialise(); // Initialise the navigation cache. - $this->cache = new navigation_cache(NAVIGATION_CACHE_NAME); + $this->cache = new navigation_cache(self::CACHE_NAME); $this->children = new navigation_node_collection(); } diff --git a/public/lib/classes/navigation/settings_navigation_ajax.php b/public/lib/classes/navigation/settings_navigation_ajax.php index 4ec4881f423..d49d6aa49af 100644 --- a/public/lib/classes/navigation/settings_navigation_ajax.php +++ b/public/lib/classes/navigation/settings_navigation_ajax.php @@ -34,7 +34,7 @@ class settings_navigation_ajax extends settings_navigation { */ public function __construct(moodle_page &$page) { $this->page = $page; - $this->cache = new navigation_cache(NAVIGATION_CACHE_NAME); + $this->cache = new navigation_cache(self::CACHE_NAME); $this->children = new navigation_node_collection(); $this->initialise(); } diff --git a/public/lib/navigationlib.php b/public/lib/navigationlib.php index 88ff1a1a24e..844d7c3b1dd 100644 --- a/public/lib/navigationlib.php +++ b/public/lib/navigationlib.php @@ -23,8 +23,23 @@ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ +defined('MOODLE_INTERNAL') || die(); + +// This file is deprecated, but it should never have been manually included by anything outside of a few select core libraries. +// Throwing an exception here should be fine because removing the manual inclusion should have no impact. +// @deprecated Since Moodle 5.1 MDL-82159. +// The constants NAVIGATION_CACHE_NAME and NAVIGATION_SITE_ADMIN_CACHE_NAME are deprecated and should not be used anymore. +// They are defined here for autocompletion within IDEs but should not be used outside of \core\navigation anyway. +throw new \core\exception\coding_exception( + 'This file should not be manually included by any component.', +); + /** - * The name that will be used to separate the navigation cache within SESSION + * @deprecated Since Moodle 5.1 MDL-82159. */ define('NAVIGATION_CACHE_NAME', 'navigation'); + +/** + * @deprecated Since Moodle 5.1 MDL-82159. + */ define('NAVIGATION_SITE_ADMIN_CACHE_NAME', 'navigationsiteadmin'); diff --git a/public/lib/setup.php b/public/lib/setup.php index cc38062035d..b79c7782a0e 100644 --- a/public/lib/setup.php +++ b/public/lib/setup.php @@ -624,7 +624,6 @@ require_once($CFG->libdir .'/setuplib.php'); // Functions that MUST be lo require_once($CFG->libdir .'/filterlib.php'); // Functions for filtering test as it is output. require_once($CFG->libdir .'/weblib.php'); // Functions relating to HTTP and content. require_once($CFG->libdir .'/outputlib.php'); // Functions for generating output. -require_once($CFG->libdir .'/navigationlib.php'); // Class for generating Navigation structure. require_once($CFG->libdir .'/dmllib.php'); // Database access. require_once($CFG->libdir .'/datalib.php'); // Legacy lib with a big-mix of functions.. require_once($CFG->libdir .'/accesslib.php'); // Access control functions. diff --git a/public/lib/tests/coverage.php b/public/lib/tests/coverage.php index 97695585140..fb9176cc6d0 100644 --- a/public/lib/tests/coverage.php +++ b/public/lib/tests/coverage.php @@ -80,7 +80,6 @@ return new class extends phpunit_coverage_info { 'modinfolib.php', 'moodlelib.php', 'myprofilelib.php', - 'navigationlib.php', 'oauthlib.php', 'outputlib.php', 'pagelib.php', diff --git a/public/r.php b/public/r.php index 55ba9b5020e..b593901c19d 100644 --- a/public/r.php +++ b/public/r.php @@ -35,7 +35,6 @@ require_once("{$CFG->libdir}/setuplib.php"); // Functions that MUST be lo require_once("{$CFG->libdir}/filterlib.php"); // Functions for filtering test as it is output. require_once("{$CFG->libdir}/weblib.php"); // Functions relating to HTTP and content. require_once("{$CFG->libdir}/outputlib.php"); // Functions for generating output. -require_once("{$CFG->libdir}/navigationlib.php"); // Class for generating Navigation structure. require_once("{$CFG->libdir}/dmllib.php"); // Database access. require_once("{$CFG->libdir}/datalib.php"); // Legacy lib with a big-mix of functions. require_once("{$CFG->libdir}/accesslib.php"); // Access control functions. diff --git a/public/user/preferences.php b/public/user/preferences.php index aecd67dad39..9abd5706b36 100644 --- a/public/user/preferences.php +++ b/public/user/preferences.php @@ -23,7 +23,6 @@ */ require_once(__DIR__ . '/../config.php'); -require_once($CFG->libdir . '/navigationlib.php'); require_login(null, false); if (isguestuser()) {