PageRenderTime 171ms CodeModel.GetById 22ms RepoModel.GetById 1ms app.codeStats 2ms

/lib/navigationlib.php

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