3 // This file is part of Moodle - http://moodle.org/
5 // Moodle is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
10 // Moodle is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU General Public License for more details.
15 // You should have received a copy of the GNU General Public License
16 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
19 * Classes for displaying and editing a nested list of items.
21 * Handles functionality for :
23 * Construction of nested list from db records with some key pointing to a parent id.
24 * Display of list with or without editing icons with optional pagination.
25 * Reordering of items works across pages.
26 * Processing of editing actions on list.
30 * @copyright Jamie Pratt
31 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
34 defined('MOODLE_INTERNAL') ||
die();
37 * Clues to reading this code:
39 * The functions that move things around the tree structure just update the
40 * database - they don't update the in-memory structure, instead they trigger a
41 * page reload so everything is rebuilt from scratch.
44 * @copyright Jamie Pratt
45 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
47 abstract class moodle_list
{
49 public $listitemclassname = 'list_item';
51 /** @var array of $listitemclassname objects. */
52 public $items = array();
54 /** @var string 'ol' or 'ul'. */
57 /** @var list_item or derived class. */
58 public $parentitem = null;
60 public $fieldnamesparent = 'parent';
62 /** @var array Records from db, only used in top level list. */
63 public $records = array();
67 /** @var array keys are child ids, values are parents. */
70 //------------------------------------------------------
71 //vars used for pagination.
72 public $page = 0; // 0 means no pagination
73 public $firstitem = 1;
74 public $lastitem = 999999;
76 public $paged = false;
78 //------------------------------------------------------
80 public $pageparamname;
86 * @param string $attributes
87 * @param boolean $editable
88 * @param moodle_url $pageurl url for this page
89 * @param integer $page if 0 no pagination. (These three params only used in top level list.)
90 * @param string $pageparamname name of url param that is used for passing page no
91 * @param integer $itemsperpage no of top level items.
93 public function __construct($type='ul', $attributes='', $editable = false, $pageurl=null, $page = 0, $pageparamname = 'page', $itemsperpage = 20) {
96 $this->editable
= $editable;
97 $this->attributes
= $attributes;
100 $this->pageparamname
= $pageparamname;
101 $this->itemsperpage
= $itemsperpage;
102 if ($pageurl === null) {
103 $this->pageurl
= new moodle_url($PAGE->url
);
104 $this->pageurl
->params(array($this->pageparamname
=> $this->page
));
106 $this->pageurl
= $pageurl;
111 * Returns html string.
113 * @param integer $indent depth of indentation.
115 public function to_html($indent=0, $extraargs=array()) {
116 if (count($this->items
)) {
117 $tabs = str_repeat("\t", $indent);
123 foreach ($this->items
as $item) {
124 $last = (count($this->items
) == $itemiter);
125 if ($this->editable
) {
126 $item->set_icon_html($first, $last, $lastitem);
128 if ($itemhtml = $item->to_html($indent+
1, $extraargs)) {
129 $html .= "$tabs\t<li".((!empty($item->attributes
))?
(' '.$item->attributes
):'').">";
140 if ($html) { //if there are list items to display then wrap them in ul / ol tag.
141 $tabs = str_repeat("\t", $indent);
142 $html = $tabs.'<'.$this->type
.((!empty($this->attributes
))?
(' '.$this->attributes
):'').">\n".$html;
143 $html .= $tabs."</".$this->type
.">\n";
151 * Recurse down the tree and find an item by it's id.
154 * @param boolean $suppresserror error if not item found?
155 * @return list_item *copy* or null if item is not found
157 public function find_item($id, $suppresserror = false) {
158 if (isset($this->items
)) {
159 foreach ($this->items
as $key => $child) {
160 if ($child->id
== $id) {
161 return $this->items
[$key];
164 foreach (array_keys($this->items
) as $key) {
165 $thischild = $this->items
[$key];
166 $ref = $thischild->children
->find_item($id, true);//error always reported at top level
173 if (!$suppresserror) {
174 print_error('listnoitem');
179 public function add_item($item) {
180 $this->items
[] = $item;
183 public function set_parent($parent) {
184 $this->parentitem
= $parent;
188 * Produces a hierarchical tree of list items from a flat array of records.
189 * 'parent' field is expected to point to a parent record.
190 * records are already sorted.
191 * If the parent field doesn't point to another record in the array then this is
194 * @param integer $offset how many list toplevel items are there in lists before this one
195 * @return array(boolean, integer) whether there is more than one page, $offset + how many toplevel items where there in this list.
198 public function list_from_records($paged = false, $offset = 0) {
199 $this->paged
= $paged;
200 $this->offset
= $offset;
201 $this->get_records();
202 $records = $this->records
;
205 $this->firstitem
= ($page - 1) * $this->itemsperpage
;
206 $this->lastitem
= $this->firstitem +
$this->itemsperpage
- 1;
209 //make a simple array which is easier to search
210 $this->childparent
= array();
211 foreach ($records as $record) {
212 $this->childparent
[$record->id
] = $record->parent
;
215 //create top level list items and they're responsible for creating their children
216 foreach ($records as $record) {
217 if (array_key_exists($record->parent
, $this->childparent
)) {
218 // This record is a child of another record, so it will be dealt
219 // with by a call to list_item::create_children, not here.
223 $inpage = $itemiter >= $this->firstitem
&& $itemiter <= $this->lastitem
;
225 // Make list item for top level for all items
226 // we need the info about the top level items for reordering peers.
227 if ($this->parentitem
!== null) {
228 $newattributes = $this->parentitem
->attributes
;
233 $this->items
[$itemiter] = new $this->listitemclassname($record, $this, $newattributes, $inpage);
236 $this->items
[$itemiter]->create_children($records, $this->childparent
, $record->id
);
238 // Don't recurse down the tree for items that are not on this page
244 return array($this->paged
, $itemiter);
248 * Should be overriden to return an array of records of list items.
250 public abstract function get_records();
253 * display list of page numbers for navigation
255 public function display_page_numbers() {
257 $topcount = count($this->items
);
258 $this->pagecount
= (integer) ceil(($topcount +
$this->offset
)/ QUESTION_PAGE_LENGTH
);
259 if (!empty($this->page
) && ($this->paged
)) {
260 $html = "<div class=\"paging\">".get_string('page').":\n";
261 foreach (range(1,$this->pagecount
) as $currentpage) {
262 if ($this->page
== $currentpage) {
263 $html .= " $currentpage \n";
266 $html .= "<a href=\"".$this->pageurl
->out(true, array($this->pageparamname
=> $currentpage))."\">";
267 $html .= " $currentpage </a>\n";
276 * Returns an array of ids of peers of an item.
278 * @param int itemid - if given, restrict records to those with this parent id.
279 * @return array peer ids
281 public function get_items_peers($itemid) {
282 $itemref = $this->find_item($itemid);
283 $peerids = $itemref->parentlist
->get_child_ids();
288 * Returns an array of ids of child items.
290 * @return array peer ids
292 public function get_child_ids() {
294 foreach ($this->items
as $child) {
295 $childids[] = $child->id
;
301 * Move a record up or down
303 * @param string $direction up / down
306 public function move_item_up_down($direction, $id) {
307 $peers = $this->get_items_peers($id);
308 $itemkey = array_search($id, $peers);
309 switch ($direction) {
311 if (isset($peers[$itemkey+
1])) {
312 $olditem = $peers[$itemkey+
1];
313 $peers[$itemkey+
1] = $id;
314 $peers[$itemkey] = $olditem;
316 print_error('listcantmoveup');
321 if (isset($peers[$itemkey-1])) {
322 $olditem = $peers[$itemkey-1];
323 $peers[$itemkey-1] = $id;
324 $peers[$itemkey] = $olditem;
326 print_error('listcantmovedown');
330 $this->reorder_peers($peers);
333 public function reorder_peers($peers) {
335 foreach ($peers as $key => $peer) {
336 $DB->set_field($this->table
, "sortorder", $key, array("id"=>$peer));
341 * @param integer $id an item index.
342 * @return object the item that used to be the parent of the item moved.
344 public function move_item_left($id) {
347 $item = $this->find_item($id);
348 if (!isset($item->parentlist
->parentitem
->parentlist
)) {
349 print_error('listcantmoveleft');
351 $newpeers = $this->get_items_peers($item->parentlist
->parentitem
->id
);
352 if (isset($item->parentlist
->parentitem
->parentlist
->parentitem
)) {
353 $newparent = $item->parentlist
->parentitem
->parentlist
->parentitem
->id
;
355 $newparent = 0; // top level item
357 $DB->set_field($this->table
, "parent", $newparent, array("id"=>$item->id
));
358 $oldparentkey = array_search($item->parentlist
->parentitem
->id
, $newpeers);
359 $neworder = array_merge(array_slice($newpeers, 0, $oldparentkey+
1), array($item->id
), array_slice($newpeers, $oldparentkey+
1));
360 $this->reorder_peers($neworder);
362 return $item->parentlist
->parentitem
;
366 * Make item with id $id the child of the peer that is just above it in the sort order.
370 public function move_item_right($id) {
373 $peers = $this->get_items_peers($id);
374 $itemkey = array_search($id, $peers);
375 if (!isset($peers[$itemkey-1])) {
376 print_error('listcantmoveright');
378 $DB->set_field($this->table
, "parent", $peers[$itemkey-1], array("id"=>$peers[$itemkey]));
379 $newparent = $this->find_item($peers[$itemkey-1]);
380 if (isset($newparent->children
)) {
381 $newpeers = $newparent->children
->get_child_ids();
384 $newpeers[] = $peers[$itemkey];
385 $this->reorder_peers($newpeers);
391 * process any actions.
393 * @param integer $left id of item to move left
394 * @param integer $right id of item to move right
395 * @param integer $moveup id of item to move up
396 * @param integer $movedown id of item to move down
399 public function process_actions($left, $right, $moveup, $movedown) {
400 //should this action be processed by this list object?
401 if (!(array_key_exists($left, $this->records
) ||
array_key_exists($right, $this->records
) ||
array_key_exists($moveup, $this->records
) ||
array_key_exists($movedown, $this->records
))) {
405 $oldparentitem = $this->move_item_left($left);
406 if ($this->item_is_last_on_page($oldparentitem->id
)) {
407 // Item has jumped onto the next page, change page when we redirect.
409 $this->pageurl
->params(array($this->pageparamname
=> $this->page
));
411 } else if (!empty($right)) {
412 $this->move_item_right($right);
413 if ($this->item_is_first_on_page($right)) {
414 // Item has jumped onto the previous page, change page when we redirect.
416 $this->pageurl
->params(array($this->pageparamname
=> $this->page
));
418 } else if (!empty($moveup)) {
419 $this->move_item_up_down('up', $moveup);
420 if ($this->item_is_first_on_page($moveup)) {
421 // Item has jumped onto the previous page, change page when we redirect.
423 $this->pageurl
->params(array($this->pageparamname
=> $this->page
));
425 } else if (!empty($movedown)) {
426 $this->move_item_up_down('down', $movedown);
427 if ($this->item_is_last_on_page($movedown)) {
428 // Item has jumped onto the next page, change page when we redirect.
430 $this->pageurl
->params(array($this->pageparamname
=> $this->page
));
436 redirect($this->pageurl
);
440 * @param integer $itemid an item id.
441 * @return boolean Is the item with the given id the first top-level item on
444 public function item_is_first_on_page($itemid) {
445 return $this->page
&& isset($this->items
[$this->firstitem
]) &&
446 $itemid == $this->items
[$this->firstitem
]->id
;
450 * @param integer $itemid an item id.
451 * @return boolean Is the item with the given id the last top-level item on
454 public function item_is_last_on_page($itemid) {
455 return $this->page
&& isset($this->items
[$this->lastitem
]) &&
456 $itemid == $this->items
[$this->lastitem
]->id
;
461 * @package moodlecore
462 * @copyright Jamie Pratt
463 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
465 abstract class list_item
{
466 /** @var integer id of record, used if list is editable. */
469 /** @var string name of this item, used if list is editable. */
472 /** @var mixed The object or string representing this item. */
474 public $fieldnamesname = 'name';
477 public $icons = array();
479 /** @var moodle_list */
482 /** @var moodle_list Set if there are any children of this listitem. */
487 * @param mixed $item fragment of html for list item or record
488 * @param object $parent reference to parent of this item
489 * @param string $attributes attributes for li tag
490 * @param boolean $display whether this item is displayed. Some items may be loaded so we have a complete
491 * structure in memory to work with for actions but are not displayed.
494 public function __construct($item, $parent, $attributes = '', $display = true) {
496 if (is_object($this->item
)) {
497 $this->id
= $this->item
->id
;
498 $this->name
= $this->item
->{$this->fieldnamesname
};
500 $this->set_parent($parent);
501 $this->attributes
= $attributes;
502 $parentlistclass = get_class($parent);
503 $this->children
= new $parentlistclass($parent->type
, $parent->attributes
, $parent->editable
, $parent->pageurl
, 0);
504 $this->children
->set_parent($this);
505 $this->display
= $display;
509 * Output the html just for this item. Called by to_html which adds html for children.
512 public function item_html($extraargs = array()) {
513 if (is_string($this->item
)) {
515 } elseif (is_object($this->item
)) {
516 //for debug purposes only. You should create a sub class to
517 //properly handle the record
518 $html = join(', ', (array)$this->item
);
526 * @param integer $indent
527 * @param array $extraargs any extra data that is needed to print the list item
528 * may be used by sub class.
529 * @return string html
531 public function to_html($indent = 0, $extraargs = array()) {
532 if (!$this->display
) {
535 $tabs = str_repeat("\t", $indent);
537 if (isset($this->children
)) {
538 $childrenhtml = $this->children
->to_html($indent+
1, $extraargs);
542 return $this->item_html($extraargs).' '.(join($this->icons
, '')).(($childrenhtml !='')?
("\n".$childrenhtml):'');
545 public function set_icon_html($first, $last, $lastitem) {
547 $strmoveup = get_string('moveup');
548 $strmovedown = get_string('movedown');
549 $strmoveleft = get_string('maketoplevelitem', 'question');
551 if (right_to_left()) { // Exchange arrows on RTL
552 $rightarrow = 'left';
553 $leftarrow = 'right';
555 $rightarrow = 'right';
559 if (isset($this->parentlist
->parentitem
)) {
560 $parentitem = $this->parentlist
->parentitem
;
561 if (isset($parentitem->parentlist
->parentitem
)) {
562 $action = get_string('makechildof', 'question', $parentitem->parentlist
->parentitem
->name
);
564 $action = $strmoveleft;
566 $url = new moodle_url($this->parentlist
->pageurl
, (array('sesskey'=>sesskey(), 'left'=>$this->id
)));
567 $this->icons
['left'] = $this->image_icon($action, $url, $leftarrow);
569 $this->icons
['left'] = $this->image_spacer();
573 $url = new moodle_url($this->parentlist
->pageurl
, (array('sesskey'=>sesskey(), 'moveup'=>$this->id
)));
574 $this->icons
['up'] = $this->image_icon($strmoveup, $url, 'up');
576 $this->icons
['up'] = $this->image_spacer();
580 $url = new moodle_url($this->parentlist
->pageurl
, (array('sesskey'=>sesskey(), 'movedown'=>$this->id
)));
581 $this->icons
['down'] = $this->image_icon($strmovedown, $url, 'down');
583 $this->icons
['down'] = $this->image_spacer();
586 if (!empty($lastitem)) {
587 $makechildof = get_string('makechildof', 'question', $lastitem->name
);
588 $url = new moodle_url($this->parentlist
->pageurl
, (array('sesskey'=>sesskey(), 'right'=>$this->id
)));
589 $this->icons
['right'] = $this->image_icon($makechildof, $url, $rightarrow);
591 $this->icons
['right'] = $this->image_spacer();
595 public function image_icon($action, $url, $icon) {
597 return '<a title="' . s($action) .'" href="'.$url.'">
598 <img src="' . $OUTPUT->pix_url('t/'.$icon) . '" class="iconsmall" alt="' . s($action). '" /></a> ';
601 public function image_spacer() {
603 return '<img src="' . $OUTPUT->pix_url('spacer') . '" class="iconsmall" alt="" />';
607 * Recurse down tree creating list_items, called from moodle_list::list_from_records
609 * @param array $records
610 * @param array $children
611 * @param integer $thisrecordid
613 public function create_children(&$records, &$children, $thisrecordid) {
614 //keys where value is $thisrecordid
615 $thischildren = array_keys($children, $thisrecordid);
616 foreach ($thischildren as $child) {
617 $thisclass = get_class($this);
618 $newlistitem = new $thisclass($records[$child], $this->children
, $this->attributes
);
619 $this->children
->add_item($newlistitem);
620 $newlistitem->create_children($records, $children, $records[$child]->id
);
624 public function set_parent($parent) {
625 $this->parentlist
= $parent;