See Release Notes
Long Term Support Release
Differences Between: [Versions 310 and 401] [Versions 311 and 401] [Versions 39 and 401] [Versions 400 and 401] [Versions 401 and 402] [Versions 401 and 403]
1 <?php 2 // This file is part of Moodle - http://moodle.org/ 3 // 4 // Moodle is free software: you can redistribute it and/or modify 5 // it under the terms of the GNU General Public License as published by 6 // the Free Software Foundation, either version 3 of the License, or 7 // (at your option) any later version. 8 // 9 // Moodle is distributed in the hope that it will be useful, 10 // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 // GNU General Public License for more details. 13 // 14 // You should have received a copy of the GNU General Public License 15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>. 16 17 /** 18 * This file contains classes used to manage the navigation structures within Moodle. 19 * 20 * @since Moodle 2.0 21 * @package core 22 * @copyright 2009 Sam Hemelryk 23 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later 24 */ 25 26 use core_contentbank\contentbank; 27 28 defined('MOODLE_INTERNAL') || die(); 29 30 /** 31 * The name that will be used to separate the navigation cache within SESSION 32 */ 33 define('NAVIGATION_CACHE_NAME', 'navigation'); 34 define('NAVIGATION_SITE_ADMIN_CACHE_NAME', 'navigationsiteadmin'); 35 36 /** 37 * This class is used to represent a node in a navigation tree 38 * 39 * This class is used to represent a node in a navigation tree within Moodle, 40 * the tree could be one of global navigation, settings navigation, or the navbar. 41 * Each node can be one of two types either a Leaf (default) or a branch. 42 * When a node is first created it is created as a leaf, when/if children are added 43 * the node then becomes a branch. 44 * 45 * @package core 46 * @category navigation 47 * @copyright 2009 Sam Hemelryk 48 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later 49 */ 50 class navigation_node implements renderable { 51 /** @var int Used to identify this node a leaf (default) 0 */ 52 const NODETYPE_LEAF = 0; 53 /** @var int Used to identify this node a branch, happens with children 1 */ 54 const NODETYPE_BRANCH = 1; 55 /** @var null Unknown node type null */ 56 const TYPE_UNKNOWN = null; 57 /** @var int System node type 0 */ 58 const TYPE_ROOTNODE = 0; 59 /** @var int System node type 1 */ 60 const TYPE_SYSTEM = 1; 61 /** @var int Category node type 10 */ 62 const TYPE_CATEGORY = 10; 63 /** var int Category displayed in MyHome navigation node */ 64 const TYPE_MY_CATEGORY = 11; 65 /** @var int Course node type 20 */ 66 const TYPE_COURSE = 20; 67 /** @var int Course Structure node type 30 */ 68 const TYPE_SECTION = 30; 69 /** @var int Activity node type, e.g. Forum, Quiz 40 */ 70 const TYPE_ACTIVITY = 40; 71 /** @var int Resource node type, e.g. Link to a file, or label 50 */ 72 const TYPE_RESOURCE = 50; 73 /** @var int A custom node type, default when adding without specifing type 60 */ 74 const TYPE_CUSTOM = 60; 75 /** @var int Setting node type, used only within settings nav 70 */ 76 const TYPE_SETTING = 70; 77 /** @var int site admin branch node type, used only within settings nav 71 */ 78 const TYPE_SITE_ADMIN = 71; 79 /** @var int Setting node type, used only within settings nav 80 */ 80 const TYPE_USER = 80; 81 /** @var int Setting node type, used for containers of no importance 90 */ 82 const TYPE_CONTAINER = 90; 83 /** var int Course the current user is not enrolled in */ 84 const COURSE_OTHER = 0; 85 /** var int Course the current user is enrolled in but not viewing */ 86 const COURSE_MY = 1; 87 /** var int Course the current user is currently viewing */ 88 const COURSE_CURRENT = 2; 89 /** var string The course index page navigation node */ 90 const COURSE_INDEX_PAGE = 'courseindexpage'; 91 92 /** @var int Parameter to aid the coder in tracking [optional] */ 93 public $id = null; 94 /** @var string|int The identifier for the node, used to retrieve the node */ 95 public $key = null; 96 /** @var string The text to use for the node */ 97 public $text = null; 98 /** @var string Short text to use if requested [optional] */ 99 public $shorttext = null; 100 /** @var string The title attribute for an action if one is defined */ 101 public $title = null; 102 /** @var string A string that can be used to build a help button */ 103 public $helpbutton = null; 104 /** @var moodle_url|action_link|null An action for the node (link) */ 105 public $action = null; 106 /** @var pix_icon The path to an icon to use for this node */ 107 public $icon = null; 108 /** @var int See TYPE_* constants defined for this class */ 109 public $type = self::TYPE_UNKNOWN; 110 /** @var int See NODETYPE_* constants defined for this class */ 111 public $nodetype = self::NODETYPE_LEAF; 112 /** @var bool If set to true the node will be collapsed by default */ 113 public $collapse = false; 114 /** @var bool If set to true the node will be expanded by default */ 115 public $forceopen = false; 116 /** @var array An array of CSS classes for the node */ 117 public $classes = array(); 118 /** @var navigation_node_collection An array of child nodes */ 119 public $children = array(); 120 /** @var bool If set to true the node will be recognised as active */ 121 public $isactive = false; 122 /** @var bool If set to true the node will be dimmed */ 123 public $hidden = false; 124 /** @var bool If set to false the node will not be displayed */ 125 public $display = true; 126 /** @var bool If set to true then an HR will be printed before the node */ 127 public $preceedwithhr = false; 128 /** @var bool If set to true the the navigation bar should ignore this node */ 129 public $mainnavonly = false; 130 /** @var bool If set to true a title will be added to the action no matter what */ 131 public $forcetitle = false; 132 /** @var navigation_node A reference to the node parent, you should never set this directly you should always call set_parent */ 133 public $parent = null; 134 /** @var bool Override to not display the icon even if one is provided **/ 135 public $hideicon = false; 136 /** @var bool Set to true if we KNOW that this node can be expanded. */ 137 public $isexpandable = false; 138 /** @var array */ 139 protected $namedtypes = array(0 => 'system', 10 => 'category', 20 => 'course', 30 => 'structure', 40 => 'activity', 140 50 => 'resource', 60 => 'custom', 70 => 'setting', 71 => 'siteadmin', 80 => 'user', 141 90 => 'container'); 142 /** @var moodle_url */ 143 protected static $fullmeurl = null; 144 /** @var bool toogles auto matching of active node */ 145 public static $autofindactive = true; 146 /** @var bool should we load full admin tree or rely on AJAX for performance reasons */ 147 protected static $loadadmintree = false; 148 /** @var mixed If set to an int, that section will be included even if it has no activities */ 149 public $includesectionnum = false; 150 /** @var bool does the node need to be loaded via ajax */ 151 public $requiresajaxloading = false; 152 /** @var bool If set to true this node will be added to the "flat" navigation */ 153 public $showinflatnavigation = false; 154 /** @var bool If set to true this node will be forced into a "more" menu whenever possible */ 155 public $forceintomoremenu = false; 156 /** @var bool If set to true this node will be displayed in the "secondary" navigation when applicable */ 157 public $showinsecondarynavigation = true; 158 /** @var bool If set to true the children of this node will be displayed within a submenu when applicable */ 159 public $showchildreninsubmenu = false; 160 161 /** 162 * Constructs a new navigation_node 163 * 164 * @param array|string $properties Either an array of properties or a string to use 165 * as the text for the node 166 */ 167 public function __construct($properties) { 168 if (is_array($properties)) { 169 // Check the array for each property that we allow to set at construction. 170 // text - The main content for the node 171 // shorttext - A short text if required for the node 172 // icon - The icon to display for the node 173 // type - The type of the node 174 // key - The key to use to identify the node 175 // parent - A reference to the nodes parent 176 // action - The action to attribute to this node, usually a URL to link to 177 if (array_key_exists('text', $properties)) { 178 $this->text = $properties['text']; 179 } 180 if (array_key_exists('shorttext', $properties)) { 181 $this->shorttext = $properties['shorttext']; 182 } 183 if (!array_key_exists('icon', $properties)) { 184 $properties['icon'] = new pix_icon('i/navigationitem', ''); 185 } 186 $this->icon = $properties['icon']; 187 if ($this->icon instanceof pix_icon) { 188 if (empty($this->icon->attributes['class'])) { 189 $this->icon->attributes['class'] = 'navicon'; 190 } else { 191 $this->icon->attributes['class'] .= ' navicon'; 192 } 193 } 194 if (array_key_exists('type', $properties)) { 195 $this->type = $properties['type']; 196 } else { 197 $this->type = self::TYPE_CUSTOM; 198 } 199 if (array_key_exists('key', $properties)) { 200 $this->key = $properties['key']; 201 } 202 // This needs to happen last because of the check_if_active call that occurs 203 if (array_key_exists('action', $properties)) { 204 $this->action = $properties['action']; 205 if (is_string($this->action)) { 206 $this->action = new moodle_url($this->action); 207 } 208 if (self::$autofindactive) { 209 $this->check_if_active(); 210 } 211 } 212 if (array_key_exists('parent', $properties)) { 213 $this->set_parent($properties['parent']); 214 } 215 } else if (is_string($properties)) { 216 $this->text = $properties; 217 } 218 if ($this->text === null) { 219 throw new coding_exception('You must set the text for the node when you create it.'); 220 } 221 // Instantiate a new navigation node collection for this nodes children 222 $this->children = new navigation_node_collection(); 223 } 224 225 /** 226 * Checks if this node is the active node. 227 * 228 * This is determined by comparing the action for the node against the 229 * defined URL for the page. A match will see this node marked as active. 230 * 231 * @param int $strength One of URL_MATCH_EXACT, URL_MATCH_PARAMS, or URL_MATCH_BASE 232 * @return bool 233 */ 234 public function check_if_active($strength=URL_MATCH_EXACT) { 235 global $FULLME, $PAGE; 236 // Set fullmeurl if it hasn't already been set 237 if (self::$fullmeurl == null) { 238 if ($PAGE->has_set_url()) { 239 self::override_active_url(new moodle_url($PAGE->url)); 240 } else { 241 self::override_active_url(new moodle_url($FULLME)); 242 } 243 } 244 245 // Compare the action of this node against the fullmeurl 246 if ($this->action instanceof moodle_url && $this->action->compare(self::$fullmeurl, $strength)) { 247 $this->make_active(); 248 return true; 249 } 250 return false; 251 } 252 253 /** 254 * True if this nav node has siblings in the tree. 255 * 256 * @return bool 257 */ 258 public function has_siblings() { 259 if (empty($this->parent) || empty($this->parent->children)) { 260 return false; 261 } 262 if ($this->parent->children instanceof navigation_node_collection) { 263 $count = $this->parent->children->count(); 264 } else { 265 $count = count($this->parent->children); 266 } 267 return ($count > 1); 268 } 269 270 /** 271 * Get a list of sibling navigation nodes at the same level as this one. 272 * 273 * @return bool|array of navigation_node 274 */ 275 public function get_siblings() { 276 // Returns a list of the siblings of the current node for display in a flat navigation element. Either 277 // the in-page links or the breadcrumb links. 278 $siblings = false; 279 280 if ($this->has_siblings()) { 281 $siblings = []; 282 foreach ($this->parent->children as $child) { 283 if ($child->display) { 284 $siblings[] = $child; 285 } 286 } 287 } 288 return $siblings; 289 } 290 291 /** 292 * This sets the URL that the URL of new nodes get compared to when locating 293 * the active node. 294 * 295 * The active node is the node that matches the URL set here. By default this 296 * is either $PAGE->url or if that hasn't been set $FULLME. 297 * 298 * @param moodle_url $url The url to use for the fullmeurl. 299 * @param bool $loadadmintree use true if the URL point to administration tree 300 */ 301 public static function override_active_url(moodle_url $url, $loadadmintree = false) { 302 // Clone the URL, in case the calling script changes their URL later. 303 self::$fullmeurl = new moodle_url($url); 304 // True means we do not want AJAX loaded admin tree, required for all admin pages. 305 if ($loadadmintree) { 306 // Do not change back to false if already set. 307 self::$loadadmintree = true; 308 } 309 } 310 311 /** 312 * Use when page is linked from the admin tree, 313 * if not used navigation could not find the page using current URL 314 * because the tree is not fully loaded. 315 */ 316 public static function require_admin_tree() { 317 self::$loadadmintree = true; 318 } 319 320 /** 321 * Creates a navigation node, ready to add it as a child using add_node 322 * function. (The created node needs to be added before you can use it.) 323 * @param string $text 324 * @param moodle_url|action_link $action 325 * @param int $type 326 * @param string $shorttext 327 * @param string|int $key 328 * @param pix_icon $icon 329 * @return navigation_node 330 */ 331 public static function create($text, $action=null, $type=self::TYPE_CUSTOM, 332 $shorttext=null, $key=null, pix_icon $icon=null) { 333 if ($action && !($action instanceof moodle_url || $action instanceof action_link)) { 334 debugging( 335 "It is required that the action provided be either an action_url|moodle_url." . 336 " Please update your definition.", E_NOTICE); 337 } 338 // Properties array used when creating the new navigation node 339 $itemarray = array( 340 'text' => $text, 341 'type' => $type 342 ); 343 // Set the action if one was provided 344 if ($action!==null) { 345 $itemarray['action'] = $action; 346 } 347 // Set the shorttext if one was provided 348 if ($shorttext!==null) { 349 $itemarray['shorttext'] = $shorttext; 350 } 351 // Set the icon if one was provided 352 if ($icon!==null) { 353 $itemarray['icon'] = $icon; 354 } 355 // Set the key 356 $itemarray['key'] = $key; 357 // Construct and return 358 return new navigation_node($itemarray); 359 } 360 361 /** 362 * Adds a navigation node as a child of this node. 363 * 364 * @param string $text 365 * @param moodle_url|action_link $action 366 * @param int $type 367 * @param string $shorttext 368 * @param string|int $key 369 * @param pix_icon $icon 370 * @return navigation_node 371 */ 372 public function add($text, $action=null, $type=self::TYPE_CUSTOM, $shorttext=null, $key=null, pix_icon $icon=null) { 373 if ($action && is_string($action)) { 374 $action = new moodle_url($action); 375 } 376 // Create child node 377 $childnode = self::create($text, $action, $type, $shorttext, $key, $icon); 378 379 // Add the child to end and return 380 return $this->add_node($childnode); 381 } 382 383 /** 384 * Adds a navigation node as a child of this one, given a $node object 385 * created using the create function. 386 * @param navigation_node $childnode Node to add 387 * @param string $beforekey 388 * @return navigation_node The added node 389 */ 390 public function add_node(navigation_node $childnode, $beforekey=null) { 391 // First convert the nodetype for this node to a branch as it will now have children 392 if ($this->nodetype !== self::NODETYPE_BRANCH) { 393 $this->nodetype = self::NODETYPE_BRANCH; 394 } 395 // Set the parent to this node 396 $childnode->set_parent($this); 397 398 // Default the key to the number of children if not provided 399 if ($childnode->key === null) { 400 $childnode->key = $this->children->count(); 401 } 402 403 // Add the child using the navigation_node_collections add method 404 $node = $this->children->add($childnode, $beforekey); 405 406 // If added node is a category node or the user is logged in and it's a course 407 // then mark added node as a branch (makes it expandable by AJAX) 408 $type = $childnode->type; 409 if (($type == self::TYPE_CATEGORY) || (isloggedin() && ($type == self::TYPE_COURSE)) || ($type == self::TYPE_MY_CATEGORY) || 410 ($type === self::TYPE_SITE_ADMIN)) { 411 $node->nodetype = self::NODETYPE_BRANCH; 412 } 413 // If this node is hidden mark it's children as hidden also 414 if ($this->hidden) { 415 $node->hidden = true; 416 } 417 // Return added node (reference returned by $this->children->add() 418 return $node; 419 } 420 421 /** 422 * Return a list of all the keys of all the child nodes. 423 * @return array the keys. 424 */ 425 public function get_children_key_list() { 426 return $this->children->get_key_list(); 427 } 428 429 /** 430 * Searches for a node of the given type with the given key. 431 * 432 * This searches this node plus all of its children, and their children.... 433 * If you know the node you are looking for is a child of this node then please 434 * use the get method instead. 435 * 436 * @param int|string $key The key of the node we are looking for 437 * @param int $type One of navigation_node::TYPE_* 438 * @return navigation_node|false 439 */ 440 public function find($key, $type) { 441 return $this->children->find($key, $type); 442 } 443 444 /** 445 * Walk the tree building up a list of all the flat navigation nodes. 446 * 447 * @deprecated since Moodle 4.0 448 * @param flat_navigation $nodes List of the found flat navigation nodes. 449 * @param boolean $showdivider Show a divider before the first node. 450 * @param string $label A label for the collection of navigation links. 451 */ 452 public function build_flat_navigation_list(flat_navigation $nodes, $showdivider = false, $label = '') { 453 debugging("Function has been deprecated with the deprecation of the flat_navigation class."); 454 if ($this->showinflatnavigation) { 455 $indent = 0; 456 if ($this->type == self::TYPE_COURSE || $this->key === self::COURSE_INDEX_PAGE) { 457 $indent = 1; 458 } 459 $flat = new flat_navigation_node($this, $indent); 460 $flat->set_showdivider($showdivider, $label); 461 $nodes->add($flat); 462 } 463 foreach ($this->children as $child) { 464 $child->build_flat_navigation_list($nodes, false); 465 } 466 } 467 468 /** 469 * Get the child of this node that has the given key + (optional) type. 470 * 471 * If you are looking for a node and want to search all children + their children 472 * then please use the find method instead. 473 * 474 * @param int|string $key The key of the node we are looking for 475 * @param int $type One of navigation_node::TYPE_* 476 * @return navigation_node|false 477 */ 478 public function get($key, $type=null) { 479 return $this->children->get($key, $type); 480 } 481 482 /** 483 * Removes this node. 484 * 485 * @return bool 486 */ 487 public function remove() { 488 return $this->parent->children->remove($this->key, $this->type); 489 } 490 491 /** 492 * Checks if this node has or could have any children 493 * 494 * @return bool Returns true if it has children or could have (by AJAX expansion) 495 */ 496 public function has_children() { 497 return ($this->nodetype === navigation_node::NODETYPE_BRANCH || $this->children->count()>0 || $this->isexpandable); 498 } 499 500 /** 501 * Marks this node as active and forces it open. 502 * 503 * Important: If you are here because you need to mark a node active to get 504 * the navigation to do what you want have you looked at {@link navigation_node::override_active_url()}? 505 * You can use it to specify a different URL to match the active navigation node on 506 * rather than having to locate and manually mark a node active. 507 */ 508 public function make_active() { 509 $this->isactive = true; 510 $this->add_class('active_tree_node'); 511 $this->force_open(); 512 if ($this->parent !== null) { 513 $this->parent->make_inactive(); 514 } 515 } 516 517 /** 518 * Marks a node as inactive and recusised back to the base of the tree 519 * doing the same to all parents. 520 */ 521 public function make_inactive() { 522 $this->isactive = false; 523 $this->remove_class('active_tree_node'); 524 if ($this->parent !== null) { 525 $this->parent->make_inactive(); 526 } 527 } 528 529 /** 530 * Forces this node to be open and at the same time forces open all 531 * parents until the root node. 532 * 533 * Recursive. 534 */ 535 public function force_open() { 536 $this->forceopen = true; 537 if ($this->parent !== null) { 538 $this->parent->force_open(); 539 } 540 } 541 542 /** 543 * Adds a CSS class to this node. 544 * 545 * @param string $class 546 * @return bool 547 */ 548 public function add_class($class) { 549 if (!in_array($class, $this->classes)) { 550 $this->classes[] = $class; 551 } 552 return true; 553 } 554 555 /** 556 * Removes a CSS class from this node. 557 * 558 * @param string $class 559 * @return bool True if the class was successfully removed. 560 */ 561 public function remove_class($class) { 562 if (in_array($class, $this->classes)) { 563 $key = array_search($class,$this->classes); 564 if ($key!==false) { 565 // Remove the class' array element. 566 unset($this->classes[$key]); 567 // Reindex the array to avoid failures when the classes array is iterated later in mustache templates. 568 $this->classes = array_values($this->classes); 569 570 return true; 571 } 572 } 573 return false; 574 } 575 576 /** 577 * Sets the title for this node and forces Moodle to utilise it. 578 * 579 * Note that this method is named identically to the public "title" property of the class, which unfortunately confuses 580 * our Mustache renderer, because it will see the method and try and call it without any arguments (hence must be nullable) 581 * before trying to access the public property 582 * 583 * @param string|null $title 584 * @return string 585 */ 586 public function title(?string $title = null): string { 587 if ($title !== null) { 588 $this->title = $title; 589 $this->forcetitle = true; 590 } 591 return (string) $this->title; 592 } 593 594 /** 595 * Resets the page specific information on this node if it is being unserialised. 596 */ 597 public function __wakeup(){ 598 $this->forceopen = false; 599 $this->isactive = false; 600 $this->remove_class('active_tree_node'); 601 } 602 603 /** 604 * Checks if this node or any of its children contain the active node. 605 * 606 * Recursive. 607 * 608 * @return bool 609 */ 610 public function contains_active_node() { 611 if ($this->isactive) { 612 return true; 613 } else { 614 foreach ($this->children as $child) { 615 if ($child->isactive || $child->contains_active_node()) { 616 return true; 617 } 618 } 619 } 620 return false; 621 } 622 623 /** 624 * To better balance the admin tree, we want to group all the short top branches together. 625 * 626 * This means < 8 nodes and no subtrees. 627 * 628 * @return bool 629 */ 630 public function is_short_branch() { 631 $limit = 8; 632 if ($this->children->count() >= $limit) { 633 return false; 634 } 635 foreach ($this->children as $child) { 636 if ($child->has_children()) { 637 return false; 638 } 639 } 640 return true; 641 } 642 643 /** 644 * Finds the active node. 645 * 646 * Searches this nodes children plus all of the children for the active node 647 * and returns it if found. 648 * 649 * Recursive. 650 * 651 * @return navigation_node|false 652 */ 653 public function find_active_node() { 654 if ($this->isactive) { 655 return $this; 656 } else { 657 foreach ($this->children as &$child) { 658 $outcome = $child->find_active_node(); 659 if ($outcome !== false) { 660 return $outcome; 661 } 662 } 663 } 664 return false; 665 } 666 667 /** 668 * Searches all children for the best matching active node 669 * @param int $strength The url match to be made. 670 * @return navigation_node|false 671 */ 672 public function search_for_active_node($strength = URL_MATCH_BASE) { 673 if ($this->check_if_active($strength)) { 674 return $this; 675 } else { 676 foreach ($this->children as &$child) { 677 $outcome = $child->search_for_active_node($strength); 678 if ($outcome !== false) { 679 return $outcome; 680 } 681 } 682 } 683 return false; 684 } 685 686 /** 687 * Gets the content for this node. 688 * 689 * @param bool $shorttext If true shorttext is used rather than the normal text 690 * @return string 691 */ 692 public function get_content($shorttext=false) { 693 $navcontext = \context_helper::get_navigation_filter_context(null); 694 $options = !empty($navcontext) ? ['context' => $navcontext] : null; 695 696 if ($shorttext && $this->shorttext!==null) { 697 return format_string($this->shorttext, null, $options); 698 } else { 699 return format_string($this->text, null, $options); 700 } 701 } 702 703 /** 704 * Gets the title to use for this node. 705 * 706 * @return string 707 */ 708 public function get_title() { 709 if ($this->forcetitle || $this->action != null){ 710 return $this->title; 711 } else { 712 return ''; 713 } 714 } 715 716 /** 717 * Used to easily determine if this link in the breadcrumbs has a valid action/url. 718 * 719 * @return boolean 720 */ 721 public function has_action() { 722 return !empty($this->action); 723 } 724 725 /** 726 * Used to easily determine if the action is an internal link. 727 * 728 * @return bool 729 */ 730 public function has_internal_action(): bool { 731 global $CFG; 732 if ($this->has_action()) { 733 $url = $this->action(); 734 if ($this->action() instanceof \action_link) { 735 $url = $this->action()->url; 736 } 737 738 if (($url->out() === $CFG->wwwroot) || (strpos($url->out(), $CFG->wwwroot.'/') === 0)) { 739 return true; 740 } 741 } 742 return false; 743 } 744 745 /** 746 * Used to easily determine if this link in the breadcrumbs is hidden. 747 * 748 * @return boolean 749 */ 750 public function is_hidden() { 751 return $this->hidden; 752 } 753 754 /** 755 * Gets the CSS class to add to this node to describe its type 756 * 757 * @return string 758 */ 759 public function get_css_type() { 760 if (array_key_exists($this->type, $this->namedtypes)) { 761 return 'type_'.$this->namedtypes[$this->type]; 762 } 763 return 'type_unknown'; 764 } 765 766 /** 767 * Finds all nodes that are expandable by AJAX 768 * 769 * @param array $expandable An array by reference to populate with expandable nodes. 770 */ 771 public function find_expandable(array &$expandable) { 772 foreach ($this->children as &$child) { 773 if ($child->display && $child->has_children() && $child->children->count() == 0) { 774 $child->id = 'expandable_branch_'.$child->type.'_'.clean_param($child->key, PARAM_ALPHANUMEXT); 775 $this->add_class('canexpand'); 776 $child->requiresajaxloading = true; 777 $expandable[] = array('id' => $child->id, 'key' => $child->key, 'type' => $child->type); 778 } 779 $child->find_expandable($expandable); 780 } 781 } 782 783 /** 784 * Finds all nodes of a given type (recursive) 785 * 786 * @param int $type One of navigation_node::TYPE_* 787 * @return array 788 */ 789 public function find_all_of_type($type) { 790 $nodes = $this->children->type($type); 791 foreach ($this->children as &$node) { 792 $childnodes = $node->find_all_of_type($type); 793 $nodes = array_merge($nodes, $childnodes); 794 } 795 return $nodes; 796 } 797 798 /** 799 * Removes this node if it is empty 800 */ 801 public function trim_if_empty() { 802 if ($this->children->count() == 0) { 803 $this->remove(); 804 } 805 } 806 807 /** 808 * Creates a tab representation of this nodes children that can be used 809 * with print_tabs to produce the tabs on a page. 810 * 811 * call_user_func_array('print_tabs', $node->get_tabs_array()); 812 * 813 * @param array $inactive 814 * @param bool $return 815 * @return array Array (tabs, selected, inactive, activated, return) 816 */ 817 public function get_tabs_array(array $inactive=array(), $return=false) { 818 $tabs = array(); 819 $rows = array(); 820 $selected = null; 821 $activated = array(); 822 foreach ($this->children as $node) { 823 $tabs[] = new tabobject($node->key, $node->action, $node->get_content(), $node->get_title()); 824 if ($node->contains_active_node()) { 825 if ($node->children->count() > 0) { 826 $activated[] = $node->key; 827 foreach ($node->children as $child) { 828 if ($child->contains_active_node()) { 829 $selected = $child->key; 830 } 831 $rows[] = new tabobject($child->key, $child->action, $child->get_content(), $child->get_title()); 832 } 833 } else { 834 $selected = $node->key; 835 } 836 } 837 } 838 return array(array($tabs, $rows), $selected, $inactive, $activated, $return); 839 } 840 841 /** 842 * Sets the parent for this node and if this node is active ensures that the tree is properly 843 * adjusted as well. 844 * 845 * @param navigation_node $parent 846 */ 847 public function set_parent(navigation_node $parent) { 848 // Set the parent (thats the easy part) 849 $this->parent = $parent; 850 // Check if this node is active (this is checked during construction) 851 if ($this->isactive) { 852 // Force all of the parent nodes open so you can see this node 853 $this->parent->force_open(); 854 // Make all parents inactive so that its clear where we are. 855 $this->parent->make_inactive(); 856 } 857 } 858 859 /** 860 * Hides the node and any children it has. 861 * 862 * @since Moodle 2.5 863 * @param array $typestohide Optional. An array of node types that should be hidden. 864 * If null all nodes will be hidden. 865 * If an array is given then nodes will only be hidden if their type mtatches an element in the array. 866 * e.g. array(navigation_node::TYPE_COURSE) would hide only course nodes. 867 */ 868 public function hide(array $typestohide = null) { 869 if ($typestohide === null || in_array($this->type, $typestohide)) { 870 $this->display = false; 871 if ($this->has_children()) { 872 foreach ($this->children as $child) { 873 $child->hide($typestohide); 874 } 875 } 876 } 877 } 878 879 /** 880 * Get the action url for this navigation node. 881 * Called from templates. 882 * 883 * @since Moodle 3.2 884 */ 885 public function action() { 886 if ($this->action instanceof moodle_url) { 887 return $this->action; 888 } else if ($this->action instanceof action_link) { 889 return $this->action->url; 890 } 891 return $this->action; 892 } 893 894 /** 895 * Return an array consisting of the additional attributes for the action url. 896 * 897 * @return array Formatted array to parse in a template 898 */ 899 public function actionattributes() { 900 if ($this->action instanceof action_link) { 901 return array_map(function($key, $value) { 902 return [ 903 'name' => $key, 904 'value' => $value 905 ]; 906 }, array_keys($this->action->attributes), $this->action->attributes); 907 } 908 909 return []; 910 } 911 912 /** 913 * Check whether the node's action is of type action_link. 914 * 915 * @return bool 916 */ 917 public function is_action_link() { 918 return $this->action instanceof action_link; 919 } 920 921 /** 922 * Return an array consisting of the actions for the action link. 923 * 924 * @return array Formatted array to parse in a template 925 */ 926 public function action_link_actions() { 927 global $PAGE; 928 929 if (!$this->is_action_link()) { 930 return []; 931 } 932 933 $actionid = $this->action->attributes['id']; 934 $actionsdata = array_map(function($action) use ($PAGE, $actionid) { 935 $data = $action->export_for_template($PAGE->get_renderer('core')); 936 $data->id = $actionid; 937 return $data; 938 }, !empty($this->action->actions) ? $this->action->actions : []); 939 940 return ['actions' => $actionsdata]; 941 } 942 943 /** 944 * Sets whether the node and its children should be added into a "more" menu whenever possible. 945 * 946 * @param bool $forceintomoremenu 947 */ 948 public function set_force_into_more_menu(bool $forceintomoremenu = false) { 949 $this->forceintomoremenu = $forceintomoremenu; 950 foreach ($this->children as $child) { 951 $child->set_force_into_more_menu($forceintomoremenu); 952 } 953 } 954 955 /** 956 * Sets whether the node and its children should be displayed in the "secondary" navigation when applicable. 957 * 958 * @param bool $show 959 */ 960 public function set_show_in_secondary_navigation(bool $show = true) { 961 $this->showinsecondarynavigation = $show; 962 foreach ($this->children as $child) { 963 $child->set_show_in_secondary_navigation($show); 964 } 965 } 966 967 /** 968 * Add the menu item to handle locking and unlocking of a conext. 969 * 970 * @param \navigation_node $node Node to add 971 * @param \context $context The context to be locked 972 */ 973 protected function add_context_locking_node(\navigation_node $node, \context $context) { 974 global $CFG; 975 // Manage context locking. 976 if (!empty($CFG->contextlocking) && has_capability('moodle/site:managecontextlocks', $context)) { 977 $parentcontext = $context->get_parent_context(); 978 if (empty($parentcontext) || !$parentcontext->locked) { 979 if ($context->locked) { 980 $lockicon = 'i/unlock'; 981 $lockstring = get_string('managecontextunlock', 'admin'); 982 } else { 983 $lockicon = 'i/lock'; 984 $lockstring = get_string('managecontextlock', 'admin'); 985 } 986 $node->add( 987 $lockstring, 988 new moodle_url( 989 '/admin/lock.php', 990 [ 991 'id' => $context->id, 992 ] 993 ), 994 self::TYPE_SETTING, 995 null, 996 'contextlocking', 997 new pix_icon($lockicon, '') 998 ); 999 } 1000 } 1001 1002 } 1003 } 1004 1005 /** 1006 * Navigation node collection 1007 * 1008 * This class is responsible for managing a collection of navigation nodes. 1009 * It is required because a node's unique identifier is a combination of both its 1010 * key and its type. 1011 * 1012 * Originally an array was used with a string key that was a combination of the two 1013 * however it was decided that a better solution would be to use a class that 1014 * implements the standard IteratorAggregate interface. 1015 * 1016 * @package core 1017 * @category navigation 1018 * @copyright 2010 Sam Hemelryk 1019 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later 1020 */ 1021 class navigation_node_collection implements IteratorAggregate, Countable { 1022 /** 1023 * A multidimensional array to where the first key is the type and the second 1024 * key is the nodes key. 1025 * @var array 1026 */ 1027 protected $collection = array(); 1028 /** 1029 * An array that contains references to nodes in the same order they were added. 1030 * This is maintained as a progressive array. 1031 * @var array 1032 */ 1033 protected $orderedcollection = array(); 1034 /** 1035 * A reference to the last node that was added to the collection 1036 * @var navigation_node 1037 */ 1038 protected $last = null; 1039 /** 1040 * The total number of items added to this array. 1041 * @var int 1042 */ 1043 protected $count = 0; 1044 1045 /** 1046 * Label for collection of nodes. 1047 * @var string 1048 */ 1049 protected $collectionlabel = ''; 1050 1051 /** 1052 * Adds a navigation node to the collection 1053 * 1054 * @param navigation_node $node Node to add 1055 * @param string $beforekey If specified, adds before a node with this key, 1056 * otherwise adds at end 1057 * @return navigation_node Added node 1058 */ 1059 public function add(navigation_node $node, $beforekey=null) { 1060 global $CFG; 1061 $key = $node->key; 1062 $type = $node->type; 1063 1064 // First check we have a 2nd dimension for this type 1065 if (!array_key_exists($type, $this->orderedcollection)) { 1066 $this->orderedcollection[$type] = array(); 1067 } 1068 // Check for a collision and report if debugging is turned on 1069 if ($CFG->debug && array_key_exists($key, $this->orderedcollection[$type])) { 1070 debugging('Navigation node intersect: Adding a node that already exists '.$key, DEBUG_DEVELOPER); 1071 } 1072 1073 // Find the key to add before 1074 $newindex = $this->count; 1075 $last = true; 1076 if ($beforekey !== null) { 1077 foreach ($this->collection as $index => $othernode) { 1078 if ($othernode->key === $beforekey) { 1079 $newindex = $index; 1080 $last = false; 1081 break; 1082 } 1083 } 1084 if ($newindex === $this->count) { 1085 debugging('Navigation node add_before: Reference node not found ' . $beforekey . 1086 ', options: ' . implode(' ', $this->get_key_list()), DEBUG_DEVELOPER); 1087 } 1088 } 1089 1090 // Add the node to the appropriate place in the by-type structure (which 1091 // is not ordered, despite the variable name) 1092 $this->orderedcollection[$type][$key] = $node; 1093 if (!$last) { 1094 // Update existing references in the ordered collection (which is the 1095 // one that isn't called 'ordered') to shuffle them along if required 1096 for ($oldindex = $this->count; $oldindex > $newindex; $oldindex--) { 1097 $this->collection[$oldindex] = $this->collection[$oldindex - 1]; 1098 } 1099 } 1100 // Add a reference to the node to the progressive collection. 1101 $this->collection[$newindex] = $this->orderedcollection[$type][$key]; 1102 // Update the last property to a reference to this new node. 1103 $this->last = $this->orderedcollection[$type][$key]; 1104 1105 // Reorder the array by index if needed 1106 if (!$last) { 1107 ksort($this->collection); 1108 } 1109 $this->count++; 1110 // Return the reference to the now added node 1111 return $node; 1112 } 1113 1114 /** 1115 * Return a list of all the keys of all the nodes. 1116 * @return array the keys. 1117 */ 1118 public function get_key_list() { 1119 $keys = array(); 1120 foreach ($this->collection as $node) { 1121 $keys[] = $node->key; 1122 } 1123 return $keys; 1124 } 1125 1126 /** 1127 * Set a label for this collection. 1128 * 1129 * @param string $label 1130 */ 1131 public function set_collectionlabel($label) { 1132 $this->collectionlabel = $label; 1133 } 1134 1135 /** 1136 * Return a label for this collection. 1137 * 1138 * @return string 1139 */ 1140 public function get_collectionlabel() { 1141 return $this->collectionlabel; 1142 } 1143 1144 /** 1145 * Fetches a node from this collection. 1146 * 1147 * @param string|int $key The key of the node we want to find. 1148 * @param int $type One of navigation_node::TYPE_*. 1149 * @return navigation_node|null 1150 */ 1151 public function get($key, $type=null) { 1152 if ($type !== null) { 1153 // If the type is known then we can simply check and fetch 1154 if (!empty($this->orderedcollection[$type][$key])) { 1155 return $this->orderedcollection[$type][$key]; 1156 } 1157 } else { 1158 // Because we don't know the type we look in the progressive array 1159 foreach ($this->collection as $node) { 1160 if ($node->key === $key) { 1161 return $node; 1162 } 1163 } 1164 } 1165 return false; 1166 } 1167 1168 /** 1169 * Searches for a node with matching key and type. 1170 * 1171 * This function searches both the nodes in this collection and all of 1172 * the nodes in each collection belonging to the nodes in this collection. 1173 * 1174 * Recursive. 1175 * 1176 * @param string|int $key The key of the node we want to find. 1177 * @param int $type One of navigation_node::TYPE_*. 1178 * @return navigation_node|null 1179 */ 1180 public function find($key, $type=null) { 1181 if ($type !== null && array_key_exists($type, $this->orderedcollection) && array_key_exists($key, $this->orderedcollection[$type])) { 1182 return $this->orderedcollection[$type][$key]; 1183 } else { 1184 $nodes = $this->getIterator(); 1185 // Search immediate children first 1186 foreach ($nodes as &$node) { 1187 if ($node->key === $key && ($type === null || $type === $node->type)) { 1188 return $node; 1189 } 1190 } 1191 // Now search each childs children 1192 foreach ($nodes as &$node) { 1193 $result = $node->children->find($key, $type); 1194 if ($result !== false) { 1195 return $result; 1196 } 1197 } 1198 } 1199 return false; 1200 } 1201 1202 /** 1203 * Fetches the last node that was added to this collection 1204 * 1205 * @return navigation_node 1206 */ 1207 public function last() { 1208 return $this->last; 1209 } 1210 1211 /** 1212 * Fetches all nodes of a given type from this collection 1213 * 1214 * @param string|int $type node type being searched for. 1215 * @return array ordered collection 1216 */ 1217 public function type($type) { 1218 if (!array_key_exists($type, $this->orderedcollection)) { 1219 $this->orderedcollection[$type] = array(); 1220 } 1221 return $this->orderedcollection[$type]; 1222 } 1223 /** 1224 * Removes the node with the given key and type from the collection 1225 * 1226 * @param string|int $key The key of the node we want to find. 1227 * @param int $type 1228 * @return bool 1229 */ 1230 public function remove($key, $type=null) { 1231 $child = $this->get($key, $type); 1232 if ($child !== false) { 1233 foreach ($this->collection as $colkey => $node) { 1234 if ($node->key === $key && (is_null($type) || $node->type == $type)) { 1235 unset($this->collection[$colkey]); 1236 $this->collection = array_values($this->collection); 1237 break; 1238 } 1239 } 1240 unset($this->orderedcollection[$child->type][$child->key]); 1241 $this->count--; 1242 return true; 1243 } 1244 return false; 1245 } 1246 1247 /** 1248 * Gets the number of nodes in this collection 1249 * 1250 * This option uses an internal count rather than counting the actual options to avoid 1251 * a performance hit through the count function. 1252 * 1253 * @return int 1254 */ 1255 public function count(): int { 1256 return $this->count; 1257 } 1258 /** 1259 * Gets an array iterator for the collection. 1260 * 1261 * This is required by the IteratorAggregator interface and is used by routines 1262 * such as the foreach loop. 1263 * 1264 * @return ArrayIterator 1265 */ 1266 public function getIterator(): Traversable { 1267 return new ArrayIterator($this->collection); 1268 } 1269 } 1270 1271 /** 1272 * The global navigation class used for... the global navigation 1273 * 1274 * This class is used by PAGE to store the global navigation for the site 1275 * and is then used by the settings nav and navbar to save on processing and DB calls 1276 * 1277 * See 1278 * {@link lib/pagelib.php} {@link moodle_page::initialise_theme_and_output()} 1279 * {@link lib/ajax/getnavbranch.php} Called by ajax 1280 * 1281 * @package core 1282 * @category navigation 1283 * @copyright 2009 Sam Hemelryk 1284 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later 1285 */ 1286 class global_navigation extends navigation_node { 1287 /** @var moodle_page The Moodle page this navigation object belongs to. */ 1288 protected $page; 1289 /** @var bool switch to let us know if the navigation object is initialised*/ 1290 protected $initialised = false; 1291 /** @var array An array of course information */ 1292 protected $mycourses = array(); 1293 /** @var navigation_node[] An array for containing root navigation nodes */ 1294 protected $rootnodes = array(); 1295 /** @var bool A switch for whether to show empty sections in the navigation */ 1296 protected $showemptysections = true; 1297 /** @var bool A switch for whether courses should be shown within categories on the navigation. */ 1298 protected $showcategories = null; 1299 /** @var null@var bool A switch for whether or not to show categories in the my courses branch. */ 1300 protected $showmycategories = null; 1301 /** @var array An array of stdClasses for users that the navigation is extended for */ 1302 protected $extendforuser = array(); 1303 /** @var navigation_cache */ 1304 protected $cache; 1305 /** @var array An array of course ids that are present in the navigation */ 1306 protected $addedcourses = array(); 1307 /** @var bool */ 1308 protected $allcategoriesloaded = false; 1309 /** @var array An array of category ids that are included in the navigation */ 1310 protected $addedcategories = array(); 1311 /** @var int expansion limit */ 1312 protected $expansionlimit = 0; 1313 /** @var int userid to allow parent to see child's profile page navigation */ 1314 protected $useridtouseforparentchecks = 0; 1315 /** @var cache_session A cache that stores information on expanded courses */ 1316 protected $cacheexpandcourse = null; 1317 1318 /** Used when loading categories to load all top level categories [parent = 0] **/ 1319 const LOAD_ROOT_CATEGORIES = 0; 1320 /** Used when loading categories to load all categories **/ 1321 const LOAD_ALL_CATEGORIES = -1; 1322 1323 /** 1324 * Constructs a new global navigation 1325 * 1326 * @param moodle_page $page The page this navigation object belongs to 1327 */ 1328 public function __construct(moodle_page $page) { 1329 global $CFG, $SITE, $USER; 1330 1331 if (during_initial_install()) { 1332 return; 1333 } 1334 1335 $homepage = get_home_page(); 1336 if ($homepage == HOMEPAGE_SITE) { 1337 // We are using the site home for the root element. 1338 $properties = array( 1339 'key' => 'home', 1340 'type' => navigation_node::TYPE_SYSTEM, 1341 'text' => get_string('home'), 1342 'action' => new moodle_url('/'), 1343 'icon' => new pix_icon('i/home', '') 1344 ); 1345 } else if ($homepage == HOMEPAGE_MYCOURSES) { 1346 // We are using the user's course summary page for the root element. 1347 $properties = array( 1348 'key' => 'mycourses', 1349 'type' => navigation_node::TYPE_SYSTEM, 1350 'text' => get_string('mycourses'), 1351 'action' => new moodle_url('/my/courses.php'), 1352 'icon' => new pix_icon('i/course', '') 1353 ); 1354 } else { 1355 // We are using the users my moodle for the root element. 1356 $properties = array( 1357 'key' => 'myhome', 1358 'type' => navigation_node::TYPE_SYSTEM, 1359 'text' => get_string('myhome'), 1360 'action' => new moodle_url('/my/'), 1361 'icon' => new pix_icon('i/dashboard', '') 1362 ); 1363 } 1364 1365 // Use the parents constructor.... good good reuse 1366 parent::__construct($properties); 1367 $this->showinflatnavigation = true; 1368 1369 // Initalise and set defaults 1370 $this->page = $page; 1371 $this->forceopen = true; 1372 $this->cache = new navigation_cache(NAVIGATION_CACHE_NAME); 1373 } 1374 1375 /** 1376 * Mutator to set userid to allow parent to see child's profile 1377 * page navigation. See MDL-25805 for initial issue. Linked to it 1378 * is an issue explaining why this is a REALLY UGLY HACK thats not 1379 * for you to use! 1380 * 1381 * @param int $userid userid of profile page that parent wants to navigate around. 1382 */ 1383 public function set_userid_for_parent_checks($userid) { 1384 $this->useridtouseforparentchecks = $userid; 1385 } 1386 1387 1388 /** 1389 * Initialises the navigation object. 1390 * 1391 * This causes the navigation object to look at the current state of the page 1392 * that it is associated with and then load the appropriate content. 1393 * 1394 * This should only occur the first time that the navigation structure is utilised 1395 * which will normally be either when the navbar is called to be displayed or 1396 * when a block makes use of it. 1397 * 1398 * @return bool 1399 */ 1400 public function initialise() { 1401 global $CFG, $SITE, $USER; 1402 // Check if it has already been initialised 1403 if ($this->initialised || during_initial_install()) { 1404 return true; 1405 } 1406 $this->initialised = true; 1407 1408 // Set up the five base root nodes. These are nodes where we will put our 1409 // content and are as follows: 1410 // site: Navigation for the front page. 1411 // myprofile: User profile information goes here. 1412 // currentcourse: The course being currently viewed. 1413 // mycourses: The users courses get added here. 1414 // courses: Additional courses are added here. 1415 // users: Other users information loaded here. 1416 $this->rootnodes = array(); 1417 $defaulthomepage = get_home_page(); 1418 if ($defaulthomepage == HOMEPAGE_SITE) { 1419 // The home element should be my moodle because the root element is the site 1420 if (isloggedin() && !isguestuser()) { // Makes no sense if you aren't logged in 1421 if (!empty($CFG->enabledashboard)) { 1422 // Only add dashboard to home if it's enabled. 1423 $this->rootnodes['home'] = $this->add(get_string('myhome'), new moodle_url('/my/'), 1424 self::TYPE_SETTING, null, 'myhome', new pix_icon('i/dashboard', '')); 1425 $this->rootnodes['home']->showinflatnavigation = true; 1426 } 1427 } 1428 } else { 1429 // The home element should be the site because the root node is my moodle 1430 $this->rootnodes['home'] = $this->add(get_string('sitehome'), new moodle_url('/'), 1431 self::TYPE_SETTING, null, 'home', new pix_icon('i/home', '')); 1432 $this->rootnodes['home']->showinflatnavigation = true; 1433 if (!empty($CFG->defaulthomepage) && 1434 ($CFG->defaulthomepage == HOMEPAGE_MY || $CFG->defaulthomepage == HOMEPAGE_MYCOURSES)) { 1435 // We need to stop automatic redirection 1436 $this->rootnodes['home']->action->param('redirect', '0'); 1437 } 1438 } 1439 $this->rootnodes['site'] = $this->add_course($SITE); 1440 $this->rootnodes['myprofile'] = $this->add(get_string('profile'), null, self::TYPE_USER, null, 'myprofile'); 1441 $this->rootnodes['currentcourse'] = $this->add(get_string('currentcourse'), null, self::TYPE_ROOTNODE, null, 'currentcourse'); 1442 $this->rootnodes['mycourses'] = $this->add( 1443 get_string('mycourses'), 1444 new moodle_url('/my/courses.php'), 1445 self::TYPE_ROOTNODE, 1446 null, 1447 'mycourses', 1448 new pix_icon('i/course', '') 1449 ); 1450 // We do not need to show this node in the breadcrumbs if the default homepage is mycourses. 1451 // It will be automatically handled by the breadcrumb generator. 1452 if ($defaulthomepage == HOMEPAGE_MYCOURSES) { 1453 $this->rootnodes['mycourses']->mainnavonly = true; 1454 } 1455 1456 $this->rootnodes['courses'] = $this->add(get_string('courses'), new moodle_url('/course/index.php'), self::TYPE_ROOTNODE, null, 'courses'); 1457 if (!core_course_category::user_top()) { 1458 $this->rootnodes['courses']->hide(); 1459 } 1460 $this->rootnodes['users'] = $this->add(get_string('users'), null, self::TYPE_ROOTNODE, null, 'users'); 1461 1462 // We always load the frontpage course to ensure it is available without 1463 // JavaScript enabled. 1464 $this->add_front_page_course_essentials($this->rootnodes['site'], $SITE); 1465 $this->load_course_sections($SITE, $this->rootnodes['site']); 1466 1467 $course = $this->page->course; 1468 $this->load_courses_enrolled(); 1469 1470 // $issite gets set to true if the current pages course is the sites frontpage course 1471 $issite = ($this->page->course->id == $SITE->id); 1472 1473 // Determine if the user is enrolled in any course. 1474 $enrolledinanycourse = enrol_user_sees_own_courses(); 1475 1476 $this->rootnodes['currentcourse']->mainnavonly = true; 1477 if ($enrolledinanycourse) { 1478 $this->rootnodes['mycourses']->isexpandable = true; 1479 $this->rootnodes['mycourses']->showinflatnavigation = true; 1480 if ($CFG->navshowallcourses) { 1481 // When we show all courses we need to show both the my courses and the regular courses branch. 1482 $this->rootnodes['courses']->isexpandable = true; 1483 } 1484 } else { 1485 $this->rootnodes['courses']->isexpandable = true; 1486 } 1487 $this->rootnodes['mycourses']->forceopen = true; 1488 1489 $canviewcourseprofile = true; 1490 1491 // Next load context specific content into the navigation 1492 switch ($this->page->context->contextlevel) { 1493 case CONTEXT_SYSTEM : 1494 // Nothing left to do here I feel. 1495 break; 1496 case CONTEXT_COURSECAT : 1497 // This is essential, we must load categories. 1498 $this->load_all_categories($this->page->context->instanceid, true); 1499 break; 1500 case CONTEXT_BLOCK : 1501 case CONTEXT_COURSE : 1502 if ($issite) { 1503 // Nothing left to do here. 1504 break; 1505 } 1506 1507 // Load the course associated with the current page into the navigation. 1508 $coursenode = $this->add_course($course, false, self::COURSE_CURRENT); 1509 // If the course wasn't added then don't try going any further. 1510 if (!$coursenode) { 1511 $canviewcourseprofile = false; 1512 break; 1513 } 1514 1515 // If the user is not enrolled then we only want to show the 1516 // course node and not populate it. 1517 1518 // Not enrolled, can't view, and hasn't switched roles 1519 if (!can_access_course($course, null, '', true)) { 1520 if ($coursenode->isexpandable === true) { 1521 // Obviously the situation has changed, update the cache and adjust the node. 1522 // This occurs if the user access to a course has been revoked (one way or another) after 1523 // initially logging in for this session. 1524 $this->get_expand_course_cache()->set($course->id, 1); 1525 $coursenode->isexpandable = true; 1526 $coursenode->nodetype = self::NODETYPE_BRANCH; 1527 } 1528 // Very ugly hack - do not force "parents" to enrol into course their child is enrolled in, 1529 // this hack has been propagated from user/view.php to display the navigation node. (MDL-25805) 1530 if (!$this->current_user_is_parent_role()) { 1531 $coursenode->make_active(); 1532 $canviewcourseprofile = false; 1533 break; 1534 } 1535 } else if ($coursenode->isexpandable === false) { 1536 // Obviously the situation has changed, update the cache and adjust the node. 1537 // This occurs if the user has been granted access to a course (one way or another) after initially 1538 // logging in for this session. 1539 $this->get_expand_course_cache()->set($course->id, 1); 1540 $coursenode->isexpandable = true; 1541 $coursenode->nodetype = self::NODETYPE_BRANCH; 1542 } 1543 1544 // Add the essentials such as reports etc... 1545 $this->add_course_essentials($coursenode, $course); 1546 // Extend course navigation with it's sections/activities 1547 $this->load_course_sections($course, $coursenode); 1548 if (!$coursenode->contains_active_node() && !$coursenode->search_for_active_node()) { 1549 $coursenode->make_active(); 1550 } 1551 1552 break; 1553 case CONTEXT_MODULE : 1554 if ($issite) { 1555 // If this is the site course then most information will have 1556 // already been loaded. 1557 // However we need to check if there is more content that can 1558 // yet be loaded for the specific module instance. 1559 $activitynode = $this->rootnodes['site']->find($this->page->cm->id, navigation_node::TYPE_ACTIVITY); 1560 if ($activitynode) { 1561 $this->load_activity($this->page->cm, $this->page->course, $activitynode); 1562 } 1563 break; 1564 } 1565 1566 $course = $this->page->course; 1567 $cm = $this->page->cm; 1568 1569 // Load the course associated with the page into the navigation 1570 $coursenode = $this->add_course($course, false, self::COURSE_CURRENT); 1571 1572 // If the course wasn't added then don't try going any further. 1573 if (!$coursenode) { 1574 $canviewcourseprofile = false; 1575 break; 1576 } 1577 1578 // If the user is not enrolled then we only want to show the 1579 // course node and not populate it. 1580 if (!can_access_course($course, null, '', true)) { 1581 $coursenode->make_active(); 1582 $canviewcourseprofile = false; 1583 break; 1584 } 1585 1586 $this->add_course_essentials($coursenode, $course); 1587 1588 // Load the course sections into the page 1589 $this->load_course_sections($course, $coursenode, null, $cm); 1590 $activity = $coursenode->find($cm->id, navigation_node::TYPE_ACTIVITY); 1591 if (!empty($activity)) { 1592 // Finally load the cm specific navigaton information 1593 $this->load_activity($cm, $course, $activity); 1594 // Check if we have an active ndoe 1595 if (!$activity->contains_active_node() && !$activity->search_for_active_node()) { 1596 // And make the activity node active. 1597 $activity->make_active(); 1598 } 1599 } 1600 break; 1601 case CONTEXT_USER : 1602 if ($issite) { 1603 // The users profile information etc is already loaded 1604 // for the front page. 1605 break; 1606 } 1607 $course = $this->page->course; 1608 // Load the course associated with the user into the navigation 1609 $coursenode = $this->add_course($course, false, self::COURSE_CURRENT); 1610 1611 // If the course wasn't added then don't try going any further. 1612 if (!$coursenode) { 1613 $canviewcourseprofile = false; 1614 break; 1615 } 1616 1617 // If the user is not enrolled then we only want to show the 1618 // course node and not populate it. 1619 if (!can_access_course($course, null, '', true)) { 1620 $coursenode->make_active(); 1621 $canviewcourseprofile = false; 1622 break; 1623 } 1624 $this->add_course_essentials($coursenode, $course); 1625 $this->load_course_sections($course, $coursenode); 1626 break; 1627 } 1628 1629 // Load for the current user 1630 $this->load_for_user(); 1631 if ($this->page->context->contextlevel >= CONTEXT_COURSE && $this->page->context->instanceid != $SITE->id && $canviewcourseprofile) { 1632 $this->load_for_user(null, true); 1633 } 1634 // Load each extending user into the navigation. 1635 foreach ($this->extendforuser as $user) { 1636 if ($user->id != $USER->id) { 1637 $this->load_for_user($user); 1638 } 1639 } 1640 1641 // Give the local plugins a chance to include some navigation if they want. 1642 $this->load_local_plugin_navigation(); 1643 1644 // Remove any empty root nodes 1645 foreach ($this->rootnodes as $node) { 1646 // Dont remove the home node 1647 /** @var navigation_node $node */ 1648 if (!in_array($node->key, ['home', 'mycourses', 'myhome']) && !$node->has_children() && !$node->isactive) { 1649 $node->remove(); 1650 } 1651 } 1652 1653 if (!$this->contains_active_node()) { 1654 $this->search_for_active_node(); 1655 } 1656 1657 // If the user is not logged in modify the navigation structure. 1658 if (!isloggedin()) { 1659 $activities = clone($this->rootnodes['site']->children); 1660 $this->rootnodes['site']->remove(); 1661 $children = clone($this->children); 1662 $this->children = new navigation_node_collection(); 1663 foreach ($activities as $child) { 1664 $this->children->add($child); 1665 } 1666 foreach ($children as $child) { 1667 $this->children->add($child); 1668 } 1669 } 1670 return true; 1671 } 1672 1673 /** 1674 * This function gives local plugins an opportunity to modify navigation. 1675 */ 1676 protected function load_local_plugin_navigation() { 1677 foreach (get_plugin_list_with_function('local', 'extend_navigation') as $function) { 1678 $function($this); 1679 } 1680 } 1681 1682 /** 1683 * Returns true if the current user is a parent of the user being currently viewed. 1684 * 1685 * If the current user is not viewing another user, or if the current user does not hold any parent roles over the 1686 * other user being viewed this function returns false. 1687 * In order to set the user for whom we are checking against you must call {@link set_userid_for_parent_checks()} 1688 * 1689 * @since Moodle 2.4 1690 * @return bool 1691 */ 1692 protected function current_user_is_parent_role() { 1693 global $USER, $DB; 1694 if ($this->useridtouseforparentchecks && $this->useridtouseforparentchecks != $USER->id) { 1695 $usercontext = context_user::instance($this->useridtouseforparentchecks, MUST_EXIST); 1696 if (!has_capability('moodle/user:viewdetails', $usercontext)) { 1697 return false; 1698 } 1699 if ($DB->record_exists('role_assignments', array('userid' => $USER->id, 'contextid' => $usercontext->id))) { 1700 return true; 1701 } 1702 } 1703 return false; 1704 } 1705 1706 /** 1707 * Returns true if courses should be shown within categories on the navigation. 1708 * 1709 * @param bool $ismycourse Set to true if you are calculating this for a course. 1710 * @return bool 1711 */ 1712 protected function show_categories($ismycourse = false) { 1713 global $CFG, $DB; 1714 if ($ismycourse) { 1715 return $this->show_my_categories(); 1716 } 1717 if ($this->showcategories === null) { 1718 $show = false; 1719 if ($this->page->context->contextlevel == CONTEXT_COURSECAT) { 1720 $show = true; 1721 } else if (!empty($CFG->navshowcategories) && $DB->count_records('course_categories') > 1) { 1722 $show = true; 1723 } 1724 $this->showcategories = $show; 1725 } 1726 return $this->showcategories; 1727 } 1728 1729 /** 1730 * Returns true if we should show categories in the My Courses branch. 1731 * @return bool 1732 */ 1733 protected function show_my_categories() { 1734 global $CFG; 1735 if ($this->showmycategories === null) { 1736 $this->showmycategories = !empty($CFG->navshowmycoursecategories) && !core_course_category::is_simple_site(); 1737 } 1738 return $this->showmycategories; 1739 } 1740 1741 /** 1742 * Loads the courses in Moodle into the navigation. 1743 * 1744 * @global moodle_database $DB 1745 * @param string|array $categoryids An array containing categories to load courses 1746 * for, OR null to load courses for all categories. 1747 * @return array An array of navigation_nodes one for each course 1748 */ 1749 protected function load_all_courses($categoryids = null) { 1750 global $CFG, $DB, $SITE; 1751 1752 // Work out the limit of courses. 1753 $limit = 20; 1754 if (!empty($CFG->navcourselimit)) { 1755 $limit = $CFG->navcourselimit; 1756 } 1757 1758 $toload = (empty($CFG->navshowallcourses))?self::LOAD_ROOT_CATEGORIES:self::LOAD_ALL_CATEGORIES; 1759 1760 // If we are going to show all courses AND we are showing categories then 1761 // to save us repeated DB calls load all of the categories now 1762 if ($this->show_categories()) { 1763 $this->load_all_categories($toload); 1764 } 1765 1766 // Will be the return of our efforts 1767 $coursenodes = array(); 1768 1769 // Check if we need to show categories. 1770 if ($this->show_categories()) { 1771 // Hmmm we need to show categories... this is going to be painful. 1772 // We now need to fetch up to $limit courses for each category to 1773 // be displayed. 1774 if ($categoryids !== null) { 1775 if (!is_array($categoryids)) { 1776 $categoryids = array($categoryids); 1777 } 1778 list($categorywhere, $categoryparams) = $DB->get_in_or_equal($categoryids, SQL_PARAMS_NAMED, 'cc'); 1779 $categorywhere = 'WHERE cc.id '.$categorywhere; 1780 } else if ($toload == self::LOAD_ROOT_CATEGORIES) { 1781 $categorywhere = 'WHERE cc.depth = 1 OR cc.depth = 2'; 1782 $categoryparams = array(); 1783 } else { 1784 $categorywhere = ''; 1785 $categoryparams = array(); 1786 } 1787 1788 // First up we are going to get the categories that we are going to 1789 // need so that we can determine how best to load the courses from them. 1790 $sql = "SELECT cc.id, COUNT(c.id) AS coursecount 1791 FROM {course_categories} cc 1792 LEFT JOIN {course} c ON c.category = cc.id 1793 {$categorywhere} 1794 GROUP BY cc.id"; 1795 $categories = $DB->get_recordset_sql($sql, $categoryparams); 1796 $fullfetch = array(); 1797 $partfetch = array(); 1798 foreach ($categories as $category) { 1799 if (!$this->can_add_more_courses_to_category($category->id)) { 1800 continue; 1801 } 1802 if ($category->coursecount > $limit * 5) { 1803 $partfetch[] = $category->id; 1804 } else if ($category->coursecount > 0) { 1805 $fullfetch[] = $category->id; 1806 } 1807 } 1808 $categories->close(); 1809 1810 if (count($fullfetch)) { 1811 // First up fetch all of the courses in categories where we know that we are going to 1812 // need the majority of courses. 1813 list($categoryids, $categoryparams) = $DB->get_in_or_equal($fullfetch, SQL_PARAMS_NAMED, 'lcategory'); 1814 $ccselect = ', ' . context_helper::get_preload_record_columns_sql('ctx'); 1815 $ccjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)"; 1816 $categoryparams['contextlevel'] = CONTEXT_COURSE; 1817 $sql = "SELECT c.id, c.sortorder, c.visible, c.fullname, c.shortname, c.category $ccselect 1818 FROM {course} c 1819 $ccjoin 1820 WHERE c.category {$categoryids} 1821 ORDER BY c.sortorder ASC"; 1822 $coursesrs = $DB->get_recordset_sql($sql, $categoryparams); 1823 foreach ($coursesrs as $course) { 1824 if ($course->id == $SITE->id) { 1825 // This should not be necessary, frontpage is not in any category. 1826 continue; 1827 } 1828 if (array_key_exists($course->id, $this->addedcourses)) { 1829 // It is probably better to not include the already loaded courses 1830 // directly in SQL because inequalities may confuse query optimisers 1831 // and may interfere with query caching. 1832 continue; 1833 } 1834 if (!$this->can_add_more_courses_to_category($course->category)) { 1835 continue; 1836 } 1837 context_helper::preload_from_record($course); 1838 if (!$course->visible && !is_role_switched($course->id) && !has_capability('moodle/course:viewhiddencourses', context_course::instance($course->id))) { 1839 continue; 1840 } 1841 $coursenodes[$course->id] = $this->add_course($course); 1842 } 1843 $coursesrs->close(); 1844 } 1845 1846 if (count($partfetch)) { 1847 // Next we will work our way through the categories where we will likely only need a small 1848 // proportion of the courses. 1849 foreach ($partfetch as $categoryid) { 1850 $ccselect = ', ' . context_helper::get_preload_record_columns_sql('ctx'); 1851 $ccjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)"; 1852 $sql = "SELECT c.id, c.sortorder, c.visible, c.fullname, c.shortname, c.category $ccselect 1853 FROM {course} c 1854 $ccjoin 1855 WHERE c.category = :categoryid 1856 ORDER BY c.sortorder ASC"; 1857 $courseparams = array('categoryid' => $categoryid, 'contextlevel' => CONTEXT_COURSE); 1858 $coursesrs = $DB->get_recordset_sql($sql, $courseparams, 0, $limit * 5); 1859 foreach ($coursesrs as $course) { 1860 if ($course->id == $SITE->id) { 1861 // This should not be necessary, frontpage is not in any category. 1862 continue; 1863 } 1864 if (array_key_exists($course->id, $this->addedcourses)) { 1865 // It is probably better to not include the already loaded courses 1866 // directly in SQL because inequalities may confuse query optimisers 1867 // and may interfere with query caching. 1868 // This also helps to respect expected $limit on repeated executions. 1869 continue; 1870 } 1871 if (!$this->can_add_more_courses_to_category($course->category)) { 1872 break; 1873 } 1874 context_helper::preload_from_record($course); 1875 if (!$course->visible && !is_role_switched($course->id) && !has_capability('moodle/course:viewhiddencourses', context_course::instance($course->id))) { 1876 continue; 1877 } 1878 $coursenodes[$course->id] = $this->add_course($course); 1879 } 1880 $coursesrs->close(); 1881 } 1882 } 1883 } else { 1884 // Prepare the SQL to load the courses and their contexts 1885 list($courseids, $courseparams) = $DB->get_in_or_equal(array_keys($this->addedcourses), SQL_PARAMS_NAMED, 'lc', false); 1886 $ccselect = ', ' . context_helper::get_preload_record_columns_sql('ctx'); 1887 $ccjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)"; 1888 $courseparams['contextlevel'] = CONTEXT_COURSE; 1889 $sql = "SELECT c.id, c.sortorder, c.visible, c.fullname, c.shortname, c.category $ccselect 1890 FROM {course} c 1891 $ccjoin 1892 WHERE c.id {$courseids} 1893 ORDER BY c.sortorder ASC"; 1894 $coursesrs = $DB->get_recordset_sql($sql, $courseparams); 1895 foreach ($coursesrs as $course) { 1896 if ($course->id == $SITE->id) { 1897 // frotpage is not wanted here 1898 continue; 1899 } 1900 if ($this->page->course && ($this->page->course->id == $course->id)) { 1901 // Don't include the currentcourse in this nodelist - it's displayed in the Current course node 1902 continue; 1903 } 1904 context_helper::preload_from_record($course); 1905 if (!$course->visible && !is_role_switched($course->id) && !has_capability('moodle/course:viewhiddencourses', context_course::instance($course->id))) { 1906 continue; 1907 } 1908 $coursenodes[$course->id] = $this->add_course($course); 1909 if (count($coursenodes) >= $limit) { 1910 break; 1911 } 1912 } 1913 $coursesrs->close(); 1914 } 1915 1916 return $coursenodes; 1917 } 1918 1919 /** 1920 * Returns true if more courses can be added to the provided category. 1921 * 1922 * @param int|navigation_node|stdClass $category 1923 * @return bool 1924 */ 1925 protected function can_add_more_courses_to_category($category) { 1926 global $CFG; 1927 $limit = 20; 1928 if (!empty($CFG->navcourselimit)) { 1929 $limit = (int)$CFG->navcourselimit; 1930 } 1931 if (is_numeric($category)) { 1932 if (!array_key_exists($category, $this->addedcategories)) { 1933 return true; 1934 } 1935 $coursecount = count($this->addedcategories[$category]->children->type(self::TYPE_COURSE)); 1936 } else if ($category instanceof navigation_node) { 1937 if (($category->type != self::TYPE_CATEGORY) || ($category->type != self::TYPE_MY_CATEGORY)) { 1938 return false; 1939 } 1940 $coursecount = count($category->children->type(self::TYPE_COURSE)); 1941 } else if (is_object($category) && property_exists($category,'id')) { 1942 $coursecount = count($this->addedcategories[$category->id]->children->type(self::TYPE_COURSE)); 1943 } 1944 return ($coursecount <= $limit); 1945 } 1946 1947 /** 1948 * Loads all categories (top level or if an id is specified for that category) 1949 * 1950 * @param int $categoryid The category id to load or null/0 to load all base level categories 1951 * @param bool $showbasecategories If set to true all base level categories will be loaded as well 1952 * as the requested category and any parent categories. 1953 * @return navigation_node|void returns a navigation node if a category has been loaded. 1954 */ 1955 protected function load_all_categories($categoryid = self::LOAD_ROOT_CATEGORIES, $showbasecategories = false) { 1956 global $CFG, $DB; 1957 1958 // Check if this category has already been loaded 1959 if ($this->allcategoriesloaded || ($categoryid < 1 && $this->is_category_fully_loaded($categoryid))) { 1960 return true; 1961 } 1962 1963 $catcontextsql = context_helper::get_preload_record_columns_sql('ctx'); 1964 $sqlselect = "SELECT cc.*, $catcontextsql 1965 FROM {course_categories} cc 1966 JOIN {context} ctx ON cc.id = ctx.instanceid"; 1967 $sqlwhere = "WHERE ctx.contextlevel = ".CONTEXT_COURSECAT; 1968 $sqlorder = "ORDER BY cc.depth ASC, cc.sortorder ASC, cc.id ASC"; 1969 $params = array(); 1970 1971 $categoriestoload = array(); 1972 if ($categoryid == self::LOAD_ALL_CATEGORIES) { 1973 // We are going to load all categories regardless... prepare to fire 1974 // on the database server! 1975 } else if ($categoryid == self::LOAD_ROOT_CATEGORIES) { // can be 0 1976 // We are going to load all of the first level categories (categories without parents) 1977 $sqlwhere .= " AND cc.parent = 0"; 1978 } else if (array_key_exists($categoryid, $this->addedcategories)) { 1979 // The category itself has been loaded already so we just need to ensure its subcategories 1980 // have been loaded 1981 $addedcategories = $this->addedcategories; 1982 unset($addedcategories[$categoryid]); 1983 if (count($addedcategories) > 0) { 1984 list($sql, $params) = $DB->get_in_or_equal(array_keys($addedcategories), SQL_PARAMS_NAMED, 'parent', false); 1985 if ($showbasecategories) { 1986 // We need to include categories with parent = 0 as well 1987 $sqlwhere .= " AND (cc.parent = :categoryid OR cc.parent = 0) AND cc.parent {$sql}"; 1988 } else { 1989 // All we need is categories that match the parent 1990 $sqlwhere .= " AND cc.parent = :categoryid AND cc.parent {$sql}"; 1991 } 1992 } 1993 $params['categoryid'] = $categoryid; 1994 } else { 1995 // This category hasn't been loaded yet so we need to fetch it, work out its category path 1996 // and load this category plus all its parents and subcategories 1997 $category = $DB->get_record('course_categories', array('id' => $categoryid), 'path', MUST_EXIST); 1998 $categoriestoload = explode('/', trim($category->path, '/')); 1999 list($select, $params) = $DB->get_in_or_equal($categoriestoload); 2000 // We are going to use select twice so double the params 2001 $params = array_merge($params, $params); 2002 $basecategorysql = ($showbasecategories)?' OR cc.depth = 1':''; 2003 $sqlwhere .= " AND (cc.id {$select} OR cc.parent {$select}{$basecategorysql})"; 2004 } 2005 2006 $categoriesrs = $DB->get_recordset_sql("$sqlselect $sqlwhere $sqlorder", $params); 2007 $categories = array(); 2008 foreach ($categoriesrs as $category) { 2009 // Preload the context.. we'll need it when adding the category in order 2010 // to format the category name. 2011 context_helper::preload_from_record($category); 2012 if (array_key_exists($category->id, $this->addedcategories)) { 2013 // Do nothing, its already been added. 2014 } else if ($category->parent == '0') { 2015 // This is a root category lets add it immediately 2016 $this->add_category($category, $this->rootnodes['courses']); 2017 } else if (array_key_exists($category->parent, $this->addedcategories)) { 2018 // This categories parent has already been added we can add this immediately 2019 $this->add_category($category, $this->addedcategories[$category->parent]); 2020 } else { 2021 $categories[] = $category; 2022 } 2023 } 2024 $categoriesrs->close(); 2025 2026 // Now we have an array of categories we need to add them to the navigation. 2027 while (!empty($categories)) { 2028 $category = reset($categories); 2029 if (array_key_exists($category->id, $this->addedcategories)) { 2030 // Do nothing 2031 } else if ($category->parent == '0') { 2032 $this->add_category($category, $this->rootnodes['courses']); 2033 } else if (array_key_exists($category->parent, $this->addedcategories)) { 2034 $this->add_category($category, $this->addedcategories[$category->parent]); 2035 } else { 2036 // This category isn't in the navigation and niether is it's parent (yet). 2037 // We need to go through the category path and add all of its components in order. 2038 $path = explode('/', trim($category->path, '/')); 2039 foreach ($path as $catid) { 2040 if (!array_key_exists($catid, $this->addedcategories)) { 2041 // This category isn't in the navigation yet so add it. 2042 $subcategory = $categories[$catid]; 2043 if ($subcategory->parent == '0') { 2044 // Yay we have a root category - this likely means we will now be able 2045 // to add categories without problems. 2046 $this->add_category($subcategory, $this->rootnodes['courses']); 2047 } else if (array_key_exists($subcategory->parent, $this->addedcategories)) { 2048 // The parent is in the category (as we'd expect) so add it now. 2049 $this->add_category($subcategory, $this->addedcategories[$subcategory->parent]); 2050 // Remove the category from the categories array. 2051 unset($categories[$catid]); 2052 } else { 2053 // We should never ever arrive here - if we have then there is a bigger 2054 // problem at hand. 2055 throw new coding_exception('Category path order is incorrect and/or there are missing categories'); 2056 } 2057 } 2058 } 2059 } 2060 // Remove the category from the categories array now that we know it has been added. 2061 unset($categories[$category->id]); 2062 } 2063 if ($categoryid === self::LOAD_ALL_CATEGORIES) { 2064 $this->allcategoriesloaded = true; 2065 } 2066 // Check if there are any categories to load. 2067 if (count($categoriestoload) > 0) { 2068 $readytoloadcourses = array(); 2069 foreach ($categoriestoload as $category) { 2070 if ($this->can_add_more_courses_to_category($category)) { 2071 $readytoloadcourses[] = $category; 2072 } 2073 } 2074 if (count($readytoloadcourses)) { 2075 $this->load_all_courses($readytoloadcourses); 2076 } 2077 } 2078 2079 // Look for all categories which have been loaded 2080 if (!empty($this->addedcategories)) { 2081 $categoryids = array(); 2082 foreach ($this->addedcategories as $category) { 2083 if ($this->can_add_more_courses_to_category($category)) { 2084 $categoryids[] = $category->key; 2085 } 2086 } 2087 if ($categoryids) { 2088 list($categoriessql, $params) = $DB->get_in_or_equal($categoryids, SQL_PARAMS_NAMED); 2089 $params['limit'] = (!empty($CFG->navcourselimit))?$CFG->navcourselimit:20; 2090 $sql = "SELECT cc.id, COUNT(c.id) AS coursecount 2091 FROM {course_categories} cc 2092 JOIN {course} c ON c.category = cc.id 2093 WHERE cc.id {$categoriessql} 2094 GROUP BY cc.id 2095 HAVING COUNT(c.id) > :limit"; 2096 $excessivecategories = $DB->get_records_sql($sql, $params); 2097 foreach ($categories as &$category) { 2098 if (array_key_exists($category->key, $excessivecategories) && !$this->can_add_more_courses_to_category($category)) { 2099 $url = new moodle_url('/course/index.php', array('categoryid' => $category->key)); 2100 $category->add(get_string('viewallcourses'), $url, self::TYPE_SETTING); 2101 } 2102 } 2103 } 2104 } 2105 } 2106 2107 /** 2108 * Adds a structured category to the navigation in the correct order/place 2109 * 2110 * @param stdClass $category category to be added in navigation. 2111 * @param navigation_node $parent parent navigation node 2112 * @param int $nodetype type of node, if category is under MyHome then it's TYPE_MY_CATEGORY 2113 * @return void. 2114 */ 2115 protected function add_category(stdClass $category, navigation_node $parent, $nodetype = self::TYPE_CATEGORY) { 2116 global $CFG; 2117 if (array_key_exists($category->id, $this->addedcategories)) { 2118 return; 2119 } 2120 $canview = core_course_category::can_view_category($category); 2121 $url = $canview ? new moodle_url('/course/index.php', array('categoryid' => $category->id)) : null; 2122 $context = \context_helper::get_navigation_filter_context(context_coursecat::instance($category->id)); 2123 $categoryname = $canview ? format_string($category->name, true, ['context' => $context]) : 2124 get_string('categoryhidden'); 2125 $categorynode = $parent->add($categoryname, $url, $nodetype, $categoryname, $category->id); 2126 if (!$canview) { 2127 // User does not have required capabilities to view category. 2128 $categorynode->display = false; 2129 } else if (!$category->visible) { 2130 // Category is hidden but user has capability to view hidden categories. 2131 $categorynode->hidden = true; 2132 } 2133 $this->addedcategories[$category->id] = $categorynode; 2134 } 2135 2136 /** 2137 * Loads the given course into the navigation 2138 * 2139 * @param stdClass $course 2140 * @return navigation_node 2141 */ 2142 protected function load_course(stdClass $course) { 2143 global $SITE; 2144 if ($course->id == $SITE->id) { 2145 // This is always loaded during initialisation 2146 return $this->rootnodes['site']; 2147 } else if (array_key_exists($course->id, $this->addedcourses)) { 2148 // The course has already been loaded so return a reference 2149 return $this->addedcourses[$course->id]; 2150 } else { 2151 // Add the course 2152 return $this->add_course($course); 2153 } 2154 } 2155 2156 /** 2157 * Loads all of the courses section into the navigation. 2158 * 2159 * This function calls method from current course format, see 2160 * core_courseformat\base::extend_course_navigation() 2161 * If course module ($cm) is specified but course format failed to create the node, 2162 * the activity node is created anyway. 2163 * 2164 * By default course formats call the method global_navigation::load_generic_course_sections() 2165 * 2166 * @param stdClass $course Database record for the course 2167 * @param navigation_node $coursenode The course node within the navigation 2168 * @param null|int $sectionnum If specified load the contents of section with this relative number 2169 * @param null|cm_info $cm If specified make sure that activity node is created (either 2170 * in containg section or by calling load_stealth_activity() ) 2171 */ 2172 protected function load_course_sections(stdClass $course, navigation_node $coursenode, $sectionnum = null, $cm = null) { 2173 global $CFG, $SITE; 2174 require_once($CFG->dirroot.'/course/lib.php'); 2175 if (isset($cm->sectionnum)) { 2176 $sectionnum = $cm->sectionnum; 2177 } 2178 if ($sectionnum !== null) { 2179 $this->includesectionnum = $sectionnum; 2180 } 2181 course_get_format($course)->extend_course_navigation($this, $coursenode, $sectionnum, $cm); 2182 if (isset($cm->id)) { 2183 $activity = $coursenode->find($cm->id, self::TYPE_ACTIVITY); 2184 if (empty($activity)) { 2185 $activity = $this->load_stealth_activity($coursenode, get_fast_modinfo($course)); 2186 } 2187 } 2188 } 2189 2190 /** 2191 * Generates an array of sections and an array of activities for the given course. 2192 * 2193 * This method uses the cache to improve performance and avoid the get_fast_modinfo call 2194 * 2195 * @param stdClass $course 2196 * @return array Array($sections, $activities) 2197 */ 2198 protected function generate_sections_and_activities(stdClass $course) { 2199 global $CFG; 2200 require_once($CFG->dirroot.'/course/lib.php'); 2201 2202 $modinfo = get_fast_modinfo($course); 2203 $sections = $modinfo->get_section_info_all(); 2204 2205 // For course formats using 'numsections' trim the sections list 2206 $courseformatoptions = course_get_format($course)->get_format_options(); 2207 if (isset($courseformatoptions['numsections'])) { 2208 $sections = array_slice($sections, 0, $courseformatoptions['numsections']+1, true); 2209 } 2210 2211 $activities = array(); 2212 2213 foreach ($sections as $key => $section) { 2214 // Clone and unset summary to prevent $SESSION bloat (MDL-31802). 2215 $sections[$key] = clone($section); 2216 unset($sections[$key]->summary); 2217 $sections[$key]->hasactivites = false; 2218 if (!array_key_exists($section->section, $modinfo->sections)) { 2219 continue; 2220 } 2221 foreach ($modinfo->sections[$section->section] as $cmid) { 2222 $cm = $modinfo->cms[$cmid]; 2223 $activity = new stdClass; 2224 $activity->id = $cm->id; 2225 $activity->course = $course->id; 2226 $activity->section = $section->section; 2227 $activity->name = $cm->name; 2228 $activity->icon = $cm->icon; 2229 $activity->iconcomponent = $cm->iconcomponent; 2230 $activity->hidden = (!$cm->visible); 2231 $activity->modname = $cm->modname; 2232 $activity->nodetype = navigation_node::NODETYPE_LEAF; 2233 $activity->onclick = $cm->onclick; 2234 $url = $cm->url; 2235 if (!$url) { 2236 $activity->url = null; 2237 $activity->display = false; 2238 } else { 2239 $activity->url = $url->out(); 2240 $activity->display = $cm->is_visible_on_course_page() ? true : false; 2241 if (self::module_extends_navigation($cm->modname)) { 2242 $activity->nodetype = navigation_node::NODETYPE_BRANCH; 2243 } 2244 } 2245 $activities[$cmid] = $activity; 2246 if ($activity->display) { 2247 $sections[$key]->hasactivites = true; 2248 } 2249 } 2250 } 2251 2252 return array($sections, $activities); 2253 } 2254 2255 /** 2256 * Generically loads the course sections into the course's navigation. 2257 * 2258 * @param stdClass $course 2259 * @param navigation_node $coursenode 2260 * @return array An array of course section nodes 2261 */ 2262 public function load_generic_course_sections(stdClass $course, navigation_node $coursenode) { 2263 global $CFG, $DB, $USER, $SITE; 2264 require_once($CFG->dirroot.'/course/lib.php'); 2265 2266 list($sections, $activities) = $this->generate_sections_and_activities($course); 2267 2268 $navigationsections = array(); 2269 foreach ($sections as $sectionid => $section) { 2270 $section = clone($section); 2271 if ($course->id == $SITE->id) { 2272 $this->load_section_activities($coursenode, $section->section, $activities); 2273 } else { 2274 if (!$section->uservisible || (!$this->showemptysections && 2275 !$section->hasactivites && $this->includesectionnum !== $section->section)) { 2276 continue; 2277 } 2278 2279 $sectionname = get_section_name($course, $section); 2280 $url = course_get_url($course, $section->section, array('navigation' => true)); 2281 2282 $sectionnode = $coursenode->add($sectionname, $url, navigation_node::TYPE_SECTION, 2283 null, $section->id, new pix_icon('i/section', '')); 2284 $sectionnode->nodetype = navigation_node::NODETYPE_BRANCH; 2285 $sectionnode->hidden = (!$section->visible || !$section->available); 2286 if ($this->includesectionnum !== false && $this->includesectionnum == $section->section) { 2287 $this->load_section_activities($sectionnode, $section->section, $activities); 2288 } 2289 $section->sectionnode = $sectionnode; 2290 $navigationsections[$sectionid] = $section; 2291 } 2292 } 2293 return $navigationsections; 2294 } 2295 2296 /** 2297 * Loads all of the activities for a section into the navigation structure. 2298 * 2299 * @param navigation_node $sectionnode 2300 * @param int $sectionnumber 2301 * @param array $activities An array of activites as returned by {@link global_navigation::generate_sections_and_activities()} 2302 * @param stdClass $course The course object the section and activities relate to. 2303 * @return array Array of activity nodes 2304 */ 2305 protected function load_section_activities(navigation_node $sectionnode, $sectionnumber, array $activities, $course = null) { 2306 global $CFG, $SITE; 2307 // A static counter for JS function naming 2308 static $legacyonclickcounter = 0; 2309 2310 $activitynodes = array(); 2311 if (empty($activities)) { 2312 return $activitynodes; 2313 } 2314 2315 if (!is_object($course)) { 2316 $activity = reset($activities); 2317 $courseid = $activity->course; 2318 } else { 2319 $courseid = $course->id; 2320 } 2321 $showactivities = ($courseid != $SITE->id || !empty($CFG->navshowfrontpagemods)); 2322 2323 foreach ($activities as $activity) { 2324 if ($activity->section != $sectionnumber) { 2325 continue; 2326 } 2327 if ($activity->icon) { 2328 $icon = new pix_icon($activity->icon, get_string('modulename', $activity->modname), $activity->iconcomponent); 2329 } else { 2330 $icon = new pix_icon('monologo', get_string('modulename', $activity->modname), $activity->modname); 2331 } 2332 2333 // Prepare the default name and url for the node 2334 $displaycontext = \context_helper::get_navigation_filter_context(context_module::instance($activity->id)); 2335 $activityname = format_string($activity->name, true, ['context' => $displaycontext]); 2336 $action = new moodle_url($activity->url); 2337 2338 // Check if the onclick property is set (puke!) 2339 if (!empty($activity->onclick)) { 2340 // Increment the counter so that we have a unique number. 2341 $legacyonclickcounter++; 2342 // Generate the function name we will use 2343 $functionname = 'legacy_activity_onclick_handler_'.$legacyonclickcounter; 2344 $propogrationhandler = ''; 2345 // Check if we need to cancel propogation. Remember inline onclick 2346 // events would return false if they wanted to prevent propogation and the 2347 // default action. 2348 if (strpos($activity->onclick, 'return false')) { 2349 $propogrationhandler = 'e.halt();'; 2350 } 2351 // Decode the onclick - it has already been encoded for display (puke) 2352 $onclick = htmlspecialchars_decode($activity->onclick, ENT_QUOTES); 2353 // Build the JS function the click event will call 2354 $jscode = "function {$functionname}(e) { $propogrationhandler $onclick }"; 2355 $this->page->requires->js_amd_inline($jscode); 2356 // Override the default url with the new action link 2357 $action = new action_link($action, $activityname, new component_action('click', $functionname)); 2358 } 2359 2360 $activitynode = $sectionnode->add($activityname, $action, navigation_node::TYPE_ACTIVITY, null, $activity->id, $icon); 2361 $activitynode->title(get_string('modulename', $activity->modname)); 2362 $activitynode->hidden = $activity->hidden; 2363 $activitynode->display = $showactivities && $activity->display; 2364 $activitynode->nodetype = $activity->nodetype; 2365 $activitynodes[$activity->id] = $activitynode; 2366 } 2367 2368 return $activitynodes; 2369 } 2370 /** 2371 * Loads a stealth module from unavailable section 2372 * @param navigation_node $coursenode 2373 * @param stdClass $modinfo 2374 * @return navigation_node or null if not accessible 2375 */ 2376 protected function load_stealth_activity(navigation_node $coursenode, $modinfo) { 2377 if (empty($modinfo->cms[$this->page->cm->id])) { 2378 return null; 2379 } 2380 $cm = $modinfo->cms[$this->page->cm->id]; 2381 if ($cm->icon) { 2382 $icon = new pix_icon($cm->icon, get_string('modulename', $cm->modname), $cm->iconcomponent); 2383 } else { 2384 $icon = new pix_icon('monologo', get_string('modulename', $cm->modname), $cm->modname); 2385 } 2386 $url = $cm->url; 2387 $activitynode = $coursenode->add(format_string($cm->name), $url, navigation_node::TYPE_ACTIVITY, null, $cm->id, $icon); 2388 $activitynode->title(get_string('modulename', $cm->modname)); 2389 $activitynode->hidden = (!$cm->visible); 2390 if (!$cm->is_visible_on_course_page()) { 2391 // Do not show any error here, let the page handle exception that activity is not visible for the current user. 2392 // Also there may be no exception at all in case when teacher is logged in as student. 2393 $activitynode->display = false; 2394 } else if (!$url) { 2395 // Don't show activities that don't have links! 2396 $activitynode->display = false; 2397 } else if (self::module_extends_navigation($cm->modname)) { 2398 $activitynode->nodetype = navigation_node::NODETYPE_BRANCH; 2399 } 2400 return $activitynode; 2401 } 2402 /** 2403 * Loads the navigation structure for the given activity into the activities node. 2404 * 2405 * This method utilises a callback within the modules lib.php file to load the 2406 * content specific to activity given. 2407 * 2408 * The callback is a method: {modulename}_extend_navigation() 2409 * Examples: 2410 * * {@link forum_extend_navigation()} 2411 * * {@link workshop_extend_navigation()} 2412 * 2413 * @param cm_info|stdClass $cm 2414 * @param stdClass $course 2415 * @param navigation_node $activity 2416 * @return bool 2417 */ 2418 protected function load_activity($cm, stdClass $course, navigation_node $activity) { 2419 global $CFG, $DB; 2420 2421 // make sure we have a $cm from get_fast_modinfo as this contains activity access details 2422 if (!($cm instanceof cm_info)) { 2423 $modinfo = get_fast_modinfo($course); 2424 $cm = $modinfo->get_cm($cm->id); 2425 } 2426 $activity->nodetype = navigation_node::NODETYPE_LEAF; 2427 $activity->make_active(); 2428 $file = $CFG->dirroot.'/mod/'.$cm->modname.'/lib.php'; 2429 $function = $cm->modname.'_extend_navigation'; 2430 2431 if (file_exists($file)) { 2432 require_once($file); 2433 if (function_exists($function)) { 2434 $activtyrecord = $DB->get_record($cm->modname, array('id' => $cm->instance), '*', MUST_EXIST); 2435 $function($activity, $course, $activtyrecord, $cm); 2436 } 2437 } 2438 2439 // Allow the active advanced grading method plugin to append module navigation 2440 $featuresfunc = $cm->modname.'_supports'; 2441 if (function_exists($featuresfunc) && $featuresfunc(FEATURE_ADVANCED_GRADING)) { 2442 require_once($CFG->dirroot.'/grade/grading/lib.php'); 2443 $gradingman = get_grading_manager($cm->context, 'mod_'.$cm->modname); 2444 $gradingman->extend_navigation($this, $activity); 2445 } 2446 2447 return $activity->has_children(); 2448 } 2449 /** 2450 * Loads user specific information into the navigation in the appropriate place. 2451 * 2452 * If no user is provided the current user is assumed. 2453 * 2454 * @param stdClass $user 2455 * @param bool $forceforcontext probably force something to be loaded somewhere (ask SamH if not sure what this means) 2456 * @return bool 2457 */ 2458 protected function load_for_user($user=null, $forceforcontext=false) { 2459 global $DB, $CFG, $USER, $SITE; 2460 2461 require_once($CFG->dirroot . '/course/lib.php'); 2462 2463 if ($user === null) { 2464 // We can't require login here but if the user isn't logged in we don't 2465 // want to show anything 2466 if (!isloggedin() || isguestuser()) { 2467 return false; 2468 } 2469 $user = $USER; 2470 } else if (!is_object($user)) { 2471 // If the user is not an object then get them from the database 2472 $select = context_helper::get_preload_record_columns_sql('ctx'); 2473 $sql = "SELECT u.*, $select 2474 FROM {user} u 2475 JOIN {context} ctx ON u.id = ctx.instanceid 2476 WHERE u.id = :userid AND 2477 ctx.contextlevel = :contextlevel"; 2478 $user = $DB->get_record_sql($sql, array('userid' => (int)$user, 'contextlevel' => CONTEXT_USER), MUST_EXIST); 2479 context_helper::preload_from_record($user); 2480 } 2481 2482 $iscurrentuser = ($user->id == $USER->id); 2483 2484 $usercontext = context_user::instance($user->id); 2485 2486 // Get the course set against the page, by default this will be the site 2487 $course = $this->page->course; 2488 $baseargs = array('id'=>$user->id); 2489 if ($course->id != $SITE->id && (!$iscurrentuser || $forceforcontext)) { 2490 $coursenode = $this->add_course($course, false, self::COURSE_CURRENT); 2491 $baseargs['course'] = $course->id; 2492 $coursecontext = context_course::instance($course->id); 2493 $issitecourse = false; 2494 } else { 2495 // Load all categories and get the context for the system 2496 $coursecontext = context_system::instance(); 2497 $issitecourse = true; 2498 } 2499 2500 // Create a node to add user information under. 2501 $usersnode = null; 2502 if (!$issitecourse) { 2503 // Not the current user so add it to the participants node for the current course. 2504 $usersnode = $coursenode->get('participants', navigation_node::TYPE_CONTAINER); 2505 $userviewurl = new moodle_url('/user/view.php', $baseargs); 2506 } else if ($USER->id != $user->id) { 2507 // This is the site so add a users node to the root branch. 2508 $usersnode = $this->rootnodes['users']; 2509 if (course_can_view_participants($coursecontext)) { 2510 $usersnode->action = new moodle_url('/user/index.php', array('id' => $course->id)); 2511 } 2512 $userviewurl = new moodle_url('/user/profile.php', $baseargs); 2513 } 2514 if (!$usersnode) { 2515 // We should NEVER get here, if the course hasn't been populated 2516 // with a participants node then the navigaiton either wasn't generated 2517 // for it (you are missing a require_login or set_context call) or 2518 // you don't have access.... in the interests of no leaking informatin 2519 // we simply quit... 2520 return false; 2521 } 2522 // Add a branch for the current user. 2523 // Only reveal user details if $user is the current user, or a user to which the current user has access. 2524 $viewprofile = true; 2525 if (!$iscurrentuser) { 2526 require_once($CFG->dirroot . '/user/lib.php'); 2527 if ($this->page->context->contextlevel == CONTEXT_USER && !has_capability('moodle/user:viewdetails', $usercontext) ) { 2528 $viewprofile = false; 2529 } else if ($this->page->context->contextlevel != CONTEXT_USER && !user_can_view_profile($user, $course, $usercontext)) { 2530 $viewprofile = false; 2531 } 2532 if (!$viewprofile) { 2533 $viewprofile = user_can_view_profile($user, null, $usercontext); 2534 } 2535 } 2536 2537 // Now, conditionally add the user node. 2538 if ($viewprofile) { 2539 $canseefullname = has_capability('moodle/site:viewfullnames', $coursecontext); 2540 $usernode = $usersnode->add(fullname($user, $canseefullname), $userviewurl, self::TYPE_USER, null, 'user' . $user->id); 2541 } else { 2542 $usernode = $usersnode->add(get_string('user')); 2543 } 2544 2545 if ($this->page->context->contextlevel == CONTEXT_USER && $user->id == $this->page->context->instanceid) { 2546 $usernode->make_active(); 2547 } 2548 2549 // Add user information to the participants or user node. 2550 if ($issitecourse) { 2551 2552 // If the user is the current user or has permission to view the details of the requested 2553 // user than add a view profile link. 2554 if ($iscurrentuser || has_capability('moodle/user:viewdetails', $coursecontext) || 2555 has_capability('moodle/user:viewdetails', $usercontext)) { 2556 if ($issitecourse || ($iscurrentuser && !$forceforcontext)) { 2557 $usernode->add(get_string('viewprofile'), new moodle_url('/user/profile.php', $baseargs)); 2558 } else { 2559 $usernode->add(get_string('viewprofile'), new moodle_url('/user/view.php', $baseargs)); 2560 } 2561 } 2562 2563 if (!empty($CFG->navadduserpostslinks)) { 2564 // Add nodes for forum posts and discussions if the user can view either or both 2565 // There are no capability checks here as the content of the page is based 2566 // purely on the forums the current user has access too. 2567 $forumtab = $usernode->add(get_string('forumposts', 'forum')); 2568 $forumtab->add(get_string('posts', 'forum'), new moodle_url('/mod/forum/user.php', $baseargs)); 2569 $forumtab->add(get_string('discussions', 'forum'), new moodle_url('/mod/forum/user.php', 2570 array_merge($baseargs, array('mode' => 'discussions')))); 2571 } 2572 2573 // Add blog nodes. 2574 if (!empty($CFG->enableblogs)) { 2575 if (!$this->cache->cached('userblogoptions'.$user->id)) { 2576 require_once($CFG->dirroot.'/blog/lib.php'); 2577 // Get all options for the user. 2578 $options = blog_get_options_for_user($user); 2579 $this->cache->set('userblogoptions'.$user->id, $options); 2580 } else { 2581 $options = $this->cache->{'userblogoptions'.$user->id}; 2582 } 2583 2584 if (count($options) > 0) { 2585 $blogs = $usernode->add(get_string('blogs', 'blog'), null, navigation_node::TYPE_CONTAINER); 2586 foreach ($options as $type => $option) { 2587 if ($type == "rss") { 2588 $blogs->add($option['string'], $option['link'], settings_navigation::TYPE_SETTING, null, null, 2589 new pix_icon('i/rss', '')); 2590 } else { 2591 $blogs->add($option['string'], $option['link']); 2592 } 2593 } 2594 } 2595 } 2596 2597 // Add the messages link. 2598 // It is context based so can appear in the user's profile and in course participants information. 2599 if (!empty($CFG->messaging)) { 2600 $messageargs = array('user1' => $USER->id); 2601 if ($USER->id != $user->id) { 2602 $messageargs['user2'] = $user->id; 2603 } 2604 $url = new moodle_url('/message/index.php', $messageargs); 2605 $usernode->add(get_string('messages', 'message'), $url, self::TYPE_SETTING, null, 'messages'); 2606 } 2607 2608 // Add the "My private files" link. 2609 // This link doesn't have a unique display for course context so only display it under the user's profile. 2610 if ($issitecourse && $iscurrentuser && has_capability('moodle/user:manageownfiles', $usercontext)) { 2611 $url = new moodle_url('/user/files.php'); 2612 $usernode->add(get_string('privatefiles'), $url, self::TYPE_SETTING, null, 'privatefiles'); 2613 } 2614 2615 // Add a node to view the users notes if permitted. 2616 if (!empty($CFG->enablenotes) && 2617 has_any_capability(array('moodle/notes:manage', 'moodle/notes:view'), $coursecontext)) { 2618 $url = new moodle_url('/notes/index.php', array('user' => $user->id)); 2619 if ($coursecontext->instanceid != SITEID) { 2620 $url->param('course', $coursecontext->instanceid); 2621 } 2622 $usernode->add(get_string('notes', 'notes'), $url); 2623 } 2624 2625 // Show the grades node. 2626 if (($issitecourse && $iscurrentuser) || has_capability('moodle/user:viewdetails', $usercontext)) { 2627 require_once($CFG->dirroot . '/user/lib.php'); 2628 // Set the grades node to link to the "Grades" page. 2629 if ($course->id == SITEID) { 2630 $url = user_mygrades_url($user->id, $course->id); 2631 } else { // Otherwise we are in a course and should redirect to the user grade report (Activity report version). 2632 $url = new moodle_url('/course/user.php', array('mode' => 'grade', 'id' => $course->id, 'user' => $user->id)); 2633 } 2634 if ($USER->id != $user->id) { 2635 $usernode->add(get_string('grades', 'grades'), $url, self::TYPE_SETTING, null, 'usergrades'); 2636 } else { 2637 $usernode->add(get_string('grades', 'grades'), $url); 2638 } 2639 } 2640 2641 // If the user is the current user add the repositories for the current user. 2642 $hiddenfields = array_flip(explode(',', $CFG->hiddenuserfields)); 2643 if (!$iscurrentuser && 2644 $course->id == $SITE->id && 2645 has_capability('moodle/user:viewdetails', $usercontext) && 2646 (!in_array('mycourses', $hiddenfields) || has_capability('moodle/user:viewhiddendetails', $coursecontext))) { 2647 2648 // Add view grade report is permitted. 2649 $reports = core_component::get_plugin_list('gradereport'); 2650 arsort($reports); // User is last, we want to test it first. 2651 2652 $userscourses = enrol_get_users_courses($user->id, false, '*'); 2653 $userscoursesnode = $usernode->add(get_string('courses')); 2654 2655 $count = 0; 2656 foreach ($userscourses as $usercourse) { 2657 if ($count === (int)$CFG->navcourselimit) { 2658 $url = new moodle_url('/user/profile.php', array('id' => $user->id, 'showallcourses' => 1)); 2659 $userscoursesnode->add(get_string('showallcourses'), $url); 2660 break; 2661 } 2662 $count++; 2663 $usercoursecontext = context_course::instance($usercourse->id); 2664 $usercourseshortname = format_string($usercourse->shortname, true, array('context' => $usercoursecontext)); 2665 $usercoursenode = $userscoursesnode->add($usercourseshortname, new moodle_url('/user/view.php', 2666 array('id' => $user->id, 'course' => $usercourse->id)), self::TYPE_CONTAINER); 2667 2668 $gradeavailable = has_capability('moodle/grade:view', $usercoursecontext); 2669 if (!$gradeavailable && !empty($usercourse->showgrades) && is_array($reports) && !empty($reports)) { 2670 foreach ($reports as $plugin => $plugindir) { 2671 if (has_capability('gradereport/'.$plugin.':view', $usercoursecontext)) { 2672 // Stop when the first visible plugin is found. 2673 $gradeavailable = true; 2674 break; 2675 } 2676 } 2677 } 2678 2679 if ($gradeavailable) { 2680 $url = new moodle_url('/grade/report/index.php', array('id' => $usercourse->id)); 2681 $usercoursenode->add(get_string('grades'), $url, self::TYPE_SETTING, null, null, 2682 new pix_icon('i/grades', '')); 2683 } 2684 2685 // Add a node to view the users notes if permitted. 2686 if (!empty($CFG->enablenotes) && 2687 has_any_capability(array('moodle/notes:manage', 'moodle/notes:view'), $usercoursecontext)) { 2688 $url = new moodle_url('/notes/index.php', array('user' => $user->id, 'course' => $usercourse->id)); 2689 $usercoursenode->add(get_string('notes', 'notes'), $url, self::TYPE_SETTING); 2690 } 2691 2692 if (can_access_course($usercourse, $user->id, '', true)) { 2693 $usercoursenode->add(get_string('entercourse'), new moodle_url('/course/view.php', 2694 array('id' => $usercourse->id)), self::TYPE_SETTING, null, null, new pix_icon('i/course', '')); 2695 } 2696 2697 $reporttab = $usercoursenode->add(get_string('activityreports')); 2698 2699 $reportfunctions = get_plugin_list_with_function('report', 'extend_navigation_user', 'lib.php'); 2700 foreach ($reportfunctions as $reportfunction) { 2701 $reportfunction($reporttab, $user, $usercourse); 2702 } 2703 2704 $reporttab->trim_if_empty(); 2705 } 2706 } 2707 2708 // Let plugins hook into user navigation. 2709 $pluginsfunction = get_plugins_with_function('extend_navigation_user', 'lib.php'); 2710 foreach ($pluginsfunction as $plugintype => $plugins) { 2711 if ($plugintype != 'report') { 2712 foreach ($plugins as $pluginfunction) { 2713 $pluginfunction($usernode, $user, $usercontext, $course, $coursecontext); 2714 } 2715 } 2716 } 2717 } 2718 return true; 2719 } 2720 2721 /** 2722 * This method simply checks to see if a given module can extend the navigation. 2723 * 2724 * @todo (MDL-25290) A shared caching solution should be used to save details on what extends navigation. 2725 * 2726 * @param string $modname 2727 * @return bool 2728 */ 2729 public static function module_extends_navigation($modname) { 2730 global $CFG; 2731 static $extendingmodules = array(); 2732 if (!array_key_exists($modname, $extendingmodules)) { 2733 $extendingmodules[$modname] = false; 2734 $file = $CFG->dirroot.'/mod/'.$modname.'/lib.php'; 2735 if (file_exists($file)) { 2736 $function = $modname.'_extend_navigation'; 2737 require_once($file); 2738 $extendingmodules[$modname] = (function_exists($function)); 2739 } 2740 } 2741 return $extendingmodules[$modname]; 2742 } 2743 /** 2744 * Extends the navigation for the given user. 2745 * 2746 * @param stdClass $user A user from the database 2747 */ 2748 public function extend_for_user($user) { 2749 $this->extendforuser[] = $user; 2750 } 2751 2752 /** 2753 * Returns all of the users the navigation is being extended for 2754 * 2755 * @return array An array of extending users. 2756 */ 2757 public function get_extending_users() { 2758 return $this->extendforuser; 2759 } 2760 /** 2761 * Adds the given course to the navigation structure. 2762 * 2763 * @param stdClass $course 2764 * @param bool $forcegeneric 2765 * @param bool $ismycourse 2766 * @return navigation_node 2767 */ 2768 public function add_course(stdClass $course, $forcegeneric = false, $coursetype = self::COURSE_OTHER) { 2769 global $CFG, $SITE; 2770 2771 // We found the course... we can return it now :) 2772 if (!$forcegeneric && array_key_exists($course->id, $this->addedcourses)) { 2773 return $this->addedcourses[$course->id]; 2774 } 2775 2776 $coursecontext = context_course::instance($course->id); 2777 2778 if ($coursetype != self::COURSE_MY && $coursetype != self::COURSE_CURRENT && $course->id != $SITE->id) { 2779 if (is_role_switched($course->id)) { 2780 // user has to be able to access course in order to switch, let's skip the visibility test here 2781 } else if (!core_course_category::can_view_course_info($course)) { 2782 return false; 2783 } 2784 } 2785 2786 $issite = ($course->id == $SITE->id); 2787 $displaycontext = \context_helper::get_navigation_filter_context($coursecontext); 2788 $shortname = format_string($course->shortname, true, ['context' => $displaycontext]); 2789 $fullname = format_string($course->fullname, true, ['context' => $displaycontext]); 2790 // This is the name that will be shown for the course. 2791 $coursename = empty($CFG->navshowfullcoursenames) ? $shortname : $fullname; 2792 2793 if ($coursetype == self::COURSE_CURRENT) { 2794 if ($coursenode = $this->rootnodes['mycourses']->find($course->id, self::TYPE_COURSE)) { 2795 return $coursenode; 2796 } else { 2797 $coursetype = self::COURSE_OTHER; 2798 } 2799 } 2800 2801 // Can the user expand the course to see its content. 2802 $canexpandcourse = true; 2803 if ($issite) { 2804 $parent = $this; 2805 $url = null; 2806 if (empty($CFG->usesitenameforsitepages)) { 2807 $coursename = get_string('sitepages'); 2808 } 2809 } else if ($coursetype == self::COURSE_CURRENT) { 2810 $parent = $this->rootnodes['currentcourse']; 2811 $url = new moodle_url('/course/view.php', array('id'=>$course->id)); 2812 $canexpandcourse = $this->can_expand_course($course); 2813 } else if ($coursetype == self::COURSE_MY && !$forcegeneric) { 2814 if (!empty($CFG->navshowmycoursecategories) && ($parent = $this->rootnodes['mycourses']->find($course->category, self::TYPE_MY_CATEGORY))) { 2815 // Nothing to do here the above statement set $parent to the category within mycourses. 2816 } else { 2817 $parent = $this->rootnodes['mycourses']; 2818 } 2819 $url = new moodle_url('/course/view.php', array('id'=>$course->id)); 2820 } else { 2821 $parent = $this->rootnodes['courses']; 2822 $url = new moodle_url('/course/view.php', array('id'=>$course->id)); 2823 // They can only expand the course if they can access it. 2824 $canexpandcourse = $this->can_expand_course($course); 2825 if (!empty($course->category) && $this->show_categories($coursetype == self::COURSE_MY)) { 2826 if (!$this->is_category_fully_loaded($course->category)) { 2827 // We need to load the category structure for this course 2828 $this->load_all_categories($course->category, false); 2829 } 2830 if (array_key_exists($course->category, $this->addedcategories)) { 2831 $parent = $this->addedcategories[$course->category]; 2832 // This could lead to the course being created so we should check whether it is the case again 2833 if (!$forcegeneric && array_key_exists($course->id, $this->addedcourses)) { 2834 return $this->addedcourses[$course->id]; 2835 } 2836 } 2837 } 2838 } 2839 2840 $coursenode = $parent->add($coursename, $url, self::TYPE_COURSE, $shortname, $course->id, new pix_icon('i/course', '')); 2841 $coursenode->showinflatnavigation = $coursetype == self::COURSE_MY; 2842 2843 $coursenode->hidden = (!$course->visible); 2844 $coursenode->title(format_string($course->fullname, true, ['context' => $displaycontext, 'escape' => false])); 2845 if ($canexpandcourse) { 2846 // This course can be expanded by the user, make it a branch to make the system aware that its expandable by ajax. 2847 $coursenode->nodetype = self::NODETYPE_BRANCH; 2848 $coursenode->isexpandable = true; 2849 } else { 2850 $coursenode->nodetype = self::NODETYPE_LEAF; 2851 $coursenode->isexpandable = false; 2852 } 2853 if (!$forcegeneric) { 2854 $this->addedcourses[$course->id] = $coursenode; 2855 } 2856 2857 return $coursenode; 2858 } 2859 2860 /** 2861 * Returns a cache instance to use for the expand course cache. 2862 * @return cache_session 2863 */ 2864 protected function get_expand_course_cache() { 2865 if ($this->cacheexpandcourse === null) { 2866 $this->cacheexpandcourse = cache::make('core', 'navigation_expandcourse'); 2867 } 2868 return $this->cacheexpandcourse; 2869 } 2870 2871 /** 2872 * Checks if a user can expand a course in the navigation. 2873 * 2874 * We use a cache here because in order to be accurate we need to call can_access_course which is a costly function. 2875 * Because this functionality is basic + non-essential and because we lack good event triggering this cache 2876 * permits stale data. 2877 * In the situation the user is granted access to a course after we've initialised this session cache the cache 2878 * will be stale. 2879 * It is brought up to date in only one of two ways. 2880 * 1. The user logs out and in again. 2881 * 2. The user browses to the course they've just being given access to. 2882 * 2883 * Really all this controls is whether the node is shown as expandable or not. It is uber un-important. 2884 * 2885 * @param stdClass $course 2886 * @return bool 2887 */ 2888 protected function can_expand_course($course) { 2889 $cache = $this->get_expand_course_cache(); 2890 $canexpand = $cache->get($course->id); 2891 if ($canexpand === false) { 2892 $canexpand = isloggedin() && can_access_course($course, null, '', true); 2893 $canexpand = (int)$canexpand; 2894 $cache->set($course->id, $canexpand); 2895 } 2896 return ($canexpand === 1); 2897 } 2898 2899 /** 2900 * Returns true if the category has already been loaded as have any child categories 2901 * 2902 * @param int $categoryid 2903 * @return bool 2904 */ 2905 protected function is_category_fully_loaded($categoryid) { 2906 return (array_key_exists($categoryid, $this->addedcategories) && ($this->allcategoriesloaded || $this->addedcategories[$categoryid]->children->count() > 0)); 2907 } 2908 2909 /** 2910 * Adds essential course nodes to the navigation for the given course. 2911 * 2912 * This method adds nodes such as reports, blogs and participants 2913 * 2914 * @param navigation_node $coursenode 2915 * @param stdClass $course 2916 * @return bool returns true on successful addition of a node. 2917 */ 2918 public function add_course_essentials($coursenode, stdClass $course) { 2919 global $CFG, $SITE; 2920 require_once($CFG->dirroot . '/course/lib.php'); 2921 2922 if ($course->id == $SITE->id) { 2923 return $this->add_front_page_course_essentials($coursenode, $course); 2924 } 2925 2926 if ($coursenode == false || !($coursenode instanceof navigation_node) || $coursenode->get('participants', navigation_node::TYPE_CONTAINER)) { 2927 return true; 2928 } 2929 2930 $navoptions = course_get_user_navigation_options($this->page->context, $course); 2931 2932 //Participants 2933 if ($navoptions->participants) { 2934 $participants = $coursenode->add(get_string('participants'), new moodle_url('/user/index.php?id='.$course->id), 2935 self::TYPE_CONTAINER, get_string('participants'), 'participants', new pix_icon('i/users', '')); 2936 2937 if ($navoptions->blogs) { 2938 $blogsurls = new moodle_url('/blog/index.php'); 2939 if ($currentgroup = groups_get_course_group($course, true)) { 2940 $blogsurls->param('groupid', $currentgroup); 2941 } else { 2942 $blogsurls->param('courseid', $course->id); 2943 } 2944 $participants->add(get_string('blogscourse', 'blog'), $blogsurls->out(), self::TYPE_SETTING, null, 'courseblogs'); 2945 } 2946 2947 if ($navoptions->notes) { 2948 $participants->add(get_string('notes', 'notes'), new moodle_url('/notes/index.php', array('filtertype' => 'course', 'filterselect' => $course->id)), self::TYPE_SETTING, null, 'currentcoursenotes'); 2949 } 2950 } else if (count($this->extendforuser) > 0) { 2951 $coursenode->add(get_string('participants'), null, self::TYPE_CONTAINER, get_string('participants'), 'participants'); 2952 } 2953 2954 // Badges. 2955 if ($navoptions->badges) { 2956 $url = new moodle_url('/badges/view.php', array('type' => 2, 'id' => $course->id)); 2957 2958 $coursenode->add(get_string('coursebadges', 'badges'), $url, 2959 navigation_node::TYPE_SETTING, null, 'badgesview', 2960 new pix_icon('i/badge', get_string('coursebadges', 'badges'))); 2961 } 2962 2963 // Check access to the course and competencies page. 2964 if ($navoptions->competencies) { 2965 // Just a link to course competency. 2966 $title = get_string('competencies', 'core_competency'); 2967 $path = new moodle_url("/admin/tool/lp/coursecompetencies.php", array('courseid' => $course->id)); 2968 $coursenode->add($title, $path, navigation_node::TYPE_SETTING, null, 'competencies', 2969 new pix_icon('i/competencies', '')); 2970 } 2971 if ($navoptions->grades) { 2972 $url = new moodle_url('/grade/report/index.php', array('id'=>$course->id)); 2973 $gradenode = $coursenode->add(get_string('grades'), $url, self::TYPE_SETTING, null, 2974 'grades', new pix_icon('i/grades', '')); 2975 // If the page type matches the grade part, then make the nav drawer grade node (incl. all sub pages) active. 2976 if ($this->page->context->contextlevel < CONTEXT_MODULE && strpos($this->page->pagetype, 'grade-') === 0) { 2977 $gradenode->make_active(); 2978 } 2979 } 2980 2981 return true; 2982 } 2983 /** 2984 * This generates the structure of the course that won't be generated when 2985 * the modules and sections are added. 2986 * 2987 * Things such as the reports branch, the participants branch, blogs... get 2988 * added to the course node by this method. 2989 * 2990 * @param navigation_node $coursenode 2991 * @param stdClass $course 2992 * @return bool True for successfull generation 2993 */ 2994 public function add_front_page_course_essentials(navigation_node $coursenode, stdClass $course) { 2995 global $CFG, $USER, $COURSE, $SITE; 2996 require_once($CFG->dirroot . '/course/lib.php'); 2997 2998 if ($coursenode == false || $coursenode->get('frontpageloaded', navigation_node::TYPE_CUSTOM)) { 2999 return true; 3000 } 3001 3002 $systemcontext = context_system::instance(); 3003 $navoptions = course_get_user_navigation_options($systemcontext, $course); 3004 3005 // Hidden node that we use to determine if the front page navigation is loaded. 3006 // This required as there are not other guaranteed nodes that may be loaded. 3007 $coursenode->add('frontpageloaded', null, self::TYPE_CUSTOM, null, 'frontpageloaded')->display = false; 3008 3009 // Add My courses to the site pages within the navigation structure so the block can read it. 3010 $coursenode->add(get_string('mycourses'), new moodle_url('/my/courses.php'), self::TYPE_CUSTOM, null, 'mycourses'); 3011 3012 // Participants. 3013 if ($navoptions->participants) { 3014 $coursenode->add(get_string('participants'), new moodle_url('/user/index.php?id='.$course->id), 3015 self::TYPE_CUSTOM, get_string('participants'), 'participants'); 3016 } 3017 3018 // Blogs. 3019 if ($navoptions->blogs) { 3020 $blogsurls = new moodle_url('/blog/index.php'); 3021 $coursenode->add(get_string('blogssite', 'blog'), $blogsurls->out(), self::TYPE_SYSTEM, null, 'siteblog'); 3022 } 3023 3024 $filterselect = 0; 3025 3026 // Badges. 3027 if ($navoptions->badges) { 3028 $url = new moodle_url($CFG->wwwroot . '/badges/view.php', array('type' => 1)); 3029 $coursenode->add(get_string('sitebadges', 'badges'), $url, navigation_node::TYPE_CUSTOM); 3030 } 3031 3032 // Notes. 3033 if ($navoptions->notes) { 3034 $coursenode->add(get_string('notes', 'notes'), new moodle_url('/notes/index.php', 3035 array('filtertype' => 'course', 'filterselect' => $filterselect)), self::TYPE_SETTING, null, 'notes'); 3036 } 3037 3038 // Tags 3039 if ($navoptions->tags) { 3040 $node = $coursenode->add(get_string('tags', 'tag'), new moodle_url('/tag/search.php'), 3041 self::TYPE_SETTING, null, 'tags'); 3042 } 3043 3044 // Search. 3045 if ($navoptions->search) { 3046 $node = $coursenode->add(get_string('search', 'search'), new moodle_url('/search/index.php'), 3047 self::TYPE_SETTING, null, 'search'); 3048 } 3049 3050 if (isloggedin()) { 3051 $usercontext = context_user::instance($USER->id); 3052 if (has_capability('moodle/user:manageownfiles', $usercontext)) { 3053 $url = new moodle_url('/user/files.php'); 3054 $node = $coursenode->add(get_string('privatefiles'), $url, 3055 self::TYPE_SETTING, null, 'privatefiles', new pix_icon('i/privatefiles', '')); 3056 $node->display = false; 3057 $node->showinflatnavigation = true; 3058 $node->mainnavonly = true; 3059 } 3060 } 3061 3062 if (isloggedin()) { 3063 $context = $this->page->context; 3064 switch ($context->contextlevel) { 3065 case CONTEXT_COURSECAT: 3066 // OK, expected context level. 3067 break; 3068 case CONTEXT_COURSE: 3069 // OK, expected context level if not on frontpage. 3070 if ($COURSE->id != $SITE->id) { 3071 break; 3072 } 3073 default: 3074 // If this context is part of a course (excluding frontpage), use the course context. 3075 // Otherwise, use the system context. 3076 $coursecontext = $context->get_course_context(false); 3077 if ($coursecontext && $coursecontext->instanceid !== $SITE->id) { 3078 $context = $coursecontext; 3079 } else { 3080 $context = $systemcontext; 3081 } 3082 } 3083 3084 $params = ['contextid' => $context->id]; 3085 if (has_capability('moodle/contentbank:access', $context)) { 3086 $url = new moodle_url('/contentbank/index.php', $params); 3087 $node = $coursenode->add(get_string('contentbank'), $url, 3088 self::TYPE_CUSTOM, null, 'contentbank', new pix_icon('i/contentbank', '')); 3089 $node->showinflatnavigation = true; 3090 } 3091 } 3092 3093 return true; 3094 } 3095 3096 /** 3097 * Clears the navigation cache 3098 */ 3099 public function clear_cache() { 3100 $this->cache->clear(); 3101 } 3102 3103 /** 3104 * Sets an expansion limit for the navigation 3105 * 3106 * The expansion limit is used to prevent the display of content that has a type 3107 * greater than the provided $type. 3108 * 3109 * Can be used to ensure things such as activities or activity content don't get 3110 * shown on the navigation. 3111 * They are still generated in order to ensure the navbar still makes sense. 3112 * 3113 * @param int $type One of navigation_node::TYPE_* 3114 * @return bool true when complete. 3115 */ 3116 public function set_expansion_limit($type) { 3117 global $SITE; 3118 $nodes = $this->find_all_of_type($type); 3119 3120 // We only want to hide specific types of nodes. 3121 // Only nodes that represent "structure" in the navigation tree should be hidden. 3122 // If we hide all nodes then we risk hiding vital information. 3123 $typestohide = array( 3124 self::TYPE_CATEGORY, 3125 self::TYPE_COURSE, 3126 self::TYPE_SECTION, 3127 self::TYPE_ACTIVITY 3128 ); 3129 3130 foreach ($nodes as $node) { 3131 // We need to generate the full site node 3132 if ($type == self::TYPE_COURSE && $node->key == $SITE->id) { 3133 continue; 3134 } 3135 foreach ($node->children as $child) { 3136 $child->hide($typestohide); 3137 } 3138 } 3139 return true; 3140 } 3141 /** 3142 * Attempts to get the navigation with the given key from this nodes children. 3143 * 3144 * This function only looks at this nodes children, it does NOT look recursivily. 3145 * If the node can't be found then false is returned. 3146 * 3147 * If you need to search recursivily then use the {@link global_navigation::find()} method. 3148 * 3149 * Note: If you are trying to set the active node {@link navigation_node::override_active_url()} 3150 * may be of more use to you. 3151 * 3152 * @param string|int $key The key of the node you wish to receive. 3153 * @param int $type One of navigation_node::TYPE_* 3154 * @return navigation_node|false 3155 */ 3156 public function get($key, $type = null) { 3157 if (!$this->initialised) { 3158 $this->initialise(); 3159 } 3160 return parent::get($key, $type); 3161 } 3162 3163 /** 3164 * Searches this nodes children and their children to find a navigation node 3165 * with the matching key and type. 3166 * 3167 * This method is recursive and searches children so until either a node is 3168 * found or there are no more nodes to search. 3169 * 3170 * If you know that the node being searched for is a child of this node 3171 * then use the {@link global_navigation::get()} method instead. 3172 * 3173 * Note: If you are trying to set the active node {@link navigation_node::override_active_url()} 3174 * may be of more use to you. 3175 * 3176 * @param string|int $key The key of the node you wish to receive. 3177 * @param int $type One of navigation_node::TYPE_* 3178 * @return navigation_node|false 3179 */ 3180 public function find($key, $type) { 3181 if (!$this->initialised) { 3182 $this->initialise(); 3183 } 3184 if ($type == self::TYPE_ROOTNODE && array_key_exists($key, $this->rootnodes)) { 3185 return $this->rootnodes[$key]; 3186 } 3187 return parent::find($key, $type); 3188 } 3189 3190 /** 3191 * They've expanded the 'my courses' branch. 3192 */ 3193 protected function load_courses_enrolled() { 3194 global $CFG; 3195 3196 $limit = (int) $CFG->navcourselimit; 3197 3198 $courses = enrol_get_my_courses('*'); 3199 $flatnavcourses = []; 3200 3201 // Go through the courses and see which ones we want to display in the flatnav. 3202 foreach ($courses as $course) { 3203 $classify = course_classify_for_timeline($course); 3204 3205 if ($classify == COURSE_TIMELINE_INPROGRESS) { 3206 $flatnavcourses[$course->id] = $course; 3207 } 3208 } 3209 3210 // Get the number of courses that can be displayed in the nav block and in the flatnav. 3211 $numtotalcourses = count($courses); 3212 $numtotalflatnavcourses = count($flatnavcourses); 3213 3214 // Reduce the size of the arrays to abide by the 'navcourselimit' setting. 3215 $courses = array_slice($courses, 0, $limit, true); 3216 $flatnavcourses = array_slice($flatnavcourses, 0, $limit, true); 3217 3218 // Get the number of courses we are going to show for each. 3219 $numshowncourses = count($courses); 3220 $numshownflatnavcourses = count($flatnavcourses); 3221 if ($numshowncourses && $this->show_my_categories()) { 3222 // Generate an array containing unique values of all the courses' categories. 3223 $categoryids = array(); 3224 foreach ($courses as $course) { 3225 if (in_array($course->category, $categoryids)) { 3226 continue; 3227 } 3228 $categoryids[] = $course->category; 3229 } 3230 3231 // Array of category IDs that include the categories of the user's courses and the related course categories. 3232 $fullpathcategoryids = []; 3233 // Get the course categories for the enrolled courses' category IDs. 3234 $mycoursecategories = core_course_category::get_many($categoryids); 3235 // Loop over each of these categories and build the category tree using each category's path. 3236 foreach ($mycoursecategories as $mycoursecat) { 3237 $pathcategoryids = explode('/', $mycoursecat->path); 3238 // First element of the exploded path is empty since paths begin with '/'. 3239 array_shift($pathcategoryids); 3240 // Merge the exploded category IDs into the full list of category IDs that we will fetch. 3241 $fullpathcategoryids = array_merge($fullpathcategoryids, $pathcategoryids); 3242 } 3243 3244 // Fetch all of the categories related to the user's courses. 3245 $pathcategories = core_course_category::get_many($fullpathcategoryids); 3246 // Loop over each of these categories and build the category tree. 3247 foreach ($pathcategories as $coursecat) { 3248 // No need to process categories that have already been added. 3249 if (isset($this->addedcategories[$coursecat->id])) { 3250 continue; 3251 } 3252 // Skip categories that are not visible. 3253 if (!$coursecat->is_uservisible()) { 3254 continue; 3255 } 3256 3257 // Get this course category's parent node. 3258 $parent = null; 3259 if ($coursecat->parent && isset($this->addedcategories[$coursecat->parent])) { 3260 $parent = $this->addedcategories[$coursecat->parent]; 3261 } 3262 if (!$parent) { 3263 // If it has no parent, then it should be right under the My courses node. 3264 $parent = $this->rootnodes['mycourses']; 3265 } 3266 3267 // Build the category object based from the coursecat object. 3268 $mycategory = new stdClass(); 3269 $mycategory->id = $coursecat->id; 3270 $mycategory->name = $coursecat->name; 3271 $mycategory->visible = $coursecat->visible; 3272 3273 // Add this category to the nav tree. 3274 $this->add_category($mycategory, $parent, self::TYPE_MY_CATEGORY); 3275 } 3276 } 3277 3278 // Go through each course now and add it to the nav block, and the flatnav if applicable. 3279 foreach ($courses as $course) { 3280 $node = $this->add_course($course, false, self::COURSE_MY); 3281 if ($node) { 3282 $node->showinflatnavigation = false; 3283 // Check if we should also add this to the flat nav as well. 3284 if (isset($flatnavcourses[$course->id])) { 3285 $node->showinflatnavigation = true; 3286 } 3287 } 3288 } 3289 3290 // Go through each course in the flatnav now. 3291 foreach ($flatnavcourses as $course) { 3292 // Check if we haven't already added it. 3293 if (!isset($courses[$course->id])) { 3294 // Ok, add it to the flatnav only. 3295 $node = $this->add_course($course, false, self::COURSE_MY); 3296 $node->display = false; 3297 $node->showinflatnavigation = true; 3298 } 3299 } 3300 3301 $showmorelinkinnav = $numtotalcourses > $numshowncourses; 3302 $showmorelinkinflatnav = $numtotalflatnavcourses > $numshownflatnavcourses; 3303 // Show a link to the course page if there are more courses the user is enrolled in. 3304 if ($showmorelinkinnav || $showmorelinkinflatnav) { 3305 // Adding hash to URL so the link is not highlighted in the navigation when clicked. 3306 $url = new moodle_url('/my/courses.php'); 3307 $parent = $this->rootnodes['mycourses']; 3308 $coursenode = $parent->add(get_string('morenavigationlinks'), $url, self::TYPE_CUSTOM, null, self::COURSE_INDEX_PAGE); 3309 3310 if ($showmorelinkinnav) { 3311 $coursenode->display = true; 3312 } 3313 3314 if ($showmorelinkinflatnav) { 3315 $coursenode->showinflatnavigation = true; 3316 } 3317 } 3318 } 3319 } 3320 3321 /** 3322 * The global navigation class used especially for AJAX requests. 3323 * 3324 * The primary methods that are used in the global navigation class have been overriden 3325 * to ensure that only the relevant branch is generated at the root of the tree. 3326 * This can be done because AJAX is only used when the backwards structure for the 3327 * requested branch exists. 3328 * This has been done only because it shortens the amounts of information that is generated 3329 * which of course will speed up the response time.. because no one likes laggy AJAX. 3330 * 3331 * @package core 3332 * @category navigation 3333 * @copyright 2009 Sam Hemelryk 3334 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later 3335 */ 3336 class global_navigation_for_ajax extends global_navigation { 3337 3338 /** @var int used for determining what type of navigation_node::TYPE_* is being used */ 3339 protected $branchtype; 3340 3341 /** @var int the instance id */ 3342 protected $instanceid; 3343 3344 /** @var array Holds an array of expandable nodes */ 3345 protected $expandable = array(); 3346 3347 /** 3348 * Constructs the navigation for use in an AJAX request 3349 * 3350 * @param moodle_page $page moodle_page object 3351 * @param int $branchtype 3352 * @param int $id 3353 */ 3354 public function __construct($page, $branchtype, $id) { 3355 $this->page = $page; 3356 $this->cache = new navigation_cache(NAVIGATION_CACHE_NAME); 3357 $this->children = new navigation_node_collection(); 3358 $this->branchtype = $branchtype; 3359 $this->instanceid = $id; 3360 $this->initialise(); 3361 } 3362 /** 3363 * Initialise the navigation given the type and id for the branch to expand. 3364 * 3365 * @return array An array of the expandable nodes 3366 */ 3367 public function initialise() { 3368 global $DB, $SITE; 3369 3370 if ($this->initialised || during_initial_install()) { 3371 return $this->expandable; 3372 } 3373 $this->initialised = true; 3374 3375 $this->rootnodes = array(); 3376 $this->rootnodes['site'] = $this->add_course($SITE); 3377 $this->rootnodes['mycourses'] = $this->add( 3378 get_string('mycourses'), 3379 new moodle_url('/my/courses.php'), 3380 self::TYPE_ROOTNODE, 3381 null, 3382 'mycourses' 3383 ); 3384 $this->rootnodes['courses'] = $this->add(get_string('courses'), null, self::TYPE_ROOTNODE, null, 'courses'); 3385 // The courses branch is always displayed, and is always expandable (although may be empty). 3386 // This mimicks what is done during {@link global_navigation::initialise()}. 3387 $this->rootnodes['courses']->isexpandable = true; 3388 3389 // Branchtype will be one of navigation_node::TYPE_* 3390 switch ($this->branchtype) { 3391 case 0: 3392 if ($this->instanceid === 'mycourses') { 3393 $this->load_courses_enrolled(); 3394 } else if ($this->instanceid === 'courses') { 3395 $this->load_courses_other(); 3396 } 3397 break; 3398 case self::TYPE_CATEGORY : 3399 $this->load_category($this->instanceid); 3400 break; 3401 case self::TYPE_MY_CATEGORY : 3402 $this->load_category($this->instanceid, self::TYPE_MY_CATEGORY); 3403 break; 3404 case self::TYPE_COURSE : 3405 $course = $DB->get_record('course', array('id' => $this->instanceid), '*', MUST_EXIST); 3406 if (!can_access_course($course, null, '', true)) { 3407 // Thats OK all courses are expandable by default. We don't need to actually expand it we can just 3408 // add the course node and break. This leads to an empty node. 3409 $this->add_course($course); 3410 break; 3411 } 3412 require_course_login($course, true, null, false, true); 3413 $this->page->set_context(context_course::instance($course->id)); 3414 $coursenode = $this->add_course($course, false, self::COURSE_CURRENT); 3415 $this->add_course_essentials($coursenode, $course); 3416 $this->load_course_sections($course, $coursenode); 3417 break; 3418 case self::TYPE_SECTION : 3419 $sql = 'SELECT c.*, cs.section AS sectionnumber 3420 FROM {course} c 3421 LEFT JOIN {course_sections} cs ON cs.course = c.id 3422 WHERE cs.id = ?'; 3423 $course = $DB->get_record_sql($sql, array($this->instanceid), MUST_EXIST); 3424 require_course_login($course, true, null, false, true); 3425 $this->page->set_context(context_course::instance($course->id)); 3426 $coursenode = $this->add_course($course, false, self::COURSE_CURRENT); 3427 $this->add_course_essentials($coursenode, $course); 3428 $this->load_course_sections($course, $coursenode, $course->sectionnumber); 3429 break; 3430 case self::TYPE_ACTIVITY : 3431 $sql = "SELECT c.* 3432 FROM {course} c 3433 JOIN {course_modules} cm ON cm.course = c.id 3434 WHERE cm.id = :cmid"; 3435 $params = array('cmid' => $this->instanceid); 3436 $course = $DB->get_record_sql($sql, $params, MUST_EXIST); 3437 $modinfo = get_fast_modinfo($course); 3438 $cm = $modinfo->get_cm($this->instanceid); 3439 require_course_login($course, true, $cm, false, true); 3440 $this->page->set_context(context_module::instance($cm->id)); 3441 $coursenode = $this->add_course($course, false, self::COURSE_CURRENT); 3442 $this->load_course_sections($course, $coursenode, null, $cm); 3443 $activitynode = $coursenode->find($cm->id, self::TYPE_ACTIVITY); 3444 if ($activitynode) { 3445 $modulenode = $this->load_activity($cm, $course, $activitynode); 3446 } 3447 break; 3448 default: 3449 throw new Exception('Unknown type'); 3450 return $this->expandable; 3451 } 3452 3453 if ($this->page->context->contextlevel == CONTEXT_COURSE && $this->page->context->instanceid != $SITE->id) { 3454 $this->load_for_user(null, true); 3455 } 3456 3457 // Give the local plugins a chance to include some navigation if they want. 3458 $this->load_local_plugin_navigation(); 3459 3460 $this->find_expandable($this->expandable); 3461 return $this->expandable; 3462 } 3463 3464 /** 3465 * They've expanded the general 'courses' branch. 3466 */ 3467 protected function load_courses_other() { 3468 $this->load_all_courses(); 3469 } 3470 3471 /** 3472 * Loads a single category into the AJAX navigation. 3473 * 3474 * This function is special in that it doesn't concern itself with the parent of 3475 * the requested category or its siblings. 3476 * This is because with the AJAX navigation we know exactly what is wanted and only need to 3477 * request that. 3478 * 3479 * @global moodle_database $DB 3480 * @param int $categoryid id of category to load in navigation. 3481 * @param int $nodetype type of node, if category is under MyHome then it's TYPE_MY_CATEGORY 3482 * @return void. 3483 */ 3484 protected function load_category($categoryid, $nodetype = self::TYPE_CATEGORY) { 3485 global $CFG, $DB; 3486 3487 $limit = 20; 3488 if (!empty($CFG->navcourselimit)) { 3489 $limit = (int)$CFG->navcourselimit; 3490 } 3491 3492 $catcontextsql = context_helper::get_preload_record_columns_sql('ctx'); 3493 $sql = "SELECT cc.*, $catcontextsql 3494 FROM {course_categories} cc 3495 JOIN {context} ctx ON cc.id = ctx.instanceid 3496 WHERE ctx.contextlevel = ".CONTEXT_COURSECAT." AND 3497 (cc.id = :categoryid1 OR cc.parent = :categoryid2) 3498 ORDER BY cc.depth ASC, cc.sortorder ASC, cc.id ASC"; 3499 $params = array('categoryid1' => $categoryid, 'categoryid2' => $categoryid); 3500 $categories = $DB->get_recordset_sql($sql, $params, 0, $limit); 3501 $categorylist = array(); 3502 $subcategories = array(); 3503 $basecategory = null; 3504 foreach ($categories as $category) { 3505 $categorylist[] = $category->id; 3506 context_helper::preload_from_record($category); 3507 if ($category->id == $categoryid) { 3508 $this->add_category($category, $this, $nodetype); 3509 $basecategory = $this->addedcategories[$category->id]; 3510 } else { 3511 $subcategories[$category->id] = $category; 3512 } 3513 } 3514 $categories->close(); 3515 3516 3517 // If category is shown in MyHome then only show enrolled courses and hide empty subcategories, 3518 // else show all courses. 3519 if ($nodetype === self::TYPE_MY_CATEGORY) { 3520 $courses = enrol_get_my_courses('*'); 3521 $categoryids = array(); 3522 3523 // Only search for categories if basecategory was found. 3524 if (!is_null($basecategory)) { 3525 // Get course parent category ids. 3526 foreach ($courses as $course) { 3527 $categoryids[] = $course->category; 3528 } 3529 3530 // Get a unique list of category ids which a part of the path 3531 // to user's courses. 3532 $coursesubcategories = array(); 3533 $addedsubcategories = array(); 3534 3535 list($sql, $params) = $DB->get_in_or_equal($categoryids); 3536 $categories = $DB->get_recordset_select('course_categories', 'id '.$sql, $params, 'sortorder, id', 'id, path'); 3537 3538 foreach ($categories as $category){ 3539 $coursesubcategories = array_merge($coursesubcategories, explode('/', trim($category->path, "/"))); 3540 } 3541 $categories->close(); 3542 $coursesubcategories = array_unique($coursesubcategories); 3543 3544 // Only add a subcategory if it is part of the path to user's course and 3545 // wasn't already added. 3546 foreach ($subcategories as $subid => $subcategory) { 3547 if (in_array($subid, $coursesubcategories) && 3548 !in_array($subid, $addedsubcategories)) { 3549 $this->add_category($subcategory, $basecategory, $nodetype); 3550 $addedsubcategories[] = $subid; 3551 } 3552 } 3553 } 3554 3555 foreach ($courses as $course) { 3556 // Add course if it's in category. 3557 if (in_array($course->category, $categorylist)) { 3558 $this->add_course($course, true, self::COURSE_MY); 3559 } 3560 } 3561 } else { 3562 if (!is_null($basecategory)) { 3563 foreach ($subcategories as $key=>$category) { 3564 $this->add_category($category, $basecategory, $nodetype); 3565 } 3566 } 3567 $courses = $DB->get_recordset('course', array('category' => $categoryid), 'sortorder', '*' , 0, $limit); 3568 foreach ($courses as $course) { 3569 $this->add_course($course); 3570 } 3571 $courses->close(); 3572 } 3573 } 3574 3575 /** 3576 * Returns an array of expandable nodes 3577 * @return array 3578 */ 3579 public function get_expandable() { 3580 return $this->expandable; 3581 } 3582 } 3583 3584 /** 3585 * Navbar class 3586 * 3587 * This class is used to manage the navbar, which is initialised from the navigation 3588 * object held by PAGE 3589 * 3590 * @package core 3591 * @category navigation 3592 * @copyright 2009 Sam Hemelryk 3593 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later 3594 */ 3595 class navbar extends navigation_node { 3596 /** @var bool A switch for whether the navbar is initialised or not */ 3597 protected $initialised = false; 3598 /** @var mixed keys used to reference the nodes on the navbar */ 3599 protected $keys = array(); 3600 /** @var null|string content of the navbar */ 3601 protected $content = null; 3602 /** @var moodle_page object the moodle page that this navbar belongs to */ 3603 protected $page; 3604 /** @var bool A switch for whether to ignore the active navigation information */ 3605 protected $ignoreactive = false; 3606 /** @var bool A switch to let us know if we are in the middle of an install */ 3607 protected $duringinstall = false; 3608 /** @var bool A switch for whether the navbar has items */ 3609 protected $hasitems = false; 3610 /** @var array An array of navigation nodes for the navbar */ 3611 protected $items; 3612 /** @var array An array of child node objects */ 3613 public $children = array(); 3614 /** @var bool A switch for whether we want to include the root node in the navbar */ 3615 public $includesettingsbase = false; 3616 /** @var breadcrumb_navigation_node[] $prependchildren */ 3617 protected $prependchildren = array(); 3618 3619 /** 3620 * The almighty constructor 3621 * 3622 * @param moodle_page $page 3623 */ 3624 public function __construct(moodle_page $page) { 3625 global $CFG; 3626 if (during_initial_install()) { 3627 $this->duringinstall = true; 3628 return false; 3629 } 3630 $this->page = $page; 3631 $this->text = get_string('home'); 3632 $this->shorttext = get_string('home'); 3633 $this->action = new moodle_url($CFG->wwwroot); 3634 $this->nodetype = self::NODETYPE_BRANCH; 3635 $this->type = self::TYPE_SYSTEM; 3636 } 3637 3638 /** 3639 * Quick check to see if the navbar will have items in. 3640 * 3641 * @return bool Returns true if the navbar will have items, false otherwise 3642 */ 3643 public function has_items() { 3644 if ($this->duringinstall) { 3645 return false; 3646 } else if ($this->hasitems !== false) { 3647 return true; 3648 } 3649 $outcome = false; 3650 if (count($this->children) > 0 || count($this->prependchildren) > 0) { 3651 // There have been manually added items - there are definitely items. 3652 $outcome = true; 3653 } else if (!$this->ignoreactive) { 3654 // We will need to initialise the navigation structure to check if there are active items. 3655 $this->page->navigation->initialise($this->page); 3656 $outcome = ($this->page->navigation->contains_active_node() || $this->page->settingsnav->contains_active_node()); 3657 } 3658 $this->hasitems = $outcome; 3659 return $outcome; 3660 } 3661 3662 /** 3663 * Turn on/off ignore active 3664 * 3665 * @param bool $setting 3666 */ 3667 public function ignore_active($setting=true) { 3668 $this->ignoreactive = ($setting); 3669 } 3670 3671 /** 3672 * Gets a navigation node 3673 * 3674 * @param string|int $key for referencing the navbar nodes 3675 * @param int $type breadcrumb_navigation_node::TYPE_* 3676 * @return breadcrumb_navigation_node|bool 3677 */ 3678 public function get($key, $type = null) { 3679 foreach ($this->children as &$child) { 3680 if ($child->key === $key && ($type == null || $type == $child->type)) { 3681 return $child; 3682 } 3683 } 3684 foreach ($this->prependchildren as &$child) { 3685 if ($child->key === $key && ($type == null || $type == $child->type)) { 3686 return $child; 3687 } 3688 } 3689 return false; 3690 } 3691 /** 3692 * Returns an array of breadcrumb_navigation_nodes that make up the navbar. 3693 * 3694 * @return array 3695 */ 3696 public function get_items() { 3697 global $CFG; 3698 $items = array(); 3699 // Make sure that navigation is initialised 3700 if (!$this->has_items()) { 3701 return $items; 3702 } 3703 if ($this->items !== null) { 3704 return $this->items; 3705 } 3706 3707 if (count($this->children) > 0) { 3708 // Add the custom children. 3709 $items = array_reverse($this->children); 3710 } 3711 3712 // Check if navigation contains the active node 3713 if (!$this->ignoreactive) { 3714 // We will need to ensure the navigation has been initialised. 3715 $this->page->navigation->initialise($this->page); 3716 // Now find the active nodes on both the navigation and settings. 3717 $navigationactivenode = $this->page->navigation->find_active_node(); 3718 $settingsactivenode = $this->page->settingsnav->find_active_node(); 3719 3720 if ($navigationactivenode && $settingsactivenode) { 3721 // Parse a combined navigation tree 3722 while ($settingsactivenode && $settingsactivenode->parent !== null) { 3723 if (!$settingsactivenode->mainnavonly) { 3724 $items[] = new breadcrumb_navigation_node($settingsactivenode); 3725 } 3726 $settingsactivenode = $settingsactivenode->parent; 3727 } 3728 if (!$this->includesettingsbase) { 3729 // Removes the first node from the settings (root node) from the list 3730 array_pop($items); 3731 } 3732 while ($navigationactivenode && $navigationactivenode->parent !== null) { 3733 if (!$navigationactivenode->mainnavonly) { 3734 $items[] = new breadcrumb_navigation_node($navigationactivenode); 3735 } 3736 if (!empty($CFG->navshowcategories) && 3737 $navigationactivenode->type === self::TYPE_COURSE && 3738 $navigationactivenode->parent->key === 'currentcourse') { 3739 foreach ($this->get_course_categories() as $item) { 3740 $items[] = new breadcrumb_navigation_node($item); 3741 } 3742 } 3743 $navigationactivenode = $navigationactivenode->parent; 3744 } 3745 } else if ($navigationactivenode) { 3746 // Parse the navigation tree to get the active node 3747 while ($navigationactivenode && $navigationactivenode->parent !== null) { 3748 if (!$navigationactivenode->mainnavonly) { 3749 $items[] = new breadcrumb_navigation_node($navigationactivenode); 3750 } 3751 if (!empty($CFG->navshowcategories) && 3752 $navigationactivenode->type === self::TYPE_COURSE && 3753 $navigationactivenode->parent->key === 'currentcourse') { 3754 foreach ($this->get_course_categories() as $item) { 3755 $items[] = new breadcrumb_navigation_node($item); 3756 } 3757 } 3758 $navigationactivenode = $navigationactivenode->parent; 3759 } 3760 } else if ($settingsactivenode) { 3761 // Parse the settings navigation to get the active node 3762 while ($settingsactivenode && $settingsactivenode->parent !== null) { 3763 if (!$settingsactivenode->mainnavonly) { 3764 $items[] = new breadcrumb_navigation_node($settingsactivenode); 3765 } 3766 $settingsactivenode = $settingsactivenode->parent; 3767 } 3768 } 3769 } 3770 3771 $items[] = new breadcrumb_navigation_node(array( 3772 'text' => $this->page->navigation->text, 3773 'shorttext' => $this->page->navigation->shorttext, 3774 'key' => $this->page->navigation->key, 3775 'action' => $this->page->navigation->action 3776 )); 3777 3778 if (count($this->prependchildren) > 0) { 3779 // Add the custom children 3780 $items = array_merge($items, array_reverse($this->prependchildren)); 3781 } 3782 3783 $last = reset($items); 3784 if ($last) { 3785 $last->set_last(true); 3786 } 3787 $this->items = array_reverse($items); 3788 return $this->items; 3789 } 3790 3791 /** 3792 * Get the list of categories leading to this course. 3793 * 3794 * This function is used by {@link navbar::get_items()} to add back the "courses" 3795 * node and category chain leading to the current course. Note that this is only ever 3796 * called for the current course, so we don't need to bother taking in any parameters. 3797 * 3798 * @return array 3799 */ 3800 private function get_course_categories() { 3801 global $CFG; 3802 require_once($CFG->dirroot.'/course/lib.php'); 3803 3804 $categories = array(); 3805 $cap = 'moodle/category:viewhiddencategories'; 3806 $showcategories = !core_course_category::is_simple_site(); 3807 3808 if ($showcategories) { 3809 foreach ($this->page->categories as $category) { 3810 $context = context_coursecat::instance($category->id); 3811 if (!core_course_category::can_view_category($category)) { 3812 continue; 3813 } 3814 3815 $displaycontext = \context_helper::get_navigation_filter_context($context); 3816 $url = new moodle_url('/course/index.php', ['categoryid' => $category->id]); 3817 $name = format_string($category->name, true, ['context' => $displaycontext]); 3818 $categorynode = breadcrumb_navigation_node::create($name, $url, self::TYPE_CATEGORY, null, $category->id); 3819 if (!$category->visible) { 3820 $categorynode->hidden = true; 3821 } 3822 $categories[] = $categorynode; 3823 } 3824 } 3825 3826 // Don't show the 'course' node if enrolled in this course. 3827 $coursecontext = context_course::instance($this->page->course->id); 3828 if (!is_enrolled($coursecontext, null, '', true)) { 3829 $courses = $this->page->navigation->get('courses'); 3830 if (!$courses) { 3831 // Courses node may not be present. 3832 $courses = breadcrumb_navigation_node::create( 3833 get_string('courses'), 3834 new moodle_url('/course/index.php'), 3835 self::TYPE_CONTAINER 3836 ); 3837 } 3838 $categories[] = $courses; 3839 } 3840 3841 return $categories; 3842 } 3843 3844 /** 3845 * Add a new breadcrumb_navigation_node to the navbar, overrides parent::add 3846 * 3847 * This function overrides {@link breadcrumb_navigation_node::add()} so that we can change 3848 * the way nodes get added to allow us to simply call add and have the node added to the 3849 * end of the navbar 3850 * 3851 * @param string $text 3852 * @param string|moodle_url|action_link $action An action to associate with this node. 3853 * @param int $type One of navigation_node::TYPE_* 3854 * @param string $shorttext 3855 * @param string|int $key A key to identify this node with. Key + type is unique to a parent. 3856 * @param pix_icon $icon An optional icon to use for this node. 3857 * @return navigation_node 3858 */ 3859 public function add($text, $action=null, $type=self::TYPE_CUSTOM, $shorttext=null, $key=null, pix_icon $icon=null) { 3860 if ($this->content !== null) { 3861 debugging('Nav bar items must be printed before $OUTPUT->header() has been called', DEBUG_DEVELOPER); 3862 } 3863 3864 // Properties array used when creating the new navigation node 3865 $itemarray = array( 3866 'text' => $text, 3867 'type' => $type 3868 ); 3869 // Set the action if one was provided 3870 if ($action!==null) { 3871 $itemarray['action'] = $action; 3872 } 3873 // Set the shorttext if one was provided 3874 if ($shorttext!==null) { 3875 $itemarray['shorttext'] = $shorttext; 3876 } 3877 // Set the icon if one was provided 3878 if ($icon!==null) { 3879 $itemarray['icon'] = $icon; 3880 } 3881 // Default the key to the number of children if not provided 3882 if ($key === null) { 3883 $key = count($this->children); 3884 } 3885 // Set the key 3886 $itemarray['key'] = $key; 3887 // Set the parent to this node 3888 $itemarray['parent'] = $this; 3889 // Add the child using the navigation_node_collections add method 3890 $this->children[] = new breadcrumb_navigation_node($itemarray); 3891 return $this; 3892 } 3893 3894 /** 3895 * Prepends a new navigation_node to the start of the navbar 3896 * 3897 * @param string $text 3898 * @param string|moodle_url|action_link $action An action to associate with this node. 3899 * @param int $type One of navigation_node::TYPE_* 3900 * @param string $shorttext 3901 * @param string|int $key A key to identify this node with. Key + type is unique to a parent. 3902 * @param pix_icon $icon An optional icon to use for this node. 3903 * @return navigation_node 3904 */ 3905 public function prepend($text, $action=null, $type=self::TYPE_CUSTOM, $shorttext=null, $key=null, pix_icon $icon=null) { 3906 if ($this->content !== null) { 3907 debugging('Nav bar items must be printed before $OUTPUT->header() has been called', DEBUG_DEVELOPER); 3908 } 3909 // Properties array used when creating the new navigation node. 3910 $itemarray = array( 3911 'text' => $text, 3912 'type' => $type 3913 ); 3914 // Set the action if one was provided. 3915 if ($action!==null) { 3916 $itemarray['action'] = $action; 3917 } 3918 // Set the shorttext if one was provided. 3919 if ($shorttext!==null) { 3920 $itemarray['shorttext'] = $shorttext; 3921 } 3922 // Set the icon if one was provided. 3923 if ($icon!==null) { 3924 $itemarray['icon'] = $icon; 3925 } 3926 // Default the key to the number of children if not provided. 3927 if ($key === null) { 3928 $key = count($this->children); 3929 } 3930 // Set the key. 3931 $itemarray['key'] = $key; 3932 // Set the parent to this node. 3933 $itemarray['parent'] = $this; 3934 // Add the child node to the prepend list. 3935 $this->prependchildren[] = new breadcrumb_navigation_node($itemarray); 3936 return $this; 3937 } 3938 } 3939 3940 /** 3941 * Subclass of navigation_node allowing different rendering for the breadcrumbs 3942 * in particular adding extra metadata for search engine robots to leverage. 3943 * 3944 * @package core 3945 * @category navigation 3946 * @copyright 2015 Brendan Heywood 3947 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later 3948 */ 3949 class breadcrumb_navigation_node extends navigation_node { 3950 3951 /** @var $last boolean A flag indicating this is the last item in the list of breadcrumbs. */ 3952 private $last = false; 3953 3954 /** 3955 * A proxy constructor 3956 * 3957 * @param mixed $navnode A navigation_node or an array 3958 */ 3959 public function __construct($navnode) { 3960 if (is_array($navnode)) { 3961 parent::__construct($navnode); 3962 } else if ($navnode instanceof navigation_node) { 3963 3964 // Just clone everything. 3965 $objvalues = get_object_vars($navnode); 3966 foreach ($objvalues as $key => $value) { 3967 $this->$key = $value; 3968 } 3969 } else { 3970 throw new coding_exception('Not a valid breadcrumb_navigation_node'); 3971 } 3972 } 3973 3974 /** 3975 * Getter for "last" 3976 * @return boolean 3977 */ 3978 public function is_last() { 3979 return $this->last; 3980 } 3981 3982 /** 3983 * Setter for "last" 3984 * @param $val boolean 3985 */ 3986 public function set_last($val) { 3987 $this->last = $val; 3988 } 3989 } 3990 3991 /** 3992 * Subclass of navigation_node allowing different rendering for the flat navigation 3993 * in particular allowing dividers and indents. 3994 * 3995 * @deprecated since Moodle 4.0 - do not use any more. Leverage secondary/tertiary navigation concepts 3996 * @package core 3997 * @category navigation 3998 * @copyright 2016 Damyon Wiese 3999 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later 4000 */ 4001 class flat_navigation_node extends navigation_node { 4002 4003 /** @var $indent integer The indent level */ 4004 private $indent = 0; 4005 4006 /** @var $showdivider bool Show a divider before this element */ 4007 private $showdivider = false; 4008 4009 /** @var $collectionlabel string Label for a group of nodes */ 4010 private $collectionlabel = ''; 4011 4012 /** 4013 * A proxy constructor 4014 * 4015 * @param mixed $navnode A navigation_node or an array 4016 */ 4017 public function __construct($navnode, $indent) { 4018 debugging("Flat nav has been deprecated in favour of primary/secondary navigation concepts"); 4019 if (is_array($navnode)) { 4020 parent::__construct($navnode); 4021 } else if ($navnode instanceof navigation_node) { 4022 4023 // Just clone everything. 4024 $objvalues = get_object_vars($navnode); 4025 foreach ($objvalues as $key => $value) { 4026 $this->$key = $value; 4027 } 4028 } else { 4029 throw new coding_exception('Not a valid flat_navigation_node'); 4030 } 4031 $this->indent = $indent; 4032 } 4033 4034 /** 4035 * Setter, a label is required for a flat navigation node that shows a divider. 4036 * 4037 * @param string $label 4038 */ 4039 public function set_collectionlabel($label) { 4040 $this->collectionlabel = $label; 4041 } 4042 4043 /** 4044 * Getter, get the label for this flat_navigation node, or it's parent if it doesn't have one. 4045 * 4046 * @return string 4047 */ 4048 public function get_collectionlabel() { 4049 if (!empty($this->collectionlabel)) { 4050 return $this->collectionlabel; 4051 } 4052 if ($this->parent && ($this->parent instanceof flat_navigation_node || $this->parent instanceof flat_navigation)) { 4053 return $this->parent->get_collectionlabel(); 4054 } 4055 debugging('Navigation region requires a label', DEBUG_DEVELOPER); 4056 return ''; 4057 } 4058 4059 /** 4060 * Does this node represent a course section link. 4061 * @return boolean 4062 */ 4063 public function is_section() { 4064 return $this->type == navigation_node::TYPE_SECTION; 4065 } 4066 4067 /** 4068 * In flat navigation - sections are active if we are looking at activities in the section. 4069 * @return boolean 4070 */ 4071 public function isactive() { 4072 global $PAGE; 4073 4074 if ($this->is_section()) { 4075 $active = $PAGE->navigation->find_active_node(); 4076 if ($active) { 4077 while ($active = $active->parent) { 4078 if ($active->key == $this->key && $active->type == $this->type) { 4079 return true; 4080 } 4081 } 4082 } 4083 } 4084 return $this->isactive; 4085 } 4086 4087 /** 4088 * Getter for "showdivider" 4089 * @return boolean 4090 */ 4091 public function showdivider() { 4092 return $this->showdivider; 4093 } 4094 4095 /** 4096 * Setter for "showdivider" 4097 * @param $val boolean 4098 * @param $label string Label for the group of nodes 4099 */ 4100 public function set_showdivider($val, $label = '') { 4101 $this->showdivider = $val; 4102 if ($this->showdivider && empty($label)) { 4103 debugging('Navigation region requires a label', DEBUG_DEVELOPER); 4104 } else { 4105 $this->set_collectionlabel($label); 4106 } 4107 } 4108 4109 /** 4110 * Getter for "indent" 4111 * @return boolean 4112 */ 4113 public function get_indent() { 4114 return $this->indent; 4115 } 4116 4117 /** 4118 * Setter for "indent" 4119 * @param $val boolean 4120 */ 4121 public function set_indent($val) { 4122 $this->indent = $val; 4123 } 4124 } 4125 4126 /** 4127 * Class used to generate a collection of navigation nodes most closely related 4128 * to the current page. 4129 * 4130 * @deprecated since Moodle 4.0 - do not use any more. Leverage secondary/tertiary navigation concepts 4131 * @package core 4132 * @copyright 2016 Damyon Wiese 4133 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later 4134 */ 4135 class flat_navigation extends navigation_node_collection { 4136 /** @var moodle_page the moodle page that the navigation belongs to */ 4137 protected $page; 4138 4139 /** 4140 * Constructor. 4141 * 4142 * @param moodle_page $page 4143 */ 4144 public function __construct(moodle_page &$page) { 4145 if (during_initial_install()) { 4146 return false; 4147 } 4148 debugging("Flat navigation has been deprecated in favour of primary/secondary navigation concepts"); 4149 $this->page = $page; 4150 } 4151 4152 /** 4153 * Build the list of navigation nodes based on the current navigation and settings trees. 4154 * 4155 */ 4156 public function initialise() { 4157 global $PAGE, $USER, $OUTPUT, $CFG; 4158 if (during_initial_install()) { 4159 return; 4160 } 4161 4162 $current = false; 4163 4164 $course = $PAGE->course; 4165 4166 $this->page->navigation->initialise(); 4167 4168 // First walk the nav tree looking for "flat_navigation" nodes. 4169 if ($course->id > 1) { 4170 // It's a real course. 4171 $url = new moodle_url('/course/view.php', array('id' => $course->id)); 4172 4173 $coursecontext = context_course::instance($course->id, MUST_EXIST); 4174 $displaycontext = \context_helper::get_navigation_filter_context($coursecontext); 4175 // This is the name that will be shown for the course. 4176 $coursename = empty($CFG->navshowfullcoursenames) ? 4177 format_string($course->shortname, true, ['context' => $displaycontext]) : 4178 format_string($course->fullname, true, ['context' => $displaycontext]); 4179 4180 $flat = new flat_navigation_node(navigation_node::create($coursename, $url), 0); 4181 $flat->set_collectionlabel($coursename); 4182 $flat->key = 'coursehome'; 4183 $flat->icon = new pix_icon('i/course', ''); 4184 4185 $courseformat = course_get_format($course); 4186 $coursenode = $PAGE->navigation->find_active_node(); 4187 $targettype = navigation_node::TYPE_COURSE; 4188 4189 // Single activity format has no course node - the course node is swapped for the activity node. 4190 if (!$courseformat->has_view_page()) { 4191 $targettype = navigation_node::TYPE_ACTIVITY; 4192 } 4193 4194 while (!empty($coursenode) && ($coursenode->type != $targettype)) { 4195 $coursenode = $coursenode->parent; 4196 } 4197 // There is one very strange page in mod/feedback/view.php which thinks it is both site and course 4198 // context at the same time. That page is broken but we need to handle it (hence the SITEID). 4199 if ($coursenode && $coursenode->key != SITEID) { 4200 $this->add($flat); 4201 foreach ($coursenode->children as $child) { 4202 if ($child->action) { 4203 $flat = new flat_navigation_node($child, 0); 4204 $this->add($flat); 4205 } 4206 } 4207 } 4208 4209 $this->page->navigation->build_flat_navigation_list($this, true, get_string('site')); 4210 } else { 4211 $this->page->navigation->build_flat_navigation_list($this, false, get_string('site')); 4212 } 4213 4214 $admin = $PAGE->settingsnav->find('siteadministration', navigation_node::TYPE_SITE_ADMIN); 4215 if (!$admin) { 4216 // Try again - crazy nav tree! 4217 $admin = $PAGE->settingsnav->find('root', navigation_node::TYPE_SITE_ADMIN); 4218 } 4219 if ($admin) { 4220 $flat = new flat_navigation_node($admin, 0); 4221 $flat->set_showdivider(true, get_string('sitesettings')); 4222 $flat->key = 'sitesettings'; 4223 $flat->icon = new pix_icon('t/preferences', ''); 4224 $this->add($flat); 4225 } 4226 4227 // Add-a-block in editing mode. 4228 if (isset($this->page->theme->addblockposition) && 4229 $this->page->theme->addblockposition == BLOCK_ADDBLOCK_POSITION_FLATNAV && 4230 $PAGE->user_is_editing() && $PAGE->user_can_edit_blocks()) { 4231 $url = new moodle_url($PAGE->url, ['bui_addblock' => '', 'sesskey' => sesskey()]); 4232 $addablock = navigation_node::create(get_string('addblock'), $url); 4233 $flat = new flat_navigation_node($addablock, 0); 4234 $flat->set_showdivider(true, get_string('blocksaddedit')); 4235 $flat->key = 'addblock'; 4236 $flat->icon = new pix_icon('i/addblock', ''); 4237 $this->add($flat); 4238 4239 $addblockurl = "?{$url->get_query_string(false)}"; 4240 4241 $PAGE->requires->js_call_amd('core/addblockmodal', 'init', 4242 [$PAGE->pagetype, $PAGE->pagelayout, $addblockurl]); 4243 } 4244 } 4245 4246 /** 4247 * Override the parent so we can set a label for this collection if it has not been set yet. 4248 * 4249 * @param navigation_node $node Node to add 4250 * @param string $beforekey If specified, adds before a node with this key, 4251 * otherwise adds at end 4252 * @return navigation_node Added node 4253 */ 4254 public function add(navigation_node $node, $beforekey=null) { 4255 $result = parent::add($node, $beforekey); 4256 // Extend the parent to get a name for the collection of nodes if required. 4257 if (empty($this->collectionlabel)) { 4258 if ($node instanceof flat_navigation_node) { 4259 $this->set_collectionlabel($node->get_collectionlabel()); 4260 } 4261 } 4262 4263 return $result; 4264 } 4265 } 4266 4267 /** 4268 * Class used to manage the settings option for the current page 4269 * 4270 * This class is used to manage the settings options in a tree format (recursively) 4271 * and was created initially for use with the settings blocks. 4272 * 4273 * @package core 4274 * @category navigation 4275 * @copyright 2009 Sam Hemelryk 4276 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later 4277 */ 4278 class settings_navigation extends navigation_node { 4279 /** @var stdClass the current context */ 4280 protected $context; 4281 /** @var moodle_page the moodle page that the navigation belongs to */ 4282 protected $page; 4283 /** @var string contains administration section navigation_nodes */ 4284 protected $adminsection; 4285 /** @var bool A switch to see if the navigation node is initialised */ 4286 protected $initialised = false; 4287 /** @var array An array of users that the nodes can extend for. */ 4288 protected $userstoextendfor = array(); 4289 /** @var navigation_cache **/ 4290 protected $cache; 4291 4292 /** 4293 * Sets up the object with basic settings and preparse it for use 4294 * 4295 * @param moodle_page $page 4296 */ 4297 public function __construct(moodle_page &$page) { 4298 if (during_initial_install()) { 4299 return false; 4300 } 4301 $this->page = $page; 4302 // Initialise the main navigation. It is most important that this is done 4303 // before we try anything 4304 $this->page->navigation->initialise(); 4305 // Initialise the navigation cache 4306 $this->cache = new navigation_cache(NAVIGATION_CACHE_NAME); 4307 $this->children = new navigation_node_collection(); 4308 } 4309 4310 /** 4311 * Initialise the settings navigation based on the current context 4312 * 4313 * This function initialises the settings navigation tree for a given context 4314 * by calling supporting functions to generate major parts of the tree. 4315 * 4316 */ 4317 public function initialise() { 4318 global $DB, $SESSION, $SITE; 4319 4320 if (during_initial_install()) { 4321 return false; 4322 } else if ($this->initialised) { 4323 return true; 4324 } 4325 $this->id = 'settingsnav'; 4326 $this->context = $this->page->context; 4327 4328 $context = $this->context; 4329 if ($context->contextlevel == CONTEXT_BLOCK) { 4330 $this->load_block_settings(); 4331 $context = $context->get_parent_context(); 4332 $this->context = $context; 4333 } 4334 switch ($context->contextlevel) { 4335 case CONTEXT_SYSTEM: 4336 if ($this->page->url->compare(new moodle_url('/admin/settings.php', array('section'=>'frontpagesettings')))) { 4337 $this->load_front_page_settings(($context->id == $this->context->id)); 4338 } 4339 break; 4340 case CONTEXT_COURSECAT: 4341 $this->load_category_settings(); 4342 break; 4343 case CONTEXT_COURSE: 4344 if ($this->page->course->id != $SITE->id) { 4345 $this->load_course_settings(($context->id == $this->context->id)); 4346 } else { 4347 $this->load_front_page_settings(($context->id == $this->context->id)); 4348 } 4349 break; 4350 case CONTEXT_MODULE: 4351 $this->load_module_settings(); 4352 $this->load_course_settings(); 4353 break; 4354 case CONTEXT_USER: 4355 if ($this->page->course->id != $SITE->id) { 4356 $this->load_course_settings(); 4357 } 4358 break; 4359 } 4360 4361 $usersettings = $this->load_user_settings($this->page->course->id); 4362 4363 $adminsettings = false; 4364 if (isloggedin() && !isguestuser() && (!isset($SESSION->load_navigation_admin) || $SESSION->load_navigation_admin)) { 4365 $isadminpage = $this->is_admin_tree_needed(); 4366 4367 if (has_capability('moodle/site:configview', context_system::instance())) { 4368 if (has_capability('moodle/site:config', context_system::instance())) { 4369 // Make sure this works even if config capability changes on the fly 4370 // and also make it fast for admin right after login. 4371 $SESSION->load_navigation_admin = 1; 4372 if ($isadminpage) { 4373 $adminsettings = $this->load_administration_settings(); 4374 } 4375 4376 } else if (!isset($SESSION->load_navigation_admin)) { 4377 $adminsettings = $this->load_administration_settings(); 4378 $SESSION->load_navigation_admin = (int)($adminsettings->children->count() > 0); 4379 4380 } else if ($SESSION->load_navigation_admin) { 4381 if ($isadminpage) { 4382 $adminsettings = $this->load_administration_settings(); 4383 } 4384 } 4385 4386 // Print empty navigation node, if needed. 4387 if ($SESSION->load_navigation_admin && !$isadminpage) { 4388 if ($adminsettings) { 4389 // Do not print settings tree on pages that do not need it, this helps with performance. 4390 $adminsettings->remove(); 4391 $adminsettings = false; 4392 } 4393 $siteadminnode = $this->add(get_string('administrationsite'), new moodle_url('/admin/search.php'), 4394 self::TYPE_SITE_ADMIN, null, 'siteadministration'); 4395 $siteadminnode->id = 'expandable_branch_' . $siteadminnode->type . '_' . 4396 clean_param($siteadminnode->key, PARAM_ALPHANUMEXT); 4397 $siteadminnode->requiresajaxloading = 'true'; 4398 } 4399 } 4400 } 4401 4402 if ($context->contextlevel == CONTEXT_SYSTEM && $adminsettings) { 4403 $adminsettings->force_open(); 4404 } else if ($context->contextlevel == CONTEXT_USER && $usersettings) { 4405 $usersettings->force_open(); 4406 } 4407 4408 // At this point we give any local plugins the ability to extend/tinker with the navigation settings. 4409 $this->load_local_plugin_settings(); 4410 4411 foreach ($this->children as $key=>$node) { 4412 if ($node->nodetype == self::NODETYPE_BRANCH && $node->children->count() == 0) { 4413 // Site administration is shown as link. 4414 if (!empty($SESSION->load_navigation_admin) && ($node->type === self::TYPE_SITE_ADMIN)) { 4415 continue; 4416 } 4417 $node->remove(); 4418 } 4419 } 4420 $this->initialised = true; 4421 } 4422 /** 4423 * Override the parent function so that we can add preceeding hr's and set a 4424 * root node class against all first level element 4425 * 4426 * It does this by first calling the parent's add method {@link navigation_node::add()} 4427 * and then proceeds to use the key to set class and hr 4428 * 4429 * @param string $text text to be used for the link. 4430 * @param string|moodle_url $url url for the new node 4431 * @param int $type the type of node navigation_node::TYPE_* 4432 * @param string $shorttext 4433 * @param string|int $key a key to access the node by. 4434 * @param pix_icon $icon An icon that appears next to the node. 4435 * @return navigation_node with the new node added to it. 4436 */ 4437 public function add($text, $url=null, $type=null, $shorttext=null, $key=null, pix_icon $icon=null) { 4438 $node = parent::add($text, $url, $type, $shorttext, $key, $icon); 4439 $node->add_class('root_node'); 4440 return $node; 4441 } 4442 4443 /** 4444 * This function allows the user to add something to the start of the settings 4445 * navigation, which means it will be at the top of the settings navigation block 4446 * 4447 * @param string $text text to be used for the link. 4448 * @param string|moodle_url $url url for the new node 4449 * @param int $type the type of node navigation_node::TYPE_* 4450 * @param string $shorttext 4451 * @param string|int $key a key to access the node by. 4452 * @param pix_icon $icon An icon that appears next to the node. 4453 * @return navigation_node $node with the new node added to it. 4454 */ 4455 public function prepend($text, $url=null, $type=null, $shorttext=null, $key=null, pix_icon $icon=null) { 4456 $children = $this->children; 4457 $childrenclass = get_class($children); 4458 $this->children = new $childrenclass; 4459 $node = $this->add($text, $url, $type, $shorttext, $key, $icon); 4460 foreach ($children as $child) { 4461 $this->children->add($child); 4462 } 4463 return $node; 4464 } 4465 4466 /** 4467 * Does this page require loading of full admin tree or is 4468 * it enough rely on AJAX? 4469 * 4470 * @return bool 4471 */ 4472 protected function is_admin_tree_needed() { 4473 if (self::$loadadmintree) { 4474 // Usually external admin page or settings page. 4475 return true; 4476 } 4477 4478 if ($this->page->pagelayout === 'admin' or strpos($this->page->pagetype, 'admin-') === 0) { 4479 // Admin settings tree is intended for system level settings and management only, use navigation for the rest! 4480 if ($this->page->context->contextlevel != CONTEXT_SYSTEM) { 4481 return false; 4482 } 4483 return true; 4484 } 4485 4486 return false; 4487 } 4488 4489 /** 4490 * Load the site administration tree 4491 * 4492 * This function loads the site administration tree by using the lib/adminlib library functions 4493 * 4494 * @param navigation_node $referencebranch A reference to a branch in the settings 4495 * navigation tree 4496 * @param part_of_admin_tree $adminbranch The branch to add, if null generate the admin 4497 * tree and start at the beginning 4498 * @return mixed A key to access the admin tree by 4499 */ 4500 protected function load_administration_settings(navigation_node $referencebranch=null, part_of_admin_tree $adminbranch=null) { 4501 global $CFG; 4502 4503 // Check if we are just starting to generate this navigation. 4504 if ($referencebranch === null) { 4505 4506 // Require the admin lib then get an admin structure 4507 if (!function_exists('admin_get_root')) { 4508 require_once($CFG->dirroot.'/lib/adminlib.php'); 4509 } 4510 $adminroot = admin_get_root(false, false); 4511 // This is the active section identifier 4512 $this->adminsection = $this->page->url->param('section'); 4513 4514 // Disable the navigation from automatically finding the active node 4515 navigation_node::$autofindactive = false; 4516 $referencebranch = $this->add(get_string('administrationsite'), '/admin/search.php', self::TYPE_SITE_ADMIN, null, 'root'); 4517 foreach ($adminroot->children as $adminbranch) { 4518 $this->load_administration_settings($referencebranch, $adminbranch); 4519 } 4520 navigation_node::$autofindactive = true; 4521 4522 // Use the admin structure to locate the active page 4523 if (!$this->contains_active_node() && $current = $adminroot->locate($this->adminsection, true)) { 4524 $currentnode = $this; 4525 while (($pathkey = array_pop($current->path))!==null && $currentnode) { 4526 $currentnode = $currentnode->get($pathkey); 4527 } 4528 if ($currentnode) { 4529 $currentnode->make_active(); 4530 } 4531 } else { 4532 $this->scan_for_active_node($referencebranch); 4533 } 4534 return $referencebranch; 4535 } else if ($adminbranch->check_access()) { 4536 // We have a reference branch that we can access and is not hidden `hurrah` 4537 // Now we need to display it and any children it may have 4538 $url = null; 4539 $icon = null; 4540 4541 if ($adminbranch instanceof \core_admin\local\settings\linkable_settings_page) { 4542 if (empty($CFG->linkadmincategories) && $adminbranch instanceof admin_category) { 4543 $url = null; 4544 } else { 4545 $url = $adminbranch->get_settings_page_url(); 4546 } 4547 } 4548 4549 // Add the branch 4550 $reference = $referencebranch->add($adminbranch->visiblename, $url, self::TYPE_SETTING, null, $adminbranch->name, $icon); 4551 4552 if ($adminbranch->is_hidden()) { 4553 if (($adminbranch instanceof admin_externalpage || $adminbranch instanceof admin_settingpage) && $adminbranch->name == $this->adminsection) { 4554 $reference->add_class('hidden'); 4555 } else { 4556 $reference->display = false; 4557 } 4558 } 4559 4560 // Check if we are generating the admin notifications and whether notificiations exist 4561 if ($adminbranch->name === 'adminnotifications' && admin_critical_warnings_present()) { 4562 $reference->add_class('criticalnotification'); 4563 } 4564 // Check if this branch has children 4565 if ($reference && isset($adminbranch->children) && is_array($adminbranch->children) && count($adminbranch->children)>0) { 4566 foreach ($adminbranch->children as $branch) { 4567 // Generate the child branches as well now using this branch as the reference 4568 $this->load_administration_settings($reference, $branch); 4569 } 4570 } else { 4571 $reference->icon = new pix_icon('i/settings', ''); 4572 } 4573 } 4574 } 4575 4576 /** 4577 * This function recursivily scans nodes until it finds the active node or there 4578 * are no more nodes. 4579 * @param navigation_node $node 4580 */ 4581 protected function scan_for_active_node(navigation_node $node) { 4582 if (!$node->check_if_active() && $node->children->count()>0) { 4583 foreach ($node->children as &$child) { 4584 $this->scan_for_active_node($child); 4585 } 4586 } 4587 } 4588 4589 /** 4590 * Gets a navigation node given an array of keys that represent the path to 4591 * the desired node. 4592 * 4593 * @param array $path 4594 * @return navigation_node|false 4595 */ 4596 protected function get_by_path(array $path) { 4597 $node = $this->get(array_shift($path)); 4598 foreach ($path as $key) { 4599 $node->get($key); 4600 } 4601 return $node; 4602 } 4603 4604 /** 4605 * This function loads the course settings that are available for the user 4606 * 4607 * @param bool $forceopen If set to true the course node will be forced open 4608 * @return navigation_node|false 4609 */ 4610 protected function load_course_settings($forceopen = false) { 4611 global $CFG, $USER; 4612 require_once($CFG->dirroot . '/course/lib.php'); 4613 4614 $course = $this->page->course; 4615 $coursecontext = context_course::instance($course->id); 4616 $adminoptions = course_get_user_administration_options($course, $coursecontext); 4617 4618 // note: do not test if enrolled or viewing here because we need the enrol link in Course administration section 4619 4620 $coursenode = $this->add(get_string('courseadministration'), null, self::TYPE_COURSE, null, 'courseadmin'); 4621 if ($forceopen) { 4622 $coursenode->force_open(); 4623 } 4624 4625 4626 if ($adminoptions->update) { 4627 // Add the course settings link 4628 $url = new moodle_url('/course/edit.php', array('id'=>$course->id)); 4629 $coursenode->add(get_string('settings'), $url, self::TYPE_SETTING, null, 4630 'editsettings', new pix_icon('i/settings', '')); 4631 } 4632 4633 if ($adminoptions->editcompletion) { 4634 // Add the course completion settings link 4635 $url = new moodle_url('/course/completion.php', array('id' => $course->id)); 4636 $coursenode->add(get_string('coursecompletion', 'completion'), $url, self::TYPE_SETTING, null, 'coursecompletion', 4637 new pix_icon('i/settings', '')); 4638 } 4639 4640 if (!$adminoptions->update && $adminoptions->tags) { 4641 $url = new moodle_url('/course/tags.php', array('id' => $course->id)); 4642 $coursenode->add(get_string('coursetags', 'tag'), $url, self::TYPE_SETTING, null, 'coursetags', new pix_icon('i/settings', '')); 4643 $coursenode->get('coursetags')->set_force_into_more_menu(); 4644 } 4645 4646 // add enrol nodes 4647 enrol_add_course_navigation($coursenode, $course); 4648 4649 // Manage filters 4650 if ($adminoptions->filters) { 4651 $url = new moodle_url('/filter/manage.php', array('contextid'=>$coursecontext->id)); 4652 $coursenode->add(get_string('filters', 'admin'), $url, self::TYPE_SETTING, 4653 null, 'filtermanagement', new pix_icon('i/filter', '')); 4654 } 4655 4656 // View course reports. 4657 if ($adminoptions->reports) { 4658 $reportnav = $coursenode->add(get_string('reports'), 4659 new moodle_url('/report/view.php', ['courseid' => $coursecontext->instanceid]), 4660 self::TYPE_CONTAINER, null, 'coursereports', new pix_icon('i/stats', '')); 4661 $coursereports = core_component::get_plugin_list('coursereport'); 4662 foreach ($coursereports as $report => $dir) { 4663 $libfile = $CFG->dirroot.'/course/report/'.$report.'/lib.php'; 4664 if (file_exists($libfile)) { 4665 require_once($libfile); 4666 $reportfunction = $report.'_report_extend_navigation'; 4667 if (function_exists($report.'_report_extend_navigation')) { 4668 $reportfunction($reportnav, $course, $coursecontext); 4669 } 4670 } 4671 } 4672 4673 $reports = get_plugin_list_with_function('report', 'extend_navigation_course', 'lib.php'); 4674 foreach ($reports as $reportfunction) { 4675 $reportfunction($reportnav, $course, $coursecontext); 4676 } 4677 4678 if (!$reportnav->has_children()) { 4679 $reportnav->remove(); 4680 } 4681 } 4682 4683 // Check if we can view the gradebook's setup page. 4684 if ($adminoptions->gradebook) { 4685 $url = new moodle_url('/grade/edit/tree/index.php', array('id' => $course->id)); 4686 $coursenode->add(get_string('gradebooksetup', 'grades'), $url, self::TYPE_SETTING, 4687 null, 'gradebooksetup', new pix_icon('i/settings', '')); 4688 } 4689 4690 // Add the context locking node. 4691 $this->add_context_locking_node($coursenode, $coursecontext); 4692 4693 // Add outcome if permitted 4694 if ($adminoptions->outcomes) { 4695 $url = new moodle_url('/grade/edit/outcome/course.php', array('id'=>$course->id)); 4696 $coursenode->add(get_string('outcomes', 'grades'), $url, self::TYPE_SETTING, null, 'outcomes', new pix_icon('i/outcomes', '')); 4697 } 4698 4699 //Add badges navigation 4700 if ($adminoptions->badges) { 4701 require_once($CFG->libdir .'/badgeslib.php'); 4702 badges_add_course_navigation($coursenode, $course); 4703 } 4704 4705 // Import data from other courses. 4706 if ($adminoptions->import) { 4707 $url = new moodle_url('/backup/import.php', array('id' => $course->id)); 4708 $coursenode->add(get_string('import'), $url, self::TYPE_SETTING, null, 'import', new pix_icon('i/import', '')); 4709 } 4710 4711 // Backup this course 4712 if ($adminoptions->backup) { 4713 $url = new moodle_url('/backup/backup.php', array('id'=>$course->id)); 4714 $coursenode->add(get_string('backup'), $url, self::TYPE_SETTING, null, 'backup', new pix_icon('i/backup', '')); 4715 } 4716 4717 // Restore to this course 4718 if ($adminoptions->restore) { 4719 $url = new moodle_url('/backup/restorefile.php', array('contextid'=>$coursecontext->id)); 4720 $coursenode->add(get_string('restore'), $url, self::TYPE_SETTING, null, 'restore', new pix_icon('i/restore', '')); 4721 } 4722 4723 // Copy this course. 4724 if ($adminoptions->copy) { 4725 $url = new moodle_url('/backup/copy.php', array('id' => $course->id)); 4726 $coursenode->add(get_string('copycourse'), $url, self::TYPE_SETTING, null, 'copy', new pix_icon('t/copy', '')); 4727 } 4728 4729 // Reset this course 4730 if ($adminoptions->reset) { 4731 $url = new moodle_url('/course/reset.php', array('id'=>$course->id)); 4732 $coursenode->add(get_string('reset'), $url, self::TYPE_SETTING, null, 'reset', new pix_icon('i/return', '')); 4733 } 4734 4735 // Questions 4736 require_once($CFG->libdir . '/questionlib.php'); 4737 question_extend_settings_navigation($coursenode, $coursecontext)->trim_if_empty(); 4738 4739 if ($adminoptions->update) { 4740 // Repository Instances 4741 if (!$this->cache->cached('contexthasrepos'.$coursecontext->id)) { 4742 require_once($CFG->dirroot . '/repository/lib.php'); 4743 $editabletypes = repository::get_editable_types($coursecontext); 4744 $haseditabletypes = !empty($editabletypes); 4745 unset($editabletypes); 4746 $this->cache->set('contexthasrepos'.$coursecontext->id, $haseditabletypes); 4747 } else { 4748 $haseditabletypes = $this->cache->{'contexthasrepos'.$coursecontext->id}; 4749 } 4750 if ($haseditabletypes) { 4751 $url = new moodle_url('/repository/manage_instances.php', array('contextid' => $coursecontext->id)); 4752 $coursenode->add(get_string('repositories'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/repository', '')); 4753 } 4754 } 4755 4756 // Manage files 4757 if ($adminoptions->files) { 4758 // hidden in new courses and courses where legacy files were turned off 4759 $url = new moodle_url('/files/index.php', array('contextid'=>$coursecontext->id)); 4760 $coursenode->add(get_string('courselegacyfiles'), $url, self::TYPE_SETTING, null, 'coursefiles', new pix_icon('i/folder', '')); 4761 4762 } 4763 4764 // Let plugins hook into course navigation. 4765 $pluginsfunction = get_plugins_with_function('extend_navigation_course', 'lib.php'); 4766 foreach ($pluginsfunction as $plugintype => $plugins) { 4767 // Ignore the report plugin as it was already loaded above. 4768 if ($plugintype == 'report') { 4769 continue; 4770 } 4771 foreach ($plugins as $pluginfunction) { 4772 $pluginfunction($coursenode, $course, $coursecontext); 4773 } 4774 } 4775 4776 // Prepare data for course content download functionality if it is enabled. 4777 if (\core\content::can_export_context($coursecontext, $USER)) { 4778 $linkattr = \core_course\output\content_export_link::get_attributes($coursecontext); 4779 $actionlink = new action_link($linkattr->url, $linkattr->displaystring, null, $linkattr->elementattributes); 4780 4781 $coursenode->add($linkattr->displaystring, $actionlink, self::TYPE_SETTING, null, 'download', 4782 new pix_icon('t/download', '')); 4783 $coursenode->get('download')->set_force_into_more_menu(true); 4784 } 4785 4786 // Return we are done 4787 return $coursenode; 4788 } 4789 4790 /** 4791 * Get the moodle_page object associated to the current settings navigation. 4792 * 4793 * @return moodle_page 4794 */ 4795 public function get_page(): moodle_page { 4796 return $this->page; 4797 } 4798 4799 /** 4800 * This function calls the module function to inject module settings into the 4801 * settings navigation tree. 4802 * 4803 * This only gets called if there is a corrosponding function in the modules 4804 * lib file. 4805 * 4806 * For examples mod/forum/lib.php {@link forum_extend_settings_navigation()} 4807 * 4808 * @return navigation_node|false 4809 */ 4810 protected function load_module_settings() { 4811 global $CFG; 4812 4813 if (!$this->page->cm && $this->context->contextlevel == CONTEXT_MODULE && $this->context->instanceid) { 4814 $cm = get_coursemodule_from_id(false, $this->context->instanceid, 0, false, MUST_EXIST); 4815 $this->page->set_cm($cm, $this->page->course); 4816 } 4817 4818 $file = $CFG->dirroot.'/mod/'.$this->page->activityname.'/lib.php'; 4819 if (file_exists($file)) { 4820 require_once($file); 4821 } 4822 4823 $modulenode = $this->add(get_string('pluginadministration', $this->page->activityname), null, self::TYPE_SETTING, null, 'modulesettings'); 4824 $modulenode->nodetype = navigation_node::NODETYPE_BRANCH; 4825 $modulenode->force_open(); 4826 4827 // Settings for the module 4828 if (has_capability('moodle/course:manageactivities', $this->page->cm->context)) { 4829 $url = new moodle_url('/course/modedit.php', array('update' => $this->page->cm->id, 'return' => 1)); 4830 $modulenode->add(get_string('settings'), $url, self::TYPE_SETTING, null, 'modedit', new pix_icon('i/settings', '')); 4831 } 4832 // Assign local roles 4833 if (count(get_assignable_roles($this->page->cm->context))>0) { 4834 $url = new moodle_url('/'.$CFG->admin.'/roles/assign.php', array('contextid'=>$this->page->cm->context->id)); 4835 $modulenode->add(get_string('localroles', 'role'), $url, self::TYPE_SETTING, null, 'roleassign', 4836 new pix_icon('i/role', '')); 4837 } 4838 // Override roles 4839 if (has_capability('moodle/role:review', $this->page->cm->context) or count(get_overridable_roles($this->page->cm->context))>0) { 4840 $url = new moodle_url('/'.$CFG->admin.'/roles/permissions.php', array('contextid'=>$this->page->cm->context->id)); 4841 $modulenode->add(get_string('permissions', 'role'), $url, self::TYPE_SETTING, null, 'roleoverride', 4842 new pix_icon('i/permissions', '')); 4843 } 4844 // Check role permissions 4845 if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride','moodle/role:override', 'moodle/role:assign'), $this->page->cm->context)) { 4846 $url = new moodle_url('/'.$CFG->admin.'/roles/check.php', array('contextid'=>$this->page->cm->context->id)); 4847 $modulenode->add(get_string('checkpermissions', 'role'), $url, self::TYPE_SETTING, null, 'rolecheck', 4848 new pix_icon('i/checkpermissions', '')); 4849 } 4850 4851 // Add the context locking node. 4852 $this->add_context_locking_node($modulenode, $this->page->cm->context); 4853 4854 // Manage filters 4855 if (has_capability('moodle/filter:manage', $this->page->cm->context) && count(filter_get_available_in_context($this->page->cm->context))>0) { 4856 $url = new moodle_url('/filter/manage.php', array('contextid'=>$this->page->cm->context->id)); 4857 $modulenode->add(get_string('filters', 'admin'), $url, self::TYPE_SETTING, null, 'filtermanage', 4858 new pix_icon('i/filter', '')); 4859 } 4860 // Add reports 4861 $reports = get_plugin_list_with_function('report', 'extend_navigation_module', 'lib.php'); 4862 foreach ($reports as $reportfunction) { 4863 $reportfunction($modulenode, $this->page->cm); 4864 } 4865 // Add a backup link 4866 $featuresfunc = $this->page->activityname.'_supports'; 4867 if (function_exists($featuresfunc) && $featuresfunc(FEATURE_BACKUP_MOODLE2) && has_capability('moodle/backup:backupactivity', $this->page->cm->context)) { 4868 $url = new moodle_url('/backup/backup.php', array('id'=>$this->page->cm->course, 'cm'=>$this->page->cm->id)); 4869 $modulenode->add(get_string('backup'), $url, self::TYPE_SETTING, null, 'backup', new pix_icon('i/backup', '')); 4870 } 4871 4872 // Restore this activity 4873 $featuresfunc = $this->page->activityname.'_supports'; 4874 if (function_exists($featuresfunc) && $featuresfunc(FEATURE_BACKUP_MOODLE2) && has_capability('moodle/restore:restoreactivity', $this->page->cm->context)) { 4875 $url = new moodle_url('/backup/restorefile.php', array('contextid'=>$this->page->cm->context->id)); 4876 $modulenode->add(get_string('restore'), $url, self::TYPE_SETTING, null, 'restore', new pix_icon('i/restore', '')); 4877 } 4878 4879 // Allow the active advanced grading method plugin to append its settings 4880 $featuresfunc = $this->page->activityname.'_supports'; 4881 if (function_exists($featuresfunc) && $featuresfunc(FEATURE_ADVANCED_GRADING) && has_capability('moodle/grade:managegradingforms', $this->page->cm->context)) { 4882 require_once($CFG->dirroot.'/grade/grading/lib.php'); 4883 $gradingman = get_grading_manager($this->page->cm->context, 'mod_'.$this->page->activityname); 4884 $gradingman->extend_settings_navigation($this, $modulenode); 4885 } 4886 4887 $function = $this->page->activityname.'_extend_settings_navigation'; 4888 if (function_exists($function)) { 4889 $function($this, $modulenode); 4890 } 4891 4892 // Remove the module node if there are no children. 4893 if ($modulenode->children->count() <= 0) { 4894 $modulenode->remove(); 4895 } 4896 4897 return $modulenode; 4898 } 4899 4900 /** 4901 * Loads the user settings block of the settings nav 4902 * 4903 * This function is simply works out the userid and whether we need to load 4904 * just the current users profile settings, or the current user and the user the 4905 * current user is viewing. 4906 * 4907 * This function has some very ugly code to work out the user, if anyone has 4908 * any bright ideas please feel free to intervene. 4909 * 4910 * @param int $courseid The course id of the current course 4911 * @return navigation_node|false 4912 */ 4913 protected function load_user_settings($courseid = SITEID) { 4914 global $USER, $CFG; 4915 4916 if (isguestuser() || !isloggedin()) { 4917 return false; 4918 } 4919 4920 $navusers = $this->page->navigation->get_extending_users(); 4921 4922 if (count($this->userstoextendfor) > 0 || count($navusers) > 0) { 4923 $usernode = null; 4924 foreach ($this->userstoextendfor as $userid) { 4925 if ($userid == $USER->id) { 4926 continue; 4927 } 4928 $node = $this->generate_user_settings($courseid, $userid, 'userviewingsettings'); 4929 if (is_null($usernode)) { 4930 $usernode = $node; 4931 } 4932 } 4933 foreach ($navusers as $user) { 4934 if ($user->id == $USER->id) { 4935 continue; 4936 } 4937 $node = $this->generate_user_settings($courseid, $user->id, 'userviewingsettings'); 4938 if (is_null($usernode)) { 4939 $usernode = $node; 4940 } 4941 } 4942 $this->generate_user_settings($courseid, $USER->id); 4943 } else { 4944 $usernode = $this->generate_user_settings($courseid, $USER->id); 4945 } 4946 return $usernode; 4947 } 4948 4949 /** 4950 * Extends the settings navigation for the given user. 4951 * 4952 * Note: This method gets called automatically if you call 4953 * $PAGE->navigation->extend_for_user($userid) 4954 * 4955 * @param int $userid 4956 */ 4957 public function extend_for_user($userid) { 4958 global $CFG; 4959 4960 if (!in_array($userid, $this->userstoextendfor)) { 4961 $this->userstoextendfor[] = $userid; 4962 if ($this->initialised) { 4963 $this->generate_user_settings($this->page->course->id, $userid, 'userviewingsettings'); 4964 $children = array(); 4965 foreach ($this->children as $child) { 4966 $children[] = $child; 4967 } 4968 array_unshift($children, array_pop($children)); 4969 $this->children = new navigation_node_collection(); 4970 foreach ($children as $child) { 4971 $this->children->add($child); 4972 } 4973 } 4974 } 4975 } 4976 4977 /** 4978 * This function gets called by {@link settings_navigation::load_user_settings()} and actually works out 4979 * what can be shown/done 4980 * 4981 * @param int $courseid The current course' id 4982 * @param int $userid The user id to load for 4983 * @param string $gstitle The string to pass to get_string for the branch title 4984 * @return navigation_node|false 4985 */ 4986 protected function generate_user_settings($courseid, $userid, $gstitle='usercurrentsettings') { 4987 global $DB, $CFG, $USER, $SITE; 4988 4989 if ($courseid != $SITE->id) { 4990 if (!empty($this->page->course->id) && $this->page->course->id == $courseid) { 4991 $course = $this->page->course; 4992 } else { 4993 $select = context_helper::get_preload_record_columns_sql('ctx'); 4994 $sql = "SELECT c.*, $select 4995 FROM {course} c 4996 JOIN {context} ctx ON c.id = ctx.instanceid 4997 WHERE c.id = :courseid AND ctx.contextlevel = :contextlevel"; 4998 $params = array('courseid' => $courseid, 'contextlevel' => CONTEXT_COURSE); 4999 $course = $DB->get_record_sql($sql, $params, MUST_EXIST); 5000 context_helper::preload_from_record($course); 5001 } 5002 } else { 5003 $course = $SITE; 5004 } 5005 5006 $coursecontext = context_course::instance($course->id); // Course context 5007 $systemcontext = context_system::instance(); 5008 $currentuser = ($USER->id == $userid); 5009 5010 if ($currentuser) { 5011 $user = $USER; 5012 $usercontext = context_user::instance($user->id); // User context 5013 } else { 5014 $select = context_helper::get_preload_record_columns_sql('ctx'); 5015 $sql = "SELECT u.*, $select 5016 FROM {user} u 5017 JOIN {context} ctx ON u.id = ctx.instanceid 5018 WHERE u.id = :userid AND ctx.contextlevel = :contextlevel"; 5019 $params = array('userid' => $userid, 'contextlevel' => CONTEXT_USER); 5020 $user = $DB->get_record_sql($sql, $params, IGNORE_MISSING); 5021 if (!$user) { 5022 return false; 5023 } 5024 context_helper::preload_from_record($user); 5025 5026 // Check that the user can view the profile 5027 $usercontext = context_user::instance($user->id); // User context 5028 $canviewuser = has_capability('moodle/user:viewdetails', $usercontext); 5029 5030 if ($course->id == $SITE->id) { 5031 if ($CFG->forceloginforprofiles && !has_coursecontact_role($user->id) && !$canviewuser) { // Reduce possibility of "browsing" userbase at site level 5032 // Teachers can browse and be browsed at site level. If not forceloginforprofiles, allow access (bug #4366) 5033 return false; 5034 } 5035 } else { 5036 $canviewusercourse = has_capability('moodle/user:viewdetails', $coursecontext); 5037 $userisenrolled = is_enrolled($coursecontext, $user->id, '', true); 5038 if ((!$canviewusercourse && !$canviewuser) || !$userisenrolled) { 5039 return false; 5040 } 5041 $canaccessallgroups = has_capability('moodle/site:accessallgroups', $coursecontext); 5042 if (!$canaccessallgroups && groups_get_course_groupmode($course) == SEPARATEGROUPS && !$canviewuser) { 5043 // If groups are in use, make sure we can see that group (MDL-45874). That does not apply to parents. 5044 if ($courseid == $this->page->course->id) { 5045 $mygroups = get_fast_modinfo($this->page->course)->groups; 5046 } else { 5047 $mygroups = groups_get_user_groups($courseid); 5048 } 5049 $usergroups = groups_get_user_groups($courseid, $userid); 5050 if (!array_intersect_key($mygroups[0], $usergroups[0])) { 5051 return false; 5052 } 5053 } 5054 } 5055 } 5056 5057 $fullname = fullname($user, has_capability('moodle/site:viewfullnames', $this->page->context)); 5058 5059 $key = $gstitle; 5060 $prefurl = new moodle_url('/user/preferences.php'); 5061 if ($gstitle != 'usercurrentsettings') { 5062 $key .= $userid; 5063 $prefurl->param('userid', $userid); 5064 } 5065 5066 // Add a user setting branch. 5067 if ($gstitle == 'usercurrentsettings') { 5068 $mainpage = $this->add(get_string('home'), new moodle_url('/'), self::TYPE_CONTAINER, null, 'site'); 5069 5070 // This should be set to false as we don't want to show this to the user. It's only for generating the correct 5071 // breadcrumb. 5072 $mainpage->display = false; 5073 $homepage = get_home_page(); 5074 if (($homepage == HOMEPAGE_MY || $homepage == HOMEPAGE_MYCOURSES)) { 5075 $mainpage->mainnavonly = true; 5076 } 5077 5078 $iscurrentuser = ($user->id == $USER->id); 5079 5080 $baseargs = array('id' => $user->id); 5081 if ($course->id != $SITE->id && !$iscurrentuser) { 5082 $baseargs['course'] = $course->id; 5083 $issitecourse = false; 5084 } else { 5085 // Load all categories and get the context for the system. 5086 $issitecourse = true; 5087 } 5088 5089 // Add the user profile to the dashboard. 5090 $profilenode = $mainpage->add(get_string('profile'), new moodle_url('/user/profile.php', 5091 array('id' => $user->id)), self::TYPE_SETTING, null, 'myprofile'); 5092 5093 if (!empty($CFG->navadduserpostslinks)) { 5094 // Add nodes for forum posts and discussions if the user can view either or both 5095 // There are no capability checks here as the content of the page is based 5096 // purely on the forums the current user has access too. 5097 $forumtab = $profilenode->add(get_string('forumposts', 'forum')); 5098 $forumtab->add(get_string('posts', 'forum'), new moodle_url('/mod/forum/user.php', $baseargs), null, 'myposts'); 5099 $forumtab->add(get_string('discussions', 'forum'), new moodle_url('/mod/forum/user.php', 5100 array_merge($baseargs, array('mode' => 'discussions'))), null, 'mydiscussions'); 5101 } 5102 5103 // Add blog nodes. 5104 if (!empty($CFG->enableblogs)) { 5105 if (!$this->cache->cached('userblogoptions'.$user->id)) { 5106 require_once($CFG->dirroot.'/blog/lib.php'); 5107 // Get all options for the user. 5108 $options = blog_get_options_for_user($user); 5109 $this->cache->set('userblogoptions'.$user->id, $options); 5110 } else { 5111 $options = $this->cache->{'userblogoptions'.$user->id}; 5112 } 5113 5114 if (count($options) > 0) { 5115 $blogs = $profilenode->add(get_string('blogs', 'blog'), null, navigation_node::TYPE_CONTAINER); 5116 foreach ($options as $type => $option) { 5117 if ($type == "rss") { 5118 $blogs->add($option['string'], $option['link'], self::TYPE_SETTING, null, null, 5119 new pix_icon('i/rss', '')); 5120 } else { 5121 $blogs->add($option['string'], $option['link'], self::TYPE_SETTING, null, 'blog' . $type); 5122 } 5123 } 5124 } 5125 } 5126 5127 // Add the messages link. 5128 // It is context based so can appear in the user's profile and in course participants information. 5129 if (!empty($CFG->messaging)) { 5130 $messageargs = array('user1' => $USER->id); 5131 if ($USER->id != $user->id) { 5132 $messageargs['user2'] = $user->id; 5133 } 5134 $url = new moodle_url('/message/index.php', $messageargs); 5135 $mainpage->add(get_string('messages', 'message'), $url, self::TYPE_SETTING, null, 'messages'); 5136 } 5137 5138 // Add the "My private files" link. 5139 // This link doesn't have a unique display for course context so only display it under the user's profile. 5140 if ($issitecourse && $iscurrentuser && has_capability('moodle/user:manageownfiles', $usercontext)) { 5141 $url = new moodle_url('/user/files.php'); 5142 $mainpage->add(get_string('privatefiles'), $url, self::TYPE_SETTING, null, 'privatefiles'); 5143 } 5144 5145 // Add a node to view the users notes if permitted. 5146 if (!empty($CFG->enablenotes) && 5147 has_any_capability(array('moodle/notes:manage', 'moodle/notes:view'), $coursecontext)) { 5148 $url = new moodle_url('/notes/index.php', array('user' => $user->id)); 5149 if ($coursecontext->instanceid != SITEID) { 5150 $url->param('course', $coursecontext->instanceid); 5151 } 5152 $profilenode->add(get_string('notes', 'notes'), $url); 5153 } 5154 5155 // Show the grades node. 5156 if (($issitecourse && $iscurrentuser) || has_capability('moodle/user:viewdetails', $usercontext)) { 5157 require_once($CFG->dirroot . '/user/lib.php'); 5158 // Set the grades node to link to the "Grades" page. 5159 if ($course->id == SITEID) { 5160 $url = user_mygrades_url($user->id, $course->id); 5161 } else { // Otherwise we are in a course and should redirect to the user grade report (Activity report version). 5162 $url = new moodle_url('/course/user.php', array('mode' => 'grade', 'id' => $course->id, 'user' => $user->id)); 5163 } 5164 $mainpage->add(get_string('grades', 'grades'), $url, self::TYPE_SETTING, null, 'mygrades'); 5165 } 5166 5167 // Let plugins hook into user navigation. 5168 $pluginsfunction = get_plugins_with_function('extend_navigation_user', 'lib.php'); 5169 foreach ($pluginsfunction as $plugintype => $plugins) { 5170 if ($plugintype != 'report') { 5171 foreach ($plugins as $pluginfunction) { 5172 $pluginfunction($profilenode, $user, $usercontext, $course, $coursecontext); 5173 } 5174 } 5175 } 5176 5177 $usersetting = navigation_node::create(get_string('preferences', 'moodle'), $prefurl, self::TYPE_CONTAINER, null, $key); 5178 $mainpage->add_node($usersetting); 5179 } else { 5180 $usersetting = $this->add(get_string('preferences', 'moodle'), $prefurl, self::TYPE_CONTAINER, null, $key); 5181 $usersetting->display = false; 5182 } 5183 $usersetting->id = 'usersettings'; 5184 5185 // Check if the user has been deleted. 5186 if ($user->deleted) { 5187 if (!has_capability('moodle/user:update', $coursecontext)) { 5188 // We can't edit the user so just show the user deleted message. 5189 $usersetting->add(get_string('userdeleted'), null, self::TYPE_SETTING); 5190 } else { 5191 // We can edit the user so show the user deleted message and link it to the profile. 5192 if ($course->id == $SITE->id) { 5193 $profileurl = new moodle_url('/user/profile.php', array('id'=>$user->id)); 5194 } else { 5195 $profileurl = new moodle_url('/user/view.php', array('id'=>$user->id, 'course'=>$course->id)); 5196 } 5197 $usersetting->add(get_string('userdeleted'), $profileurl, self::TYPE_SETTING); 5198 } 5199 return true; 5200 } 5201 5202 $userauthplugin = false; 5203 if (!empty($user->auth)) { 5204 $userauthplugin = get_auth_plugin($user->auth); 5205 } 5206 5207 $useraccount = $usersetting->add(get_string('useraccount'), null, self::TYPE_CONTAINER, null, 'useraccount'); 5208 5209 // Add the profile edit link. 5210 if (isloggedin() && !isguestuser($user) && !is_mnet_remote_user($user)) { 5211 if (($currentuser || is_siteadmin($USER) || !is_siteadmin($user)) && 5212 has_capability('moodle/user:update', $systemcontext)) { 5213 $url = new moodle_url('/user/editadvanced.php', array('id'=>$user->id, 'course'=>$course->id)); 5214 $useraccount->add(get_string('editmyprofile'), $url, self::TYPE_SETTING, null, 'editprofile'); 5215 } else if ((has_capability('moodle/user:editprofile', $usercontext) && !is_siteadmin($user)) || 5216 ($currentuser && has_capability('moodle/user:editownprofile', $systemcontext))) { 5217 if ($userauthplugin && $userauthplugin->can_edit_profile()) { 5218 $url = $userauthplugin->edit_profile_url(); 5219 if (empty($url)) { 5220 $url = new moodle_url('/user/edit.php', array('id'=>$user->id, 'course'=>$course->id)); 5221 } 5222 $useraccount->add(get_string('editmyprofile'), $url, self::TYPE_SETTING, null, 'editprofile'); 5223 } 5224 } 5225 } 5226 5227 // Change password link. 5228 if ($userauthplugin && $currentuser && !\core\session\manager::is_loggedinas() && !isguestuser() && 5229 has_capability('moodle/user:changeownpassword', $systemcontext) && $userauthplugin->can_change_password()) { 5230 $passwordchangeurl = $userauthplugin->change_password_url(); 5231 if (empty($passwordchangeurl)) { 5232 $passwordchangeurl = new moodle_url('/login/change_password.php', array('id'=>$course->id)); 5233 } 5234 $useraccount->add(get_string("changepassword"), $passwordchangeurl, self::TYPE_SETTING, null, 'changepassword'); 5235 } 5236 5237 // Default homepage. 5238 $defaulthomepageuser = (!empty($CFG->defaulthomepage) && ($CFG->defaulthomepage == HOMEPAGE_USER)); 5239 if (isloggedin() && !isguestuser($user) && $defaulthomepageuser) { 5240 if ($currentuser && has_capability('moodle/user:editownprofile', $systemcontext) || 5241 has_capability('moodle/user:editprofile', $usercontext)) { 5242 $url = new moodle_url('/user/defaulthomepage.php', ['id' => $user->id]); 5243 $useraccount->add(get_string('defaulthomepageuser'), $url, self::TYPE_SETTING, null, 'defaulthomepageuser'); 5244 } 5245 } 5246 5247 if (isloggedin() && !isguestuser($user) && !is_mnet_remote_user($user)) { 5248 if ($currentuser && has_capability('moodle/user:editownprofile', $systemcontext) || 5249 has_capability('moodle/user:editprofile', $usercontext)) { 5250 $url = new moodle_url('/user/language.php', array('id' => $user->id, 'course' => $course->id)); 5251 $useraccount->add(get_string('preferredlanguage'), $url, self::TYPE_SETTING, null, 'preferredlanguage'); 5252 } 5253 } 5254 $pluginmanager = core_plugin_manager::instance(); 5255 $enabled = $pluginmanager->get_enabled_plugins('mod'); 5256 if (isset($enabled['forum']) && isloggedin() && !isguestuser($user) && !is_mnet_remote_user($user)) { 5257 if ($currentuser && has_capability('moodle/user:editownprofile', $systemcontext) || 5258 has_capability('moodle/user:editprofile', $usercontext)) { 5259 $url = new moodle_url('/user/forum.php', array('id' => $user->id, 'course' => $course->id)); 5260 $useraccount->add(get_string('forumpreferences'), $url, self::TYPE_SETTING); 5261 } 5262 } 5263 $editors = editors_get_enabled(); 5264 if (count($editors) > 1) { 5265 if (isloggedin() && !isguestuser($user) && !is_mnet_remote_user($user)) { 5266 if ($currentuser && has_capability('moodle/user:editownprofile', $systemcontext) || 5267 has_capability('moodle/user:editprofile', $usercontext)) { 5268 $url = new moodle_url('/user/editor.php', array('id' => $user->id, 'course' => $course->id)); 5269 $useraccount->add(get_string('editorpreferences'), $url, self::TYPE_SETTING); 5270 } 5271 } 5272 } 5273 5274 // Add "Calendar preferences" link. 5275 if (isloggedin() && !isguestuser($user)) { 5276 if ($currentuser && has_capability('moodle/user:editownprofile', $systemcontext) || 5277 has_capability('moodle/user:editprofile', $usercontext)) { 5278 $url = new moodle_url('/user/calendar.php', array('id' => $user->id)); 5279 $useraccount->add(get_string('calendarpreferences', 'calendar'), $url, self::TYPE_SETTING, null, 'preferredcalendar'); 5280 } 5281 } 5282 5283 // Add "Content bank preferences" link. 5284 if (isloggedin() && !isguestuser($user)) { 5285 if ($currentuser && has_capability('moodle/user:editownprofile', $systemcontext) || 5286 has_capability('moodle/user:editprofile', $usercontext)) { 5287 $url = new moodle_url('/user/contentbank.php', ['id' => $user->id]); 5288 $useraccount->add(get_string('contentbankpreferences', 'core_contentbank'), $url, self::TYPE_SETTING, 5289 null, 'contentbankpreferences'); 5290 } 5291 } 5292 5293 // View the roles settings. 5294 if (has_any_capability(['moodle/role:assign', 'moodle/role:safeoverride', 'moodle/role:override', 5295 'moodle/role:manage'], $usercontext)) { 5296 $roles = $usersetting->add(get_string('roles'), null, self::TYPE_SETTING); 5297 5298 $url = new moodle_url('/admin/roles/usersroles.php', ['userid' => $user->id, 'courseid' => $course->id]); 5299 $roles->add(get_string('thisusersroles', 'role'), $url, self::TYPE_SETTING); 5300 5301 $assignableroles = get_assignable_roles($usercontext, ROLENAME_BOTH); 5302 5303 if (!empty($assignableroles)) { 5304 $url = new moodle_url('/admin/roles/assign.php', 5305 array('contextid' => $usercontext->id, 'userid' => $user->id, 'courseid' => $course->id)); 5306 $roles->add(get_string('assignrolesrelativetothisuser', 'role'), $url, self::TYPE_SETTING); 5307 } 5308 5309 if (has_capability('moodle/role:review', $usercontext) || count(get_overridable_roles($usercontext, ROLENAME_BOTH))>0) { 5310 $url = new moodle_url('/admin/roles/permissions.php', 5311 array('contextid' => $usercontext->id, 'userid' => $user->id, 'courseid' => $course->id)); 5312 $roles->add(get_string('permissions', 'role'), $url, self::TYPE_SETTING); 5313 } 5314 5315 $url = new moodle_url('/admin/roles/check.php', 5316 array('contextid' => $usercontext->id, 'userid' => $user->id, 'courseid' => $course->id)); 5317 $roles->add(get_string('checkpermissions', 'role'), $url, self::TYPE_SETTING); 5318 } 5319 5320 // Repositories. 5321 if (!$this->cache->cached('contexthasrepos'.$usercontext->id)) { 5322 require_once($CFG->dirroot . '/repository/lib.php'); 5323 $editabletypes = repository::get_editable_types($usercontext); 5324 $haseditabletypes = !empty($editabletypes); 5325 unset($editabletypes); 5326 $this->cache->set('contexthasrepos'.$usercontext->id, $haseditabletypes); 5327 } else { 5328 $haseditabletypes = $this->cache->{'contexthasrepos'.$usercontext->id}; 5329 } 5330 if ($haseditabletypes) { 5331 $repositories = $usersetting->add(get_string('repositories', 'repository'), null, self::TYPE_SETTING); 5332 $repositories->add(get_string('manageinstances', 'repository'), new moodle_url('/repository/manage_instances.php', 5333 array('contextid' => $usercontext->id))); 5334 } 5335 5336 // Portfolio. 5337 if ($currentuser && !empty($CFG->enableportfolios) && has_capability('moodle/portfolio:export', $systemcontext)) { 5338 require_once($CFG->libdir . '/portfoliolib.php'); 5339 if (portfolio_has_visible_instances()) { 5340 $portfolio = $usersetting->add(get_string('portfolios', 'portfolio'), null, self::TYPE_SETTING); 5341 5342 $url = new moodle_url('/user/portfolio.php', array('courseid'=>$course->id)); 5343 $portfolio->add(get_string('configure', 'portfolio'), $url, self::TYPE_SETTING); 5344 5345 $url = new moodle_url('/user/portfoliologs.php', array('courseid'=>$course->id)); 5346 $portfolio->add(get_string('logs', 'portfolio'), $url, self::TYPE_SETTING); 5347 } 5348 } 5349 5350 $enablemanagetokens = false; 5351 if (!empty($CFG->enablerssfeeds)) { 5352 $enablemanagetokens = true; 5353 } else if (!is_siteadmin($USER->id) 5354 && !empty($CFG->enablewebservices) 5355 && has_capability('moodle/webservice:createtoken', context_system::instance()) ) { 5356 $enablemanagetokens = true; 5357 } 5358 // Security keys. 5359 if ($currentuser && $enablemanagetokens) { 5360 $url = new moodle_url('/user/managetoken.php'); 5361 $useraccount->add(get_string('securitykeys', 'webservice'), $url, self::TYPE_SETTING); 5362 } 5363 5364 // Messaging. 5365 if (($currentuser && has_capability('moodle/user:editownmessageprofile', $systemcontext)) || (!isguestuser($user) && 5366 has_capability('moodle/user:editmessageprofile', $usercontext) && !is_primary_admin($user->id))) { 5367 $messagingurl = new moodle_url('/message/edit.php', array('id' => $user->id)); 5368 $notificationsurl = new moodle_url('/message/notificationpreferences.php', array('userid' => $user->id)); 5369 $useraccount->add(get_string('messagepreferences', 'message'), $messagingurl, self::TYPE_SETTING); 5370 $useraccount->add(get_string('notificationpreferences', 'message'), $notificationsurl, self::TYPE_SETTING); 5371 } 5372 5373 // Blogs. 5374 if ($currentuser && !empty($CFG->enableblogs)) { 5375 $blog = $usersetting->add(get_string('blogs', 'blog'), null, navigation_node::TYPE_CONTAINER, null, 'blogs'); 5376 if (has_capability('moodle/blog:view', $systemcontext)) { 5377 $blog->add(get_string('preferences', 'blog'), new moodle_url('/blog/preferences.php'), 5378 navigation_node::TYPE_SETTING); 5379 } 5380 if (!empty($CFG->useexternalblogs) && $CFG->maxexternalblogsperuser > 0 && 5381 has_capability('moodle/blog:manageexternal', $systemcontext)) { 5382 $blog->add(get_string('externalblogs', 'blog'), new moodle_url('/blog/external_blogs.php'), 5383 navigation_node::TYPE_SETTING); 5384 $blog->add(get_string('addnewexternalblog', 'blog'), new moodle_url('/blog/external_blog_edit.php'), 5385 navigation_node::TYPE_SETTING); 5386 } 5387 // Remove the blog node if empty. 5388 $blog->trim_if_empty(); 5389 } 5390 5391 // Badges. 5392 if ($currentuser && !empty($CFG->enablebadges)) { 5393 $badges = $usersetting->add(get_string('badges'), null, navigation_node::TYPE_CONTAINER, null, 'badges'); 5394 if (has_capability('moodle/badges:manageownbadges', $usercontext)) { 5395 $url = new moodle_url('/badges/mybadges.php'); 5396 $badges->add(get_string('managebadges', 'badges'), $url, self::TYPE_SETTING); 5397 } 5398 $badges->add(get_string('preferences', 'badges'), new moodle_url('/badges/preferences.php'), 5399 navigation_node::TYPE_SETTING); 5400 if (!empty($CFG->badges_allowexternalbackpack)) { 5401 $badges->add(get_string('backpackdetails', 'badges'), new moodle_url('/badges/mybackpack.php'), 5402 navigation_node::TYPE_SETTING); 5403 } 5404 } 5405 5406 // Let plugins hook into user settings navigation. 5407 $pluginsfunction = get_plugins_with_function('extend_navigation_user_settings', 'lib.php'); 5408 foreach ($pluginsfunction as $plugintype => $plugins) { 5409 foreach ($plugins as $pluginfunction) { 5410 $pluginfunction($usersetting, $user, $usercontext, $course, $coursecontext); 5411 } 5412 } 5413 5414 return $usersetting; 5415 } 5416 5417 /** 5418 * Loads block specific settings in the navigation 5419 * 5420 * @return navigation_node 5421 */ 5422 protected function load_block_settings() { 5423 global $CFG; 5424 5425 $blocknode = $this->add($this->context->get_context_name(), null, self::TYPE_SETTING, null, 'blocksettings'); 5426 $blocknode->force_open(); 5427 5428 // Assign local roles 5429 if (get_assignable_roles($this->context, ROLENAME_ORIGINAL)) { 5430 $assignurl = new moodle_url('/'.$CFG->admin.'/roles/assign.php', array('contextid' => $this->context->id)); 5431 $blocknode->add(get_string('assignroles', 'role'), $assignurl, self::TYPE_SETTING, null, 5432 'roles', new pix_icon('i/assignroles', '')); 5433 } 5434 5435 // Override roles 5436 if (has_capability('moodle/role:review', $this->context) or count(get_overridable_roles($this->context))>0) { 5437 $url = new moodle_url('/'.$CFG->admin.'/roles/permissions.php', array('contextid'=>$this->context->id)); 5438 $blocknode->add(get_string('permissions', 'role'), $url, self::TYPE_SETTING, null, 5439 'permissions', new pix_icon('i/permissions', '')); 5440 } 5441 // Check role permissions 5442 if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride','moodle/role:override', 'moodle/role:assign'), $this->context)) { 5443 $url = new moodle_url('/'.$CFG->admin.'/roles/check.php', array('contextid'=>$this->context->id)); 5444 $blocknode->add(get_string('checkpermissions', 'role'), $url, self::TYPE_SETTING, null, 5445 'checkpermissions', new pix_icon('i/checkpermissions', '')); 5446 } 5447 5448 // Add the context locking node. 5449 $this->add_context_locking_node($blocknode, $this->context); 5450 5451 return $blocknode; 5452 } 5453 5454 /** 5455 * Loads category specific settings in the navigation 5456 * 5457 * @return navigation_node 5458 */ 5459 protected function load_category_settings() { 5460 global $CFG; 5461 5462 // We can land here while being in the context of a block, in which case we 5463 // should get the parent context which should be the category one. See self::initialise(). 5464 if ($this->context->contextlevel == CONTEXT_BLOCK) { 5465 $catcontext = $this->context->get_parent_context(); 5466 } else { 5467 $catcontext = $this->context; 5468 } 5469 5470 // Let's make sure that we always have the right context when getting here. 5471 if ($catcontext->contextlevel != CONTEXT_COURSECAT) { 5472 throw new coding_exception('Unexpected context while loading category settings.'); 5473 } 5474 5475 $categorynodetype = navigation_node::TYPE_CONTAINER; 5476 $categorynode = $this->add($catcontext->get_context_name(), null, $categorynodetype, null, 'categorysettings'); 5477 $categorynode->nodetype = navigation_node::NODETYPE_BRANCH; 5478 $categorynode->force_open(); 5479 5480 if (can_edit_in_category($catcontext->instanceid)) { 5481 $url = new moodle_url('/course/management.php', array('categoryid' => $catcontext->instanceid)); 5482 $editstring = get_string('managecategorythis'); 5483 $node = $categorynode->add($editstring, $url, self::TYPE_SETTING, null, 'managecategory', new pix_icon('i/edit', '')); 5484 $node->set_show_in_secondary_navigation(false); 5485 } 5486 5487 if (has_capability('moodle/category:manage', $catcontext)) { 5488 $editurl = new moodle_url('/course/editcategory.php', array('id' => $catcontext->instanceid)); 5489 $categorynode->add(get_string('settings'), $editurl, self::TYPE_SETTING, null, 'edit', new pix_icon('i/edit', '')); 5490 5491 $addsubcaturl = new moodle_url('/course/editcategory.php', array('parent' => $catcontext->instanceid)); 5492 $categorynode->add(get_string('addsubcategory'), $addsubcaturl, self::TYPE_SETTING, null, 5493 'addsubcat', new pix_icon('i/withsubcat', ''))->set_show_in_secondary_navigation(false); 5494 } 5495 5496 // Assign local roles 5497 $assignableroles = get_assignable_roles($catcontext); 5498 if (!empty($assignableroles)) { 5499 $assignurl = new moodle_url('/'.$CFG->admin.'/roles/assign.php', array('contextid' => $catcontext->id)); 5500 $categorynode->add(get_string('assignroles', 'role'), $assignurl, self::TYPE_SETTING, null, 'roles', new pix_icon('i/assignroles', '')); 5501 } 5502 5503 // Override roles 5504 if (has_capability('moodle/role:review', $catcontext) or count(get_overridable_roles($catcontext)) > 0) { 5505 $url = new moodle_url('/'.$CFG->admin.'/roles/permissions.php', array('contextid' => $catcontext->id)); 5506 $categorynode->add(get_string('permissions', 'role'), $url, self::TYPE_SETTING, null, 'permissions', new pix_icon('i/permissions', '')); 5507 } 5508 // Check role permissions 5509 if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride', 5510 'moodle/role:override', 'moodle/role:assign'), $catcontext)) { 5511 $url = new moodle_url('/'.$CFG->admin.'/roles/check.php', array('contextid' => $catcontext->id)); 5512 $categorynode->add(get_string('checkpermissions', 'role'), $url, self::TYPE_SETTING, null, 'rolecheck', new pix_icon('i/checkpermissions', '')); 5513 } 5514 5515 // Add the context locking node. 5516 $this->add_context_locking_node($categorynode, $catcontext); 5517 5518 // Cohorts 5519 if (has_any_capability(array('moodle/cohort:view', 'moodle/cohort:manage'), $catcontext)) { 5520 $categorynode->add(get_string('cohorts', 'cohort'), new moodle_url('/cohort/index.php', 5521 array('contextid' => $catcontext->id)), self::TYPE_SETTING, null, 'cohort', new pix_icon('i/cohort', '')); 5522 } 5523 5524 // Manage filters 5525 if (has_capability('moodle/filter:manage', $catcontext) && count(filter_get_available_in_context($catcontext)) > 0) { 5526 $url = new moodle_url('/filter/manage.php', array('contextid' => $catcontext->id)); 5527 $categorynode->add(get_string('filters', 'admin'), $url, self::TYPE_SETTING, null, 'filters', new pix_icon('i/filter', '')); 5528 } 5529 5530 // Restore. 5531 if (has_capability('moodle/restore:restorecourse', $catcontext)) { 5532 $url = new moodle_url('/backup/restorefile.php', array('contextid' => $catcontext->id)); 5533 $categorynode->add(get_string('restorecourse', 'admin'), $url, self::TYPE_SETTING, null, 'restorecourse', new pix_icon('i/restore', '')); 5534 } 5535 5536 // Let plugins hook into category settings navigation. 5537 $pluginsfunction = get_plugins_with_function('extend_navigation_category_settings', 'lib.php'); 5538 foreach ($pluginsfunction as $plugintype => $plugins) { 5539 foreach ($plugins as $pluginfunction) { 5540 $pluginfunction($categorynode, $catcontext); 5541 } 5542 } 5543 5544 $cb = new contentbank(); 5545 if ($cb->is_context_allowed($catcontext) 5546 && has_capability('moodle/contentbank:access', $catcontext)) { 5547 $url = new \moodle_url('/contentbank/index.php', ['contextid' => $catcontext->id]); 5548 $categorynode->add(get_string('contentbank'), $url, self::TYPE_CUSTOM, null, 5549 'contentbank', new \pix_icon('i/contentbank', '')); 5550 } 5551 5552 return $categorynode; 5553 } 5554 5555 /** 5556 * Determine whether the user is assuming another role 5557 * 5558 * This function checks to see if the user is assuming another role by means of 5559 * role switching. In doing this we compare each RSW key (context path) against 5560 * the current context path. This ensures that we can provide the switching 5561 * options against both the course and any page shown under the course. 5562 * 5563 * @return bool|int The role(int) if the user is in another role, false otherwise 5564 */ 5565 protected function in_alternative_role() { 5566 global $USER; 5567 if (!empty($USER->access['rsw']) && is_array($USER->access['rsw'])) { 5568 if (!empty($this->page->context) && !empty($USER->access['rsw'][$this->page->context->path])) { 5569 return $USER->access['rsw'][$this->page->context->path]; 5570 } 5571 foreach ($USER->access['rsw'] as $key=>$role) { 5572 if (strpos($this->context->path,$key)===0) { 5573 return $role; 5574 } 5575 } 5576 } 5577 return false; 5578 } 5579 5580 /** 5581 * This function loads all of the front page settings into the settings navigation. 5582 * This function is called when the user is on the front page, or $COURSE==$SITE 5583 * @param bool $forceopen (optional) 5584 * @return navigation_node 5585 */ 5586 protected function load_front_page_settings($forceopen = false) { 5587 global $SITE, $CFG; 5588 require_once($CFG->dirroot . '/course/lib.php'); 5589 5590 $course = clone($SITE); 5591 $coursecontext = context_course::instance($course->id); // Course context 5592 $adminoptions = course_get_user_administration_options($course, $coursecontext); 5593 5594 $frontpage = $this->add(get_string('frontpagesettings'), null, self::TYPE_SETTING, null, 'frontpage'); 5595 if ($forceopen) { 5596 $frontpage->force_open(); 5597 } 5598 $frontpage->id = 'frontpagesettings'; 5599 5600 if ($this->page->user_allowed_editing() && !$this->page->theme->haseditswitch) { 5601 5602 // Add the turn on/off settings 5603 $url = new moodle_url('/course/view.php', array('id'=>$course->id, 'sesskey'=>sesskey())); 5604 if ($this->page->user_is_editing()) { 5605 $url->param('edit', 'off'); 5606 $editstring = get_string('turneditingoff'); 5607 } else { 5608 $url->param('edit', 'on'); 5609 $editstring = get_string('turneditingon'); 5610 } 5611 $frontpage->add($editstring, $url, self::TYPE_SETTING, null, null, new pix_icon('i/edit', '')); 5612 } 5613 5614 if ($adminoptions->update) { 5615 // Add the course settings link 5616 $url = new moodle_url('/admin/settings.php', array('section'=>'frontpagesettings')); 5617 $frontpage->add(get_string('settings'), $url, self::TYPE_SETTING, null, 5618 'editsettings', new pix_icon('i/settings', '')); 5619 } 5620 5621 // add enrol nodes 5622 enrol_add_course_navigation($frontpage, $course); 5623 5624 // Manage filters 5625 if ($adminoptions->filters) { 5626 $url = new moodle_url('/filter/manage.php', array('contextid'=>$coursecontext->id)); 5627 $frontpage->add(get_string('filters', 'admin'), $url, self::TYPE_SETTING, 5628 null, 'filtermanagement', new pix_icon('i/filter', '')); 5629 } 5630 5631 // View course reports. 5632 if ($adminoptions->reports) { 5633 $frontpagenav = $frontpage->add(get_string('reports'), new moodle_url('/report/view.php', 5634 ['courseid' => $coursecontext->instanceid]), 5635 self::TYPE_CONTAINER, null, 'coursereports', 5636 new pix_icon('i/stats', '')); 5637 $coursereports = core_component::get_plugin_list('coursereport'); 5638 foreach ($coursereports as $report=>$dir) { 5639 $libfile = $CFG->dirroot.'/course/report/'.$report.'/lib.php'; 5640 if (file_exists($libfile)) { 5641 require_once($libfile); 5642 $reportfunction = $report.'_report_extend_navigation'; 5643 if (function_exists($report.'_report_extend_navigation')) { 5644 $reportfunction($frontpagenav, $course, $coursecontext); 5645 } 5646 } 5647 } 5648 5649 $reports = get_plugin_list_with_function('report', 'extend_navigation_course', 'lib.php'); 5650 foreach ($reports as $reportfunction) { 5651 $reportfunction($frontpagenav, $course, $coursecontext); 5652 } 5653 5654 if (!$frontpagenav->has_children()) { 5655 $frontpagenav->remove(); 5656 } 5657 } 5658 5659 // Backup this course 5660 if ($adminoptions->backup) { 5661 $url = new moodle_url('/backup/backup.php', array('id'=>$course->id)); 5662 $frontpage->add(get_string('backup'), $url, self::TYPE_SETTING, null, 'backup', new pix_icon('i/backup', '')); 5663 } 5664 5665 // Restore to this course 5666 if ($adminoptions->restore) { 5667 $url = new moodle_url('/backup/restorefile.php', array('contextid'=>$coursecontext->id)); 5668 $frontpage->add(get_string('restore'), $url, self::TYPE_SETTING, null, 'restore', new pix_icon('i/restore', '')); 5669 } 5670 5671 // Questions 5672 require_once($CFG->libdir . '/questionlib.php'); 5673 question_extend_settings_navigation($frontpage, $coursecontext)->trim_if_empty(); 5674 5675 // Manage files 5676 if ($adminoptions->files) { 5677 //hiden in new installs 5678 $url = new moodle_url('/files/index.php', array('contextid'=>$coursecontext->id)); 5679 $frontpage->add(get_string('sitelegacyfiles'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/folder', '')); 5680 } 5681 5682 // Let plugins hook into frontpage navigation. 5683 $pluginsfunction = get_plugins_with_function('extend_navigation_frontpage', 'lib.php'); 5684 foreach ($pluginsfunction as $plugintype => $plugins) { 5685 foreach ($plugins as $pluginfunction) { 5686 $pluginfunction($frontpage, $course, $coursecontext); 5687 } 5688 } 5689 5690 return $frontpage; 5691 } 5692 5693 /** 5694 * This function gives local plugins an opportunity to modify the settings navigation. 5695 */ 5696 protected function load_local_plugin_settings() { 5697 5698 foreach (get_plugin_list_with_function('local', 'extend_settings_navigation') as $function) { 5699 $function($this, $this->context); 5700 } 5701 } 5702 5703 /** 5704 * This function marks the cache as volatile so it is cleared during shutdown 5705 */ 5706 public function clear_cache() { 5707 $this->cache->volatile(); 5708 } 5709 5710 /** 5711 * Checks to see if there are child nodes available in the specific user's preference node. 5712 * If so, then they have the appropriate permissions view this user's preferences. 5713 * 5714 * @since Moodle 2.9.3 5715 * @param int $userid The user's ID. 5716 * @return bool True if child nodes exist to view, otherwise false. 5717 */ 5718 public function can_view_user_preferences($userid) { 5719 if (is_siteadmin()) { 5720 return true; 5721 } 5722 // See if any nodes are present in the preferences section for this user. 5723 $preferencenode = $this->find('userviewingsettings' . $userid, null); 5724 if ($preferencenode && $preferencenode->has_children()) { 5725 // Run through each child node. 5726 foreach ($preferencenode->children as $childnode) { 5727 // If the child node has children then this user has access to a link in the preferences page. 5728 if ($childnode->has_children()) { 5729 return true; 5730 } 5731 } 5732 } 5733 // No links found for the user to access on the preferences page. 5734 return false; 5735 } 5736 } 5737 5738 /** 5739 * Class used to populate site admin navigation for ajax. 5740 * 5741 * @package core 5742 * @category navigation 5743 * @copyright 2013 Rajesh Taneja <rajesh@moodle.com> 5744 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later 5745 */ 5746 class settings_navigation_ajax extends settings_navigation { 5747 /** 5748 * Constructs the navigation for use in an AJAX request 5749 * 5750 * @param moodle_page $page 5751 */ 5752 public function __construct(moodle_page &$page) { 5753 $this->page = $page; 5754 $this->cache = new navigation_cache(NAVIGATION_CACHE_NAME); 5755 $this->children = new navigation_node_collection(); 5756 $this->initialise(); 5757 } 5758 5759 /** 5760 * Initialise the site admin navigation. 5761 * 5762 * @return array An array of the expandable nodes 5763 */ 5764 public function initialise() { 5765 if ($this->initialised || during_initial_install()) { 5766 return false; 5767 } 5768 $this->context = $this->page->context; 5769 $this->load_administration_settings(); 5770 5771 // Check if local plugins is adding node to site admin. 5772 $this->load_local_plugin_settings(); 5773 5774 $this->initialised = true; 5775 } 5776 } 5777 5778 /** 5779 * Simple class used to output a navigation branch in XML 5780 * 5781 * @package core 5782 * @category navigation 5783 * @copyright 2009 Sam Hemelryk 5784 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later 5785 */ 5786 class navigation_json { 5787 /** @var array An array of different node types */ 5788 protected $nodetype = array('node','branch'); 5789 /** @var array An array of node keys and types */ 5790 protected $expandable = array(); 5791 /** 5792 * Turns a branch and all of its children into XML 5793 * 5794 * @param navigation_node $branch 5795 * @return string XML string 5796 */ 5797 public function convert($branch) { 5798 $xml = $this->convert_child($branch); 5799 return $xml; 5800 } 5801 /** 5802 * Set the expandable items in the array so that we have enough information 5803 * to attach AJAX events 5804 * @param array $expandable 5805 */ 5806 public function set_expandable($expandable) { 5807 foreach ($expandable as $node) { 5808 $this->expandable[$node['key'].':'.$node['type']] = $node; 5809 } 5810 } 5811 /** 5812 * Recusively converts a child node and its children to XML for output 5813 * 5814 * @param navigation_node $child The child to convert 5815 * @param int $depth Pointlessly used to track the depth of the XML structure 5816 * @return string JSON 5817 */ 5818 protected function convert_child($child, $depth=1) { 5819 if (!$child->display) { 5820 return ''; 5821 } 5822 $attributes = array(); 5823 $attributes['id'] = $child->id; 5824 $attributes['name'] = (string)$child->text; // This can be lang_string object so typecast it. 5825 $attributes['type'] = $child->type; 5826 $attributes['key'] = $child->key; 5827 $attributes['class'] = $child->get_css_type(); 5828 $attributes['requiresajaxloading'] = $child->requiresajaxloading; 5829 5830 if ($child->icon instanceof pix_icon) { 5831 $attributes['icon'] = array( 5832 'component' => $child->icon->component, 5833 'pix' => $child->icon->pix, 5834 ); 5835 foreach ($child->icon->attributes as $key=>$value) { 5836 if ($key == 'class') { 5837 $attributes['icon']['classes'] = explode(' ', $value); 5838 } else if (!array_key_exists($key, $attributes['icon'])) { 5839 $attributes['icon'][$key] = $value; 5840 } 5841 5842 } 5843 } else if (!empty($child->icon)) { 5844 $attributes['icon'] = (string)$child->icon; 5845 } 5846 5847 if ($child->forcetitle || $child->title !== $child->text) { 5848 $attributes['title'] = htmlentities($child->title ?? '', ENT_QUOTES, 'UTF-8'); 5849 } 5850 if (array_key_exists($child->key.':'.$child->type, $this->expandable)) { 5851 $attributes['expandable'] = $child->key; 5852 $child->add_class($this->expandable[$child->key.':'.$child->type]['id']); 5853 } 5854 5855 if (count($child->classes)>0) { 5856 $attributes['class'] .= ' '.join(' ',$child->classes); 5857 } 5858 if (is_string($child->action)) { 5859 $attributes['link'] = $child->action; 5860 } else if ($child->action instanceof moodle_url) { 5861 $attributes['link'] = $child->action->out(); 5862 } else if ($child->action instanceof action_link) { 5863 $attributes['link'] = $child->action->url->out(); 5864 } 5865 $attributes['hidden'] = ($child->hidden); 5866 $attributes['haschildren'] = ($child->children->count()>0 || $child->type == navigation_node::TYPE_CATEGORY); 5867 $attributes['haschildren'] = $attributes['haschildren'] || $child->type == navigation_node::TYPE_MY_CATEGORY; 5868 5869 if ($child->children->count() > 0) { 5870 $attributes['children'] = array(); 5871 foreach ($child->children as $subchild) { 5872 $attributes['children'][] = $this->convert_child($subchild, $depth+1); 5873 } 5874 } 5875 5876 if ($depth > 1) { 5877 return $attributes; 5878 } else { 5879 return json_encode($attributes); 5880 } 5881 } 5882 } 5883 5884 /** 5885 * The cache class used by global navigation and settings navigation. 5886 * 5887 * It is basically an easy access point to session with a bit of smarts to make 5888 * sure that the information that is cached is valid still. 5889 * 5890 * Example use: 5891 * <code php> 5892 * if (!$cache->viewdiscussion()) { 5893 * // Code to do stuff and produce cachable content 5894 * $cache->viewdiscussion = has_capability('mod/forum:viewdiscussion', $coursecontext); 5895 * } 5896 * $content = $cache->viewdiscussion; 5897 * </code> 5898 * 5899 * @package core 5900 * @category navigation 5901 * @copyright 2009 Sam Hemelryk 5902 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later 5903 */ 5904 class navigation_cache { 5905 /** @var int represents the time created */ 5906 protected $creation; 5907 /** @var array An array of session keys */ 5908 protected $session; 5909 /** 5910 * The string to use to segregate this particular cache. It can either be 5911 * unique to start a fresh cache or if you want to share a cache then make 5912 * it the string used in the original cache. 5913 * @var string 5914 */ 5915 protected $area; 5916 /** @var int a time that the information will time out */ 5917 protected $timeout; 5918 /** @var stdClass The current context */ 5919 protected $currentcontext; 5920 /** @var int cache time information */ 5921 const CACHETIME = 0; 5922 /** @var int cache user id */ 5923 const CACHEUSERID = 1; 5924 /** @var int cache value */ 5925 const CACHEVALUE = 2; 5926 /** @var null|array An array of navigation cache areas to expire on shutdown */ 5927 public static $volatilecaches; 5928 5929 /** 5930 * Contructor for the cache. Requires two arguments 5931 * 5932 * @param string $area The string to use to segregate this particular cache 5933 * it can either be unique to start a fresh cache or if you want 5934 * to share a cache then make it the string used in the original 5935 * cache 5936 * @param int $timeout The number of seconds to time the information out after 5937 */ 5938 public function __construct($area, $timeout=1800) { 5939 $this->creation = time(); 5940 $this->area = $area; 5941 $this->timeout = time() - $timeout; 5942 if (rand(0,100) === 0) { 5943 $this->garbage_collection(); 5944 } 5945 } 5946 5947 /** 5948 * Used to set up the cache within the SESSION. 5949 * 5950 * This is called for each access and ensure that we don't put anything into the session before 5951 * it is required. 5952 */ 5953 protected function ensure_session_cache_initialised() { 5954 global $SESSION; 5955 if (empty($this->session)) { 5956 if (!isset($SESSION->navcache)) { 5957 $SESSION->navcache = new stdClass; 5958 } 5959 if (!isset($SESSION->navcache->{$this->area})) { 5960 $SESSION->navcache->{$this->area} = array(); 5961 } 5962 $this->session = &$SESSION->navcache->{$this->area}; // pointer to array, =& is correct here 5963 } 5964 } 5965 5966 /** 5967 * Magic Method to retrieve something by simply calling using = cache->key 5968 * 5969 * @param mixed $key The identifier for the information you want out again 5970 * @return void|mixed Either void or what ever was put in 5971 */ 5972 public function __get($key) { 5973 if (!$this->cached($key)) { 5974 return; 5975 } 5976 $information = $this->session[$key][self::CACHEVALUE]; 5977 return unserialize($information); 5978 } 5979 5980 /** 5981 * Magic method that simply uses {@link set();} to store something in the cache 5982 * 5983 * @param string|int $key 5984 * @param mixed $information 5985 */ 5986 public function __set($key, $information) { 5987 $this->set($key, $information); 5988 } 5989 5990 /** 5991 * Sets some information against the cache (session) for later retrieval 5992 * 5993 * @param string|int $key 5994 * @param mixed $information 5995 */ 5996 public function set($key, $information) { 5997 global $USER; 5998 $this->ensure_session_cache_initialised(); 5999 $information = serialize($information); 6000 $this->session[$key]= array(self::CACHETIME=>time(), self::CACHEUSERID=>$USER->id, self::CACHEVALUE=>$information); 6001 } 6002 /** 6003 * Check the existence of the identifier in the cache 6004 * 6005 * @param string|int $key 6006 * @return bool 6007 */ 6008 public function cached($key) { 6009 global $USER; 6010 $this->ensure_session_cache_initialised(); 6011 if (!array_key_exists($key, $this->session) || !is_array($this->session[$key]) || $this->session[$key][self::CACHEUSERID]!=$USER->id || $this->session[$key][self::CACHETIME] < $this->timeout) { 6012 return false; 6013 } 6014 return true; 6015 } 6016 /** 6017 * Compare something to it's equivilant in the cache 6018 * 6019 * @param string $key 6020 * @param mixed $value 6021 * @param bool $serialise Whether to serialise the value before comparison 6022 * this should only be set to false if the value is already 6023 * serialised 6024 * @return bool If the value is the same false if it is not set or doesn't match 6025 */ 6026 public function compare($key, $value, $serialise = true) { 6027 if ($this->cached($key)) { 6028 if ($serialise) { 6029 $value = serialize($value); 6030 } 6031 if ($this->session[$key][self::CACHEVALUE] === $value) { 6032 return true; 6033 } 6034 } 6035 return false; 6036 } 6037 /** 6038 * Wipes the entire cache, good to force regeneration 6039 */ 6040 public function clear() { 6041 global $SESSION; 6042 unset($SESSION->navcache); 6043 $this->session = null; 6044 } 6045 /** 6046 * Checks all cache entries and removes any that have expired, good ole cleanup 6047 */ 6048 protected function garbage_collection() { 6049 if (empty($this->session)) { 6050 return true; 6051 } 6052 foreach ($this->session as $key=>$cachedinfo) { 6053 if (is_array($cachedinfo) && $cachedinfo[self::CACHETIME]<$this->timeout) { 6054 unset($this->session[$key]); 6055 } 6056 } 6057 } 6058 6059 /** 6060 * Marks the cache as being volatile (likely to change) 6061 * 6062 * Any caches marked as volatile will be destroyed at the on shutdown by 6063 * {@link navigation_node::destroy_volatile_caches()} which is registered 6064 * as a shutdown function if any caches are marked as volatile. 6065 * 6066 * @param bool $setting True to destroy the cache false not too 6067 */ 6068 public function volatile($setting = true) { 6069 if (self::$volatilecaches===null) { 6070 self::$volatilecaches = array(); 6071 core_shutdown_manager::register_function(array('navigation_cache','destroy_volatile_caches')); 6072 } 6073 6074 if ($setting) { 6075 self::$volatilecaches[$this->area] = $this->area; 6076 } else if (array_key_exists($this->area, self::$volatilecaches)) { 6077 unset(self::$volatilecaches[$this->area]); 6078 } 6079 } 6080 6081 /** 6082 * Destroys all caches marked as volatile 6083 * 6084 * This function is static and works in conjunction with the static volatilecaches 6085 * property of navigation cache. 6086 * Because this function is static it manually resets the cached areas back to an 6087 * empty array. 6088 */ 6089 public static function destroy_volatile_caches() { 6090 global $SESSION; 6091 if (is_array(self::$volatilecaches) && count(self::$volatilecaches)>0) { 6092 foreach (self::$volatilecaches as $area) { 6093 $SESSION->navcache->{$area} = array(); 6094 } 6095 } else { 6096 $SESSION->navcache = new stdClass; 6097 } 6098 } 6099 }
title
Description
Body
title
Description
Body
title
Description
Body
title
Body