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