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

/lib/navigationlib.php

https://github.com/gwamgerald/moodle-1
PHP | 4910 lines | 2969 code | 392 blank | 1549 comment | 901 complexity | ff6ca64076c0b8f53162a9a9b3a40cd9 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 navigation_node[] 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. // Load the users enrolled courses if they are viewing the My Moodle page AND the admin has not
  1068. // set that they wish to keep the My Courses branch collapsed by default.
  1069. if (!empty($CFG->navexpandmycourses) && $this->rootnodes['mycourses']->isactive){
  1070. $this->load_courses_enrolled();
  1071. } else {
  1072. $this->rootnodes['mycourses']->collapse = true;
  1073. $this->rootnodes['mycourses']->make_inactive();
  1074. }
  1075. $canviewcourseprofile = true;
  1076. // Next load context specific content into the navigation
  1077. switch ($this->page->context->contextlevel) {
  1078. case CONTEXT_SYSTEM :
  1079. // Nothing left to do here I feel.
  1080. break;
  1081. case CONTEXT_COURSECAT :
  1082. // This is essential, we must load categories.
  1083. $this->load_all_categories($this->page->context->instanceid, true);
  1084. break;
  1085. case CONTEXT_BLOCK :
  1086. case CONTEXT_COURSE :
  1087. if ($issite) {
  1088. // Nothing left to do here.
  1089. break;
  1090. }
  1091. // Load the course associated with the current page into the navigation.
  1092. $coursenode = $this->add_course($course, false, self::COURSE_CURRENT);
  1093. // If the course wasn't added then don't try going any further.
  1094. if (!$coursenode) {
  1095. $canviewcourseprofile = false;
  1096. break;
  1097. }
  1098. // If the user is not enrolled then we only want to show the
  1099. // course node and not populate it.
  1100. // Not enrolled, can't view, and hasn't switched roles
  1101. if (!can_access_course($course)) {
  1102. if ($coursenode->isexpandable === true) {
  1103. // Obviously the situation has changed, update the cache and adjust the node.
  1104. // This occurs if the user access to a course has been revoked (one way or another) after
  1105. // initially logging in for this session.
  1106. $this->get_expand_course_cache()->set($course->id, 1);
  1107. $coursenode->isexpandable = true;
  1108. $coursenode->nodetype = self::NODETYPE_BRANCH;
  1109. }
  1110. // Very ugly hack - do not force "parents" to enrol into course their child is enrolled in,
  1111. // this hack has been propagated from user/view.php to display the navigation node. (MDL-25805)
  1112. if (!$this->current_user_is_parent_role()) {
  1113. $coursenode->make_active();
  1114. $canviewcourseprofile = false;
  1115. break;
  1116. }
  1117. }
  1118. if ($coursenode->isexpandable === false) {
  1119. // Obviously the situation has changed, update the cache and adjust the node.
  1120. // This occurs if the user has been granted access to a course (one way or another) after initially
  1121. // logging in for this session.
  1122. $this->get_expand_course_cache()->set($course->id, 1);
  1123. $coursenode->isexpandable = true;
  1124. $coursenode->nodetype = self::NODETYPE_BRANCH;
  1125. }
  1126. // Add the essentials such as reports etc...
  1127. $this->add_course_essentials($coursenode, $course);
  1128. // Extend course navigation with it's sections/activities
  1129. $this->load_course_sections($course, $coursenode);
  1130. if (!$coursenode->contains_active_node() && !$coursenode->search_for_active_node()) {
  1131. $coursenode->make_active();
  1132. }
  1133. break;
  1134. case CONTEXT_MODULE :
  1135. if ($issite) {
  1136. // If this is the site course then most information will have
  1137. // already been loaded.
  1138. // However we need to check if there is more content that can
  1139. // yet be loaded for the specific module instance.
  1140. $activitynode = $this->rootnodes['site']->find($this->page->cm->id, navigation_node::TYPE_ACTIVITY);
  1141. if ($activitynode) {
  1142. $this->load_activity($this->page->cm, $this->page->course, $activitynode);
  1143. }
  1144. break;
  1145. }
  1146. $course = $this->page->course;
  1147. $cm = $this->page->cm;
  1148. // Load the course associated with the page into the navigation
  1149. $coursenode = $this->add_course($course, false, self::COURSE_CURRENT);
  1150. // If the course wasn't added then don't try going any further.
  1151. if (!$coursenode) {
  1152. $canviewcourseprofile = false;
  1153. break;
  1154. }
  1155. // If the user is not enrolled then we only want to show the
  1156. // course node and not populate it.
  1157. if (!can_access_course($course)) {
  1158. $coursenode->make_active();
  1159. $canviewcourseprofile = false;
  1160. break;
  1161. }
  1162. $this->add_course_essentials($coursenode, $course);
  1163. // Load the course sections into the page
  1164. $this->load_course_sections($course, $coursenode, null, $cm);
  1165. $activity = $coursenode->find($cm->id, navigation_node::TYPE_ACTIVITY);
  1166. if (!empty($activity)) {
  1167. // Finally load the cm specific navigaton information
  1168. $this->load_activity($cm, $course, $activity);
  1169. // Check if we have an active ndoe
  1170. if (!$activity->contains_active_node() && !$activity->search_for_active_node()) {
  1171. // And make the activity node active.
  1172. $activity->make_active();
  1173. }
  1174. }
  1175. break;
  1176. case CONTEXT_USER :
  1177. if ($issite) {
  1178. // The users profile information etc is already loaded
  1179. // for the front page.
  1180. break;
  1181. }
  1182. $course = $this->page->course;
  1183. // Load the course associated with the user into the navigation
  1184. $coursenode = $this->add_course($course, false, self::COURSE_CURRENT);
  1185. // If the course wasn't added then don't try going any further.
  1186. if (!$coursenode) {
  1187. $canviewcourseprofile = false;
  1188. break;
  1189. }
  1190. // If the user is not enrolled then we only want to show the
  1191. // course node and not populate it.
  1192. if (!can_access_course($course)) {
  1193. $coursenode->make_active();
  1194. $canviewcourseprofile = false;
  1195. break;
  1196. }
  1197. $this->add_course_essentials($coursenode, $course);
  1198. $this->load_course_sections($course, $coursenode);
  1199. break;
  1200. }
  1201. // Load for the current user
  1202. $this->load_for_user();
  1203. if ($this->page->context->contextlevel >= CONTEXT_COURSE && $this->page->context->instanceid != $SITE->id && $canviewcourseprofile) {
  1204. $this->load_for_user(null, true);
  1205. }
  1206. // Load each extending user into the navigation.
  1207. foreach ($this->extendforuser as $user) {
  1208. if ($user->id != $USER->id) {
  1209. $this->load_for_user($user);
  1210. }
  1211. }
  1212. // Give the local plugins a chance to include some navigation if they want.
  1213. foreach (core_component::get_plugin_list_with_file('local', 'lib.php', true) as $plugin => $file) {
  1214. $function = "local_{$plugin}_extends_navigation";
  1215. $oldfunction = "{$plugin}_extends_navigation";
  1216. if (function_exists($function)) {
  1217. // This is the preferred function name as there is less chance of conflicts
  1218. $function($this);
  1219. } else if (function_exists($oldfunction)) {
  1220. // We continue to support the old function name to ensure backwards compatibility
  1221. 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);
  1222. $oldfunction($this);
  1223. }
  1224. }
  1225. // Remove any empty root nodes
  1226. foreach ($this->rootnodes as $node) {
  1227. // Dont remove the home node
  1228. /** @var navigation_node $node */
  1229. if ($node->key !== 'home' && !$node->has_children() && !$node->isactive) {
  1230. $node->remove();
  1231. }
  1232. }
  1233. if (!$this->contains_active_node()) {
  1234. $this->search_for_active_node();
  1235. }
  1236. // If the user is not logged in modify the navigation structure as detailed
  1237. // in {@link http://docs.moodle.org/dev/Navigation_2.0_structure}
  1238. if (!isloggedin()) {
  1239. $activities = clone($this->rootnodes['site']->children);
  1240. $this->rootnodes['site']->remove();
  1241. $children = clone($this->children);
  1242. $this->children = new navigation_node_collection();
  1243. foreach ($activities as $child) {
  1244. $this->children->add($child);
  1245. }
  1246. foreach ($children as $child) {
  1247. $this->children->add($child);
  1248. }
  1249. }
  1250. return true;
  1251. }
  1252. /**
  1253. * Returns true if the current user is a parent of the user being currently viewed.
  1254. *
  1255. * If the current user is not viewing another user, or if the current user does not hold any parent roles over the
  1256. * other user being viewed this function returns false.
  1257. * In order to set the user for whom we are checking against you must call {@link set_userid_for_parent_checks()}
  1258. *
  1259. * @since Moodle 2.4
  1260. * @return bool
  1261. */
  1262. protected function current_user_is_parent_role() {
  1263. global $USER, $DB;
  1264. if ($this->useridtouseforparentchecks && $this->useridtouseforparentchecks != $USER->id) {
  1265. $usercontext = context_user::instance($this->useridtouseforparentchecks, MUST_EXIST);
  1266. if (!has_capability('moodle/user:viewdetails', $usercontext)) {
  1267. return false;
  1268. }
  1269. if ($DB->record_exists('role_assignments', array('userid' => $USER->id, 'contextid' => $usercontext->id))) {
  1270. return true;
  1271. }
  1272. }
  1273. return false;
  1274. }
  1275. /**
  1276. * Returns true if courses should be shown within categories on the navigation.
  1277. *
  1278. * @param bool $ismycourse Set to true if you are calculating this for a course.
  1279. * @return bool
  1280. */
  1281. protected function show_categories($ismycourse = false) {
  1282. global $CFG, $DB;
  1283. if ($ismycourse) {
  1284. return $this->show_my_categories();
  1285. }
  1286. if ($this->showcategories === null) {
  1287. $show = false;
  1288. if ($this->page->context->contextlevel == CONTEXT_COURSECAT) {
  1289. $show = true;
  1290. } else if (!empty($CFG->navshowcategories) && $DB->count_records('course_categories') > 1) {
  1291. $show = true;
  1292. }
  1293. $this->showcategories = $show;
  1294. }
  1295. return $this->showcategories;
  1296. }
  1297. /**
  1298. * Returns true if we should show categories in the My Courses branch.
  1299. * @return bool
  1300. */
  1301. protected function show_my_categories() {
  1302. global $CFG, $DB;
  1303. if ($this->showmycategories === null) {
  1304. $this->showmycategories = !empty($CFG->navshowmycoursecategories) && $DB->count_records('course_categories') > 1;
  1305. }
  1306. return $this->showmycategories;
  1307. }
  1308. /**
  1309. * Loads the courses in Moodle into the navigation.
  1310. *
  1311. * @global moodle_database $DB
  1312. * @param string|array $categoryids An array containing categories to load courses
  1313. * for, OR null to load courses for all categories.
  1314. * @return array An array of navigation_nodes one for each course
  1315. */
  1316. protected function load_all_courses($categoryids = null) {
  1317. global $CFG, $DB, $SITE;
  1318. // Work out the limit of courses.
  1319. $limit = 20;
  1320. if (!empty($CFG->navcourselimit)) {
  1321. $limit = $CFG->navcourselimit;
  1322. }
  1323. $toload = (empty($CFG->navshowallcourses))?self::LOAD_ROOT_CATEGORIES:self::LOAD_ALL_CATEGORIES;
  1324. // If we are going to show all courses AND we are showing categories then
  1325. // to save us repeated DB calls load all of the categories now
  1326. if ($this->show_categories()) {
  1327. $this->load_all_categories($toload);
  1328. }
  1329. // Will be the return of our efforts
  1330. $coursenodes = array();
  1331. // Check if we need to show categories.
  1332. if ($this->show_categories()) {
  1333. // Hmmm we need to show categories... this is going to be painful.
  1334. // We now need to fetch up to $limit courses for each category to
  1335. // be displayed.
  1336. if ($categoryids !== null) {
  1337. if (!is_array($categoryids)) {
  1338. $categoryids = array($categoryids);
  1339. }
  1340. list($categorywhere, $categoryparams) = $DB->get_in_or_equal($categoryids, SQL_PARAMS_NAMED, 'cc');
  1341. $categorywhere = 'WHERE cc.id '.$categorywhere;
  1342. } else if ($toload == self::LOAD_ROOT_CATEGORIES) {
  1343. $categorywhere = 'WHERE cc.depth = 1 OR cc.depth = 2';
  1344. $categoryparams = array();
  1345. } else {
  1346. $categorywhere = '';
  1347. $categoryparams = array();
  1348. }
  1349. // First up we are going to get the categories that we are going to
  1350. // need so that we can determine how best to load the courses from them.
  1351. $sql = "SELECT cc.id, COUNT(c.id) AS coursecount
  1352. FROM {course_categories} cc
  1353. LEFT JOIN {course} c ON c.category = cc.id
  1354. {$categorywhere}
  1355. GROUP BY cc.id";
  1356. $categories = $DB->get_recordset_sql($sql, $categoryparams);
  1357. $fullfetch = array();
  1358. $partfetch = array();
  1359. foreach ($categories as $category) {
  1360. if (!$this->can_add_more_courses_to_category($category->id)) {
  1361. continue;
  1362. }
  1363. if ($category->coursecount > $limit * 5) {
  1364. $partfetch[] = $category->id;
  1365. } else if ($category->coursecount > 0) {
  1366. $fullfetch[] = $category->id;
  1367. }
  1368. }
  1369. $categories->close();
  1370. if (count($fullfetch)) {
  1371. // First up fetch all of the courses in categories where we know that we are going to
  1372. // need the majority of courses.
  1373. list($categoryids, $categoryparams) = $DB->get_in_or_equal($fullfetch, SQL_PARAMS_NAMED, 'lcategory');
  1374. $ccselect = ', ' . context_helper::get_preload_record_columns_sql('ctx');
  1375. $ccjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
  1376. $categoryparams['contextlevel'] = CONTEXT_COURSE;
  1377. $sql = "SELECT c.id, c.sortorder, c.visible, c.fullname, c.shortname, c.category $ccselect
  1378. FROM {course} c
  1379. $ccjoin
  1380. WHERE c.category {$categoryids}
  1381. ORDER BY c.sortorder ASC";
  1382. $coursesrs = $DB->get_recordset_sql($sql, $categoryparams);
  1383. foreach ($coursesrs as $course) {
  1384. if ($course->id == $SITE->id) {
  1385. // This should not be necessary, frontpage is not in any category.
  1386. continue;
  1387. }
  1388. if (array_key_exists($course->id, $this->addedcourses)) {
  1389. // It is probably better to not include the already loaded courses
  1390. // directly in SQL because inequalities may confuse query optimisers
  1391. // and may interfere with query caching.
  1392. continue;
  1393. }
  1394. if (!$this->can_add_more_courses_to_category($course->category)) {
  1395. continue;
  1396. }
  1397. context_helper::preload_from_record($course);
  1398. if (!$course->visible && !is_role_switched($course->id) && !has_capability('moodle/course:viewhiddencourses', context_course::instance($course->id))) {
  1399. continue;
  1400. }
  1401. $coursenodes[$course->id] = $this->add_course($course);
  1402. }
  1403. $coursesrs->close();
  1404. }
  1405. if (count($partfetch)) {
  1406. // Next we will work our way through the categories where we will likely only need a small
  1407. // proportion of the courses.
  1408. foreach ($partfetch as $categoryid) {
  1409. $ccselect = ', ' . context_helper::get_preload_record_columns_sql('ctx');
  1410. $ccjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
  1411. $sql = "SELECT c.id, c.sortorder, c.visible, c.fullname, c.shortname, c.category $ccselect
  1412. FROM {course} c
  1413. $ccjoin
  1414. WHERE c.category = :categoryid
  1415. ORDER BY c.sortorder ASC";
  1416. $courseparams = array('categoryid' => $categoryid, 'contextlevel' => CONTEXT_COURSE);
  1417. $coursesrs = $DB->get_recordset_sql($sql, $courseparams, 0, $limit * 5);
  1418. foreach ($coursesrs as $course) {
  1419. if ($course->id == $SITE->id) {
  1420. // This should not be necessary, frontpage is not in any category.
  1421. continue;
  1422. }
  1423. if (array_key_exists($course->id, $this->addedcourses)) {
  1424. // It is probably better to not include the already loaded courses
  1425. // directly in SQL because inequalities may confuse query optimisers
  1426. // and may interfere with query caching.
  1427. // This also helps to respect expected $limit on repeated executions.
  1428. continue;
  1429. }
  1430. if (!$this->can_add_more_courses_to_category($course->category)) {
  1431. break;
  1432. }
  1433. context_helper::preload_from_record($course);
  1434. if (!$course->visible && !is_role_switched($course->id) && !has_capability('moodle/course:viewhiddencourses', context_course::instance($course->id))) {
  1435. continue;
  1436. }
  1437. $coursenodes[$course->id] = $this->add_course($course);
  1438. }
  1439. $coursesrs->close();
  1440. }
  1441. }
  1442. } else {
  1443. // Prepare the SQL to load the courses and their contexts
  1444. list($courseids, $courseparams) = $DB->get_in_or_equal(array_keys($this->addedcourses), SQL_PARAMS_NAMED, 'lc', false);
  1445. $ccselect = ', ' . context_helper::get_preload_record_columns_sql('ctx');
  1446. $ccjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
  1447. $courseparams['contextlevel'] = CONTEXT_COURSE;
  1448. $sql = "SELECT c.id, c.sortorder, c.visible, c.fullname, c.shortname, c.category $ccselect
  1449. FROM {course} c
  1450. $ccjoin
  1451. WHERE c.id {$courseids}
  1452. ORDER BY c.sortorder ASC";
  1453. $coursesrs = $DB->get_recordset_sql($sql, $courseparams);
  1454. foreach ($coursesrs as $course) {
  1455. if ($course->id == $SITE->id) {
  1456. // frotpage is not wanted here
  1457. continue;
  1458. }
  1459. if ($this->page->course && ($this->page->course->id == $course->id)) {
  1460. // Don't include the currentcourse in this nodelist - it's displayed in the Current course node
  1461. continue;
  1462. }
  1463. context_helper::preload_from_record($course);
  1464. if (!$course->visible && !is_role_switched($course->id) && !has_capability('moodle/course:viewhiddencourses', context_course::instance($course->id))) {
  1465. continue;
  1466. }
  1467. $coursenodes[$course->id] = $this->add_course($course);
  1468. if (count($coursenodes) >= $limit) {
  1469. break;
  1470. }
  1471. }
  1472. $coursesrs->close();
  1473. }
  1474. return $coursenodes;
  1475. }
  1476. /**
  1477. * Returns true if more courses can be added to the provided category.
  1478. *
  1479. * @param int|navigation_node|stdClass $category
  1480. * @return bool
  1481. */
  1482. protected function can_add_more_courses_to_category($category) {
  1483. global $CFG;
  1484. $limit = 20;
  1485. if (!empty($CFG->navcourselimit)) {
  1486. $limit = (int)$CFG->navcourselimit;
  1487. }
  1488. if (is_numeric($category)) {
  1489. if (!array_key_exists($category, $this->addedcategories)) {
  1490. return true;
  1491. }
  1492. $coursecount = count($this->addedcategories[$category]->children->type(self::TYPE_COURSE));
  1493. } else if ($category instanceof navigation_node) {
  1494. if (($category->type != self::TYPE_CATEGORY) || ($category->type != self::TYPE_MY_CATEGORY)) {
  1495. return false;
  1496. }
  1497. $coursecount = count($category->children->type(self::TYPE_COURSE));
  1498. } else if (is_object($category) && property_exists($category,'id')) {
  1499. $coursecount = count($this->addedcategories[$category->id]->children->type(self::TYPE_COURSE));
  1500. }
  1501. return ($coursecount <= $limit);
  1502. }
  1503. /**
  1504. * Loads all categories (top level or if an id is specified for that category)
  1505. *
  1506. * @param int $categoryid The category id to load or null/0 to load all base level categories
  1507. * @param bool $showbasecategories If set to true all base level categories will be loaded as well
  1508. * as the requested category and any parent categories.
  1509. * @return navigation_node|void returns a navigation node if a category has been loaded.
  1510. */
  1511. protected function load_all_categories($categoryid = self::LOAD_ROOT_CATEGORIES, $showbasecategories = false) {
  1512. global $CFG, $DB;
  1513. // Check if this category has already been loaded
  1514. if ($this->allcategoriesloaded || ($categoryid < 1 && $this->is_category_fully_loaded($categoryid))) {
  1515. return true;
  1516. }
  1517. $catcontextsql = context_helper::get_preload_record_columns_sql('ctx');
  1518. $sqlselect = "SELECT cc.*, $catcontextsql
  1519. FROM {course_categories} cc
  1520. JOIN {context} ctx ON cc.id = ctx.instanceid";
  1521. $sqlwhere = "WHERE ctx.contextlevel = ".CONTEXT_COURSECAT;
  1522. $sqlorder = "ORDER BY cc.depth ASC, cc.sortorder ASC, cc.id ASC";
  1523. $params = array();
  1524. $categoriestoload = array();
  1525. if ($categoryid == self::LOAD_ALL_CATEGORIES) {
  1526. // We are going to load all categories regardless... prepare to fire
  1527. // on the database server!
  1528. } else if ($categoryid == self::LOAD_ROOT_CATEGORIES) { // can be 0
  1529. // We are going to load all of the first level categories (categories without parents)
  1530. $sqlwhere .= " AND cc.parent = 0";
  1531. } else if (array_key_exists($categoryid, $this->addedcategories)) {
  1532. // The category itself has been loaded already so we just need to ensure its subcategories
  1533. // have been loaded
  1534. list($sql, $params) = $DB->get_in_or_equal(array_keys($this->addedcategories), SQL_PARAMS_NAMED, 'parent', false);
  1535. if ($showbasecategories) {
  1536. // We need to include categories with parent = 0 as well
  1537. $sqlwhere .= " AND (cc.parent = :categoryid OR cc.parent = 0) AND cc.parent {$sql}";
  1538. } else {
  1539. // All we need is categories that match the parent
  1540. $sqlwhere .= " AND cc.parent = :categoryid AND cc.parent {$sql}";
  1541. }
  1542. $params['categoryid'] = $categoryid;
  1543. } else {
  1544. // This category hasn't been loaded yet so we need to fetch it, work out its category path
  1545. // and load this category plus all its parents and subcategories
  1546. $category = $DB->get_record('course_categories', array('id' => $categoryid), 'path', MUST_EXIST);
  1547. $categoriestoload = explode('/', trim($category->path, '/'));
  1548. list($select, $params) = $DB->get_in_or_equal($categoriestoload);
  1549. // We are going to use select twice so double the params
  1550. $params = array_merge($params, $params);
  1551. $basecategorysql = ($showbasecategories)?' OR cc.depth = 1':'';
  1552. $sqlwhere .= " AND (cc.id {$select} OR cc.parent {$select}{$basecategorysql})";
  1553. }
  1554. $categoriesrs = $DB->get_recordset_sql("$sqlselect $sqlwhere $sqlorder", $params);
  1555. $categories = array();
  1556. foreach ($categoriesrs as $category) {
  1557. // Preload the context.. we'll need it when adding the category in order
  1558. // to format the category name.
  1559. context_helper::preload_from_record($category);
  1560. if (array_key_exists($category->id, $this->addedcategories)) {
  1561. // Do nothing, its already been added.
  1562. } else if ($category->parent == '0') {
  1563. // This is a root category lets add it immediately
  1564. $this->add_category($category, $this->rootnodes['courses']);
  1565. } else if (array_key_exists($category->parent, $this->addedcategories)) {
  1566. // This categories parent has already been added we can add this immediately
  1567. $this->add_category($category, $this->addedcategories[$category->parent]);
  1568. } else {
  1569. $categories[] = $category;
  1570. }
  1571. }
  1572. $categoriesrs->close();
  1573. // Now we have an array of categories we need to add them to the navigation.
  1574. while (!empty($categories)) {
  1575. $category = reset($categories);
  1576. if (array_key_exists($category->id, $this->addedcategories)) {
  1577. // Do nothing
  1578. } else if ($category->parent == '0') {
  1579. $this->add_category($category, $this->rootnodes['courses']);
  1580. } else if (array_key_exists($category->parent, $this->addedcategories)) {
  1581. $this->add_category($category, $this->addedcategories[$category->parent]);
  1582. } else {
  1583. // This category isn't in the navigation and niether is it's parent (yet).
  1584. // We need to go through the category path and add all of its components in order.
  1585. $path = explode('/', trim($category->path, '/'));
  1586. foreach ($path as $catid) {
  1587. if (!array_key_exists($catid, $this->addedcategories)) {
  1588. // This category isn't in the navigation yet so add it.
  1589. $subcategory = $categories[$catid];
  1590. if ($subcategory->parent == '0') {
  1591. // Yay we have a root category - this likely means we will now be able
  1592. // to add categories without problems.
  1593. $this->add_category($subcategory, $this->rootnodes['courses']);
  1594. } else if (array_key_exists($subcategory->parent, $this->addedcategories)) {
  1595. // The parent is in the category (as we'd expect) so add it now.
  1596. $this->add_category($subcategory, $this->addedcategories[$subcategory->parent]);
  1597. // Remove the category from the categories array.
  1598. unset($categories[$catid]);
  1599. } else {
  1600. // We should never ever arrive here - if we have then there is a bigger
  1601. // problem at hand.
  1602. throw new coding_exception('Category path order is incorrect and/or there are missing categories');
  1603. }
  1604. }
  1605. }
  1606. }
  1607. // Remove the category from the categories array now that we know it has been added.
  1608. unset($categories[$category->id]);
  1609. }
  1610. if ($categoryid === self::LOAD_ALL_CATEGORIES) {
  1611. $this->allcategoriesloaded = true;
  1612. }
  1613. // Check if there are any categories to load.
  1614. if (count($categoriestoload) > 0) {
  1615. $readytoloadcourses = array();
  1616. foreach ($categoriestoload as $category) {
  1617. if ($this->can_add_more_courses_to_category($category)) {
  1618. $readytoloadcourses[] = $category;
  1619. }
  1620. }
  1621. if (count($readytoloadcourses)) {
  1622. $this->load_all_courses($readytoloadcourses);
  1623. }
  1624. }
  1625. // Look for all categories which have been loaded
  1626. if (!empty($this->addedcategories)) {
  1627. $categoryids = array();
  1628. foreach ($this->addedcategories as $category) {
  1629. if ($this->can_add_more_courses_to_category($category)) {
  1630. $categoryids[] = $category->key;
  1631. }
  1632. }
  1633. if ($categoryids) {
  1634. list($categoriessql, $params) = $DB->get_in_or_equal($categoryids, SQL_PARAMS_NAMED);
  1635. $params['limit'] = (!empty($CFG->navcourselimit))?$CFG->navcourselimit:20;
  1636. $sql = "SELECT cc.id, COUNT(c.id) AS coursecount
  1637. FROM {course_categories} cc
  1638. JOIN {course} c ON c.category = cc.id
  1639. WHERE cc.id {$categoriessql}
  1640. GROUP BY cc.id
  1641. HAVING COUNT(c.id) > :limit";
  1642. $excessivecategories = $DB->get_records_sql($sql, $params);
  1643. foreach ($categories as &$category) {
  1644. if (array_key_exists($category->key, $excessivecategories) && !$this->can_add_more_courses_to_category($category)) {
  1645. $url = new moodle_url('/course/index.php', array('categoryid' => $category->key));
  1646. $category->add(get_string('viewallcourses'), $url, self::TYPE_SETTING);
  1647. }
  1648. }
  1649. }
  1650. }
  1651. }
  1652. /**
  1653. * Adds a structured category to the navigation in the correct order/place
  1654. *
  1655. * @param stdClass $category category to be added in navigation.
  1656. * @param navigation_node $parent parent navigation node
  1657. * @param int $nodetype type of node, if category is under MyHome then it's TYPE_MY_CATEGORY
  1658. * @return void.
  1659. */
  1660. protected function add_category(stdClass $category, navigation_node $parent, $nodetype = self::TYPE_CATEGORY) {
  1661. if (array_key_exists($category->id, $this->addedcategories)) {
  1662. return;
  1663. }
  1664. $url = new moodle_url('/course/index.php', array('categoryid' => $category->id));
  1665. $context = context_coursecat::instance($category->id);
  1666. $categoryname = format_string($category->name, true, array('context' => $context));
  1667. $categorynode = $parent->add($categoryname, $url, $nodetype, $categoryname, $category->id);
  1668. if (empty($category->visible)) {
  1669. if (has_capability('moodle/category:viewhiddencategories', context_system::instance())) {
  1670. $categorynode->hidden = true;
  1671. } else {
  1672. $categorynode->display = false;
  1673. }
  1674. }
  1675. $this->addedcategories[$category->id] = $categorynode;
  1676. }
  1677. /**
  1678. * Loads the given course into the navigation
  1679. *
  1680. * @param stdClass $course
  1681. * @return navigation_node
  1682. */
  1683. protected function load_course(stdClass $course) {
  1684. global $SITE;
  1685. if ($course->id == $SITE->id) {
  1686. // This is always loaded during initialisation
  1687. return $this->rootnodes['site'];
  1688. } else if (array_key_exists($course->id, $this->addedcourses)) {
  1689. // The course has already been loaded so return a reference
  1690. return $this->addedcourses[$course->id];
  1691. } else {
  1692. // Add the course
  1693. return $this->add_course($course);
  1694. }
  1695. }
  1696. /**
  1697. * Loads all of the courses section into the navigation.
  1698. *
  1699. * This function calls method from current course format, see
  1700. * {@link format_base::extend_course_navigation()}
  1701. * If course module ($cm) is specified but course format failed to create the node,
  1702. * the activity node is created anyway.
  1703. *
  1704. * By default course formats call the method {@link global_navigation::load_generic_course_sections()}
  1705. *
  1706. * @param stdClass $course Database record for the course
  1707. * @param navigation_node $coursenode The course node within the navigation
  1708. * @param null|int $sectionnum If specified load the contents of section with this relative number
  1709. * @param null|cm_info $cm If specified make sure that activity node is created (either
  1710. * in containg section or by calling load_stealth_activity() )
  1711. */
  1712. protected function load_course_sections(stdClass $course, navigation_node $coursenode, $sectionnum = null, $cm = null) {
  1713. global $CFG, $SITE;
  1714. require_once($CFG->dirroot.'/course/lib.php');
  1715. if (isset($cm->sectionnum)) {
  1716. $sectionnum = $cm->sectionnum;
  1717. }
  1718. if ($sectionnum !== null) {
  1719. $this->includesectionnum = $sectionnum;
  1720. }
  1721. course_get_format($course)->extend_course_navigation($this, $coursenode, $sectionnum, $cm);
  1722. if (isset($cm->id)) {
  1723. $activity = $coursenode->find($cm->id, self::TYPE_ACTIVITY);
  1724. if (empty($activity)) {
  1725. $activity = $this->load_stealth_activity($coursenode, get_fast_modinfo($course));
  1726. }
  1727. }
  1728. }
  1729. /**
  1730. * Generates an array of sections and an array of activities for the given course.
  1731. *
  1732. * This method uses the cache to improve performance and avoid the get_fast_modinfo call
  1733. *
  1734. * @param stdClass $course
  1735. * @return array Array($sections, $activities)
  1736. */
  1737. protected function generate_sections_and_activities(stdClass $course) {
  1738. global $CFG;
  1739. require_once($CFG->dirroot.'/course/lib.php');
  1740. $modinfo = get_fast_modinfo($course);
  1741. $sections = $modinfo->get_section_info_all();
  1742. // For course formats using 'numsections' trim the sections list
  1743. $courseformatoptions = course_get_format($course)->get_format_options();
  1744. if (isset($courseformatoptions['numsections'])) {
  1745. $sections = array_slice($sections, 0, $courseformatoptions['numsections']+1, true);
  1746. }
  1747. $activities = array();
  1748. foreach ($sections as $key => $section) {
  1749. // Clone and unset summary to prevent $SESSION bloat (MDL-31802).
  1750. $sections[$key] = clone($section);
  1751. unset($sections[$key]->summary);
  1752. $sections[$key]->hasactivites = false;
  1753. if (!array_key_exists($section->section, $modinfo->sections)) {
  1754. continue;
  1755. }
  1756. foreach ($modinfo->sections[$section->section] as $cmid) {
  1757. $cm = $modinfo->cms[$cmid];
  1758. $activity = new stdClass;
  1759. $activity->id = $cm->id;
  1760. $activity->course = $course->id;
  1761. $activity->section = $section->section;
  1762. $activity->name = $cm->name;
  1763. $activity->icon = $cm->icon;
  1764. $activity->iconcomponent = $cm->iconcomponent;
  1765. $activity->hidden = (!$cm->visible);
  1766. $activity->modname = $cm->modname;
  1767. $activity->nodetype = navigation_node::NODETYPE_LEAF;
  1768. $activity->onclick = $cm->onclick;
  1769. $url = $cm->url;
  1770. if (!$url) {
  1771. $activity->url = null;
  1772. $activity->display = false;
  1773. } else {
  1774. $activity->url = $url->out();
  1775. $activity->display = $cm->uservisible ? true : false;
  1776. if (self::module_extends_navigation($cm->modname)) {
  1777. $activity->nodetype = navigation_node::NODETYPE_BRANCH;
  1778. }
  1779. }
  1780. $activities[$cmid] = $activity;
  1781. if ($activity->display) {
  1782. $sections[$key]->hasactivites = true;
  1783. }
  1784. }
  1785. }
  1786. return array($sections, $activities);
  1787. }
  1788. /**
  1789. * Generically loads the course sections into the course's navigation.
  1790. *
  1791. * @param stdClass $course
  1792. * @param navigation_node $coursenode
  1793. * @return array An array of course section nodes
  1794. */
  1795. public function load_generic_course_sections(stdClass $course, navigation_node $coursenode) {
  1796. global $CFG, $DB, $USER, $SITE;
  1797. require_once($CFG->dirroot.'/course/lib.php');
  1798. list($sections, $activities) = $this->generate_sections_and_activities($course);
  1799. $navigationsections = array();
  1800. foreach ($sections as $sectionid => $section) {
  1801. $section = clone($section);
  1802. if ($course->id == $SITE->id) {
  1803. $this->load_section_activities($coursenode, $section->section, $activities);
  1804. } else {
  1805. if (!$section->uservisible || (!$this->showemptysections &&
  1806. !$section->hasactivites && $this->includesectionnum !== $section->section)) {
  1807. continue;
  1808. }
  1809. $sectionname = get_section_name($course, $section);
  1810. $url = course_get_url($course, $section->section, array('navigation' => true));
  1811. $sectionnode = $coursenode->add($sectionname, $url, navigation_node::TYPE_SECTION, null, $section->id);
  1812. $sectionnode->nodetype = navigation_node::NODETYPE_BRANCH;
  1813. $sectionnode->hidden = (!$section->visible || !$section->available);
  1814. if ($this->includesectionnum !== false && $this->includesectionnum == $section->section) {
  1815. $this->load_section_activities($sectionnode, $section->section, $activities);
  1816. }
  1817. $section->sectionnode = $sectionnode;
  1818. $navigationsections[$sectionid] = $section;
  1819. }
  1820. }
  1821. return $navigationsections;
  1822. }
  1823. /**
  1824. * Loads all of the activities for a section into the navigation structure.
  1825. *
  1826. * @param navigation_node $sectionnode
  1827. * @param int $sectionnumber
  1828. * @param array $activities An array of activites as returned by {@link global_navigation::generate_sections_and_activities()}
  1829. * @param stdClass $course The course object the section and activities relate to.
  1830. * @return array Array of activity nodes
  1831. */
  1832. protected function load_section_activities(navigation_node $sectionnode, $sectionnumber, array $activities, $course = null) {
  1833. global $CFG, $SITE;
  1834. // A static counter for JS function naming
  1835. static $legacyonclickcounter = 0;
  1836. $activitynodes = array();
  1837. if (empty($activities)) {
  1838. return $activitynodes;
  1839. }
  1840. if (!is_object($course)) {
  1841. $activity = reset($activities);
  1842. $courseid = $activity->course;
  1843. } else {
  1844. $courseid = $course->id;
  1845. }
  1846. $showactivities = ($courseid != $SITE->id || !empty($CFG->navshowfrontpagemods));
  1847. foreach ($activities as $activity) {
  1848. if ($activity->section != $sectionnumber) {
  1849. continue;
  1850. }
  1851. if ($activity->icon) {
  1852. $icon = new pix_icon($activity->icon, get_string('modulename', $activity->modname), $activity->iconcomponent);
  1853. } else {
  1854. $icon = new pix_icon('icon', get_string('modulename', $activity->modname), $activity->modname);
  1855. }
  1856. // Prepare the default name and url for the node
  1857. $activityname = format_string($activity->name, true, array('context' => context_module::instance($activity->id)));
  1858. $action = new moodle_url($activity->url);
  1859. // Check if the onclick property is set (puke!)
  1860. if (!empty($activity->onclick)) {
  1861. // Increment the counter so that we have a unique number.
  1862. $legacyonclickcounter++;
  1863. // Generate the function name we will use
  1864. $functionname = 'legacy_activity_onclick_handler_'.$legacyonclickcounter;
  1865. $propogrationhandler = '';
  1866. // Check if we need to cancel propogation. Remember inline onclick
  1867. // events would return false if they wanted to prevent propogation and the
  1868. // default action.
  1869. if (strpos($activity->onclick, 'return false')) {
  1870. $propogrationhandler = 'e.halt();';
  1871. }
  1872. // Decode the onclick - it has already been encoded for display (puke)
  1873. $onclick = htmlspecialchars_decode($activity->onclick, ENT_QUOTES);
  1874. // Build the JS function the click event will call
  1875. $jscode = "function {$functionname}(e) { $propogrationhandler $onclick }";
  1876. $this->page->requires->js_init_code($jscode);
  1877. // Override the default url with the new action link
  1878. $action = new action_link($action, $activityname, new component_action('click', $functionname));
  1879. }
  1880. $activitynode = $sectionnode->add($activityname, $action, navigation_node::TYPE_ACTIVITY, null, $activity->id, $icon);
  1881. $activitynode->title(get_string('modulename', $activity->modname));
  1882. $activitynode->hidden = $activity->hidden;
  1883. $activitynode->display = $showactivities && $activity->display;
  1884. $activitynode->nodetype = $activity->nodetype;
  1885. $activitynodes[$activity->id] = $activitynode;
  1886. }
  1887. return $activitynodes;
  1888. }
  1889. /**
  1890. * Loads a stealth module from unavailable section
  1891. * @param navigation_node $coursenode
  1892. * @param stdClass $modinfo
  1893. * @return navigation_node or null if not accessible
  1894. */
  1895. protected function load_stealth_activity(navigation_node $coursenode, $modinfo) {
  1896. if (empty($modinfo->cms[$this->page->cm->id])) {
  1897. return null;
  1898. }
  1899. $cm = $modinfo->cms[$this->page->cm->id];
  1900. if ($cm->icon) {
  1901. $icon = new pix_icon($cm->icon, get_string('modulename', $cm->modname), $cm->iconcomponent);
  1902. } else {
  1903. $icon = new pix_icon('icon', get_string('modulename', $cm->modname), $cm->modname);
  1904. }
  1905. $url = $cm->url;
  1906. $activitynode = $coursenode->add(format_string($cm->name), $url, navigation_node::TYPE_ACTIVITY, null, $cm->id, $icon);
  1907. $activitynode->title(get_string('modulename', $cm->modname));
  1908. $activitynode->hidden = (!$cm->visible);
  1909. if (!$cm->uservisible) {
  1910. // Do not show any error here, let the page handle exception that activity is not visible for the current user.
  1911. // Also there may be no exception at all in case when teacher is logged in as student.
  1912. $activitynode->display = false;
  1913. } else if (!$url) {
  1914. // Don't show activities that don't have links!
  1915. $activitynode->display = false;
  1916. } else if (self::module_extends_navigation($cm->modname)) {
  1917. $activitynode->nodetype = navigation_node::NODETYPE_BRANCH;
  1918. }
  1919. return $activitynode;
  1920. }
  1921. /**
  1922. * Loads the navigation structure for the given activity into the activities node.
  1923. *
  1924. * This method utilises a callback within the modules lib.php file to load the
  1925. * content specific to activity given.
  1926. *
  1927. * The callback is a method: {modulename}_extend_navigation()
  1928. * Examples:
  1929. * * {@link forum_extend_navigation()}
  1930. * * {@link workshop_extend_navigation()}
  1931. *
  1932. * @param cm_info|stdClass $cm
  1933. * @param stdClass $course
  1934. * @param navigation_node $activity
  1935. * @return bool
  1936. */
  1937. protected function load_activity($cm, stdClass $course, navigation_node $activity) {
  1938. global $CFG, $DB;
  1939. // make sure we have a $cm from get_fast_modinfo as this contains activity access details
  1940. if (!($cm instanceof cm_info)) {
  1941. $modinfo = get_fast_modinfo($course);
  1942. $cm = $modinfo->get_cm($cm->id);
  1943. }
  1944. $activity->nodetype = navigation_node::NODETYPE_LEAF;
  1945. $activity->make_active();
  1946. $file = $CFG->dirroot.'/mod/'.$cm->modname.'/lib.php';
  1947. $function = $cm->modname.'_extend_navigation';
  1948. if (file_exists($file)) {
  1949. require_once($file);
  1950. if (function_exists($function)) {
  1951. $activtyrecord = $DB->get_record($cm->modname, array('id' => $cm->instance), '*', MUST_EXIST);
  1952. $function($activity, $course, $activtyrecord, $cm);
  1953. }
  1954. }
  1955. // Allow the active advanced grading method plugin to append module navigation
  1956. $featuresfunc = $cm->modname.'_supports';
  1957. if (function_exists($featuresfunc) && $featuresfunc(FEATURE_ADVANCED_GRADING)) {
  1958. require_once($CFG->dirroot.'/grade/grading/lib.php');
  1959. $gradingman = get_grading_manager($cm->context, $cm->modname);
  1960. $gradingman->extend_navigation($this, $activity);
  1961. }
  1962. return $activity->has_children();
  1963. }
  1964. /**
  1965. * Loads user specific information into the navigation in the appropriate place.
  1966. *
  1967. * If no user is provided the current user is assumed.
  1968. *
  1969. * @param stdClass $user
  1970. * @param bool $forceforcontext probably force something to be loaded somewhere (ask SamH if not sure what this means)
  1971. * @return bool
  1972. */
  1973. protected function load_for_user($user=null, $forceforcontext=false) {
  1974. global $DB, $CFG, $USER, $SITE;
  1975. if ($user === null) {
  1976. // We can't require login here but if the user isn't logged in we don't
  1977. // want to show anything
  1978. if (!isloggedin() || isguestuser()) {
  1979. return false;
  1980. }
  1981. $user = $USER;
  1982. } else if (!is_object($user)) {
  1983. // If the user is not an object then get them from the database
  1984. $select = context_helper::get_preload_record_columns_sql('ctx');
  1985. $sql = "SELECT u.*, $select
  1986. FROM {user} u
  1987. JOIN {context} ctx ON u.id = ctx.instanceid
  1988. WHERE u.id = :userid AND
  1989. ctx.contextlevel = :contextlevel";
  1990. $user = $DB->get_record_sql($sql, array('userid' => (int)$user, 'contextlevel' => CONTEXT_USER), MUST_EXIST);
  1991. context_helper::preload_from_record($user);
  1992. }
  1993. $iscurrentuser = ($user->id == $USER->id);
  1994. $usercontext = context_user::instance($user->id);
  1995. // Get the course set against the page, by default this will be the site
  1996. $course = $this->page->course;
  1997. $baseargs = array('id'=>$user->id);
  1998. if ($course->id != $SITE->id && (!$iscurrentuser || $forceforcontext)) {
  1999. $coursenode = $this->add_course($course, false, self::COURSE_CURRENT);
  2000. $baseargs['course'] = $course->id;
  2001. $coursecontext = context_course::instance($course->id);
  2002. $issitecourse = false;
  2003. } else {
  2004. // Load all categories and get the context for the system
  2005. $coursecontext = context_system::instance();
  2006. $issitecourse = true;
  2007. }
  2008. // Create a node to add user information under.
  2009. if ($iscurrentuser && !$forceforcontext) {
  2010. // If it's the current user the information will go under the profile root node
  2011. $usernode = $this->rootnodes['myprofile'];
  2012. $course = get_site();
  2013. $coursecontext = context_course::instance($course->id);
  2014. $issitecourse = true;
  2015. } else {
  2016. if (!$issitecourse) {
  2017. // Not the current user so add it to the participants node for the current course
  2018. $usersnode = $coursenode->get('participants', navigation_node::TYPE_CONTAINER);
  2019. $userviewurl = new moodle_url('/user/view.php', $baseargs);
  2020. } else {
  2021. // This is the site so add a users node to the root branch
  2022. $usersnode = $this->rootnodes['users'];
  2023. if (has_capability('moodle/course:viewparticipants', $coursecontext)) {
  2024. $usersnode->action = new moodle_url('/user/index.php', array('id'=>$course->id));
  2025. }
  2026. $userviewurl = new moodle_url('/user/profile.php', $baseargs);
  2027. }
  2028. if (!$usersnode) {
  2029. // We should NEVER get here, if the course hasn't been populated
  2030. // with a participants node then the navigaiton either wasn't generated
  2031. // for it (you are missing a require_login or set_context call) or
  2032. // you don't have access.... in the interests of no leaking informatin
  2033. // we simply quit...
  2034. return false;
  2035. }
  2036. // Add a branch for the current user
  2037. $canseefullname = has_capability('moodle/site:viewfullnames', $coursecontext);
  2038. $usernode = $usersnode->add(fullname($user, $canseefullname), $userviewurl, self::TYPE_USER, null, $user->id);
  2039. if ($this->page->context->contextlevel == CONTEXT_USER && $user->id == $this->page->context->instanceid) {
  2040. $usernode->make_active();
  2041. }
  2042. }
  2043. // If the user is the current user or has permission to view the details of the requested
  2044. // user than add a view profile link.
  2045. if ($iscurrentuser || has_capability('moodle/user:viewdetails', $coursecontext) || has_capability('moodle/user:viewdetails', $usercontext)) {
  2046. if ($issitecourse || ($iscurrentuser && !$forceforcontext)) {
  2047. $usernode->add(get_string('viewprofile'), new moodle_url('/user/profile.php',$baseargs));
  2048. } else {
  2049. $usernode->add(get_string('viewprofile'), new moodle_url('/user/view.php',$baseargs));
  2050. }
  2051. }
  2052. if (!empty($CFG->navadduserpostslinks)) {
  2053. // Add nodes for forum posts and discussions if the user can view either or both
  2054. // There are no capability checks here as the content of the page is based
  2055. // purely on the forums the current user has access too.
  2056. $forumtab = $usernode->add(get_string('forumposts', 'forum'));
  2057. $forumtab->add(get_string('posts', 'forum'), new moodle_url('/mod/forum/user.php', $baseargs));
  2058. $forumtab->add(get_string('discussions', 'forum'), new moodle_url('/mod/forum/user.php', array_merge($baseargs, array('mode'=>'discussions'))));
  2059. }
  2060. // Add blog nodes
  2061. if (!empty($CFG->enableblogs)) {
  2062. if (!$this->cache->cached('userblogoptions'.$user->id)) {
  2063. require_once($CFG->dirroot.'/blog/lib.php');
  2064. // Get all options for the user
  2065. $options = blog_get_options_for_user($user);
  2066. $this->cache->set('userblogoptions'.$user->id, $options);
  2067. } else {
  2068. $options = $this->cache->{'userblogoptions'.$user->id};
  2069. }
  2070. if (count($options) > 0) {
  2071. $blogs = $usernode->add(get_string('blogs', 'blog'), null, navigation_node::TYPE_CONTAINER);
  2072. foreach ($options as $type => $option) {
  2073. if ($type == "rss") {
  2074. $blogs->add($option['string'], $option['link'], settings_navigation::TYPE_SETTING, null, null, new pix_icon('i/rss', ''));
  2075. } else {
  2076. $blogs->add($option['string'], $option['link']);
  2077. }
  2078. }
  2079. }
  2080. }
  2081. if (!empty($CFG->messaging)) {
  2082. $messageargs = array('user1' => $USER->id);
  2083. if ($USER->id != $user->id) {
  2084. $messageargs['user2'] = $user->id;
  2085. }
  2086. if ($course->id != $SITE->id) {
  2087. $messageargs['viewing'] = MESSAGE_VIEW_COURSE. $course->id;
  2088. }
  2089. $url = new moodle_url('/message/index.php',$messageargs);
  2090. $usernode->add(get_string('messages', 'message'), $url, self::TYPE_SETTING, null, 'messages');
  2091. }
  2092. if ($iscurrentuser && has_capability('moodle/user:manageownfiles', context_user::instance($USER->id))) {
  2093. $url = new moodle_url('/user/files.php');
  2094. $usernode->add(get_string('myfiles'), $url, self::TYPE_SETTING);
  2095. }
  2096. if (!empty($CFG->enablebadges) && $iscurrentuser &&
  2097. has_capability('moodle/badges:manageownbadges', context_user::instance($USER->id))) {
  2098. $url = new moodle_url('/badges/mybadges.php');
  2099. $usernode->add(get_string('mybadges', 'badges'), $url, self::TYPE_SETTING);
  2100. }
  2101. // Add a node to view the users notes if permitted
  2102. if (!empty($CFG->enablenotes) && has_any_capability(array('moodle/notes:manage', 'moodle/notes:view'), $coursecontext)) {
  2103. $url = new moodle_url('/notes/index.php',array('user'=>$user->id));
  2104. if ($coursecontext->instanceid != SITEID) {
  2105. $url->param('course', $coursecontext->instanceid);
  2106. }
  2107. $usernode->add(get_string('notes', 'notes'), $url);
  2108. }
  2109. // If the user is the current user add the repositories for the current user
  2110. $hiddenfields = array_flip(explode(',', $CFG->hiddenuserfields));
  2111. if ($iscurrentuser) {
  2112. if (!$this->cache->cached('contexthasrepos'.$usercontext->id)) {
  2113. require_once($CFG->dirroot . '/repository/lib.php');
  2114. $editabletypes = repository::get_editable_types($usercontext);
  2115. $haseditabletypes = !empty($editabletypes);
  2116. unset($editabletypes);
  2117. $this->cache->set('contexthasrepos'.$usercontext->id, $haseditabletypes);
  2118. } else {
  2119. $haseditabletypes = $this->cache->{'contexthasrepos'.$usercontext->id};
  2120. }
  2121. if ($haseditabletypes) {
  2122. $usernode->add(get_string('repositories', 'repository'), new moodle_url('/repository/manage_instances.php', array('contextid' => $usercontext->id)));
  2123. }
  2124. } else if ($course->id == $SITE->id && has_capability('moodle/user:viewdetails', $usercontext) && (!in_array('mycourses', $hiddenfields) || has_capability('moodle/user:viewhiddendetails', $coursecontext))) {
  2125. // Add view grade report is permitted
  2126. $reports = core_component::get_plugin_list('gradereport');
  2127. arsort($reports); // user is last, we want to test it first
  2128. $userscourses = enrol_get_users_courses($user->id);
  2129. $userscoursesnode = $usernode->add(get_string('courses'));
  2130. foreach ($userscourses as $usercourse) {
  2131. $usercoursecontext = context_course::instance($usercourse->id);
  2132. $usercourseshortname = format_string($usercourse->shortname, true, array('context' => $usercoursecontext));
  2133. $usercoursenode = $userscoursesnode->add($usercourseshortname, new moodle_url('/user/view.php', array('id'=>$user->id, 'course'=>$usercourse->id)), self::TYPE_CONTAINER);
  2134. $gradeavailable = has_capability('moodle/grade:viewall', $usercoursecontext);
  2135. if (!$gradeavailable && !empty($usercourse->showgrades) && is_array($reports) && !empty($reports)) {
  2136. foreach ($reports as $plugin => $plugindir) {
  2137. if (has_capability('gradereport/'.$plugin.':view', $usercoursecontext)) {
  2138. //stop when the first visible plugin is found
  2139. $gradeavailable = true;
  2140. break;
  2141. }
  2142. }
  2143. }
  2144. if ($gradeavailable) {
  2145. $url = new moodle_url('/grade/report/index.php', array('id'=>$usercourse->id));
  2146. $usercoursenode->add(get_string('grades'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/grades', ''));
  2147. }
  2148. // Add a node to view the users notes if permitted
  2149. if (!empty($CFG->enablenotes) && has_any_capability(array('moodle/notes:manage', 'moodle/notes:view'), $usercoursecontext)) {
  2150. $url = new moodle_url('/notes/index.php',array('user'=>$user->id, 'course'=>$usercourse->id));
  2151. $usercoursenode->add(get_string('notes', 'notes'), $url, self::TYPE_SETTING);
  2152. }
  2153. if (can_access_course($usercourse, $user->id)) {
  2154. $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', ''));
  2155. }
  2156. $reporttab = $usercoursenode->add(get_string('activityreports'));
  2157. $reports = get_plugin_list_with_function('report', 'extend_navigation_user', 'lib.php');
  2158. foreach ($reports as $reportfunction) {
  2159. $reportfunction($reporttab, $user, $usercourse);
  2160. }
  2161. $reporttab->trim_if_empty();
  2162. }
  2163. }
  2164. return true;
  2165. }
  2166. /**
  2167. * This method simply checks to see if a given module can extend the navigation.
  2168. *
  2169. * @todo (MDL-25290) A shared caching solution should be used to save details on what extends navigation.
  2170. *
  2171. * @param string $modname
  2172. * @return bool
  2173. */
  2174. public static function module_extends_navigation($modname) {
  2175. global $CFG;
  2176. static $extendingmodules = array();
  2177. if (!array_key_exists($modname, $extendingmodules)) {
  2178. $extendingmodules[$modname] = false;
  2179. $file = $CFG->dirroot.'/mod/'.$modname.'/lib.php';
  2180. if (file_exists($file)) {
  2181. $function = $modname.'_extend_navigation';
  2182. require_once($file);
  2183. $extendingmodules[$modname] = (function_exists($function));
  2184. }
  2185. }
  2186. return $extendingmodules[$modname];
  2187. }
  2188. /**
  2189. * Extends the navigation for the given user.
  2190. *
  2191. * @param stdClass $user A user from the database
  2192. */
  2193. public function extend_for_user($user) {
  2194. $this->extendforuser[] = $user;
  2195. }
  2196. /**
  2197. * Returns all of the users the navigation is being extended for
  2198. *
  2199. * @return array An array of extending users.
  2200. */
  2201. public function get_extending_users() {
  2202. return $this->extendforuser;
  2203. }
  2204. /**
  2205. * Adds the given course to the navigation structure.
  2206. *
  2207. * @param stdClass $course
  2208. * @param bool $forcegeneric
  2209. * @param bool $ismycourse
  2210. * @return navigation_node
  2211. */
  2212. public function add_course(stdClass $course, $forcegeneric = false, $coursetype = self::COURSE_OTHER) {
  2213. global $CFG, $SITE;
  2214. // We found the course... we can return it now :)
  2215. if (!$forcegeneric && array_key_exists($course->id, $this->addedcourses)) {
  2216. return $this->addedcourses[$course->id];
  2217. }
  2218. $coursecontext = context_course::instance($course->id);
  2219. if ($course->id != $SITE->id && !$course->visible) {
  2220. if (is_role_switched($course->id)) {
  2221. // user has to be able to access course in order to switch, let's skip the visibility test here
  2222. } else if (!has_capability('moodle/course:viewhiddencourses', $coursecontext)) {
  2223. return false;
  2224. }
  2225. }
  2226. $issite = ($course->id == $SITE->id);
  2227. $shortname = format_string($course->shortname, true, array('context' => $coursecontext));
  2228. $fullname = format_string($course->fullname, true, array('context' => $coursecontext));
  2229. // This is the name that will be shown for the course.
  2230. $coursename = empty($CFG->navshowfullcoursenames) ? $shortname : $fullname;
  2231. // Can the user expand the course to see its content.
  2232. $canexpandcourse = true;
  2233. if ($issite) {
  2234. $parent = $this;
  2235. $url = null;
  2236. if (empty($CFG->usesitenameforsitepages)) {
  2237. $coursename = get_string('sitepages');
  2238. }
  2239. } else if ($coursetype == self::COURSE_CURRENT) {
  2240. $parent = $this->rootnodes['currentcourse'];
  2241. $url = new moodle_url('/course/view.php', array('id'=>$course->id));
  2242. } else if ($coursetype == self::COURSE_MY && !$forcegeneric) {
  2243. if (!empty($CFG->navshowmycoursecategories) && ($parent = $this->rootnodes['mycourses']->find($course->category, self::TYPE_MY_CATEGORY))) {
  2244. // Nothing to do here the above statement set $parent to the category within mycourses.
  2245. } else {
  2246. $parent = $this->rootnodes['mycourses'];
  2247. }
  2248. $url = new moodle_url('/course/view.php', array('id'=>$course->id));
  2249. } else {
  2250. $parent = $this->rootnodes['courses'];
  2251. $url = new moodle_url('/course/view.php', array('id'=>$course->id));
  2252. // They can only expand the course if they can access it.
  2253. $canexpandcourse = $this->can_expand_course($course);
  2254. if (!empty($course->category) && $this->show_categories($coursetype == self::COURSE_MY)) {
  2255. if (!$this->is_category_fully_loaded($course->category)) {
  2256. // We need to load the category structure for this course
  2257. $this->load_all_categories($course->category, false);
  2258. }
  2259. if (array_key_exists($course->category, $this->addedcategories)) {
  2260. $parent = $this->addedcategories[$course->category];
  2261. // This could lead to the course being created so we should check whether it is the case again
  2262. if (!$forcegeneric && array_key_exists($course->id, $this->addedcourses)) {
  2263. return $this->addedcourses[$course->id];
  2264. }
  2265. }
  2266. }
  2267. }
  2268. $coursenode = $parent->add($coursename, $url, self::TYPE_COURSE, $shortname, $course->id);
  2269. $coursenode->hidden = (!$course->visible);
  2270. // We need to decode &amp;'s here as they will have been added by format_string above and attributes will be encoded again
  2271. // later.
  2272. $coursenode->title(str_replace('&amp;', '&', $fullname));
  2273. if ($canexpandcourse) {
  2274. // This course can be expanded by the user, make it a branch to make the system aware that its expandable by ajax.
  2275. $coursenode->nodetype = self::NODETYPE_BRANCH;
  2276. $coursenode->isexpandable = true;
  2277. } else {
  2278. $coursenode->nodetype = self::NODETYPE_LEAF;
  2279. $coursenode->isexpandable = false;
  2280. }
  2281. if (!$forcegeneric) {
  2282. $this->addedcourses[$course->id] = $coursenode;
  2283. }
  2284. return $coursenode;
  2285. }
  2286. /**
  2287. * Returns a cache instance to use for the expand course cache.
  2288. * @return cache_session
  2289. */
  2290. protected function get_expand_course_cache() {
  2291. if ($this->cacheexpandcourse === null) {
  2292. $this->cacheexpandcourse = cache::make('core', 'navigation_expandcourse');
  2293. }
  2294. return $this->cacheexpandcourse;
  2295. }
  2296. /**
  2297. * Checks if a user can expand a course in the navigation.
  2298. *
  2299. * We use a cache here because in order to be accurate we need to call can_access_course which is a costly function.
  2300. * Because this functionality is basic + non-essential and because we lack good event triggering this cache
  2301. * permits stale data.
  2302. * In the situation the user is granted access to a course after we've initialised this session cache the cache
  2303. * will be stale.
  2304. * It is brought up to date in only one of two ways.
  2305. * 1. The user logs out and in again.
  2306. * 2. The user browses to the course they've just being given access to.
  2307. *
  2308. * Really all this controls is whether the node is shown as expandable or not. It is uber un-important.
  2309. *
  2310. * @param stdClass $course
  2311. * @return bool
  2312. */
  2313. protected function can_expand_course($course) {
  2314. $cache = $this->get_expand_course_cache();
  2315. $canexpand = $cache->get($course->id);
  2316. if ($canexpand === false) {
  2317. $canexpand = isloggedin() && can_access_course($course);
  2318. $canexpand = (int)$canexpand;
  2319. $cache->set($course->id, $canexpand);
  2320. }
  2321. return ($canexpand === 1);
  2322. }
  2323. /**
  2324. * Returns true if the category has already been loaded as have any child categories
  2325. *
  2326. * @param int $categoryid
  2327. * @return bool
  2328. */
  2329. protected function is_category_fully_loaded($categoryid) {
  2330. return (array_key_exists($categoryid, $this->addedcategories) && ($this->allcategoriesloaded || $this->addedcategories[$categoryid]->children->count() > 0));
  2331. }
  2332. /**
  2333. * Adds essential course nodes to the navigation for the given course.
  2334. *
  2335. * This method adds nodes such as reports, blogs and participants
  2336. *
  2337. * @param navigation_node $coursenode
  2338. * @param stdClass $course
  2339. * @return bool returns true on successful addition of a node.
  2340. */
  2341. public function add_course_essentials($coursenode, stdClass $course) {
  2342. global $CFG, $SITE;
  2343. if ($course->id == $SITE->id) {
  2344. return $this->add_front_page_course_essentials($coursenode, $course);
  2345. }
  2346. if ($coursenode == false || !($coursenode instanceof navigation_node) || $coursenode->get('participants', navigation_node::TYPE_CONTAINER)) {
  2347. return true;
  2348. }
  2349. //Participants
  2350. if (has_capability('moodle/course:viewparticipants', $this->page->context)) {
  2351. $participants = $coursenode->add(get_string('participants'), new moodle_url('/user/index.php?id='.$course->id), self::TYPE_CONTAINER, get_string('participants'), 'participants');
  2352. if (!empty($CFG->enableblogs)) {
  2353. if (($CFG->bloglevel == BLOG_GLOBAL_LEVEL or ($CFG->bloglevel == BLOG_SITE_LEVEL and (isloggedin() and !isguestuser())))
  2354. and has_capability('moodle/blog:view', context_system::instance())) {
  2355. $blogsurls = new moodle_url('/blog/index.php');
  2356. if ($course->id == $SITE->id) {
  2357. $blogsurls->param('courseid', 0);
  2358. } else if ($currentgroup = groups_get_course_group($course, true)) {
  2359. $blogsurls->param('groupid', $currentgroup);
  2360. } else {
  2361. $blogsurls->param('courseid', $course->id);
  2362. }
  2363. $participants->add(get_string('blogscourse','blog'), $blogsurls->out());
  2364. }
  2365. }
  2366. if (!empty($CFG->enablenotes) && (has_capability('moodle/notes:manage', $this->page->context) || has_capability('moodle/notes:view', $this->page->context))) {
  2367. $participants->add(get_string('notes','notes'), new moodle_url('/notes/index.php', array('filtertype'=>'course', 'filterselect'=>$course->id)));
  2368. }
  2369. } else if (count($this->extendforuser) > 0 || $this->page->course->id == $course->id) {
  2370. $participants = $coursenode->add(get_string('participants'), null, self::TYPE_CONTAINER, get_string('participants'), 'participants');
  2371. }
  2372. // Badges.
  2373. if (!empty($CFG->enablebadges) && !empty($CFG->badges_allowcoursebadges) &&
  2374. has_capability('moodle/badges:viewbadges', $this->page->context)) {
  2375. $url = new moodle_url('/badges/view.php', array('type' => 2, 'id' => $course->id));
  2376. $coursenode->add(get_string('coursebadges', 'badges'), null,
  2377. navigation_node::TYPE_CONTAINER, null, 'coursebadges');
  2378. $coursenode->get('coursebadges')->add(get_string('badgesview', 'badges'), $url,
  2379. navigation_node::TYPE_SETTING, null, 'badgesview',
  2380. new pix_icon('i/badge', get_string('badgesview', 'badges')));
  2381. }
  2382. return true;
  2383. }
  2384. /**
  2385. * This generates the structure of the course that won't be generated when
  2386. * the modules and sections are added.
  2387. *
  2388. * Things such as the reports branch, the participants branch, blogs... get
  2389. * added to the course node by this method.
  2390. *
  2391. * @param navigation_node $coursenode
  2392. * @param stdClass $course
  2393. * @return bool True for successfull generation
  2394. */
  2395. public function add_front_page_course_essentials(navigation_node $coursenode, stdClass $course) {
  2396. global $CFG;
  2397. if ($coursenode == false || $coursenode->get('frontpageloaded', navigation_node::TYPE_CUSTOM)) {
  2398. return true;
  2399. }
  2400. // Hidden node that we use to determine if the front page navigation is loaded.
  2401. // This required as there are not other guaranteed nodes that may be loaded.
  2402. $coursenode->add('frontpageloaded', null, self::TYPE_CUSTOM, null, 'frontpageloaded')->display = false;
  2403. //Participants
  2404. if (has_capability('moodle/course:viewparticipants', context_system::instance())) {
  2405. $coursenode->add(get_string('participants'), new moodle_url('/user/index.php?id='.$course->id), self::TYPE_CUSTOM, get_string('participants'), 'participants');
  2406. }
  2407. $filterselect = 0;
  2408. // Blogs
  2409. if (!empty($CFG->enableblogs)
  2410. and ($CFG->bloglevel == BLOG_GLOBAL_LEVEL or ($CFG->bloglevel == BLOG_SITE_LEVEL and (isloggedin() and !isguestuser())))
  2411. and has_capability('moodle/blog:view', context_system::instance())) {
  2412. $blogsurls = new moodle_url('/blog/index.php', array('courseid' => $filterselect));
  2413. $coursenode->add(get_string('blogssite','blog'), $blogsurls->out());
  2414. }
  2415. //Badges
  2416. if (!empty($CFG->enablebadges) && has_capability('moodle/badges:viewbadges', $this->page->context)) {
  2417. $url = new moodle_url($CFG->wwwroot . '/badges/view.php', array('type' => 1));
  2418. $coursenode->add(get_string('sitebadges', 'badges'), $url, navigation_node::TYPE_CUSTOM);
  2419. }
  2420. // Notes
  2421. if (!empty($CFG->enablenotes) && (has_capability('moodle/notes:manage', $this->page->context) || has_capability('moodle/notes:view', $this->page->context))) {
  2422. $coursenode->add(get_string('notes','notes'), new moodle_url('/notes/index.php', array('filtertype'=>'course', 'filterselect'=>$filterselect)));
  2423. }
  2424. // Tags
  2425. if (!empty($CFG->usetags) && isloggedin()) {
  2426. $coursenode->add(get_string('tags', 'tag'), new moodle_url('/tag/search.php'));
  2427. }
  2428. if (isloggedin()) {
  2429. // Calendar
  2430. $calendarurl = new moodle_url('/calendar/view.php', array('view' => 'month'));
  2431. $coursenode->add(get_string('calendar', 'calendar'), $calendarurl, self::TYPE_CUSTOM, null, 'calendar');
  2432. }
  2433. return true;
  2434. }
  2435. /**
  2436. * Clears the navigation cache
  2437. */
  2438. public function clear_cache() {
  2439. $this->cache->clear();
  2440. }
  2441. /**
  2442. * Sets an expansion limit for the navigation
  2443. *
  2444. * The expansion limit is used to prevent the display of content that has a type
  2445. * greater than the provided $type.
  2446. *
  2447. * Can be used to ensure things such as activities or activity content don't get
  2448. * shown on the navigation.
  2449. * They are still generated in order to ensure the navbar still makes sense.
  2450. *
  2451. * @param int $type One of navigation_node::TYPE_*
  2452. * @return bool true when complete.
  2453. */
  2454. public function set_expansion_limit($type) {
  2455. global $SITE;
  2456. $nodes = $this->find_all_of_type($type);
  2457. // We only want to hide specific types of nodes.
  2458. // Only nodes that represent "structure" in the navigation tree should be hidden.
  2459. // If we hide all nodes then we risk hiding vital information.
  2460. $typestohide = array(
  2461. self::TYPE_CATEGORY,
  2462. self::TYPE_COURSE,
  2463. self::TYPE_SECTION,
  2464. self::TYPE_ACTIVITY
  2465. );
  2466. foreach ($nodes as $node) {
  2467. // We need to generate the full site node
  2468. if ($type == self::TYPE_COURSE && $node->key == $SITE->id) {
  2469. continue;
  2470. }
  2471. foreach ($node->children as $child) {
  2472. $child->hide($typestohide);
  2473. }
  2474. }
  2475. return true;
  2476. }
  2477. /**
  2478. * Attempts to get the navigation with the given key from this nodes children.
  2479. *
  2480. * This function only looks at this nodes children, it does NOT look recursivily.
  2481. * If the node can't be found then false is returned.
  2482. *
  2483. * If you need to search recursivily then use the {@link global_navigation::find()} method.
  2484. *
  2485. * Note: If you are trying to set the active node {@link navigation_node::override_active_url()}
  2486. * may be of more use to you.
  2487. *
  2488. * @param string|int $key The key of the node you wish to receive.
  2489. * @param int $type One of navigation_node::TYPE_*
  2490. * @return navigation_node|false
  2491. */
  2492. public function get($key, $type = null) {
  2493. if (!$this->initialised) {
  2494. $this->initialise();
  2495. }
  2496. return parent::get($key, $type);
  2497. }
  2498. /**
  2499. * Searches this nodes children and their children to find a navigation node
  2500. * with the matching key and type.
  2501. *
  2502. * This method is recursive and searches children so until either a node is
  2503. * found or there are no more nodes to search.
  2504. *
  2505. * If you know that the node being searched for is a child of this node
  2506. * then use the {@link global_navigation::get()} method instead.
  2507. *
  2508. * Note: If you are trying to set the active node {@link navigation_node::override_active_url()}
  2509. * may be of more use to you.
  2510. *
  2511. * @param string|int $key The key of the node you wish to receive.
  2512. * @param int $type One of navigation_node::TYPE_*
  2513. * @return navigation_node|false
  2514. */
  2515. public function find($key, $type) {
  2516. if (!$this->initialised) {
  2517. $this->initialise();
  2518. }
  2519. if ($type == self::TYPE_ROOTNODE && array_key_exists($key, $this->rootnodes)) {
  2520. return $this->rootnodes[$key];
  2521. }
  2522. return parent::find($key, $type);
  2523. }
  2524. /**
  2525. * They've expanded the 'my courses' branch.
  2526. */
  2527. protected function load_courses_enrolled() {
  2528. global $CFG, $DB;
  2529. $sortorder = 'visible DESC';
  2530. // Prevent undefined $CFG->navsortmycoursessort errors.
  2531. if (empty($CFG->navsortmycoursessort)) {
  2532. $CFG->navsortmycoursessort = 'sortorder';
  2533. }
  2534. // Append the chosen sortorder.
  2535. $sortorder = $sortorder . ',' . $CFG->navsortmycoursessort . ' ASC';
  2536. $courses = enrol_get_my_courses(null, $sortorder);
  2537. if (count($courses) && $this->show_my_categories()) {
  2538. // OK Actually we are loading categories. We only want to load categories that have a parent of 0.
  2539. // In order to make sure we load everything required we must first find the categories that are not
  2540. // base categories and work out the bottom category in thier path.
  2541. $categoryids = array();
  2542. foreach ($courses as $course) {
  2543. $categoryids[] = $course->category;
  2544. }
  2545. $categoryids = array_unique($categoryids);
  2546. list($sql, $params) = $DB->get_in_or_equal($categoryids);
  2547. $categories = $DB->get_recordset_select('course_categories', 'id '.$sql.' AND parent <> 0', $params, 'sortorder, id', 'id, path');
  2548. foreach ($categories as $category) {
  2549. $bits = explode('/', trim($category->path,'/'));
  2550. $categoryids[] = array_shift($bits);
  2551. }
  2552. $categoryids = array_unique($categoryids);
  2553. $categories->close();
  2554. // Now we load the base categories.
  2555. list($sql, $params) = $DB->get_in_or_equal($categoryids);
  2556. $categories = $DB->get_recordset_select('course_categories', 'id '.$sql.' AND parent = 0', $params, 'sortorder, id');
  2557. foreach ($categories as $category) {
  2558. $this->add_category($category, $this->rootnodes['mycourses'], self::TYPE_MY_CATEGORY);
  2559. }
  2560. $categories->close();
  2561. } else {
  2562. foreach ($courses as $course) {
  2563. $this->add_course($course, false, self::COURSE_MY);
  2564. }
  2565. }
  2566. }
  2567. }
  2568. /**
  2569. * The global navigation class used especially for AJAX requests.
  2570. *
  2571. * The primary methods that are used in the global navigation class have been overriden
  2572. * to ensure that only the relevant branch is generated at the root of the tree.
  2573. * This can be done because AJAX is only used when the backwards structure for the
  2574. * requested branch exists.
  2575. * This has been done only because it shortens the amounts of information that is generated
  2576. * which of course will speed up the response time.. because no one likes laggy AJAX.
  2577. *
  2578. * @package core
  2579. * @category navigation
  2580. * @copyright 2009 Sam Hemelryk
  2581. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  2582. */
  2583. class global_navigation_for_ajax extends global_navigation {
  2584. /** @var int used for determining what type of navigation_node::TYPE_* is being used */
  2585. protected $branchtype;
  2586. /** @var int the instance id */
  2587. protected $instanceid;
  2588. /** @var array Holds an array of expandable nodes */
  2589. protected $expandable = array();
  2590. /**
  2591. * Constructs the navigation for use in an AJAX request
  2592. *
  2593. * @param moodle_page $page moodle_page object
  2594. * @param int $branchtype
  2595. * @param int $id
  2596. */
  2597. public function __construct($page, $branchtype, $id) {
  2598. $this->page = $page;
  2599. $this->cache = new navigation_cache(NAVIGATION_CACHE_NAME);
  2600. $this->children = new navigation_node_collection();
  2601. $this->branchtype = $branchtype;
  2602. $this->instanceid = $id;
  2603. $this->initialise();
  2604. }
  2605. /**
  2606. * Initialise the navigation given the type and id for the branch to expand.
  2607. *
  2608. * @return array An array of the expandable nodes
  2609. */
  2610. public function initialise() {
  2611. global $DB, $SITE;
  2612. if ($this->initialised || during_initial_install()) {
  2613. return $this->expandable;
  2614. }
  2615. $this->initialised = true;
  2616. $this->rootnodes = array();
  2617. $this->rootnodes['site'] = $this->add_course($SITE);
  2618. $this->rootnodes['mycourses'] = $this->add(get_string('mycourses'), new moodle_url('/my'), self::TYPE_ROOTNODE, null, 'mycourses');
  2619. $this->rootnodes['courses'] = $this->add(get_string('courses'), null, self::TYPE_ROOTNODE, null, 'courses');
  2620. // The courses branch is always displayed, and is always expandable (although may be empty).
  2621. // This mimicks what is done during {@link global_navigation::initialise()}.
  2622. $this->rootnodes['courses']->isexpandable = true;
  2623. // Branchtype will be one of navigation_node::TYPE_*
  2624. switch ($this->branchtype) {
  2625. case 0:
  2626. if ($this->instanceid === 'mycourses') {
  2627. $this->load_courses_enrolled();
  2628. } else if ($this->instanceid === 'courses') {
  2629. $this->load_courses_other();
  2630. }
  2631. break;
  2632. case self::TYPE_CATEGORY :
  2633. $this->load_category($this->instanceid);
  2634. break;
  2635. case self::TYPE_MY_CATEGORY :
  2636. $this->load_category($this->instanceid, self::TYPE_MY_CATEGORY);
  2637. break;
  2638. case self::TYPE_COURSE :
  2639. $course = $DB->get_record('course', array('id' => $this->instanceid), '*', MUST_EXIST);
  2640. if (!can_access_course($course)) {
  2641. // Thats OK all courses are expandable by default. We don't need to actually expand it we can just
  2642. // add the course node and break. This leads to an empty node.
  2643. $this->add_course($course);
  2644. break;
  2645. }
  2646. require_course_login($course, true, null, false, true);
  2647. $this->page->set_context(context_course::instance($course->id));
  2648. $coursenode = $this->add_course($course);
  2649. $this->add_course_essentials($coursenode, $course);
  2650. $this->load_course_sections($course, $coursenode);
  2651. break;
  2652. case self::TYPE_SECTION :
  2653. $sql = 'SELECT c.*, cs.section AS sectionnumber
  2654. FROM {course} c
  2655. LEFT JOIN {course_sections} cs ON cs.course = c.id
  2656. WHERE cs.id = ?';
  2657. $course = $DB->get_record_sql($sql, array($this->instanceid), MUST_EXIST);
  2658. require_course_login($course, true, null, false, true);
  2659. $this->page->set_context(context_course::instance($course->id));
  2660. $coursenode = $this->add_course($course);
  2661. $this->add_course_essentials($coursenode, $course);
  2662. $this->load_course_sections($course, $coursenode, $course->sectionnumber);
  2663. break;
  2664. case self::TYPE_ACTIVITY :
  2665. $sql = "SELECT c.*
  2666. FROM {course} c
  2667. JOIN {course_modules} cm ON cm.course = c.id
  2668. WHERE cm.id = :cmid";
  2669. $params = array('cmid' => $this->instanceid);
  2670. $course = $DB->get_record_sql($sql, $params, MUST_EXIST);
  2671. $modinfo = get_fast_modinfo($course);
  2672. $cm = $modinfo->get_cm($this->instanceid);
  2673. require_course_login($course, true, $cm, false, true);
  2674. $this->page->set_context(context_module::instance($cm->id));
  2675. $coursenode = $this->load_course($course);
  2676. if ($course->id != $SITE->id) {
  2677. $this->load_course_sections($course, $coursenode, null, $cm);
  2678. }
  2679. $modulenode = $this->load_activity($cm, $course, $coursenode->find($cm->id, self::TYPE_ACTIVITY));
  2680. break;
  2681. default:
  2682. throw new Exception('Unknown type');
  2683. return $this->expandable;
  2684. }
  2685. if ($this->page->context->contextlevel == CONTEXT_COURSE && $this->page->context->instanceid != $SITE->id) {
  2686. $this->load_for_user(null, true);
  2687. }
  2688. $this->find_expandable($this->expandable);
  2689. return $this->expandable;
  2690. }
  2691. /**
  2692. * They've expanded the general 'courses' branch.
  2693. */
  2694. protected function load_courses_other() {
  2695. $this->load_all_courses();
  2696. }
  2697. /**
  2698. * Loads a single category into the AJAX navigation.
  2699. *
  2700. * This function is special in that it doesn't concern itself with the parent of
  2701. * the requested category or its siblings.
  2702. * This is because with the AJAX navigation we know exactly what is wanted and only need to
  2703. * request that.
  2704. *
  2705. * @global moodle_database $DB
  2706. * @param int $categoryid id of category to load in navigation.
  2707. * @param int $nodetype type of node, if category is under MyHome then it's TYPE_MY_CATEGORY
  2708. * @return void.
  2709. */
  2710. protected function load_category($categoryid, $nodetype = self::TYPE_CATEGORY) {
  2711. global $CFG, $DB;
  2712. $limit = 20;
  2713. if (!empty($CFG->navcourselimit)) {
  2714. $limit = (int)$CFG->navcourselimit;
  2715. }
  2716. $catcontextsql = context_helper::get_preload_record_columns_sql('ctx');
  2717. $sql = "SELECT cc.*, $catcontextsql
  2718. FROM {course_categories} cc
  2719. JOIN {context} ctx ON cc.id = ctx.instanceid
  2720. WHERE ctx.contextlevel = ".CONTEXT_COURSECAT." AND
  2721. (cc.id = :categoryid1 OR cc.parent = :categoryid2)
  2722. ORDER BY cc.depth ASC, cc.sortorder ASC, cc.id ASC";
  2723. $params = array('categoryid1' => $categoryid, 'categoryid2' => $categoryid);
  2724. $categories = $DB->get_recordset_sql($sql, $params, 0, $limit);
  2725. $categorylist = array();
  2726. $subcategories = array();
  2727. $basecategory = null;
  2728. foreach ($categories as $category) {
  2729. $categorylist[] = $category->id;
  2730. context_helper::preload_from_record($category);
  2731. if ($category->id == $categoryid) {
  2732. $this->add_category($category, $this, $nodetype);
  2733. $basecategory = $this->addedcategories[$category->id];
  2734. } else {
  2735. $subcategories[$category->id] = $category;
  2736. }
  2737. }
  2738. $categories->close();
  2739. // If category is shown in MyHome then only show enrolled courses and hide empty subcategories,
  2740. // else show all courses.
  2741. if ($nodetype === self::TYPE_MY_CATEGORY) {
  2742. $courses = enrol_get_my_courses();
  2743. $categoryids = array();
  2744. // Only search for categories if basecategory was found.
  2745. if (!is_null($basecategory)) {
  2746. // Get course parent category ids.
  2747. foreach ($courses as $course) {
  2748. $categoryids[] = $course->category;
  2749. }
  2750. // Get a unique list of category ids which a part of the path
  2751. // to user's courses.
  2752. $coursesubcategories = array();
  2753. $addedsubcategories = array();
  2754. list($sql, $params) = $DB->get_in_or_equal($categoryids);
  2755. $categories = $DB->get_recordset_select('course_categories', 'id '.$sql, $params, 'sortorder, id', 'id, path');
  2756. foreach ($categories as $category){
  2757. $coursesubcategories = array_merge($coursesubcategories, explode('/', trim($category->path, "/")));
  2758. }
  2759. $coursesubcategories = array_unique($coursesubcategories);
  2760. // Only add a subcategory if it is part of the path to user's course and
  2761. // wasn't already added.
  2762. foreach ($subcategories as $subid => $subcategory) {
  2763. if (in_array($subid, $coursesubcategories) &&
  2764. !in_array($subid, $addedsubcategories)) {
  2765. $this->add_category($subcategory, $basecategory, $nodetype);
  2766. $addedsubcategories[] = $subid;
  2767. }
  2768. }
  2769. }
  2770. foreach ($courses as $course) {
  2771. // Add course if it's in category.
  2772. if (in_array($course->category, $categorylist)) {
  2773. $this->add_course($course, true, self::COURSE_MY);
  2774. }
  2775. }
  2776. } else {
  2777. if (!is_null($basecategory)) {
  2778. foreach ($subcategories as $key=>$category) {
  2779. $this->add_category($category, $basecategory, $nodetype);
  2780. }
  2781. }
  2782. $courses = $DB->get_recordset('course', array('category' => $categoryid), 'sortorder', '*' , 0, $limit);
  2783. foreach ($courses as $course) {
  2784. $this->add_course($course);
  2785. }
  2786. $courses->close();
  2787. }
  2788. }
  2789. /**
  2790. * Returns an array of expandable nodes
  2791. * @return array
  2792. */
  2793. public function get_expandable() {
  2794. return $this->expandable;
  2795. }
  2796. }
  2797. /**
  2798. * Navbar class
  2799. *
  2800. * This class is used to manage the navbar, which is initialised from the navigation
  2801. * object held by PAGE
  2802. *
  2803. * @package core
  2804. * @category navigation
  2805. * @copyright 2009 Sam Hemelryk
  2806. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  2807. */
  2808. class navbar extends navigation_node {
  2809. /** @var bool A switch for whether the navbar is initialised or not */
  2810. protected $initialised = false;
  2811. /** @var mixed keys used to reference the nodes on the navbar */
  2812. protected $keys = array();
  2813. /** @var null|string content of the navbar */
  2814. protected $content = null;
  2815. /** @var moodle_page object the moodle page that this navbar belongs to */
  2816. protected $page;
  2817. /** @var bool A switch for whether to ignore the active navigation information */
  2818. protected $ignoreactive = false;
  2819. /** @var bool A switch to let us know if we are in the middle of an install */
  2820. protected $duringinstall = false;
  2821. /** @var bool A switch for whether the navbar has items */
  2822. protected $hasitems = false;
  2823. /** @var array An array of navigation nodes for the navbar */
  2824. protected $items;
  2825. /** @var array An array of child node objects */
  2826. public $children = array();
  2827. /** @var bool A switch for whether we want to include the root node in the navbar */
  2828. public $includesettingsbase = false;
  2829. /** @var navigation_node[] $prependchildren */
  2830. protected $prependchildren = array();
  2831. /**
  2832. * The almighty constructor
  2833. *
  2834. * @param moodle_page $page
  2835. */
  2836. public function __construct(moodle_page $page) {
  2837. global $CFG;
  2838. if (during_initial_install()) {
  2839. $this->duringinstall = true;
  2840. return false;
  2841. }
  2842. $this->page = $page;
  2843. $this->text = get_string('home');
  2844. $this->shorttext = get_string('home');
  2845. $this->action = new moodle_url($CFG->wwwroot);
  2846. $this->nodetype = self::NODETYPE_BRANCH;
  2847. $this->type = self::TYPE_SYSTEM;
  2848. }
  2849. /**
  2850. * Quick check to see if the navbar will have items in.
  2851. *
  2852. * @return bool Returns true if the navbar will have items, false otherwise
  2853. */
  2854. public function has_items() {
  2855. if ($this->duringinstall) {
  2856. return false;
  2857. } else if ($this->hasitems !== false) {
  2858. return true;
  2859. }
  2860. $this->page->navigation->initialise($this->page);
  2861. $activenodefound = ($this->page->navigation->contains_active_node() ||
  2862. $this->page->settingsnav->contains_active_node());
  2863. $outcome = (count($this->children) > 0 || count($this->prependchildren) || (!$this->ignoreactive && $activenodefound));
  2864. $this->hasitems = $outcome;
  2865. return $outcome;
  2866. }
  2867. /**
  2868. * Turn on/off ignore active
  2869. *
  2870. * @param bool $setting
  2871. */
  2872. public function ignore_active($setting=true) {
  2873. $this->ignoreactive = ($setting);
  2874. }
  2875. /**
  2876. * Gets a navigation node
  2877. *
  2878. * @param string|int $key for referencing the navbar nodes
  2879. * @param int $type navigation_node::TYPE_*
  2880. * @return navigation_node|bool
  2881. */
  2882. public function get($key, $type = null) {
  2883. foreach ($this->children as &$child) {
  2884. if ($child->key === $key && ($type == null || $type == $child->type)) {
  2885. return $child;
  2886. }
  2887. }
  2888. foreach ($this->prependchildren as &$child) {
  2889. if ($child->key === $key && ($type == null || $type == $child->type)) {
  2890. return $child;
  2891. }
  2892. }
  2893. return false;
  2894. }
  2895. /**
  2896. * Returns an array of navigation_node's that make up the navbar.
  2897. *
  2898. * @return array
  2899. */
  2900. public function get_items() {
  2901. global $CFG;
  2902. $items = array();
  2903. // Make sure that navigation is initialised
  2904. if (!$this->has_items()) {
  2905. return $items;
  2906. }
  2907. if ($this->items !== null) {
  2908. return $this->items;
  2909. }
  2910. if (count($this->children) > 0) {
  2911. // Add the custom children.
  2912. $items = array_reverse($this->children);
  2913. }
  2914. $navigationactivenode = $this->page->navigation->find_active_node();
  2915. $settingsactivenode = $this->page->settingsnav->find_active_node();
  2916. // Check if navigation contains the active node
  2917. if (!$this->ignoreactive) {
  2918. if ($navigationactivenode && $settingsactivenode) {
  2919. // Parse a combined navigation tree
  2920. while ($settingsactivenode && $settingsactivenode->parent !== null) {
  2921. if (!$settingsactivenode->mainnavonly) {
  2922. $items[] = $settingsactivenode;
  2923. }
  2924. $settingsactivenode = $settingsactivenode->parent;
  2925. }
  2926. if (!$this->includesettingsbase) {
  2927. // Removes the first node from the settings (root node) from the list
  2928. array_pop($items);
  2929. }
  2930. while ($navigationactivenode && $navigationactivenode->parent !== null) {
  2931. if (!$navigationactivenode->mainnavonly) {
  2932. $items[] = $navigationactivenode;
  2933. }
  2934. if (!empty($CFG->navshowcategories) &&
  2935. $navigationactivenode->type === self::TYPE_COURSE &&
  2936. $navigationactivenode->parent->key === 'currentcourse') {
  2937. $items = array_merge($items, $this->get_course_categories());
  2938. }
  2939. $navigationactivenode = $navigationactivenode->parent;
  2940. }
  2941. } else if ($navigationactivenode) {
  2942. // Parse the navigation tree to get the active node
  2943. while ($navigationactivenode && $navigationactivenode->parent !== null) {
  2944. if (!$navigationactivenode->mainnavonly) {
  2945. $items[] = $navigationactivenode;
  2946. }
  2947. if (!empty($CFG->navshowcategories) &&
  2948. $navigationactivenode->type === self::TYPE_COURSE &&
  2949. $navigationactivenode->parent->key === 'currentcourse') {
  2950. $items = array_merge($items, $this->get_course_categories());
  2951. }
  2952. $navigationactivenode = $navigationactivenode->parent;
  2953. }
  2954. } else if ($settingsactivenode) {
  2955. // Parse the settings navigation to get the active node
  2956. while ($settingsactivenode && $settingsactivenode->parent !== null) {
  2957. if (!$settingsactivenode->mainnavonly) {
  2958. $items[] = $settingsactivenode;
  2959. }
  2960. $settingsactivenode = $settingsactivenode->parent;
  2961. }
  2962. }
  2963. }
  2964. $items[] = new navigation_node(array(
  2965. 'text'=>$this->page->navigation->text,
  2966. 'shorttext'=>$this->page->navigation->shorttext,
  2967. 'key'=>$this->page->navigation->key,
  2968. 'action'=>$this->page->navigation->action
  2969. ));
  2970. if (count($this->prependchildren) > 0) {
  2971. // Add the custom children
  2972. $items = array_merge($items, array_reverse($this->prependchildren));
  2973. }
  2974. $this->items = array_reverse($items);
  2975. return $this->items;
  2976. }
  2977. /**
  2978. * Get the list of categories leading to this course.
  2979. *
  2980. * This function is used by {@link navbar::get_items()} to add back the "courses"
  2981. * node and category chain leading to the current course. Note that this is only ever
  2982. * called for the current course, so we don't need to bother taking in any parameters.
  2983. *
  2984. * @return array
  2985. */
  2986. private function get_course_categories() {
  2987. global $CFG;
  2988. require_once($CFG->dirroot.'/course/lib.php');
  2989. $categories = array();
  2990. $cap = 'moodle/category:viewhiddencategories';
  2991. foreach ($this->page->categories as $category) {
  2992. if (!$category->visible && !has_capability($cap, get_category_or_system_context($category->parent))) {
  2993. continue;
  2994. }
  2995. $url = new moodle_url('/course/index.php', array('categoryid' => $category->id));
  2996. $name = format_string($category->name, true, array('context' => context_coursecat::instance($category->id)));
  2997. $categorynode = navigation_node::create($name, $url, self::TYPE_CATEGORY, null, $category->id);
  2998. if (!$category->visible) {
  2999. $categorynode->hidden = true;
  3000. }
  3001. $categories[] = $categorynode;
  3002. }
  3003. if (is_enrolled(context_course::instance($this->page->course->id))) {
  3004. $courses = $this->page->navigation->get('mycourses');
  3005. } else {
  3006. $courses = $this->page->navigation->get('courses');
  3007. }
  3008. if (!$courses) {
  3009. // Courses node may not be present.
  3010. $courses = navigation_node::create(
  3011. get_string('courses'),
  3012. new moodle_url('/course/index.php'),
  3013. self::TYPE_CONTAINER
  3014. );
  3015. }
  3016. $categories[] = $courses;
  3017. return $categories;
  3018. }
  3019. /**
  3020. * Add a new navigation_node to the navbar, overrides parent::add
  3021. *
  3022. * This function overrides {@link navigation_node::add()} so that we can change
  3023. * the way nodes get added to allow us to simply call add and have the node added to the
  3024. * end of the navbar
  3025. *
  3026. * @param string $text
  3027. * @param string|moodle_url|action_link $action An action to associate with this node.
  3028. * @param int $type One of navigation_node::TYPE_*
  3029. * @param string $shorttext
  3030. * @param string|int $key A key to identify this node with. Key + type is unique to a parent.
  3031. * @param pix_icon $icon An optional icon to use for this node.
  3032. * @return navigation_node
  3033. */
  3034. public function add($text, $action=null, $type=self::TYPE_CUSTOM, $shorttext=null, $key=null, pix_icon $icon=null) {
  3035. if ($this->content !== null) {
  3036. debugging('Nav bar items must be printed before $OUTPUT->header() has been called', DEBUG_DEVELOPER);
  3037. }
  3038. // Properties array used when creating the new navigation node
  3039. $itemarray = array(
  3040. 'text' => $text,
  3041. 'type' => $type
  3042. );
  3043. // Set the action if one was provided
  3044. if ($action!==null) {
  3045. $itemarray['action'] = $action;
  3046. }
  3047. // Set the shorttext if one was provided
  3048. if ($shorttext!==null) {
  3049. $itemarray['shorttext'] = $shorttext;
  3050. }
  3051. // Set the icon if one was provided
  3052. if ($icon!==null) {
  3053. $itemarray['icon'] = $icon;
  3054. }
  3055. // Default the key to the number of children if not provided
  3056. if ($key === null) {
  3057. $key = count($this->children);
  3058. }
  3059. // Set the key
  3060. $itemarray['key'] = $key;
  3061. // Set the parent to this node
  3062. $itemarray['parent'] = $this;
  3063. // Add the child using the navigation_node_collections add method
  3064. $this->children[] = new navigation_node($itemarray);
  3065. return $this;
  3066. }
  3067. /**
  3068. * Prepends a new navigation_node to the start of the navbar
  3069. *
  3070. * @param string $text
  3071. * @param string|moodle_url|action_link $action An action to associate with this node.
  3072. * @param int $type One of navigation_node::TYPE_*
  3073. * @param string $shorttext
  3074. * @param string|int $key A key to identify this node with. Key + type is unique to a parent.
  3075. * @param pix_icon $icon An optional icon to use for this node.
  3076. * @return navigation_node
  3077. */
  3078. public function prepend($text, $action=null, $type=self::TYPE_CUSTOM, $shorttext=null, $key=null, pix_icon $icon=null) {
  3079. if ($this->content !== null) {
  3080. debugging('Nav bar items must be printed before $OUTPUT->header() has been called', DEBUG_DEVELOPER);
  3081. }
  3082. // Properties array used when creating the new navigation node.
  3083. $itemarray = array(
  3084. 'text' => $text,
  3085. 'type' => $type
  3086. );
  3087. // Set the action if one was provided.
  3088. if ($action!==null) {
  3089. $itemarray['action'] = $action;
  3090. }
  3091. // Set the shorttext if one was provided.
  3092. if ($shorttext!==null) {
  3093. $itemarray['shorttext'] = $shorttext;
  3094. }
  3095. // Set the icon if one was provided.
  3096. if ($icon!==null) {
  3097. $itemarray['icon'] = $icon;
  3098. }
  3099. // Default the key to the number of children if not provided.
  3100. if ($key === null) {
  3101. $key = count($this->children);
  3102. }
  3103. // Set the key.
  3104. $itemarray['key'] = $key;
  3105. // Set the parent to this node.
  3106. $itemarray['parent'] = $this;
  3107. // Add the child node to the prepend list.
  3108. $this->prependchildren[] = new navigation_node($itemarray);
  3109. return $this;
  3110. }
  3111. }
  3112. /**
  3113. * Class used to manage the settings option for the current page
  3114. *
  3115. * This class is used to manage the settings options in a tree format (recursively)
  3116. * and was created initially for use with the settings blocks.
  3117. *
  3118. * @package core
  3119. * @category navigation
  3120. * @copyright 2009 Sam Hemelryk
  3121. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  3122. */
  3123. class settings_navigation extends navigation_node {
  3124. /** @var stdClass the current context */
  3125. protected $context;
  3126. /** @var moodle_page the moodle page that the navigation belongs to */
  3127. protected $page;
  3128. /** @var string contains administration section navigation_nodes */
  3129. protected $adminsection;
  3130. /** @var bool A switch to see if the navigation node is initialised */
  3131. protected $initialised = false;
  3132. /** @var array An array of users that the nodes can extend for. */
  3133. protected $userstoextendfor = array();
  3134. /** @var navigation_cache **/
  3135. protected $cache;
  3136. /**
  3137. * Sets up the object with basic settings and preparse it for use
  3138. *
  3139. * @param moodle_page $page
  3140. */
  3141. public function __construct(moodle_page &$page) {
  3142. if (during_initial_install()) {
  3143. return false;
  3144. }
  3145. $this->page = $page;
  3146. // Initialise the main navigation. It is most important that this is done
  3147. // before we try anything
  3148. $this->page->navigation->initialise();
  3149. // Initialise the navigation cache
  3150. $this->cache = new navigation_cache(NAVIGATION_CACHE_NAME);
  3151. $this->children = new navigation_node_collection();
  3152. }
  3153. /**
  3154. * Initialise the settings navigation based on the current context
  3155. *
  3156. * This function initialises the settings navigation tree for a given context
  3157. * by calling supporting functions to generate major parts of the tree.
  3158. *
  3159. */
  3160. public function initialise() {
  3161. global $DB, $SESSION, $SITE;
  3162. if (during_initial_install()) {
  3163. return false;
  3164. } else if ($this->initialised) {
  3165. return true;
  3166. }
  3167. $this->id = 'settingsnav';
  3168. $this->context = $this->page->context;
  3169. $context = $this->context;
  3170. if ($context->contextlevel == CONTEXT_BLOCK) {
  3171. $this->load_block_settings();
  3172. $context = $context->get_parent_context();
  3173. }
  3174. switch ($context->contextlevel) {
  3175. case CONTEXT_SYSTEM:
  3176. if ($this->page->url->compare(new moodle_url('/admin/settings.php', array('section'=>'frontpagesettings')))) {
  3177. $this->load_front_page_settings(($context->id == $this->context->id));
  3178. }
  3179. break;
  3180. case CONTEXT_COURSECAT:
  3181. $this->load_category_settings();
  3182. break;
  3183. case CONTEXT_COURSE:
  3184. if ($this->page->course->id != $SITE->id) {
  3185. $this->load_course_settings(($context->id == $this->context->id));
  3186. } else {
  3187. $this->load_front_page_settings(($context->id == $this->context->id));
  3188. }
  3189. break;
  3190. case CONTEXT_MODULE:
  3191. $this->load_module_settings();
  3192. $this->load_course_settings();
  3193. break;
  3194. case CONTEXT_USER:
  3195. if ($this->page->course->id != $SITE->id) {
  3196. $this->load_course_settings();
  3197. }
  3198. break;
  3199. }
  3200. $usersettings = $this->load_user_settings($this->page->course->id);
  3201. $adminsettings = false;
  3202. if (isloggedin() && !isguestuser() && (!isset($SESSION->load_navigation_admin) || $SESSION->load_navigation_admin)) {
  3203. $isadminpage = $this->is_admin_tree_needed();
  3204. if (has_capability('moodle/site:config', context_system::instance())) {
  3205. // Make sure this works even if config capability changes on the fly
  3206. // and also make it fast for admin right after login.
  3207. $SESSION->load_navigation_admin = 1;
  3208. if ($isadminpage) {
  3209. $adminsettings = $this->load_administration_settings();
  3210. }
  3211. } else if (!isset($SESSION->load_navigation_admin)) {
  3212. $adminsettings = $this->load_administration_settings();
  3213. $SESSION->load_navigation_admin = (int)($adminsettings->children->count() > 0);
  3214. } else if ($SESSION->load_navigation_admin) {
  3215. if ($isadminpage) {
  3216. $adminsettings = $this->load_administration_settings();
  3217. }
  3218. }
  3219. // Print empty navigation node, if needed.
  3220. if ($SESSION->load_navigation_admin && !$isadminpage) {
  3221. if ($adminsettings) {
  3222. // Do not print settings tree on pages that do not need it, this helps with performance.
  3223. $adminsettings->remove();
  3224. $adminsettings = false;
  3225. }
  3226. $siteadminnode = $this->add(get_string('administrationsite'), new moodle_url('/admin'), self::TYPE_SITE_ADMIN, null, 'siteadministration');
  3227. $siteadminnode->id = 'expandable_branch_'.$siteadminnode->type.'_'.clean_param($siteadminnode->key, PARAM_ALPHANUMEXT);
  3228. $this->page->requires->data_for_js('siteadminexpansion', $siteadminnode);
  3229. }
  3230. }
  3231. if ($context->contextlevel == CONTEXT_SYSTEM && $adminsettings) {
  3232. $adminsettings->force_open();
  3233. } else if ($context->contextlevel == CONTEXT_USER && $usersettings) {
  3234. $usersettings->force_open();
  3235. }
  3236. // Check if the user is currently logged in as another user
  3237. if (\core\session\manager::is_loggedinas()) {
  3238. // Get the actual user, we need this so we can display an informative return link
  3239. $realuser = \core\session\manager::get_realuser();
  3240. // Add the informative return to original user link
  3241. $url = new moodle_url('/course/loginas.php',array('id'=>$this->page->course->id, 'return'=>1,'sesskey'=>sesskey()));
  3242. $this->add(get_string('returntooriginaluser', 'moodle', fullname($realuser, true)), $url, self::TYPE_SETTING, null, null, new pix_icon('t/left', ''));
  3243. }
  3244. // At this point we give any local plugins the ability to extend/tinker with the navigation settings.
  3245. $this->load_local_plugin_settings();
  3246. foreach ($this->children as $key=>$node) {
  3247. if ($node->nodetype != self::NODETYPE_BRANCH || $node->children->count()===0) {
  3248. // Site administration is shown as link.
  3249. if (!empty($SESSION->load_navigation_admin) && ($node->type === self::TYPE_SITE_ADMIN)) {
  3250. continue;
  3251. }
  3252. $node->remove();
  3253. }
  3254. }
  3255. $this->initialised = true;
  3256. }
  3257. /**
  3258. * Override the parent function so that we can add preceeding hr's and set a
  3259. * root node class against all first level element
  3260. *
  3261. * It does this by first calling the parent's add method {@link navigation_node::add()}
  3262. * and then proceeds to use the key to set class and hr
  3263. *
  3264. * @param string $text text to be used for the link.
  3265. * @param string|moodle_url $url url for the new node
  3266. * @param int $type the type of node navigation_node::TYPE_*
  3267. * @param string $shorttext
  3268. * @param string|int $key a key to access the node by.
  3269. * @param pix_icon $icon An icon that appears next to the node.
  3270. * @return navigation_node with the new node added to it.
  3271. */
  3272. public function add($text, $url=null, $type=null, $shorttext=null, $key=null, pix_icon $icon=null) {
  3273. $node = parent::add($text, $url, $type, $shorttext, $key, $icon);
  3274. $node->add_class('root_node');
  3275. return $node;
  3276. }
  3277. /**
  3278. * This function allows the user to add something to the start of the settings
  3279. * navigation, which means it will be at the top of the settings navigation block
  3280. *
  3281. * @param string $text text to be used for the link.
  3282. * @param string|moodle_url $url url for the new node
  3283. * @param int $type the type of node navigation_node::TYPE_*
  3284. * @param string $shorttext
  3285. * @param string|int $key a key to access the node by.
  3286. * @param pix_icon $icon An icon that appears next to the node.
  3287. * @return navigation_node $node with the new node added to it.
  3288. */
  3289. public function prepend($text, $url=null, $type=null, $shorttext=null, $key=null, pix_icon $icon=null) {
  3290. $children = $this->children;
  3291. $childrenclass = get_class($children);
  3292. $this->children = new $childrenclass;
  3293. $node = $this->add($text, $url, $type, $shorttext, $key, $icon);
  3294. foreach ($children as $child) {
  3295. $this->children->add($child);
  3296. }
  3297. return $node;
  3298. }
  3299. /**
  3300. * Does this page require loading of full admin tree or is
  3301. * it enough rely on AJAX?
  3302. *
  3303. * @return bool
  3304. */
  3305. protected function is_admin_tree_needed() {
  3306. if (self::$loadadmintree) {
  3307. // Usually external admin page or settings page.
  3308. return true;
  3309. }
  3310. if ($this->page->pagelayout === 'admin' or strpos($this->page->pagetype, 'admin-') === 0) {
  3311. // Admin settings tree is intended for system level settings and management only, use navigation for the rest!
  3312. if ($this->page->context->contextlevel != CONTEXT_SYSTEM) {
  3313. return false;
  3314. }
  3315. return true;
  3316. }
  3317. return false;
  3318. }
  3319. /**
  3320. * Load the site administration tree
  3321. *
  3322. * This function loads the site administration tree by using the lib/adminlib library functions
  3323. *
  3324. * @param navigation_node $referencebranch A reference to a branch in the settings
  3325. * navigation tree
  3326. * @param part_of_admin_tree $adminbranch The branch to add, if null generate the admin
  3327. * tree and start at the beginning
  3328. * @return mixed A key to access the admin tree by
  3329. */
  3330. protected function load_administration_settings(navigation_node $referencebranch=null, part_of_admin_tree $adminbranch=null) {
  3331. global $CFG;
  3332. // Check if we are just starting to generate this navigation.
  3333. if ($referencebranch === null) {
  3334. // Require the admin lib then get an admin structure
  3335. if (!function_exists('admin_get_root')) {
  3336. require_once($CFG->dirroot.'/lib/adminlib.php');
  3337. }
  3338. $adminroot = admin_get_root(false, false);
  3339. // This is the active section identifier
  3340. $this->adminsection = $this->page->url->param('section');
  3341. // Disable the navigation from automatically finding the active node
  3342. navigation_node::$autofindactive = false;
  3343. $referencebranch = $this->add(get_string('administrationsite'), null, self::TYPE_SITE_ADMIN, null, 'root');
  3344. foreach ($adminroot->children as $adminbranch) {
  3345. $this->load_administration_settings($referencebranch, $adminbranch);
  3346. }
  3347. navigation_node::$autofindactive = true;
  3348. // Use the admin structure to locate the active page
  3349. if (!$this->contains_active_node() && $current = $adminroot->locate($this->adminsection, true)) {
  3350. $currentnode = $this;
  3351. while (($pathkey = array_pop($current->path))!==null && $currentnode) {
  3352. $currentnode = $currentnode->get($pathkey);
  3353. }
  3354. if ($currentnode) {
  3355. $currentnode->make_active();
  3356. }
  3357. } else {
  3358. $this->scan_for_active_node($referencebranch);
  3359. }
  3360. return $referencebranch;
  3361. } else if ($adminbranch->check_access()) {
  3362. // We have a reference branch that we can access and is not hidden `hurrah`
  3363. // Now we need to display it and any children it may have
  3364. $url = null;
  3365. $icon = null;
  3366. if ($adminbranch instanceof admin_settingpage) {
  3367. $url = new moodle_url('/'.$CFG->admin.'/settings.php', array('section'=>$adminbranch->name));
  3368. } else if ($adminbranch instanceof admin_externalpage) {
  3369. $url = $adminbranch->url;
  3370. } else if (!empty($CFG->linkadmincategories) && $adminbranch instanceof admin_category) {
  3371. $url = new moodle_url('/'.$CFG->admin.'/category.php', array('category' => $adminbranch->name));
  3372. }
  3373. // Add the branch
  3374. $reference = $referencebranch->add($adminbranch->visiblename, $url, self::TYPE_SETTING, null, $adminbranch->name, $icon);
  3375. if ($adminbranch->is_hidden()) {
  3376. if (($adminbranch instanceof admin_externalpage || $adminbranch instanceof admin_settingpage) && $adminbranch->name == $this->adminsection) {
  3377. $reference->add_class('hidden');
  3378. } else {
  3379. $reference->display = false;
  3380. }
  3381. }
  3382. // Check if we are generating the admin notifications and whether notificiations exist
  3383. if ($adminbranch->name === 'adminnotifications' && admin_critical_warnings_present()) {
  3384. $reference->add_class('criticalnotification');
  3385. }
  3386. // Check if this branch has children
  3387. if ($reference && isset($adminbranch->children) && is_array($adminbranch->children) && count($adminbranch->children)>0) {
  3388. foreach ($adminbranch->children as $branch) {
  3389. // Generate the child branches as well now using this branch as the reference
  3390. $this->load_administration_settings($reference, $branch);
  3391. }
  3392. } else {
  3393. $reference->icon = new pix_icon('i/settings', '');
  3394. }
  3395. }
  3396. }
  3397. /**
  3398. * This function recursivily scans nodes until it finds the active node or there
  3399. * are no more nodes.
  3400. * @param navigation_node $node
  3401. */
  3402. protected function scan_for_active_node(navigation_node $node) {
  3403. if (!$node->check_if_active() && $node->children->count()>0) {
  3404. foreach ($node->children as &$child) {
  3405. $this->scan_for_active_node($child);
  3406. }
  3407. }
  3408. }
  3409. /**
  3410. * Gets a navigation node given an array of keys that represent the path to
  3411. * the desired node.
  3412. *
  3413. * @param array $path
  3414. * @return navigation_node|false
  3415. */
  3416. protected function get_by_path(array $path) {
  3417. $node = $this->get(array_shift($path));
  3418. foreach ($path as $key) {
  3419. $node->get($key);
  3420. }
  3421. return $node;
  3422. }
  3423. /**
  3424. * This function loads the course settings that are available for the user
  3425. *
  3426. * @param bool $forceopen If set to true the course node will be forced open
  3427. * @return navigation_node|false
  3428. */
  3429. protected function load_course_settings($forceopen = false) {
  3430. global $CFG;
  3431. $course = $this->page->course;
  3432. $coursecontext = context_course::instance($course->id);
  3433. // note: do not test if enrolled or viewing here because we need the enrol link in Course administration section
  3434. $coursenode = $this->add(get_string('courseadministration'), null, self::TYPE_COURSE, null, 'courseadmin');
  3435. if ($forceopen) {
  3436. $coursenode->force_open();
  3437. }
  3438. if ($this->page->user_allowed_editing()) {
  3439. // Add the turn on/off settings
  3440. if ($this->page->url->compare(new moodle_url('/course/view.php'), URL_MATCH_BASE)) {
  3441. // We are on the course page, retain the current page params e.g. section.
  3442. $baseurl = clone($this->page->url);
  3443. $baseurl->param('sesskey', sesskey());
  3444. } else {
  3445. // Edit on the main course page.
  3446. $baseurl = new moodle_url('/course/view.php', array('id'=>$course->id, 'return'=>$this->page->url->out_as_local_url(false), 'sesskey'=>sesskey()));
  3447. }
  3448. $editurl = clone($baseurl);
  3449. if ($this->page->user_is_editing()) {
  3450. $editurl->param('edit', 'off');
  3451. $editstring = get_string('turneditingoff');
  3452. } else {
  3453. $editurl->param('edit', 'on');
  3454. $editstring = get_string('turneditingon');
  3455. }
  3456. $coursenode->add($editstring, $editurl, self::TYPE_SETTING, null, 'turneditingonoff', new pix_icon('i/edit', ''));
  3457. }
  3458. if (has_capability('moodle/course:update', $coursecontext)) {
  3459. // Add the course settings link
  3460. $url = new moodle_url('/course/edit.php', array('id'=>$course->id));
  3461. $coursenode->add(get_string('editsettings'), $url, self::TYPE_SETTING, null, 'editsettings', new pix_icon('i/settings', ''));
  3462. // Add the course completion settings link
  3463. if ($CFG->enablecompletion && $course->enablecompletion) {
  3464. $url = new moodle_url('/course/completion.php', array('id'=>$course->id));
  3465. $coursenode->add(get_string('coursecompletion', 'completion'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/settings', ''));
  3466. }
  3467. }
  3468. // add enrol nodes
  3469. enrol_add_course_navigation($coursenode, $course);
  3470. // Manage filters
  3471. if (has_capability('moodle/filter:manage', $coursecontext) && count(filter_get_available_in_context($coursecontext))>0) {
  3472. $url = new moodle_url('/filter/manage.php', array('contextid'=>$coursecontext->id));
  3473. $coursenode->add(get_string('filters', 'admin'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/filter', ''));
  3474. }
  3475. // View course reports.
  3476. if (has_capability('moodle/site:viewreports', $coursecontext)) { // Basic capability for listing of reports.
  3477. $reportnav = $coursenode->add(get_string('reports'), null, self::TYPE_CONTAINER, null, null,
  3478. new pix_icon('i/stats', ''));
  3479. $coursereports = core_component::get_plugin_list('coursereport');
  3480. foreach ($coursereports as $report => $dir) {
  3481. $libfile = $CFG->dirroot.'/course/report/'.$report.'/lib.php';
  3482. if (file_exists($libfile)) {
  3483. require_once($libfile);
  3484. $reportfunction = $report.'_report_extend_navigation';
  3485. if (function_exists($report.'_report_extend_navigation')) {
  3486. $reportfunction($reportnav, $course, $coursecontext);
  3487. }
  3488. }
  3489. }
  3490. $reports = get_plugin_list_with_function('report', 'extend_navigation_course', 'lib.php');
  3491. foreach ($reports as $reportfunction) {
  3492. $reportfunction($reportnav, $course, $coursecontext);
  3493. }
  3494. }
  3495. // Add view grade report is permitted
  3496. $reportavailable = false;
  3497. if (has_capability('moodle/grade:viewall', $coursecontext)) {
  3498. $reportavailable = true;
  3499. } else if (!empty($course->showgrades)) {
  3500. $reports = core_component::get_plugin_list('gradereport');
  3501. if (is_array($reports) && count($reports)>0) { // Get all installed reports
  3502. arsort($reports); // user is last, we want to test it first
  3503. foreach ($reports as $plugin => $plugindir) {
  3504. if (has_capability('gradereport/'.$plugin.':view', $coursecontext)) {
  3505. //stop when the first visible plugin is found
  3506. $reportavailable = true;
  3507. break;
  3508. }
  3509. }
  3510. }
  3511. }
  3512. if ($reportavailable) {
  3513. $url = new moodle_url('/grade/report/index.php', array('id'=>$course->id));
  3514. $gradenode = $coursenode->add(get_string('grades'), $url, self::TYPE_SETTING, null, 'grades', new pix_icon('i/grades', ''));
  3515. }
  3516. // Add outcome if permitted
  3517. if (!empty($CFG->enableoutcomes) && has_capability('moodle/course:update', $coursecontext)) {
  3518. $url = new moodle_url('/grade/edit/outcome/course.php', array('id'=>$course->id));
  3519. $coursenode->add(get_string('outcomes', 'grades'), $url, self::TYPE_SETTING, null, 'outcomes', new pix_icon('i/outcomes', ''));
  3520. }
  3521. //Add badges navigation
  3522. require_once($CFG->libdir .'/badgeslib.php');
  3523. badges_add_course_navigation($coursenode, $course);
  3524. // Backup this course
  3525. if (has_capability('moodle/backup:backupcourse', $coursecontext)) {
  3526. $url = new moodle_url('/backup/backup.php', array('id'=>$course->id));
  3527. $coursenode->add(get_string('backup'), $url, self::TYPE_SETTING, null, 'backup', new pix_icon('i/backup', ''));
  3528. }
  3529. // Restore to this course
  3530. if (has_capability('moodle/restore:restorecourse', $coursecontext)) {
  3531. $url = new moodle_url('/backup/restorefile.php', array('contextid'=>$coursecontext->id));
  3532. $coursenode->add(get_string('restore'), $url, self::TYPE_SETTING, null, 'restore', new pix_icon('i/restore', ''));
  3533. }
  3534. // Import data from other courses
  3535. if (has_capability('moodle/restore:restoretargetimport', $coursecontext)) {
  3536. $url = new moodle_url('/backup/import.php', array('id'=>$course->id));
  3537. $coursenode->add(get_string('import'), $url, self::TYPE_SETTING, null, 'import', new pix_icon('i/import', ''));
  3538. }
  3539. // Publish course on a hub
  3540. if (has_capability('moodle/course:publish', $coursecontext)) {
  3541. $url = new moodle_url('/course/publish/index.php', array('id'=>$course->id));
  3542. $coursenode->add(get_string('publish'), $url, self::TYPE_SETTING, null, 'publish', new pix_icon('i/publish', ''));
  3543. }
  3544. // Reset this course
  3545. if (has_capability('moodle/course:reset', $coursecontext)) {
  3546. $url = new moodle_url('/course/reset.php', array('id'=>$course->id));
  3547. $coursenode->add(get_string('reset'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/return', ''));
  3548. }
  3549. // Questions
  3550. require_once($CFG->libdir . '/questionlib.php');
  3551. question_extend_settings_navigation($coursenode, $coursecontext)->trim_if_empty();
  3552. if (has_capability('moodle/course:update', $coursecontext)) {
  3553. // Repository Instances
  3554. if (!$this->cache->cached('contexthasrepos'.$coursecontext->id)) {
  3555. require_once($CFG->dirroot . '/repository/lib.php');
  3556. $editabletypes = repository::get_editable_types($coursecontext);
  3557. $haseditabletypes = !empty($editabletypes);
  3558. unset($editabletypes);
  3559. $this->cache->set('contexthasrepos'.$coursecontext->id, $haseditabletypes);
  3560. } else {
  3561. $haseditabletypes = $this->cache->{'contexthasrepos'.$coursecontext->id};
  3562. }
  3563. if ($haseditabletypes) {
  3564. $url = new moodle_url('/repository/manage_instances.php', array('contextid' => $coursecontext->id));
  3565. $coursenode->add(get_string('repositories'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/repository', ''));
  3566. }
  3567. }
  3568. // Manage files
  3569. if ($course->legacyfiles == 2 and has_capability('moodle/course:managefiles', $coursecontext)) {
  3570. // hidden in new courses and courses where legacy files were turned off
  3571. $url = new moodle_url('/files/index.php', array('contextid'=>$coursecontext->id));
  3572. $coursenode->add(get_string('courselegacyfiles'), $url, self::TYPE_SETTING, null, 'coursefiles', new pix_icon('i/folder', ''));
  3573. }
  3574. // Switch roles
  3575. $roles = array();
  3576. $assumedrole = $this->in_alternative_role();
  3577. if ($assumedrole !== false) {
  3578. $roles[0] = get_string('switchrolereturn');
  3579. }
  3580. if (has_capability('moodle/role:switchroles', $coursecontext)) {
  3581. $availableroles = get_switchable_roles($coursecontext);
  3582. if (is_array($availableroles)) {
  3583. foreach ($availableroles as $key=>$role) {
  3584. if ($assumedrole == (int)$key) {
  3585. continue;
  3586. }
  3587. $roles[$key] = $role;
  3588. }
  3589. }
  3590. }
  3591. if (is_array($roles) && count($roles)>0) {
  3592. $switchroles = $this->add(get_string('switchroleto'));
  3593. if ((count($roles)==1 && array_key_exists(0, $roles))|| $assumedrole!==false) {
  3594. $switchroles->force_open();
  3595. }
  3596. foreach ($roles as $key => $name) {
  3597. $url = new moodle_url('/course/switchrole.php', array('id'=>$course->id, 'sesskey'=>sesskey(), 'switchrole'=>$key, 'returnurl'=>$this->page->url->out_as_local_url(false)));
  3598. $switchroles->add($name, $url, self::TYPE_SETTING, null, $key, new pix_icon('i/switchrole', ''));
  3599. }
  3600. }
  3601. // Return we are done
  3602. return $coursenode;
  3603. }
  3604. /**
  3605. * This function calls the module function to inject module settings into the
  3606. * settings navigation tree.
  3607. *
  3608. * This only gets called if there is a corrosponding function in the modules
  3609. * lib file.
  3610. *
  3611. * For examples mod/forum/lib.php {@link forum_extend_settings_navigation()}
  3612. *
  3613. * @return navigation_node|false
  3614. */
  3615. protected function load_module_settings() {
  3616. global $CFG;
  3617. if (!$this->page->cm && $this->context->contextlevel == CONTEXT_MODULE && $this->context->instanceid) {
  3618. $cm = get_coursemodule_from_id(false, $this->context->instanceid, 0, false, MUST_EXIST);
  3619. $this->page->set_cm($cm, $this->page->course);
  3620. }
  3621. $file = $CFG->dirroot.'/mod/'.$this->page->activityname.'/lib.php';
  3622. if (file_exists($file)) {
  3623. require_once($file);
  3624. }
  3625. $modulenode = $this->add(get_string('pluginadministration', $this->page->activityname), null, self::TYPE_SETTING, null, 'modulesettings');
  3626. $modulenode->force_open();
  3627. // Settings for the module
  3628. if (has_capability('moodle/course:manageactivities', $this->page->cm->context)) {
  3629. $url = new moodle_url('/course/modedit.php', array('update' => $this->page->cm->id, 'return' => 1));
  3630. $modulenode->add(get_string('editsettings'), $url, navigation_node::TYPE_SETTING, null, 'modedit');
  3631. }
  3632. // Assign local roles
  3633. if (count(get_assignable_roles($this->page->cm->context))>0) {
  3634. $url = new moodle_url('/'.$CFG->admin.'/roles/assign.php', array('contextid'=>$this->page->cm->context->id));
  3635. $modulenode->add(get_string('localroles', 'role'), $url, self::TYPE_SETTING, null, 'roleassign');
  3636. }
  3637. // Override roles
  3638. if (has_capability('moodle/role:review', $this->page->cm->context) or count(get_overridable_roles($this->page->cm->context))>0) {
  3639. $url = new moodle_url('/'.$CFG->admin.'/roles/permissions.php', array('contextid'=>$this->page->cm->context->id));
  3640. $modulenode->add(get_string('permissions', 'role'), $url, self::TYPE_SETTING, null, 'roleoverride');
  3641. }
  3642. // Check role permissions
  3643. if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride','moodle/role:override', 'moodle/role:assign'), $this->page->cm->context)) {
  3644. $url = new moodle_url('/'.$CFG->admin.'/roles/check.php', array('contextid'=>$this->page->cm->context->id));
  3645. $modulenode->add(get_string('checkpermissions', 'role'), $url, self::TYPE_SETTING, null, 'rolecheck');
  3646. }
  3647. // Manage filters
  3648. if (has_capability('moodle/filter:manage', $this->page->cm->context) && count(filter_get_available_in_context($this->page->cm->context))>0) {
  3649. $url = new moodle_url('/filter/manage.php', array('contextid'=>$this->page->cm->context->id));
  3650. $modulenode->add(get_string('filters', 'admin'), $url, self::TYPE_SETTING, null, 'filtermanage');
  3651. }
  3652. // Add reports
  3653. $reports = get_plugin_list_with_function('report', 'extend_navigation_module', 'lib.php');
  3654. foreach ($reports as $reportfunction) {
  3655. $reportfunction($modulenode, $this->page->cm);
  3656. }
  3657. // Add a backup link
  3658. $featuresfunc = $this->page->activityname.'_supports';
  3659. if (function_exists($featuresfunc) && $featuresfunc(FEATURE_BACKUP_MOODLE2) && has_capability('moodle/backup:backupactivity', $this->page->cm->context)) {
  3660. $url = new moodle_url('/backup/backup.php', array('id'=>$this->page->cm->course, 'cm'=>$this->page->cm->id));
  3661. $modulenode->add(get_string('backup'), $url, self::TYPE_SETTING, null, 'backup');
  3662. }
  3663. // Restore this activity
  3664. $featuresfunc = $this->page->activityname.'_supports';
  3665. if (function_exists($featuresfunc) && $featuresfunc(FEATURE_BACKUP_MOODLE2) && has_capability('moodle/restore:restoreactivity', $this->page->cm->context)) {
  3666. $url = new moodle_url('/backup/restorefile.php', array('contextid'=>$this->page->cm->context->id));
  3667. $modulenode->add(get_string('restore'), $url, self::TYPE_SETTING, null, 'restore');
  3668. }
  3669. // Allow the active advanced grading method plugin to append its settings
  3670. $featuresfunc = $this->page->activityname.'_supports';
  3671. if (function_exists($featuresfunc) && $featuresfunc(FEATURE_ADVANCED_GRADING) && has_capability('moodle/grade:managegradingforms', $this->page->cm->context)) {
  3672. require_once($CFG->dirroot.'/grade/grading/lib.php');
  3673. $gradingman = get_grading_manager($this->page->cm->context, $this->page->activityname);
  3674. $gradingman->extend_settings_navigation($this, $modulenode);
  3675. }
  3676. $function = $this->page->activityname.'_extend_settings_navigation';
  3677. if (!function_exists($function)) {
  3678. return $modulenode;
  3679. }
  3680. $function($this, $modulenode);
  3681. // Remove the module node if there are no children
  3682. if (empty($modulenode->children)) {
  3683. $modulenode->remove();
  3684. }
  3685. return $modulenode;
  3686. }
  3687. /**
  3688. * Loads the user settings block of the settings nav
  3689. *
  3690. * This function is simply works out the userid and whether we need to load
  3691. * just the current users profile settings, or the current user and the user the
  3692. * current user is viewing.
  3693. *
  3694. * This function has some very ugly code to work out the user, if anyone has
  3695. * any bright ideas please feel free to intervene.
  3696. *
  3697. * @param int $courseid The course id of the current course
  3698. * @return navigation_node|false
  3699. */
  3700. protected function load_user_settings($courseid = SITEID) {
  3701. global $USER, $CFG;
  3702. if (isguestuser() || !isloggedin()) {
  3703. return false;
  3704. }
  3705. $navusers = $this->page->navigation->get_extending_users();
  3706. if (count($this->userstoextendfor) > 0 || count($navusers) > 0) {
  3707. $usernode = null;
  3708. foreach ($this->userstoextendfor as $userid) {
  3709. if ($userid == $USER->id) {
  3710. continue;
  3711. }
  3712. $node = $this->generate_user_settings($courseid, $userid, 'userviewingsettings');
  3713. if (is_null($usernode)) {
  3714. $usernode = $node;
  3715. }
  3716. }
  3717. foreach ($navusers as $user) {
  3718. if ($user->id == $USER->id) {
  3719. continue;
  3720. }
  3721. $node = $this->generate_user_settings($courseid, $user->id, 'userviewingsettings');
  3722. if (is_null($usernode)) {
  3723. $usernode = $node;
  3724. }
  3725. }
  3726. $this->generate_user_settings($courseid, $USER->id);
  3727. } else {
  3728. $usernode = $this->generate_user_settings($courseid, $USER->id);
  3729. }
  3730. return $usernode;
  3731. }
  3732. /**
  3733. * Extends the settings navigation for the given user.
  3734. *
  3735. * Note: This method gets called automatically if you call
  3736. * $PAGE->navigation->extend_for_user($userid)
  3737. *
  3738. * @param int $userid
  3739. */
  3740. public function extend_for_user($userid) {
  3741. global $CFG;
  3742. if (!in_array($userid, $this->userstoextendfor)) {
  3743. $this->userstoextendfor[] = $userid;
  3744. if ($this->initialised) {
  3745. $this->generate_user_settings($this->page->course->id, $userid, 'userviewingsettings');
  3746. $children = array();
  3747. foreach ($this->children as $child) {
  3748. $children[] = $child;
  3749. }
  3750. array_unshift($children, array_pop($children));
  3751. $this->children = new navigation_node_collection();
  3752. foreach ($children as $child) {
  3753. $this->children->add($child);
  3754. }
  3755. }
  3756. }
  3757. }
  3758. /**
  3759. * This function gets called by {@link settings_navigation::load_user_settings()} and actually works out
  3760. * what can be shown/done
  3761. *
  3762. * @param int $courseid The current course' id
  3763. * @param int $userid The user id to load for
  3764. * @param string $gstitle The string to pass to get_string for the branch title
  3765. * @return navigation_node|false
  3766. */
  3767. protected function generate_user_settings($courseid, $userid, $gstitle='usercurrentsettings') {
  3768. global $DB, $CFG, $USER, $SITE;
  3769. if ($courseid != $SITE->id) {
  3770. if (!empty($this->page->course->id) && $this->page->course->id == $courseid) {
  3771. $course = $this->page->course;
  3772. } else {
  3773. $select = context_helper::get_preload_record_columns_sql('ctx');
  3774. $sql = "SELECT c.*, $select
  3775. FROM {course} c
  3776. JOIN {context} ctx ON c.id = ctx.instanceid
  3777. WHERE c.id = :courseid AND ctx.contextlevel = :contextlevel";
  3778. $params = array('courseid' => $courseid, 'contextlevel' => CONTEXT_COURSE);
  3779. $course = $DB->get_record_sql($sql, $params, MUST_EXIST);
  3780. context_helper::preload_from_record($course);
  3781. }
  3782. } else {
  3783. $course = $SITE;
  3784. }
  3785. $coursecontext = context_course::instance($course->id); // Course context
  3786. $systemcontext = context_system::instance();
  3787. $currentuser = ($USER->id == $userid);
  3788. if ($currentuser) {
  3789. $user = $USER;
  3790. $usercontext = context_user::instance($user->id); // User context
  3791. } else {
  3792. $select = context_helper::get_preload_record_columns_sql('ctx');
  3793. $sql = "SELECT u.*, $select
  3794. FROM {user} u
  3795. JOIN {context} ctx ON u.id = ctx.instanceid
  3796. WHERE u.id = :userid AND ctx.contextlevel = :contextlevel";
  3797. $params = array('userid' => $userid, 'contextlevel' => CONTEXT_USER);
  3798. $user = $DB->get_record_sql($sql, $params, IGNORE_MISSING);
  3799. if (!$user) {
  3800. return false;
  3801. }
  3802. context_helper::preload_from_record($user);
  3803. // Check that the user can view the profile
  3804. $usercontext = context_user::instance($user->id); // User context
  3805. $canviewuser = has_capability('moodle/user:viewdetails', $usercontext);
  3806. if ($course->id == $SITE->id) {
  3807. if ($CFG->forceloginforprofiles && !has_coursecontact_role($user->id) && !$canviewuser) { // Reduce possibility of "browsing" userbase at site level
  3808. // Teachers can browse and be browsed at site level. If not forceloginforprofiles, allow access (bug #4366)
  3809. return false;
  3810. }
  3811. } else {
  3812. $canviewusercourse = has_capability('moodle/user:viewdetails', $coursecontext);
  3813. $userisenrolled = is_enrolled($coursecontext, $user->id);
  3814. if ((!$canviewusercourse && !$canviewuser) || !$userisenrolled) {
  3815. return false;
  3816. }
  3817. $canaccessallgroups = has_capability('moodle/site:accessallgroups', $coursecontext);
  3818. if (!$canaccessallgroups && groups_get_course_groupmode($course) == SEPARATEGROUPS) {
  3819. // If groups are in use, make sure we can see that group
  3820. return false;
  3821. }
  3822. }
  3823. }
  3824. $fullname = fullname($user, has_capability('moodle/site:viewfullnames', $this->page->context));
  3825. $key = $gstitle;
  3826. if ($gstitle != 'usercurrentsettings') {
  3827. $key .= $userid;
  3828. }
  3829. // Add a user setting branch
  3830. $usersetting = $this->add(get_string($gstitle, 'moodle', $fullname), null, self::TYPE_CONTAINER, null, $key);
  3831. $usersetting->id = 'usersettings';
  3832. if ($this->page->context->contextlevel == CONTEXT_USER && $this->page->context->instanceid == $user->id) {
  3833. // Automatically start by making it active
  3834. $usersetting->make_active();
  3835. }
  3836. // Check if the user has been deleted
  3837. if ($user->deleted) {
  3838. if (!has_capability('moodle/user:update', $coursecontext)) {
  3839. // We can't edit the user so just show the user deleted message
  3840. $usersetting->add(get_string('userdeleted'), null, self::TYPE_SETTING);
  3841. } else {
  3842. // We can edit the user so show the user deleted message and link it to the profile
  3843. if ($course->id == $SITE->id) {
  3844. $profileurl = new moodle_url('/user/profile.php', array('id'=>$user->id));
  3845. } else {
  3846. $profileurl = new moodle_url('/user/view.php', array('id'=>$user->id, 'course'=>$course->id));
  3847. }
  3848. $usersetting->add(get_string('userdeleted'), $profileurl, self::TYPE_SETTING);
  3849. }
  3850. return true;
  3851. }
  3852. $userauthplugin = false;
  3853. if (!empty($user->auth)) {
  3854. $userauthplugin = get_auth_plugin($user->auth);
  3855. }
  3856. // Add the profile edit link
  3857. if (isloggedin() && !isguestuser($user) && !is_mnet_remote_user($user)) {
  3858. if (($currentuser || is_siteadmin($USER) || !is_siteadmin($user)) && has_capability('moodle/user:update', $systemcontext)) {
  3859. $url = new moodle_url('/user/editadvanced.php', array('id'=>$user->id, 'course'=>$course->id));
  3860. $usersetting->add(get_string('editmyprofile'), $url, self::TYPE_SETTING);
  3861. } else if ((has_capability('moodle/user:editprofile', $usercontext) && !is_siteadmin($user)) || ($currentuser && has_capability('moodle/user:editownprofile', $systemcontext))) {
  3862. if ($userauthplugin && $userauthplugin->can_edit_profile()) {
  3863. $url = $userauthplugin->edit_profile_url();
  3864. if (empty($url)) {
  3865. $url = new moodle_url('/user/edit.php', array('id'=>$user->id, 'course'=>$course->id));
  3866. }
  3867. $usersetting->add(get_string('editmyprofile'), $url, self::TYPE_SETTING);
  3868. }
  3869. }
  3870. }
  3871. // Change password link
  3872. if ($userauthplugin && $currentuser && !\core\session\manager::is_loggedinas() && !isguestuser() && has_capability('moodle/user:changeownpassword', $systemcontext) && $userauthplugin->can_change_password()) {
  3873. $passwordchangeurl = $userauthplugin->change_password_url();
  3874. if (empty($passwordchangeurl)) {
  3875. $passwordchangeurl = new moodle_url('/login/change_password.php', array('id'=>$course->id));
  3876. }
  3877. $usersetting->add(get_string("changepassword"), $passwordchangeurl, self::TYPE_SETTING);
  3878. }
  3879. // View the roles settings
  3880. if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride','moodle/role:override', 'moodle/role:manage'), $usercontext)) {
  3881. $roles = $usersetting->add(get_string('roles'), null, self::TYPE_SETTING);
  3882. $url = new moodle_url('/admin/roles/usersroles.php', array('userid'=>$user->id, 'courseid'=>$course->id));
  3883. $roles->add(get_string('thisusersroles', 'role'), $url, self::TYPE_SETTING);
  3884. $assignableroles = get_assignable_roles($usercontext, ROLENAME_BOTH);
  3885. if (!empty($assignableroles)) {
  3886. $url = new moodle_url('/admin/roles/assign.php', array('contextid'=>$usercontext->id,'userid'=>$user->id, 'courseid'=>$course->id));
  3887. $roles->add(get_string('assignrolesrelativetothisuser', 'role'), $url, self::TYPE_SETTING);
  3888. }
  3889. if (has_capability('moodle/role:review', $usercontext) || count(get_overridable_roles($usercontext, ROLENAME_BOTH))>0) {
  3890. $url = new moodle_url('/admin/roles/permissions.php', array('contextid'=>$usercontext->id,'userid'=>$user->id, 'courseid'=>$course->id));
  3891. $roles->add(get_string('permissions', 'role'), $url, self::TYPE_SETTING);
  3892. }
  3893. $url = new moodle_url('/admin/roles/check.php', array('contextid'=>$usercontext->id,'userid'=>$user->id, 'courseid'=>$course->id));
  3894. $roles->add(get_string('checkpermissions', 'role'), $url, self::TYPE_SETTING);
  3895. }
  3896. // Portfolio
  3897. if ($currentuser && !empty($CFG->enableportfolios) && has_capability('moodle/portfolio:export', $systemcontext)) {
  3898. require_once($CFG->libdir . '/portfoliolib.php');
  3899. if (portfolio_has_visible_instances()) {
  3900. $portfolio = $usersetting->add(get_string('portfolios', 'portfolio'), null, self::TYPE_SETTING);
  3901. $url = new moodle_url('/user/portfolio.php', array('courseid'=>$course->id));
  3902. $portfolio->add(get_string('configure', 'portfolio'), $url, self::TYPE_SETTING);
  3903. $url = new moodle_url('/user/portfoliologs.php', array('courseid'=>$course->id));
  3904. $portfolio->add(get_string('logs', 'portfolio'), $url, self::TYPE_SETTING);
  3905. }
  3906. }
  3907. $enablemanagetokens = false;
  3908. if (!empty($CFG->enablerssfeeds)) {
  3909. $enablemanagetokens = true;
  3910. } else if (!is_siteadmin($USER->id)
  3911. && !empty($CFG->enablewebservices)
  3912. && has_capability('moodle/webservice:createtoken', context_system::instance()) ) {
  3913. $enablemanagetokens = true;
  3914. }
  3915. // Security keys
  3916. if ($currentuser && $enablemanagetokens) {
  3917. $url = new moodle_url('/user/managetoken.php', array('sesskey'=>sesskey()));
  3918. $usersetting->add(get_string('securitykeys', 'webservice'), $url, self::TYPE_SETTING);
  3919. }
  3920. // Messaging
  3921. if (($currentuser && has_capability('moodle/user:editownmessageprofile', $systemcontext)) || (!isguestuser($user) && has_capability('moodle/user:editmessageprofile', $usercontext) && !is_primary_admin($user->id))) {
  3922. $url = new moodle_url('/message/edit.php', array('id'=>$user->id));
  3923. $usersetting->add(get_string('messaging', 'message'), $url, self::TYPE_SETTING);
  3924. }
  3925. // Blogs
  3926. if ($currentuser && !empty($CFG->enableblogs)) {
  3927. $blog = $usersetting->add(get_string('blogs', 'blog'), null, navigation_node::TYPE_CONTAINER, null, 'blogs');
  3928. $blog->add(get_string('preferences', 'blog'), new moodle_url('/blog/preferences.php'), navigation_node::TYPE_SETTING);
  3929. if (!empty($CFG->useexternalblogs) && $CFG->maxexternalblogsperuser > 0 && has_capability('moodle/blog:manageexternal', context_system::instance())) {
  3930. $blog->add(get_string('externalblogs', 'blog'), new moodle_url('/blog/external_blogs.php'), navigation_node::TYPE_SETTING);
  3931. $blog->add(get_string('addnewexternalblog', 'blog'), new moodle_url('/blog/external_blog_edit.php'), navigation_node::TYPE_SETTING);
  3932. }
  3933. }
  3934. // Badges.
  3935. if ($currentuser && !empty($CFG->enablebadges)) {
  3936. $badges = $usersetting->add(get_string('badges'), null, navigation_node::TYPE_CONTAINER, null, 'badges');
  3937. $badges->add(get_string('preferences'), new moodle_url('/badges/preferences.php'), navigation_node::TYPE_SETTING);
  3938. if (!empty($CFG->badges_allowexternalbackpack)) {
  3939. $badges->add(get_string('backpackdetails', 'badges'), new moodle_url('/badges/mybackpack.php'), navigation_node::TYPE_SETTING);
  3940. }
  3941. }
  3942. // Add reports node.
  3943. $reporttab = $usersetting->add(get_string('activityreports'));
  3944. $reports = get_plugin_list_with_function('report', 'extend_navigation_user', 'lib.php');
  3945. foreach ($reports as $reportfunction) {
  3946. $reportfunction($reporttab, $user, $course);
  3947. }
  3948. $anyreport = has_capability('moodle/user:viewuseractivitiesreport', $usercontext);
  3949. if ($anyreport || ($course->showreports && $currentuser)) {
  3950. // Add grade hardcoded grade report if necessary.
  3951. $gradeaccess = false;
  3952. if (has_capability('moodle/grade:viewall', $coursecontext)) {
  3953. // Can view all course grades.
  3954. $gradeaccess = true;
  3955. } else if ($course->showgrades) {
  3956. if ($currentuser && has_capability('moodle/grade:view', $coursecontext)) {
  3957. // Can view own grades.
  3958. $gradeaccess = true;
  3959. } else if (has_capability('moodle/grade:viewall', $usercontext)) {
  3960. // Can view grades of this user - parent most probably.
  3961. $gradeaccess = true;
  3962. } else if ($anyreport) {
  3963. // Can view grades of this user - parent most probably.
  3964. $gradeaccess = true;
  3965. }
  3966. }
  3967. if ($gradeaccess) {
  3968. $reporttab->add(get_string('grade'), new moodle_url('/course/user.php', array('mode'=>'grade', 'id'=>$course->id,
  3969. 'user'=>$usercontext->instanceid)));
  3970. }
  3971. }
  3972. // Check the number of nodes in the report node... if there are none remove the node
  3973. $reporttab->trim_if_empty();
  3974. // Login as ...
  3975. if (!$user->deleted and !$currentuser && !\core\session\manager::is_loggedinas() && has_capability('moodle/user:loginas', $coursecontext) && !is_siteadmin($user->id)) {
  3976. $url = new moodle_url('/course/loginas.php', array('id'=>$course->id, 'user'=>$user->id, 'sesskey'=>sesskey()));
  3977. $usersetting->add(get_string('loginas'), $url, self::TYPE_SETTING);
  3978. }
  3979. return $usersetting;
  3980. }
  3981. /**
  3982. * Loads block specific settings in the navigation
  3983. *
  3984. * @return navigation_node
  3985. */
  3986. protected function load_block_settings() {
  3987. global $CFG;
  3988. $blocknode = $this->add($this->context->get_context_name(), null, self::TYPE_SETTING, null, 'blocksettings');
  3989. $blocknode->force_open();
  3990. // Assign local roles
  3991. $assignurl = new moodle_url('/'.$CFG->admin.'/roles/assign.php', array('contextid'=>$this->context->id));
  3992. $blocknode->add(get_string('assignroles', 'role'), $assignurl, self::TYPE_SETTING);
  3993. // Override roles
  3994. if (has_capability('moodle/role:review', $this->context) or count(get_overridable_roles($this->context))>0) {
  3995. $url = new moodle_url('/'.$CFG->admin.'/roles/permissions.php', array('contextid'=>$this->context->id));
  3996. $blocknode->add(get_string('permissions', 'role'), $url, self::TYPE_SETTING);
  3997. }
  3998. // Check role permissions
  3999. if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride','moodle/role:override', 'moodle/role:assign'), $this->context)) {
  4000. $url = new moodle_url('/'.$CFG->admin.'/roles/check.php', array('contextid'=>$this->context->id));
  4001. $blocknode->add(get_string('checkpermissions', 'role'), $url, self::TYPE_SETTING);
  4002. }
  4003. return $blocknode;
  4004. }
  4005. /**
  4006. * Loads category specific settings in the navigation
  4007. *
  4008. * @return navigation_node
  4009. */
  4010. protected function load_category_settings() {
  4011. global $CFG;
  4012. $categorynode = $this->add($this->context->get_context_name(), null, null, null, 'categorysettings');
  4013. $categorynode->force_open();
  4014. if (can_edit_in_category($this->context->instanceid)) {
  4015. $url = new moodle_url('/course/management.php', array('categoryid' => $this->context->instanceid));
  4016. $editstring = get_string('managecategorythis');
  4017. $categorynode->add($editstring, $url, self::TYPE_SETTING, null, null, new pix_icon('i/edit', ''));
  4018. }
  4019. if (has_capability('moodle/category:manage', $this->context)) {
  4020. $editurl = new moodle_url('/course/editcategory.php', array('id' => $this->context->instanceid));
  4021. $categorynode->add(get_string('editcategorythis'), $editurl, self::TYPE_SETTING, null, 'edit', new pix_icon('i/edit', ''));
  4022. $addsubcaturl = new moodle_url('/course/editcategory.php', array('parent' => $this->context->instanceid));
  4023. $categorynode->add(get_string('addsubcategory'), $addsubcaturl, self::TYPE_SETTING, null, 'addsubcat', new pix_icon('i/withsubcat', ''));
  4024. }
  4025. // Assign local roles
  4026. if (has_capability('moodle/role:assign', $this->context)) {
  4027. $assignurl = new moodle_url('/'.$CFG->admin.'/roles/assign.php', array('contextid'=>$this->context->id));
  4028. $categorynode->add(get_string('assignroles', 'role'), $assignurl, self::TYPE_SETTING, null, 'roles', new pix_icon('i/assignroles', ''));
  4029. }
  4030. // Override roles
  4031. if (has_capability('moodle/role:review', $this->context) or count(get_overridable_roles($this->context))>0) {
  4032. $url = new moodle_url('/'.$CFG->admin.'/roles/permissions.php', array('contextid'=>$this->context->id));
  4033. $categorynode->add(get_string('permissions', 'role'), $url, self::TYPE_SETTING, null, 'permissions', new pix_icon('i/permissions', ''));
  4034. }
  4035. // Check role permissions
  4036. if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride','moodle/role:override', 'moodle/role:assign'), $this->context)) {
  4037. $url = new moodle_url('/'.$CFG->admin.'/roles/check.php', array('contextid'=>$this->context->id));
  4038. $categorynode->add(get_string('checkpermissions', 'role'), $url, self::TYPE_SETTING, null, 'checkpermissions', new pix_icon('i/checkpermissions', ''));
  4039. }
  4040. // Cohorts
  4041. if (has_any_capability(array('moodle/cohort:view', 'moodle/cohort:manage'), $this->context)) {
  4042. $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', ''));
  4043. }
  4044. // Manage filters
  4045. if (has_capability('moodle/filter:manage', $this->context) && count(filter_get_available_in_context($this->context))>0) {
  4046. $url = new moodle_url('/filter/manage.php', array('contextid'=>$this->context->id));
  4047. $categorynode->add(get_string('filters', 'admin'), $url, self::TYPE_SETTING, null, 'filters', new pix_icon('i/filter', ''));
  4048. }
  4049. // Restore.
  4050. if (has_capability('moodle/course:create', $this->context)) {
  4051. $url = new moodle_url('/backup/restorefile.php', array('contextid' => $this->context->id));
  4052. $categorynode->add(get_string('restorecourse', 'admin'), $url, self::TYPE_SETTING, null, 'restorecourse', new pix_icon('i/restore', ''));
  4053. }
  4054. return $categorynode;
  4055. }
  4056. /**
  4057. * Determine whether the user is assuming another role
  4058. *
  4059. * This function checks to see if the user is assuming another role by means of
  4060. * role switching. In doing this we compare each RSW key (context path) against
  4061. * the current context path. This ensures that we can provide the switching
  4062. * options against both the course and any page shown under the course.
  4063. *
  4064. * @return bool|int The role(int) if the user is in another role, false otherwise
  4065. */
  4066. protected function in_alternative_role() {
  4067. global $USER;
  4068. if (!empty($USER->access['rsw']) && is_array($USER->access['rsw'])) {
  4069. if (!empty($this->page->context) && !empty($USER->access['rsw'][$this->page->context->path])) {
  4070. return $USER->access['rsw'][$this->page->context->path];
  4071. }
  4072. foreach ($USER->access['rsw'] as $key=>$role) {
  4073. if (strpos($this->context->path,$key)===0) {
  4074. return $role;
  4075. }
  4076. }
  4077. }
  4078. return false;
  4079. }
  4080. /**
  4081. * This function loads all of the front page settings into the settings navigation.
  4082. * This function is called when the user is on the front page, or $COURSE==$SITE
  4083. * @param bool $forceopen (optional)
  4084. * @return navigation_node
  4085. */
  4086. protected function load_front_page_settings($forceopen = false) {
  4087. global $SITE, $CFG;
  4088. $course = clone($SITE);
  4089. $coursecontext = context_course::instance($course->id); // Course context
  4090. $frontpage = $this->add(get_string('frontpagesettings'), null, self::TYPE_SETTING, null, 'frontpage');
  4091. if ($forceopen) {
  4092. $frontpage->force_open();
  4093. }
  4094. $frontpage->id = 'frontpagesettings';
  4095. if ($this->page->user_allowed_editing()) {
  4096. // Add the turn on/off settings
  4097. $url = new moodle_url('/course/view.php', array('id'=>$course->id, 'sesskey'=>sesskey()));
  4098. if ($this->page->user_is_editing()) {
  4099. $url->param('edit', 'off');
  4100. $editstring = get_string('turneditingoff');
  4101. } else {
  4102. $url->param('edit', 'on');
  4103. $editstring = get_string('turneditingon');
  4104. }
  4105. $frontpage->add($editstring, $url, self::TYPE_SETTING, null, null, new pix_icon('i/edit', ''));
  4106. }
  4107. if (has_capability('moodle/course:update', $coursecontext)) {
  4108. // Add the course settings link
  4109. $url = new moodle_url('/admin/settings.php', array('section'=>'frontpagesettings'));
  4110. $frontpage->add(get_string('editsettings'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/settings', ''));
  4111. }
  4112. // add enrol nodes
  4113. enrol_add_course_navigation($frontpage, $course);
  4114. // Manage filters
  4115. if (has_capability('moodle/filter:manage', $coursecontext) && count(filter_get_available_in_context($coursecontext))>0) {
  4116. $url = new moodle_url('/filter/manage.php', array('contextid'=>$coursecontext->id));
  4117. $frontpage->add(get_string('filters', 'admin'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/filter', ''));
  4118. }
  4119. // View course reports.
  4120. if (has_capability('moodle/site:viewreports', $coursecontext)) { // Basic capability for listing of reports.
  4121. $frontpagenav = $frontpage->add(get_string('reports'), null, self::TYPE_CONTAINER, null, null,
  4122. new pix_icon('i/stats', ''));
  4123. $coursereports = core_component::get_plugin_list('coursereport');
  4124. foreach ($coursereports as $report=>$dir) {
  4125. $libfile = $CFG->dirroot.'/course/report/'.$report.'/lib.php';
  4126. if (file_exists($libfile)) {
  4127. require_once($libfile);
  4128. $reportfunction = $report.'_report_extend_navigation';
  4129. if (function_exists($report.'_report_extend_navigation')) {
  4130. $reportfunction($frontpagenav, $course, $coursecontext);
  4131. }
  4132. }
  4133. }
  4134. $reports = get_plugin_list_with_function('report', 'extend_navigation_course', 'lib.php');
  4135. foreach ($reports as $reportfunction) {
  4136. $reportfunction($frontpagenav, $course, $coursecontext);
  4137. }
  4138. }
  4139. // Backup this course
  4140. if (has_capability('moodle/backup:backupcourse', $coursecontext)) {
  4141. $url = new moodle_url('/backup/backup.php', array('id'=>$course->id));
  4142. $frontpage->add(get_string('backup'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/backup', ''));
  4143. }
  4144. // Restore to this course
  4145. if (has_capability('moodle/restore:restorecourse', $coursecontext)) {
  4146. $url = new moodle_url('/backup/restorefile.php', array('contextid'=>$coursecontext->id));
  4147. $frontpage->add(get_string('restore'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/restore', ''));
  4148. }
  4149. // Questions
  4150. require_once($CFG->libdir . '/questionlib.php');
  4151. question_extend_settings_navigation($frontpage, $coursecontext)->trim_if_empty();
  4152. // Manage files
  4153. if ($course->legacyfiles == 2 and has_capability('moodle/course:managefiles', $this->context)) {
  4154. //hiden in new installs
  4155. $url = new moodle_url('/files/index.php', array('contextid'=>$coursecontext->id));
  4156. $frontpage->add(get_string('sitelegacyfiles'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/folder', ''));
  4157. }
  4158. return $frontpage;
  4159. }
  4160. /**
  4161. * This function gives local plugins an opportunity to modify the settings navigation.
  4162. */
  4163. protected function load_local_plugin_settings() {
  4164. // Get all local plugins with an extend_settings_navigation function in their lib.php file
  4165. foreach (get_plugin_list_with_function('local', 'extends_settings_navigation') as $function) {
  4166. // Call each function providing this (the settings navigation) and the current context.
  4167. $function($this, $this->context);
  4168. }
  4169. }
  4170. /**
  4171. * This function marks the cache as volatile so it is cleared during shutdown
  4172. */
  4173. public function clear_cache() {
  4174. $this->cache->volatile();
  4175. }
  4176. }
  4177. /**
  4178. * Class used to populate site admin navigation for ajax.
  4179. *
  4180. * @package core
  4181. * @category navigation
  4182. * @copyright 2013 Rajesh Taneja <rajesh@moodle.com>
  4183. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  4184. */
  4185. class settings_navigation_ajax extends settings_navigation {
  4186. /**
  4187. * Constructs the navigation for use in an AJAX request
  4188. *
  4189. * @param moodle_page $page
  4190. */
  4191. public function __construct(moodle_page &$page) {
  4192. $this->page = $page;
  4193. $this->cache = new navigation_cache(NAVIGATION_CACHE_NAME);
  4194. $this->children = new navigation_node_collection();
  4195. $this->initialise();
  4196. }
  4197. /**
  4198. * Initialise the site admin navigation.
  4199. *
  4200. * @return array An array of the expandable nodes
  4201. */
  4202. public function initialise() {
  4203. if ($this->initialised || during_initial_install()) {
  4204. return false;
  4205. }
  4206. $this->context = $this->page->context;
  4207. $this->load_administration_settings();
  4208. // Check if local plugins is adding node to site admin.
  4209. $this->load_local_plugin_settings();
  4210. $this->initialised = true;
  4211. }
  4212. }
  4213. /**
  4214. * Simple class used to output a navigation branch in XML
  4215. *
  4216. * @package core
  4217. * @category navigation
  4218. * @copyright 2009 Sam Hemelryk
  4219. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  4220. */
  4221. class navigation_json {
  4222. /** @var array An array of different node types */
  4223. protected $nodetype = array('node','branch');
  4224. /** @var array An array of node keys and types */
  4225. protected $expandable = array();
  4226. /**
  4227. * Turns a branch and all of its children into XML
  4228. *
  4229. * @param navigation_node $branch
  4230. * @return string XML string
  4231. */
  4232. public function convert($branch) {
  4233. $xml = $this->convert_child($branch);
  4234. return $xml;
  4235. }
  4236. /**
  4237. * Set the expandable items in the array so that we have enough information
  4238. * to attach AJAX events
  4239. * @param array $expandable
  4240. */
  4241. public function set_expandable($expandable) {
  4242. foreach ($expandable as $node) {
  4243. $this->expandable[$node['key'].':'.$node['type']] = $node;
  4244. }
  4245. }
  4246. /**
  4247. * Recusively converts a child node and its children to XML for output
  4248. *
  4249. * @param navigation_node $child The child to convert
  4250. * @param int $depth Pointlessly used to track the depth of the XML structure
  4251. * @return string JSON
  4252. */
  4253. protected function convert_child($child, $depth=1) {
  4254. if (!$child->display) {
  4255. return '';
  4256. }
  4257. $attributes = array();
  4258. $attributes['id'] = $child->id;
  4259. $attributes['name'] = (string)$child->text; // This can be lang_string object so typecast it.
  4260. $attributes['type'] = $child->type;
  4261. $attributes['key'] = $child->key;
  4262. $attributes['class'] = $child->get_css_type();
  4263. if ($child->icon instanceof pix_icon) {
  4264. $attributes['icon'] = array(
  4265. 'component' => $child->icon->component,
  4266. 'pix' => $child->icon->pix,
  4267. );
  4268. foreach ($child->icon->attributes as $key=>$value) {
  4269. if ($key == 'class') {
  4270. $attributes['icon']['classes'] = explode(' ', $value);
  4271. } else if (!array_key_exists($key, $attributes['icon'])) {
  4272. $attributes['icon'][$key] = $value;
  4273. }
  4274. }
  4275. } else if (!empty($child->icon)) {
  4276. $attributes['icon'] = (string)$child->icon;
  4277. }
  4278. if ($child->forcetitle || $child->title !== $child->text) {
  4279. $attributes['title'] = htmlentities($child->title, ENT_QUOTES, 'UTF-8');
  4280. }
  4281. if (array_key_exists($child->key.':'.$child->type, $this->expandable)) {
  4282. $attributes['expandable'] = $child->key;
  4283. $child->add_class($this->expandable[$child->key.':'.$child->type]['id']);
  4284. }
  4285. if (count($child->classes)>0) {
  4286. $attributes['class'] .= ' '.join(' ',$child->classes);
  4287. }
  4288. if (is_string($child->action)) {
  4289. $attributes['link'] = $child->action;
  4290. } else if ($child->action instanceof moodle_url) {
  4291. $attributes['link'] = $child->action->out();
  4292. } else if ($child->action instanceof action_link) {
  4293. $attributes['link'] = $child->action->url->out();
  4294. }
  4295. $attributes['hidden'] = ($child->hidden);
  4296. $attributes['haschildren'] = ($child->children->count()>0 || $child->type == navigation_node::TYPE_CATEGORY);
  4297. $attributes['haschildren'] = $attributes['haschildren'] || $child->type == navigation_node::TYPE_MY_CATEGORY;
  4298. if ($child->children->count() > 0) {
  4299. $attributes['children'] = array();
  4300. foreach ($child->children as $subchild) {
  4301. $attributes['children'][] = $this->convert_child($subchild, $depth+1);
  4302. }
  4303. }
  4304. if ($depth > 1) {
  4305. return $attributes;
  4306. } else {
  4307. return json_encode($attributes);
  4308. }
  4309. }
  4310. }
  4311. /**
  4312. * The cache class used by global navigation and settings navigation.
  4313. *
  4314. * It is basically an easy access point to session with a bit of smarts to make
  4315. * sure that the information that is cached is valid still.
  4316. *
  4317. * Example use:
  4318. * <code php>
  4319. * if (!$cache->viewdiscussion()) {
  4320. * // Code to do stuff and produce cachable content
  4321. * $cache->viewdiscussion = has_capability('mod/forum:viewdiscussion', $coursecontext);
  4322. * }
  4323. * $content = $cache->viewdiscussion;
  4324. * </code>
  4325. *
  4326. * @package core
  4327. * @category navigation
  4328. * @copyright 2009 Sam Hemelryk
  4329. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  4330. */
  4331. class navigation_cache {
  4332. /** @var int represents the time created */
  4333. protected $creation;
  4334. /** @var array An array of session keys */
  4335. protected $session;
  4336. /**
  4337. * The string to use to segregate this particular cache. It can either be
  4338. * unique to start a fresh cache or if you want to share a cache then make
  4339. * it the string used in the original cache.
  4340. * @var string
  4341. */
  4342. protected $area;
  4343. /** @var int a time that the information will time out */
  4344. protected $timeout;
  4345. /** @var stdClass The current context */
  4346. protected $currentcontext;
  4347. /** @var int cache time information */
  4348. const CACHETIME = 0;
  4349. /** @var int cache user id */
  4350. const CACHEUSERID = 1;
  4351. /** @var int cache value */
  4352. const CACHEVALUE = 2;
  4353. /** @var null|array An array of navigation cache areas to expire on shutdown */
  4354. public static $volatilecaches;
  4355. /**
  4356. * Contructor for the cache. Requires two arguments
  4357. *
  4358. * @param string $area The string to use to segregate this particular cache
  4359. * it can either be unique to start a fresh cache or if you want
  4360. * to share a cache then make it the string used in the original
  4361. * cache
  4362. * @param int $timeout The number of seconds to time the information out after
  4363. */
  4364. public function __construct($area, $timeout=1800) {
  4365. $this->creation = time();
  4366. $this->area = $area;
  4367. $this->timeout = time() - $timeout;
  4368. if (rand(0,100) === 0) {
  4369. $this->garbage_collection();
  4370. }
  4371. }
  4372. /**
  4373. * Used to set up the cache within the SESSION.
  4374. *
  4375. * This is called for each access and ensure that we don't put anything into the session before
  4376. * it is required.
  4377. */
  4378. protected function ensure_session_cache_initialised() {
  4379. global $SESSION;
  4380. if (empty($this->session)) {
  4381. if (!isset($SESSION->navcache)) {
  4382. $SESSION->navcache = new stdClass;
  4383. }
  4384. if (!isset($SESSION->navcache->{$this->area})) {
  4385. $SESSION->navcache->{$this->area} = array();
  4386. }
  4387. $this->session = &$SESSION->navcache->{$this->area}; // pointer to array, =& is correct here
  4388. }
  4389. }
  4390. /**
  4391. * Magic Method to retrieve something by simply calling using = cache->key
  4392. *
  4393. * @param mixed $key The identifier for the information you want out again
  4394. * @return void|mixed Either void or what ever was put in
  4395. */
  4396. public function __get($key) {
  4397. if (!$this->cached($key)) {
  4398. return;
  4399. }
  4400. $information = $this->session[$key][self::CACHEVALUE];
  4401. return unserialize($information);
  4402. }
  4403. /**
  4404. * Magic method that simply uses {@link set();} to store something in the cache
  4405. *
  4406. * @param string|int $key
  4407. * @param mixed $information
  4408. */
  4409. public function __set($key, $information) {
  4410. $this->set($key, $information);
  4411. }
  4412. /**
  4413. * Sets some information against the cache (session) for later retrieval
  4414. *
  4415. * @param string|int $key
  4416. * @param mixed $information
  4417. */
  4418. public function set($key, $information) {
  4419. global $USER;
  4420. $this->ensure_session_cache_initialised();
  4421. $information = serialize($information);
  4422. $this->session[$key]= array(self::CACHETIME=>time(), self::CACHEUSERID=>$USER->id, self::CACHEVALUE=>$information);
  4423. }
  4424. /**
  4425. * Check the existence of the identifier in the cache
  4426. *
  4427. * @param string|int $key
  4428. * @return bool
  4429. */
  4430. public function cached($key) {
  4431. global $USER;
  4432. $this->ensure_session_cache_initialised();
  4433. 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) {
  4434. return false;
  4435. }
  4436. return true;
  4437. }
  4438. /**
  4439. * Compare something to it's equivilant in the cache
  4440. *
  4441. * @param string $key
  4442. * @param mixed $value
  4443. * @param bool $serialise Whether to serialise the value before comparison
  4444. * this should only be set to false if the value is already
  4445. * serialised
  4446. * @return bool If the value is the same false if it is not set or doesn't match
  4447. */
  4448. public function compare($key, $value, $serialise = true) {
  4449. if ($this->cached($key)) {
  4450. if ($serialise) {
  4451. $value = serialize($value);
  4452. }
  4453. if ($this->session[$key][self::CACHEVALUE] === $value) {
  4454. return true;
  4455. }
  4456. }
  4457. return false;
  4458. }
  4459. /**
  4460. * Wipes the entire cache, good to force regeneration
  4461. */
  4462. public function clear() {
  4463. global $SESSION;
  4464. unset($SESSION->navcache);
  4465. $this->session = null;
  4466. }
  4467. /**
  4468. * Checks all cache entries and removes any that have expired, good ole cleanup
  4469. */
  4470. protected function garbage_collection() {
  4471. if (empty($this->session)) {
  4472. return true;
  4473. }
  4474. foreach ($this->session as $key=>$cachedinfo) {
  4475. if (is_array($cachedinfo) && $cachedinfo[self::CACHETIME]<$this->timeout) {
  4476. unset($this->session[$key]);
  4477. }
  4478. }
  4479. }
  4480. /**
  4481. * Marks the cache as being volatile (likely to change)
  4482. *
  4483. * Any caches marked as volatile will be destroyed at the on shutdown by
  4484. * {@link navigation_node::destroy_volatile_caches()} which is registered
  4485. * as a shutdown function if any caches are marked as volatile.
  4486. *
  4487. * @param bool $setting True to destroy the cache false not too
  4488. */
  4489. public function volatile($setting = true) {
  4490. if (self::$volatilecaches===null) {
  4491. self::$volatilecaches = array();
  4492. core_shutdown_manager::register_function(array('navigation_cache','destroy_volatile_caches'));
  4493. }
  4494. if ($setting) {
  4495. self::$volatilecaches[$this->area] = $this->area;
  4496. } else if (array_key_exists($this->area, self::$volatilecaches)) {
  4497. unset(self::$volatilecaches[$this->area]);
  4498. }
  4499. }
  4500. /**
  4501. * Destroys all caches marked as volatile
  4502. *
  4503. * This function is static and works in conjunction with the static volatilecaches
  4504. * property of navigation cache.
  4505. * Because this function is static it manually resets the cached areas back to an
  4506. * empty array.
  4507. */
  4508. public static function destroy_volatile_caches() {
  4509. global $SESSION;
  4510. if (is_array(self::$volatilecaches) && count(self::$volatilecaches)>0) {
  4511. foreach (self::$volatilecaches as $area) {
  4512. $SESSION->navcache->{$area} = array();
  4513. }
  4514. } else {
  4515. $SESSION->navcache = new stdClass;
  4516. }
  4517. }
  4518. }