PageRenderTime 91ms CodeModel.GetById 26ms RepoModel.GetById 0ms app.codeStats 1ms

/lib/navigationlib.php

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