PageRenderTime 124ms CodeModel.GetById 18ms RepoModel.GetById 2ms app.codeStats 2ms

/lib/navigationlib.php

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