PageRenderTime 66ms CodeModel.GetById 27ms RepoModel.GetById 1ms app.codeStats 1ms

/lib/navigationlib.php

https://github.com/lsuits/moodle
PHP | 4905 lines | 2966 code | 392 blank | 1547 comment | 899 complexity | aca9fb727abc7da1c073158d58ad1c88 MD5 | raw file
Possible License(s): GPL-3.0, LGPL-2.1, BSD-3-Clause, Apache-2.0

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

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