PageRenderTime 187ms CodeModel.GetById 142ms app.highlight 28ms RepoModel.GetById 1ms app.codeStats 1ms

/lib/navigationlib.php

https://github.com/dongsheng/moodle
PHP | 5241 lines | 3214 code | 425 blank | 1602 comment | 964 complexity | 547a94b38a2758aaefb971074168d4b8 MD5 | raw file

Large files files are truncated, but you can click here to view the full file

   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
  26defined('MOODLE_INTERNAL') || die();
  27
  28/**
  29 * The name that will be used to separate the navigation cache within SESSION
  30 */
  31define('NAVIGATION_CACHE_NAME', 'navigation');
  32define('NAVIGATION_SITE_ADMIN_CACHE_NAME', 'navigationsiteadmin');
  33
  34/**
  35 * This class is used to represent a node in a navigation tree
  36 *
  37 * This class is used to represent a node in a navigation tree within Moodle,
  38 * the tree could be one of global navigation, settings navigation, or the navbar.
  39 * Each node can be one of two types either a Leaf (default) or a branch.
  40 * When a node is first created it is created as a leaf, when/if children are added
  41 * the node then becomes a branch.
  42 *
  43 * @package   core
  44 * @category  navigation
  45 * @copyright 2009 Sam Hemelryk
  46 * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  47 */
  48class navigation_node implements renderable {
  49    /** @var int Used to identify this node a leaf (default) 0 */
  50    const NODETYPE_LEAF =   0;
  51    /** @var int Used to identify this node a branch, happens with children  1 */
  52    const NODETYPE_BRANCH = 1;
  53    /** @var null Unknown node type null */
  54    const TYPE_UNKNOWN =    null;
  55    /** @var int System node type 0 */
  56    const TYPE_ROOTNODE =   0;
  57    /** @var int System node type 1 */
  58    const TYPE_SYSTEM =     1;
  59    /** @var int Category node type 10 */
  60    const TYPE_CATEGORY =   10;
  61    /** var int Category displayed in MyHome navigation node */
  62    const TYPE_MY_CATEGORY = 11;
  63    /** @var int Course node type 20 */
  64    const TYPE_COURSE =     20;
  65    /** @var int Course Structure node type 30 */
  66    const TYPE_SECTION =    30;
  67    /** @var int Activity node type, e.g. Forum, Quiz 40 */
  68    const TYPE_ACTIVITY =   40;
  69    /** @var int Resource node type, e.g. Link to a file, or label 50 */
  70    const TYPE_RESOURCE =   50;
  71    /** @var int A custom node type, default when adding without specifing type 60 */
  72    const TYPE_CUSTOM =     60;
  73    /** @var int Setting node type, used only within settings nav 70 */
  74    const TYPE_SETTING =    70;
  75    /** @var int site admin branch node type, used only within settings nav 71 */
  76    const TYPE_SITE_ADMIN = 71;
  77    /** @var int Setting node type, used only within settings nav 80 */
  78    const TYPE_USER =       80;
  79    /** @var int Setting node type, used for containers of no importance 90 */
  80    const TYPE_CONTAINER =  90;
  81    /** var int Course the current user is not enrolled in */
  82    const COURSE_OTHER = 0;
  83    /** var int Course the current user is enrolled in but not viewing */
  84    const COURSE_MY = 1;
  85    /** var int Course the current user is currently viewing */
  86    const COURSE_CURRENT = 2;
  87
  88    /** @var int Parameter to aid the coder in tracking [optional] */
  89    public $id = null;
  90    /** @var string|int The identifier for the node, used to retrieve the node */
  91    public $key = null;
  92    /** @var string The text to use for the node */
  93    public $text = null;
  94    /** @var string Short text to use if requested [optional] */
  95    public $shorttext = null;
  96    /** @var string The title attribute for an action if one is defined */
  97    public $title = null;
  98    /** @var string A string that can be used to build a help button */
  99    public $helpbutton = null;
 100    /** @var moodle_url|action_link|null An action for the node (link) */
 101    public $action = null;
 102    /** @var pix_icon The path to an icon to use for this node */
 103    public $icon = null;
 104    /** @var int See TYPE_* constants defined for this class */
 105    public $type = self::TYPE_UNKNOWN;
 106    /** @var int See NODETYPE_* constants defined for this class */
 107    public $nodetype = self::NODETYPE_LEAF;
 108    /** @var bool If set to true the node will be collapsed by default */
 109    public $collapse = false;
 110    /** @var bool If set to true the node will be expanded by default */
 111    public $forceopen = false;
 112    /** @var array An array of CSS classes for the node */
 113    public $classes = array();
 114    /** @var navigation_node_collection An array of child nodes */
 115    public $children = array();
 116    /** @var bool If set to true the node will be recognised as active */
 117    public $isactive = false;
 118    /** @var bool If set to true the node will be dimmed */
 119    public $hidden = false;
 120    /** @var bool If set to false the node will not be displayed */
 121    public $display = true;
 122    /** @var bool If set to true then an HR will be printed before the node */
 123    public $preceedwithhr = false;
 124    /** @var bool If set to true the the navigation bar should ignore this node */
 125    public $mainnavonly = false;
 126    /** @var bool If set to true a title will be added to the action no matter what */
 127    public $forcetitle = false;
 128    /** @var navigation_node A reference to the node parent, you should never set this directly you should always call set_parent */
 129    public $parent = null;
 130    /** @var bool Override to not display the icon even if one is provided **/
 131    public $hideicon = false;
 132    /** @var bool Set to true if we KNOW that this node can be expanded.  */
 133    public $isexpandable = false;
 134    /** @var array */
 135    protected $namedtypes = array(0=>'system',10=>'category',20=>'course',30=>'structure',40=>'activity',50=>'resource',60=>'custom',70=>'setting',71=>'siteadmin', 80=>'user');
 136    /** @var moodle_url */
 137    protected static $fullmeurl = null;
 138    /** @var bool toogles auto matching of active node */
 139    public static $autofindactive = true;
 140    /** @var bool should we load full admin tree or rely on AJAX for performance reasons */
 141    protected static $loadadmintree = false;
 142    /** @var mixed If set to an int, that section will be included even if it has no activities */
 143    public $includesectionnum = false;
 144
 145    /**
 146     * Constructs a new navigation_node
 147     *
 148     * @param array|string $properties Either an array of properties or a string to use
 149     *                     as the text for the node
 150     */
 151    public function __construct($properties) {
 152        if (is_array($properties)) {
 153            // Check the array for each property that we allow to set at construction.
 154            // text         - The main content for the node
 155            // shorttext    - A short text if required for the node
 156            // icon         - The icon to display for the node
 157            // type         - The type of the node
 158            // key          - The key to use to identify the node
 159            // parent       - A reference to the nodes parent
 160            // action       - The action to attribute to this node, usually a URL to link to
 161            if (array_key_exists('text', $properties)) {
 162                $this->text = $properties['text'];
 163            }
 164            if (array_key_exists('shorttext', $properties)) {
 165                $this->shorttext = $properties['shorttext'];
 166            }
 167            if (!array_key_exists('icon', $properties)) {
 168                $properties['icon'] = new pix_icon('i/navigationitem', '');
 169            }
 170            $this->icon = $properties['icon'];
 171            if ($this->icon instanceof pix_icon) {
 172                if (empty($this->icon->attributes['class'])) {
 173                    $this->icon->attributes['class'] = 'navicon';
 174                } else {
 175                    $this->icon->attributes['class'] .= ' navicon';
 176                }
 177            }
 178            if (array_key_exists('type', $properties)) {
 179                $this->type = $properties['type'];
 180            } else {
 181                $this->type = self::TYPE_CUSTOM;
 182            }
 183            if (array_key_exists('key', $properties)) {
 184                $this->key = $properties['key'];
 185            }
 186            // This needs to happen last because of the check_if_active call that occurs
 187            if (array_key_exists('action', $properties)) {
 188                $this->action = $properties['action'];
 189                if (is_string($this->action)) {
 190                    $this->action = new moodle_url($this->action);
 191                }
 192                if (self::$autofindactive) {
 193                    $this->check_if_active();
 194                }
 195            }
 196            if (array_key_exists('parent', $properties)) {
 197                $this->set_parent($properties['parent']);
 198            }
 199        } else if (is_string($properties)) {
 200            $this->text = $properties;
 201        }
 202        if ($this->text === null) {
 203            throw new coding_exception('You must set the text for the node when you create it.');
 204        }
 205        // Instantiate a new navigation node collection for this nodes children
 206        $this->children = new navigation_node_collection();
 207    }
 208
 209    /**
 210     * Checks if this node is the active node.
 211     *
 212     * This is determined by comparing the action for the node against the
 213     * defined URL for the page. A match will see this node marked as active.
 214     *
 215     * @param int $strength One of URL_MATCH_EXACT, URL_MATCH_PARAMS, or URL_MATCH_BASE
 216     * @return bool
 217     */
 218    public function check_if_active($strength=URL_MATCH_EXACT) {
 219        global $FULLME, $PAGE;
 220        // Set fullmeurl if it hasn't already been set
 221        if (self::$fullmeurl == null) {
 222            if ($PAGE->has_set_url()) {
 223                self::override_active_url(new moodle_url($PAGE->url));
 224            } else {
 225                self::override_active_url(new moodle_url($FULLME));
 226            }
 227        }
 228
 229        // Compare the action of this node against the fullmeurl
 230        if ($this->action instanceof moodle_url && $this->action->compare(self::$fullmeurl, $strength)) {
 231            $this->make_active();
 232            return true;
 233        }
 234        return false;
 235    }
 236
 237    /**
 238     * This sets the URL that the URL of new nodes get compared to when locating
 239     * the active node.
 240     *
 241     * The active node is the node that matches the URL set here. By default this
 242     * is either $PAGE->url or if that hasn't been set $FULLME.
 243     *
 244     * @param moodle_url $url The url to use for the fullmeurl.
 245     * @param bool $loadadmintree use true if the URL point to administration tree
 246     */
 247    public static function override_active_url(moodle_url $url, $loadadmintree = false) {
 248        // Clone the URL, in case the calling script changes their URL later.
 249        self::$fullmeurl = new moodle_url($url);
 250        // True means we do not want AJAX loaded admin tree, required for all admin pages.
 251        if ($loadadmintree) {
 252            // Do not change back to false if already set.
 253            self::$loadadmintree = true;
 254        }
 255    }
 256
 257    /**
 258     * Use when page is linked from the admin tree,
 259     * if not used navigation could not find the page using current URL
 260     * because the tree is not fully loaded.
 261     */
 262    public static function require_admin_tree() {
 263        self::$loadadmintree = true;
 264    }
 265
 266    /**
 267     * Creates a navigation node, ready to add it as a child using add_node
 268     * function. (The created node needs to be added before you can use it.)
 269     * @param string $text
 270     * @param moodle_url|action_link $action
 271     * @param int $type
 272     * @param string $shorttext
 273     * @param string|int $key
 274     * @param pix_icon $icon
 275     * @return navigation_node
 276     */
 277    public static function create($text, $action=null, $type=self::TYPE_CUSTOM,
 278            $shorttext=null, $key=null, pix_icon $icon=null) {
 279        // Properties array used when creating the new navigation node
 280        $itemarray = array(
 281            'text' => $text,
 282            'type' => $type
 283        );
 284        // Set the action if one was provided
 285        if ($action!==null) {
 286            $itemarray['action'] = $action;
 287        }
 288        // Set the shorttext if one was provided
 289        if ($shorttext!==null) {
 290            $itemarray['shorttext'] = $shorttext;
 291        }
 292        // Set the icon if one was provided
 293        if ($icon!==null) {
 294            $itemarray['icon'] = $icon;
 295        }
 296        // Set the key
 297        $itemarray['key'] = $key;
 298        // Construct and return
 299        return new navigation_node($itemarray);
 300    }
 301
 302    /**
 303     * Adds a navigation node as a child of this node.
 304     *
 305     * @param string $text
 306     * @param moodle_url|action_link $action
 307     * @param int $type
 308     * @param string $shorttext
 309     * @param string|int $key
 310     * @param pix_icon $icon
 311     * @return navigation_node
 312     */
 313    public function add($text, $action=null, $type=self::TYPE_CUSTOM, $shorttext=null, $key=null, pix_icon $icon=null) {
 314        // Create child node
 315        $childnode = self::create($text, $action, $type, $shorttext, $key, $icon);
 316
 317        // Add the child to end and return
 318        return $this->add_node($childnode);
 319    }
 320
 321    /**
 322     * Adds a navigation node as a child of this one, given a $node object
 323     * created using the create function.
 324     * @param navigation_node $childnode Node to add
 325     * @param string $beforekey
 326     * @return navigation_node The added node
 327     */
 328    public function add_node(navigation_node $childnode, $beforekey=null) {
 329        // First convert the nodetype for this node to a branch as it will now have children
 330        if ($this->nodetype !== self::NODETYPE_BRANCH) {
 331            $this->nodetype = self::NODETYPE_BRANCH;
 332        }
 333        // Set the parent to this node
 334        $childnode->set_parent($this);
 335
 336        // Default the key to the number of children if not provided
 337        if ($childnode->key === null) {
 338            $childnode->key = $this->children->count();
 339        }
 340
 341        // Add the child using the navigation_node_collections add method
 342        $node = $this->children->add($childnode, $beforekey);
 343
 344        // If added node is a category node or the user is logged in and it's a course
 345        // then mark added node as a branch (makes it expandable by AJAX)
 346        $type = $childnode->type;
 347        if (($type == self::TYPE_CATEGORY) || (isloggedin() && ($type == self::TYPE_COURSE)) || ($type == self::TYPE_MY_CATEGORY) ||
 348                ($type === self::TYPE_SITE_ADMIN)) {
 349            $node->nodetype = self::NODETYPE_BRANCH;
 350        }
 351        // If this node is hidden mark it's children as hidden also
 352        if ($this->hidden) {
 353            $node->hidden = true;
 354        }
 355        // Return added node (reference returned by $this->children->add()
 356        return $node;
 357    }
 358
 359    /**
 360     * Return a list of all the keys of all the child nodes.
 361     * @return array the keys.
 362     */
 363    public function get_children_key_list() {
 364        return $this->children->get_key_list();
 365    }
 366
 367    /**
 368     * Searches for a node of the given type with the given key.
 369     *
 370     * This searches this node plus all of its children, and their children....
 371     * If you know the node you are looking for is a child of this node then please
 372     * use the get method instead.
 373     *
 374     * @param int|string $key The key of the node we are looking for
 375     * @param int $type One of navigation_node::TYPE_*
 376     * @return navigation_node|false
 377     */
 378    public function find($key, $type) {
 379        return $this->children->find($key, $type);
 380    }
 381
 382    /**
 383     * Get the child of this node that has the given key + (optional) type.
 384     *
 385     * If you are looking for a node and want to search all children + their children
 386     * then please use the find method instead.
 387     *
 388     * @param int|string $key The key of the node we are looking for
 389     * @param int $type One of navigation_node::TYPE_*
 390     * @return navigation_node|false
 391     */
 392    public function get($key, $type=null) {
 393        return $this->children->get($key, $type);
 394    }
 395
 396    /**
 397     * Removes this node.
 398     *
 399     * @return bool
 400     */
 401    public function remove() {
 402        return $this->parent->children->remove($this->key, $this->type);
 403    }
 404
 405    /**
 406     * Checks if this node has or could have any children
 407     *
 408     * @return bool Returns true if it has children or could have (by AJAX expansion)
 409     */
 410    public function has_children() {
 411        return ($this->nodetype === navigation_node::NODETYPE_BRANCH || $this->children->count()>0 || $this->isexpandable);
 412    }
 413
 414    /**
 415     * Marks this node as active and forces it open.
 416     *
 417     * Important: If you are here because you need to mark a node active to get
 418     * the navigation to do what you want have you looked at {@link navigation_node::override_active_url()}?
 419     * You can use it to specify a different URL to match the active navigation node on
 420     * rather than having to locate and manually mark a node active.
 421     */
 422    public function make_active() {
 423        $this->isactive = true;
 424        $this->add_class('active_tree_node');
 425        $this->force_open();
 426        if ($this->parent !== null) {
 427            $this->parent->make_inactive();
 428        }
 429    }
 430
 431    /**
 432     * Marks a node as inactive and recusised back to the base of the tree
 433     * doing the same to all parents.
 434     */
 435    public function make_inactive() {
 436        $this->isactive = false;
 437        $this->remove_class('active_tree_node');
 438        if ($this->parent !== null) {
 439            $this->parent->make_inactive();
 440        }
 441    }
 442
 443    /**
 444     * Forces this node to be open and at the same time forces open all
 445     * parents until the root node.
 446     *
 447     * Recursive.
 448     */
 449    public function force_open() {
 450        $this->forceopen = true;
 451        if ($this->parent !== null) {
 452            $this->parent->force_open();
 453        }
 454    }
 455
 456    /**
 457     * Adds a CSS class to this node.
 458     *
 459     * @param string $class
 460     * @return bool
 461     */
 462    public function add_class($class) {
 463        if (!in_array($class, $this->classes)) {
 464            $this->classes[] = $class;
 465        }
 466        return true;
 467    }
 468
 469    /**
 470     * Removes a CSS class from this node.
 471     *
 472     * @param string $class
 473     * @return bool True if the class was successfully removed.
 474     */
 475    public function remove_class($class) {
 476        if (in_array($class, $this->classes)) {
 477            $key = array_search($class,$this->classes);
 478            if ($key!==false) {
 479                unset($this->classes[$key]);
 480                return true;
 481            }
 482        }
 483        return false;
 484    }
 485
 486    /**
 487     * Sets the title for this node and forces Moodle to utilise it.
 488     * @param string $title
 489     */
 490    public function title($title) {
 491        $this->title = $title;
 492        $this->forcetitle = true;
 493    }
 494
 495    /**
 496     * Resets the page specific information on this node if it is being unserialised.
 497     */
 498    public function __wakeup(){
 499        $this->forceopen = false;
 500        $this->isactive = false;
 501        $this->remove_class('active_tree_node');
 502    }
 503
 504    /**
 505     * Checks if this node or any of its children contain the active node.
 506     *
 507     * Recursive.
 508     *
 509     * @return bool
 510     */
 511    public function contains_active_node() {
 512        if ($this->isactive) {
 513            return true;
 514        } else {
 515            foreach ($this->children as $child) {
 516                if ($child->isactive || $child->contains_active_node()) {
 517                    return true;
 518                }
 519            }
 520        }
 521        return false;
 522    }
 523
 524    /**
 525     * Finds the active node.
 526     *
 527     * Searches this nodes children plus all of the children for the active node
 528     * and returns it if found.
 529     *
 530     * Recursive.
 531     *
 532     * @return navigation_node|false
 533     */
 534    public function find_active_node() {
 535        if ($this->isactive) {
 536            return $this;
 537        } else {
 538            foreach ($this->children as &$child) {
 539                $outcome = $child->find_active_node();
 540                if ($outcome !== false) {
 541                    return $outcome;
 542                }
 543            }
 544        }
 545        return false;
 546    }
 547
 548    /**
 549     * Searches all children for the best matching active node
 550     * @return navigation_node|false
 551     */
 552    public function search_for_active_node() {
 553        if ($this->check_if_active(URL_MATCH_BASE)) {
 554            return $this;
 555        } else {
 556            foreach ($this->children as &$child) {
 557                $outcome = $child->search_for_active_node();
 558                if ($outcome !== false) {
 559                    return $outcome;
 560                }
 561            }
 562        }
 563        return false;
 564    }
 565
 566    /**
 567     * Gets the content for this node.
 568     *
 569     * @param bool $shorttext If true shorttext is used rather than the normal text
 570     * @return string
 571     */
 572    public function get_content($shorttext=false) {
 573        if ($shorttext && $this->shorttext!==null) {
 574            return format_string($this->shorttext);
 575        } else {
 576            return format_string($this->text);
 577        }
 578    }
 579
 580    /**
 581     * Gets the title to use for this node.
 582     *
 583     * @return string
 584     */
 585    public function get_title() {
 586        if ($this->forcetitle || $this->action != null){
 587            return $this->title;
 588        } else {
 589            return '';
 590        }
 591    }
 592
 593    /**
 594     * Gets the CSS class to add to this node to describe its type
 595     *
 596     * @return string
 597     */
 598    public function get_css_type() {
 599        if (array_key_exists($this->type, $this->namedtypes)) {
 600            return 'type_'.$this->namedtypes[$this->type];
 601        }
 602        return 'type_unknown';
 603    }
 604
 605    /**
 606     * Finds all nodes that are expandable by AJAX
 607     *
 608     * @param array $expandable An array by reference to populate with expandable nodes.
 609     */
 610    public function find_expandable(array &$expandable) {
 611        foreach ($this->children as &$child) {
 612            if ($child->display && $child->has_children() && $child->children->count() == 0) {
 613                $child->id = 'expandable_branch_'.$child->type.'_'.clean_param($child->key, PARAM_ALPHANUMEXT);
 614                $this->add_class('canexpand');
 615                $expandable[] = array('id' => $child->id, 'key' => $child->key, 'type' => $child->type);
 616            }
 617            $child->find_expandable($expandable);
 618        }
 619    }
 620
 621    /**
 622     * Finds all nodes of a given type (recursive)
 623     *
 624     * @param int $type One of navigation_node::TYPE_*
 625     * @return array
 626     */
 627    public function find_all_of_type($type) {
 628        $nodes = $this->children->type($type);
 629        foreach ($this->children as &$node) {
 630            $childnodes = $node->find_all_of_type($type);
 631            $nodes = array_merge($nodes, $childnodes);
 632        }
 633        return $nodes;
 634    }
 635
 636    /**
 637     * Removes this node if it is empty
 638     */
 639    public function trim_if_empty() {
 640        if ($this->children->count() == 0) {
 641            $this->remove();
 642        }
 643    }
 644
 645    /**
 646     * Creates a tab representation of this nodes children that can be used
 647     * with print_tabs to produce the tabs on a page.
 648     *
 649     * call_user_func_array('print_tabs', $node->get_tabs_array());
 650     *
 651     * @param array $inactive
 652     * @param bool $return
 653     * @return array Array (tabs, selected, inactive, activated, return)
 654     */
 655    public function get_tabs_array(array $inactive=array(), $return=false) {
 656        $tabs = array();
 657        $rows = array();
 658        $selected = null;
 659        $activated = array();
 660        foreach ($this->children as $node) {
 661            $tabs[] = new tabobject($node->key, $node->action, $node->get_content(), $node->get_title());
 662            if ($node->contains_active_node()) {
 663                if ($node->children->count() > 0) {
 664                    $activated[] = $node->key;
 665                    foreach ($node->children as $child) {
 666                        if ($child->contains_active_node()) {
 667                            $selected = $child->key;
 668                        }
 669                        $rows[] = new tabobject($child->key, $child->action, $child->get_content(), $child->get_title());
 670                    }
 671                } else {
 672                    $selected = $node->key;
 673                }
 674            }
 675        }
 676        return array(array($tabs, $rows), $selected, $inactive, $activated, $return);
 677    }
 678
 679    /**
 680     * Sets the parent for this node and if this node is active ensures that the tree is properly
 681     * adjusted as well.
 682     *
 683     * @param navigation_node $parent
 684     */
 685    public function set_parent(navigation_node $parent) {
 686        // Set the parent (thats the easy part)
 687        $this->parent = $parent;
 688        // Check if this node is active (this is checked during construction)
 689        if ($this->isactive) {
 690            // Force all of the parent nodes open so you can see this node
 691            $this->parent->force_open();
 692            // Make all parents inactive so that its clear where we are.
 693            $this->parent->make_inactive();
 694        }
 695    }
 696
 697    /**
 698     * Hides the node and any children it has.
 699     *
 700     * @since Moodle 2.5
 701     * @param array $typestohide Optional. An array of node types that should be hidden.
 702     *      If null all nodes will be hidden.
 703     *      If an array is given then nodes will only be hidden if their type mtatches an element in the array.
 704     *          e.g. array(navigation_node::TYPE_COURSE) would hide only course nodes.
 705     */
 706    public function hide(array $typestohide = null) {
 707        if ($typestohide === null || in_array($this->type, $typestohide)) {
 708            $this->display = false;
 709            if ($this->has_children()) {
 710                foreach ($this->children as $child) {
 711                    $child->hide($typestohide);
 712                }
 713            }
 714        }
 715    }
 716}
 717
 718/**
 719 * Navigation node collection
 720 *
 721 * This class is responsible for managing a collection of navigation nodes.
 722 * It is required because a node's unique identifier is a combination of both its
 723 * key and its type.
 724 *
 725 * Originally an array was used with a string key that was a combination of the two
 726 * however it was decided that a better solution would be to use a class that
 727 * implements the standard IteratorAggregate interface.
 728 *
 729 * @package   core
 730 * @category  navigation
 731 * @copyright 2010 Sam Hemelryk
 732 * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 733 */
 734class navigation_node_collection implements IteratorAggregate {
 735    /**
 736     * A multidimensional array to where the first key is the type and the second
 737     * key is the nodes key.
 738     * @var array
 739     */
 740    protected $collection = array();
 741    /**
 742     * An array that contains references to nodes in the same order they were added.
 743     * This is maintained as a progressive array.
 744     * @var array
 745     */
 746    protected $orderedcollection = array();
 747    /**
 748     * A reference to the last node that was added to the collection
 749     * @var navigation_node
 750     */
 751    protected $last = null;
 752    /**
 753     * The total number of items added to this array.
 754     * @var int
 755     */
 756    protected $count = 0;
 757
 758    /**
 759     * Adds a navigation node to the collection
 760     *
 761     * @param navigation_node $node Node to add
 762     * @param string $beforekey If specified, adds before a node with this key,
 763     *   otherwise adds at end
 764     * @return navigation_node Added node
 765     */
 766    public function add(navigation_node $node, $beforekey=null) {
 767        global $CFG;
 768        $key = $node->key;
 769        $type = $node->type;
 770
 771        // First check we have a 2nd dimension for this type
 772        if (!array_key_exists($type, $this->orderedcollection)) {
 773            $this->orderedcollection[$type] = array();
 774        }
 775        // Check for a collision and report if debugging is turned on
 776        if ($CFG->debug && array_key_exists($key, $this->orderedcollection[$type])) {
 777            debugging('Navigation node intersect: Adding a node that already exists '.$key, DEBUG_DEVELOPER);
 778        }
 779
 780        // Find the key to add before
 781        $newindex = $this->count;
 782        $last = true;
 783        if ($beforekey !== null) {
 784            foreach ($this->collection as $index => $othernode) {
 785                if ($othernode->key === $beforekey) {
 786                    $newindex = $index;
 787                    $last = false;
 788                    break;
 789                }
 790            }
 791            if ($newindex === $this->count) {
 792                debugging('Navigation node add_before: Reference node not found ' . $beforekey .
 793                        ', options: ' . implode(' ', $this->get_key_list()), DEBUG_DEVELOPER);
 794            }
 795        }
 796
 797        // Add the node to the appropriate place in the by-type structure (which
 798        // is not ordered, despite the variable name)
 799        $this->orderedcollection[$type][$key] = $node;
 800        if (!$last) {
 801            // Update existing references in the ordered collection (which is the
 802            // one that isn't called 'ordered') to shuffle them along if required
 803            for ($oldindex = $this->count; $oldindex > $newindex; $oldindex--) {
 804                $this->collection[$oldindex] = $this->collection[$oldindex - 1];
 805            }
 806        }
 807        // Add a reference to the node to the progressive collection.
 808        $this->collection[$newindex] = $this->orderedcollection[$type][$key];
 809        // Update the last property to a reference to this new node.
 810        $this->last = $this->orderedcollection[$type][$key];
 811
 812        // Reorder the array by index if needed
 813        if (!$last) {
 814            ksort($this->collection);
 815        }
 816        $this->count++;
 817        // Return the reference to the now added node
 818        return $node;
 819    }
 820
 821    /**
 822     * Return a list of all the keys of all the nodes.
 823     * @return array the keys.
 824     */
 825    public function get_key_list() {
 826        $keys = array();
 827        foreach ($this->collection as $node) {
 828            $keys[] = $node->key;
 829        }
 830        return $keys;
 831    }
 832
 833    /**
 834     * Fetches a node from this collection.
 835     *
 836     * @param string|int $key The key of the node we want to find.
 837     * @param int $type One of navigation_node::TYPE_*.
 838     * @return navigation_node|null
 839     */
 840    public function get($key, $type=null) {
 841        if ($type !== null) {
 842            // If the type is known then we can simply check and fetch
 843            if (!empty($this->orderedcollection[$type][$key])) {
 844                return $this->orderedcollection[$type][$key];
 845            }
 846        } else {
 847            // Because we don't know the type we look in the progressive array
 848            foreach ($this->collection as $node) {
 849                if ($node->key === $key) {
 850                    return $node;
 851                }
 852            }
 853        }
 854        return false;
 855    }
 856
 857    /**
 858     * Searches for a node with matching key and type.
 859     *
 860     * This function searches both the nodes in this collection and all of
 861     * the nodes in each collection belonging to the nodes in this collection.
 862     *
 863     * Recursive.
 864     *
 865     * @param string|int $key  The key of the node we want to find.
 866     * @param int $type  One of navigation_node::TYPE_*.
 867     * @return navigation_node|null
 868     */
 869    public function find($key, $type=null) {
 870        if ($type !== null && array_key_exists($type, $this->orderedcollection) && array_key_exists($key, $this->orderedcollection[$type])) {
 871            return $this->orderedcollection[$type][$key];
 872        } else {
 873            $nodes = $this->getIterator();
 874            // Search immediate children first
 875            foreach ($nodes as &$node) {
 876                if ($node->key === $key && ($type === null || $type === $node->type)) {
 877                    return $node;
 878                }
 879            }
 880            // Now search each childs children
 881            foreach ($nodes as &$node) {
 882                $result = $node->children->find($key, $type);
 883                if ($result !== false) {
 884                    return $result;
 885                }
 886            }
 887        }
 888        return false;
 889    }
 890
 891    /**
 892     * Fetches the last node that was added to this collection
 893     *
 894     * @return navigation_node
 895     */
 896    public function last() {
 897        return $this->last;
 898    }
 899
 900    /**
 901     * Fetches all nodes of a given type from this collection
 902     *
 903     * @param string|int $type  node type being searched for.
 904     * @return array ordered collection
 905     */
 906    public function type($type) {
 907        if (!array_key_exists($type, $this->orderedcollection)) {
 908            $this->orderedcollection[$type] = array();
 909        }
 910        return $this->orderedcollection[$type];
 911    }
 912    /**
 913     * Removes the node with the given key and type from the collection
 914     *
 915     * @param string|int $key The key of the node we want to find.
 916     * @param int $type
 917     * @return bool
 918     */
 919    public function remove($key, $type=null) {
 920        $child = $this->get($key, $type);
 921        if ($child !== false) {
 922            foreach ($this->collection as $colkey => $node) {
 923                if ($node->key === $key && $node->type == $type) {
 924                    unset($this->collection[$colkey]);
 925                    $this->collection = array_values($this->collection);
 926                    break;
 927                }
 928            }
 929            unset($this->orderedcollection[$child->type][$child->key]);
 930            $this->count--;
 931            return true;
 932        }
 933        return false;
 934    }
 935
 936    /**
 937     * Gets the number of nodes in this collection
 938     *
 939     * This option uses an internal count rather than counting the actual options to avoid
 940     * a performance hit through the count function.
 941     *
 942     * @return int
 943     */
 944    public function count() {
 945        return $this->count;
 946    }
 947    /**
 948     * Gets an array iterator for the collection.
 949     *
 950     * This is required by the IteratorAggregator interface and is used by routines
 951     * such as the foreach loop.
 952     *
 953     * @return ArrayIterator
 954     */
 955    public function getIterator() {
 956        return new ArrayIterator($this->collection);
 957    }
 958}
 959
 960/**
 961 * The global navigation class used for... the global navigation
 962 *
 963 * This class is used by PAGE to store the global navigation for the site
 964 * and is then used by the settings nav and navbar to save on processing and DB calls
 965 *
 966 * See
 967 * {@link lib/pagelib.php} {@link moodle_page::initialise_theme_and_output()}
 968 * {@link lib/ajax/getnavbranch.php} Called by ajax
 969 *
 970 * @package   core
 971 * @category  navigation
 972 * @copyright 2009 Sam Hemelryk
 973 * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 974 */
 975class global_navigation extends navigation_node {
 976    /** @var moodle_page The Moodle page this navigation object belongs to. */
 977    protected $page;
 978    /** @var bool switch to let us know if the navigation object is initialised*/
 979    protected $initialised = false;
 980    /** @var array An array of course information */
 981    protected $mycourses = array();
 982    /** @var navigation_node[] An array for containing  root navigation nodes */
 983    protected $rootnodes = array();
 984    /** @var bool A switch for whether to show empty sections in the navigation */
 985    protected $showemptysections = true;
 986    /** @var bool A switch for whether courses should be shown within categories on the navigation. */
 987    protected $showcategories = null;
 988    /** @var null@var bool A switch for whether or not to show categories in the my courses branch. */
 989    protected $showmycategories = null;
 990    /** @var array An array of stdClasses for users that the navigation is extended for */
 991    protected $extendforuser = array();
 992    /** @var navigation_cache */
 993    protected $cache;
 994    /** @var array An array of course ids that are present in the navigation */
 995    protected $addedcourses = array();
 996    /** @var bool */
 997    protected $allcategoriesloaded = false;
 998    /** @var array An array of category ids that are included in the navigation */
 999    protected $addedcategories = array();
1000    /** @var int expansion limit */
1001    protected $expansionlimit = 0;
1002    /** @var int userid to allow parent to see child's profile page navigation */
1003    protected $useridtouseforparentchecks = 0;
1004    /** @var cache_session A cache that stores information on expanded courses */
1005    protected $cacheexpandcourse = null;
1006
1007    /** Used when loading categories to load all top level categories [parent = 0] **/
1008    const LOAD_ROOT_CATEGORIES = 0;
1009    /** Used when loading categories to load all categories **/
1010    const LOAD_ALL_CATEGORIES = -1;
1011
1012    /**
1013     * Constructs a new global navigation
1014     *
1015     * @param moodle_page $page The page this navigation object belongs to
1016     */
1017    public function __construct(moodle_page $page) {
1018        global $CFG, $SITE, $USER;
1019
1020        if (during_initial_install()) {
1021            return;
1022        }
1023
1024        if (get_home_page() == HOMEPAGE_SITE) {
1025            // We are using the site home for the root element
1026            $properties = array(
1027                'key' => 'home',
1028                'type' => navigation_node::TYPE_SYSTEM,
1029                'text' => get_string('home'),
1030                'action' => new moodle_url('/')
1031            );
1032        } else {
1033            // We are using the users my moodle for the root element
1034            $properties = array(
1035                'key' => 'myhome',
1036                'type' => navigation_node::TYPE_SYSTEM,
1037                'text' => get_string('myhome'),
1038                'action' => new moodle_url('/my/')
1039            );
1040        }
1041
1042        // Use the parents constructor.... good good reuse
1043        parent::__construct($properties);
1044
1045        // Initalise and set defaults
1046        $this->page = $page;
1047        $this->forceopen = true;
1048        $this->cache = new navigation_cache(NAVIGATION_CACHE_NAME);
1049    }
1050
1051    /**
1052     * Mutator to set userid to allow parent to see child's profile
1053     * page navigation. See MDL-25805 for initial issue. Linked to it
1054     * is an issue explaining why this is a REALLY UGLY HACK thats not
1055     * for you to use!
1056     *
1057     * @param int $userid userid of profile page that parent wants to navigate around.
1058     */
1059    public function set_userid_for_parent_checks($userid) {
1060        $this->useridtouseforparentchecks = $userid;
1061    }
1062
1063
1064    /**
1065     * Initialises the navigation object.
1066     *
1067     * This causes the navigation object to look at the current state of the page
1068     * that it is associated with and then load the appropriate content.
1069     *
1070     * This should only occur the first time that the navigation structure is utilised
1071     * which will normally be either when the navbar is called to be displayed or
1072     * when a block makes use of it.
1073     *
1074     * @return bool
1075     */
1076    public function initialise() {
1077        global $CFG, $SITE, $USER;
1078        // Check if it has already been initialised
1079        if ($this->initialised || during_initial_install()) {
1080            return true;
1081        }
1082        $this->initialised = true;
1083
1084        // Set up the five base root nodes. These are nodes where we will put our
1085        // content and are as follows:
1086        // site: Navigation for the front page.
1087        // myprofile: User profile information goes here.
1088        // currentcourse: The course being currently viewed.
1089        // mycourses: The users courses get added here.
1090        // courses: Additional courses are added here.
1091        // users: Other users information loaded here.
1092        $this->rootnodes = array();
1093        if (get_home_page() == HOMEPAGE_SITE) {
1094            // The home element should be my moodle because the root element is the site
1095            if (isloggedin() && !isguestuser()) {  // Makes no sense if you aren't logged in
1096                $this->rootnodes['home'] = $this->add(get_string('myhome'), new moodle_url('/my/'), self::TYPE_SETTING, null, 'home');
1097            }
1098        } else {
1099            // The home element should be the site because the root node is my moodle
1100            $this->rootnodes['home'] = $this->add(get_string('sitehome'), new moodle_url('/'), self::TYPE_SETTING, null, 'home');
1101            if (!empty($CFG->defaulthomepage) && ($CFG->defaulthomepage == HOMEPAGE_MY)) {
1102                // We need to stop automatic redirection
1103                $this->rootnodes['home']->action->param('redirect', '0');
1104            }
1105        }
1106        $this->rootnodes['site'] = $this->add_course($SITE);
1107        $this->rootnodes['myprofile'] = $this->add(get_string('profile'), null, self::TYPE_USER, null, 'myprofile');
1108        $this->rootnodes['currentcourse'] = $this->add(get_string('currentcourse'), null, self::TYPE_ROOTNODE, null, 'currentcourse');
1109        $this->rootnodes['mycourses'] = $this->add(get_string('mycourses'), null, self::TYPE_ROOTNODE, null, 'mycourses');
1110        $this->rootnodes['courses'] = $this->add(get_string('courses'), new moodle_url('/course/index.php'), self::TYPE_ROOTNODE, null, 'courses');
1111        $this->rootnodes['users'] = $this->add(get_string('users'), null, self::TYPE_ROOTNODE, null, 'users');
1112
1113        // We always load the frontpage course to ensure it is available without
1114        // JavaScript enabled.
1115        $this->add_front_page_course_essentials($this->rootnodes['site'], $SITE);
1116        $this->load_course_sections($SITE, $this->rootnodes['site']);
1117
1118        $course = $this->page->course;
1119
1120        // $issite gets set to true if the current pages course is the sites frontpage course
1121        $issite = ($this->page->course->id == $SITE->id);
1122        // Determine if the user is enrolled in any course.
1123        $enrolledinanycourse = enrol_user_sees_own_courses();
1124
1125        $this->rootnodes['currentcourse']->mainnavonly = true;
1126        if ($enrolledinanycourse) {
1127            $this->rootnodes['mycourses']->isexpandable = true;
1128            if ($CFG->navshowallcourses) {
1129                // When we show all courses we need to show both the my courses and the regular courses branch.
1130                $this->rootnodes['courses']->isexpandable = true;
1131            }
1132        } else {
1133            $this->rootnodes['courses']->isexpandable = true;
1134        }
1135
1136        // Load the users enrolled courses if they are viewing the My Moodle page AND the admin has not
1137        // set that they wish to keep the My Courses branch collapsed by default.
1138        if (!empty($CFG->navexpandmycourses) && $this->page->pagelayout === 'mydashboard'){
1139            $this->rootnodes['mycourses']->forceopen = true;
1140            $this->load_courses_enrolled();
1141        } else {
1142            $this->rootnodes['mycourses']->collapse = true;
1143            $this->rootnodes['mycourses']->make_inactive();
1144        }
1145
1146        $canviewcourseprofile = true;
1147
1148        // Next load context specific content into the navigation
1149        switch ($this->page->context->contextlevel) {
1150            case CONTEXT_SYSTEM :
1151                // Nothing left to do here I feel.
1152                break;
1153            case CONTEXT_COURSECAT :
1154                // This is essential, we must load categories.
1155                $this->load_all_categories($this->page->context->instanceid, true);
1156                break;
1157            case CONTEXT_BLOCK :
1158            case CONTEXT_COURSE :
1159                if ($issite) {
1160                    // Nothing left to do here.
1161                    break;
1162                }
1163
1164                // Load the course associated with the current page into the navigation.
1165                $coursenode = $this->add_course($course, false, self::COURSE_CURRENT);
1166                // If the course wasn't added then don't try going any further.
1167                if (!$coursenode) {
1168                    $canviewcourseprofile = false;
1169                    break;
1170                }
1171
1172                // If the user is not enrolled then we only want to show the
1173                // course node and not populate it.
1174
1175                // Not enrolled, can't view, and hasn't switched roles
1176                if (!can_access_course($course, null, '', true)) {
1177                    if ($coursenode->isexpandable === true) {
1178                        // Obviously the situation has changed, update the cache and adjust the node.
1179                        // This occurs if the user access to a course has been revoked (one way or another) after
1180                        // initially logging in for this session.
1181                        $this->get_expand_course_cache()->set($course->id, 1);
1182                        $coursenode->isexpandable = true;
1183                        $coursenode->nodetype = self::NODETYPE_BRANCH;
1184                    }
1185                    // Very ugly hack - do not force "parents" to enrol into course their child is enrolled in,
1186                    // this hack has been propagated from user/view.php to display the navigation node. (MDL-25805)
1187                    if (!$this->current_user_is_parent_role()) {
1188                        $coursenode->make_active();
1189                        $canviewcourseprofile = false;
1190                        break;
1191                    }
1192                } else if ($coursenode->isexpandable === false) {
1193                    // Obviously the situation has changed, update the cache and adjust the node.
1194                    // This occurs if the user has been granted access to a course (one way or another) after initially
1195                    // logging in for this session.
1196                    $this->get_expand_course_cache()->set($course->id, 1);
1197                    $coursenode->isexpandable = true;
1198                    $coursenode->nodetype = self::NODETYPE_BRANCH;
1199                }
1200
1201                // Add the essentials such as reports etc...
1202                $this->add_course_essentials($coursenode, $course);
1203                // Extend course navigation with it's sections/activities
1204                $this->load_course_sections($course, $coursenode);
1205                if (!$coursenode->contains_active_node() && !$coursenode->search_for_active_node()) {
1206                    $coursenode->make_active();
1207                }
1208
1209                break;
1210            case CONTEXT_MODULE :
1211                if ($issite) {
1212                    // If this is the site course then most information will have
1213                    // already been loaded.
1214                    // However we need to check if there is more content that can
1215                    // yet be loaded for the specific module instance.
1216                    $activitynode = $this->rootnodes['site']->find($this->page->cm->id, navigation_node::TYPE_ACTIVITY);
1217                    if ($activitynode) {
1218                        $this->load_activity($this->page->cm, $this->page->course, $activitynode);
1219                    }
1220                    break;
1221                }
1222
1223                $course = $this->page->course;
1224                $cm = $this->page->cm;
1225
1226                // Load the course associated with the page into the navigation
1227                $coursenode = $this->add_course($course, false, self::COURSE_CURRENT);
1228
1229                // If the course wasn't added then don't try going any further.
1230                if (!$coursenode) {
1231                    $canviewcourseprofile = false;
1232                    break;
1233                }
1234
1235                // If the user is not enrolled then we only want to show the
1236                // course node and not populate it.
1237                if (!can_access_course($course, null, '', true)) {
1238                    $coursenode->make_active();
1239                    $canviewcourseprofile = false;
1240                    break;
1241                }
1242
1243                $this->add_course_essentials($coursenode, $course);
1244
1245                // Load the course sections into the page
1246                $this->load_course_sections($course, $coursenode, null, $cm);
1247                $activity = $coursenode->find($cm->id, navigation_node::TYPE_ACTIVITY);
1248                if (!empty($activity)) {
1249                    // Finally load the cm specific navigaton information
1250                    $this->load_activity($cm, $course, $activity);
1251                    // Check if we have an active ndoe
1252                    if (!$activity->contains_active_node() && !$activity->search_for_active_node()) {
1253                        // And make the activity node active.
1254                        $activity->make_active();
1255                    }
1256                }
1257                break;
1258            case CONTEXT_USER :
1259                if ($issite) {
1260                    // The users profile information etc is already loaded
1261                    // for the front page.
1262                    break;
1263                }
1264                $course = $this->page->course;
1265                // Load the course associated with the user into the navigation
1266                $coursenode = $this->add_course($course, false, self::COURSE_CURRENT);
1267
1268                // If the course wasn't added then don't try going any further.
1269                if (!$coursenode) {
1270                    $canviewcourseprofile = false;
1271                    break;
1272                }
1273
1274                // If the user is not enrolled then we only want to show the
1275                // course node and not populate it.
1276                if (!can_access_course($course, null, '', true)) {
1277                    $coursenode->make_active();
1278                    $canviewcourseprofile = false;
1279                    break;
1280                }
1281                $this->add_course_essentials($coursenode, $course);
1282                $this->load_course_sections($course, $coursenode);
1283                break;
1284        }
1285
1286        // Load for the current user
1287        $this->load_f…

Large files files are truncated, but you can click here to view the full file