MDL-67585 core_course: add content_item_service class
[moodle.git] / lib / listlib.php
blob67520aebbcd630b162f05ff649ae7edb20c579aa
1 <?php
3 // This file is part of Moodle - http://moodle.org/
4 //
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.
9 //
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/>.
18 /**
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.
28 * @package core
29 * @subpackage lib
30 * @copyright Jamie Pratt
31 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
34 defined('MOODLE_INTERNAL') || die();
36 /**
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.
43 * @package moodlecore
44 * @copyright Jamie Pratt
45 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
47 abstract class moodle_list {
48 public $attributes;
49 public $listitemclassname = 'list_item';
51 /** @var array of $listitemclassname objects. */
52 public $items = array();
54 /** @var string 'ol' or 'ul'. */
55 public $type;
57 /** @var list_item or derived class. */
58 public $parentitem = null;
59 public $table;
60 public $fieldnamesparent = 'parent';
62 /** @var array Records from db, only used in top level list. */
63 public $records = array();
65 public $editable;
67 /** @var array keys are child ids, values are parents. */
68 public $childparent;
70 //------------------------------------------------------
71 //vars used for pagination.
72 public $page = 0; // 0 means no pagination
73 public $firstitem = 1;
74 public $lastitem = 999999;
75 public $pagecount;
76 public $paged = false;
77 public $offset = 0;
78 //------------------------------------------------------
79 public $pageurl;
80 public $pageparamname;
82 /**
83 * Constructor.
85 * @param string $type
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) {
94 global $PAGE;
96 $this->editable = $editable;
97 $this->attributes = $attributes;
98 $this->type = $type;
99 $this->page = $page;
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));
105 } else {
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);
118 $first = true;
119 $itemiter = 1;
120 $lastitem = '';
121 $html = '';
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):'').">";
130 $html .= $itemhtml;
131 $html .= "</li>\n";
133 $first = false;
134 $lastitem = $item;
135 $itemiter++;
137 } else {
138 $html = '';
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";
144 } else {
145 $html ='';
147 return $html;
151 * Recurse down the tree and find an item by it's id.
153 * @param integer $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
167 if ($ref !== null) {
168 return $ref;
173 if (!$suppresserror) {
174 print_error('listnoitem');
176 return null;
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
192 * a top level list
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;
203 $page = $this->page;
204 if (!empty($page)) {
205 $this->firstitem = ($page - 1) * $this->itemsperpage;
206 $this->lastitem = $this->firstitem + $this->itemsperpage - 1;
208 $itemiter = $offset;
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.
220 continue;
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;
229 } else {
230 $newattributes = '';
233 $this->items[$itemiter] = new $this->listitemclassname($record, $this, $newattributes, $inpage);
235 if ($inpage) {
236 $this->items[$itemiter]->create_children($records, $this->childparent, $record->id);
237 } else {
238 // Don't recurse down the tree for items that are not on this page
239 $this->paged = true;
242 $itemiter++;
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() {
256 $html = '';
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";
265 else {
266 $html .= "<a href=\"".$this->pageurl->out(true, array($this->pageparamname => $currentpage))."\">";
267 $html .= " $currentpage </a>\n";
270 $html .= "</div>";
272 return $html;
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();
284 return $peerids;
288 * Returns an array of ids of child items.
290 * @return array peer ids
292 public function get_child_ids() {
293 $childids = array();
294 foreach ($this->items as $child) {
295 $childids[] = $child->id;
297 return $childids;
301 * Returns the value to be used as the parent for the $item when it goes to the top level.
302 * Override if needed.
304 * @param list_item $item The item which its top level parent is going to be returned.
305 * @return int
307 public function get_top_level_parent_id($item) {
308 return 0; // Top level items have no parent.
312 * Move a record up or down
314 * @param string $direction up / down
315 * @param integer $id
317 public function move_item_up_down($direction, $id) {
318 $peers = $this->get_items_peers($id);
319 $itemkey = array_search($id, $peers);
320 switch ($direction) {
321 case 'down' :
322 if (isset($peers[$itemkey+1])) {
323 $olditem = $peers[$itemkey+1];
324 $peers[$itemkey+1] = $id;
325 $peers[$itemkey] = $olditem;
326 } else {
327 print_error('listcantmoveup');
329 break;
331 case 'up' :
332 if (isset($peers[$itemkey-1])) {
333 $olditem = $peers[$itemkey-1];
334 $peers[$itemkey-1] = $id;
335 $peers[$itemkey] = $olditem;
336 } else {
337 print_error('listcantmovedown');
339 break;
341 $this->reorder_peers($peers);
344 public function reorder_peers($peers) {
345 global $DB;
346 foreach ($peers as $key => $peer) {
347 $DB->set_field($this->table, "sortorder", $key, array("id"=>$peer));
352 * Moves the item one step up in the tree.
354 * @param int $id an item index.
355 * @return list_item the item that used to be the parent of the item moved.
357 public function move_item_left($id) {
358 global $DB;
360 $item = $this->find_item($id);
361 if (!isset($item->parentlist->parentitem->parentlist)) {
362 print_error('listcantmoveleft');
363 } else {
364 $newpeers = $this->get_items_peers($item->parentlist->parentitem->id);
365 if (isset($item->parentlist->parentitem->parentlist->parentitem)) {
366 $newparent = $item->parentlist->parentitem->parentlist->parentitem->id;
367 } else {
368 $newparent = $this->get_top_level_parent_id($item);
370 $DB->set_field($this->table, "parent", $newparent, array("id"=>$item->id));
371 $oldparentkey = array_search($item->parentlist->parentitem->id, $newpeers);
372 $neworder = array_merge(array_slice($newpeers, 0, $oldparentkey+1), array($item->id), array_slice($newpeers, $oldparentkey+1));
373 $this->reorder_peers($neworder);
375 return $item->parentlist->parentitem;
379 * Make item with id $id the child of the peer that is just above it in the sort order.
381 * @param integer $id
383 public function move_item_right($id) {
384 global $DB;
386 $peers = $this->get_items_peers($id);
387 $itemkey = array_search($id, $peers);
388 if (!isset($peers[$itemkey-1])) {
389 print_error('listcantmoveright');
390 } else {
391 $DB->set_field($this->table, "parent", $peers[$itemkey-1], array("id"=>$peers[$itemkey]));
392 $newparent = $this->find_item($peers[$itemkey-1]);
393 if (isset($newparent->children)) {
394 $newpeers = $newparent->children->get_child_ids();
396 if ($newpeers) {
397 $newpeers[] = $peers[$itemkey];
398 $this->reorder_peers($newpeers);
404 * process any actions.
406 * @param integer $left id of item to move left
407 * @param integer $right id of item to move right
408 * @param integer $moveup id of item to move up
409 * @param integer $movedown id of item to move down
410 * @return unknown
412 public function process_actions($left, $right, $moveup, $movedown) {
413 //should this action be processed by this list object?
414 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))) {
415 return false;
417 if (!empty($left)) {
418 $oldparentitem = $this->move_item_left($left);
419 if ($this->item_is_last_on_page($oldparentitem->id)) {
420 // Item has jumped onto the next page, change page when we redirect.
421 $this->page ++;
422 $this->pageurl->params(array($this->pageparamname => $this->page));
424 } else if (!empty($right)) {
425 $this->move_item_right($right);
426 if ($this->item_is_first_on_page($right)) {
427 // Item has jumped onto the previous page, change page when we redirect.
428 $this->page --;
429 $this->pageurl->params(array($this->pageparamname => $this->page));
431 } else if (!empty($moveup)) {
432 $this->move_item_up_down('up', $moveup);
433 if ($this->item_is_first_on_page($moveup)) {
434 // Item has jumped onto the previous page, change page when we redirect.
435 $this->page --;
436 $this->pageurl->params(array($this->pageparamname => $this->page));
438 } else if (!empty($movedown)) {
439 $this->move_item_up_down('down', $movedown);
440 if ($this->item_is_last_on_page($movedown)) {
441 // Item has jumped onto the next page, change page when we redirect.
442 $this->page ++;
443 $this->pageurl->params(array($this->pageparamname => $this->page));
445 } else {
446 return false;
449 redirect($this->pageurl);
453 * @param integer $itemid an item id.
454 * @return boolean Is the item with the given id the first top-level item on
455 * the current page?
457 public function item_is_first_on_page($itemid) {
458 return $this->page && isset($this->items[$this->firstitem]) &&
459 $itemid == $this->items[$this->firstitem]->id;
463 * @param integer $itemid an item id.
464 * @return boolean Is the item with the given id the last top-level item on
465 * the current page?
467 public function item_is_last_on_page($itemid) {
468 return $this->page && isset($this->items[$this->lastitem]) &&
469 $itemid == $this->items[$this->lastitem]->id;
474 * @package moodlecore
475 * @copyright Jamie Pratt
476 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
478 abstract class list_item {
479 /** @var integer id of record, used if list is editable. */
480 public $id;
482 /** @var string name of this item, used if list is editable. */
483 public $name;
485 /** @var mixed The object or string representing this item. */
486 public $item;
487 public $fieldnamesname = 'name';
488 public $attributes;
489 public $display;
490 public $icons = array();
492 /** @var moodle_list */
493 public $parentlist;
495 /** @var moodle_list Set if there are any children of this listitem. */
496 public $children;
499 * Constructor
500 * @param mixed $item fragment of html for list item or record
501 * @param object $parent reference to parent of this item
502 * @param string $attributes attributes for li tag
503 * @param boolean $display whether this item is displayed. Some items may be loaded so we have a complete
504 * structure in memory to work with for actions but are not displayed.
505 * @return list_item
507 public function __construct($item, $parent, $attributes = '', $display = true) {
508 $this->item = $item;
509 if (is_object($this->item)) {
510 $this->id = $this->item->id;
511 $this->name = $this->item->{$this->fieldnamesname};
513 $this->set_parent($parent);
514 $this->attributes = $attributes;
515 $parentlistclass = get_class($parent);
516 $this->children = new $parentlistclass($parent->type, $parent->attributes, $parent->editable, $parent->pageurl, 0);
517 $this->children->set_parent($this);
518 $this->display = $display;
522 * Output the html just for this item. Called by to_html which adds html for children.
525 public function item_html($extraargs = array()) {
526 if (is_string($this->item)) {
527 $html = $this->item;
528 } elseif (is_object($this->item)) {
529 //for debug purposes only. You should create a sub class to
530 //properly handle the record
531 $html = join(', ', (array)$this->item);
533 return $html;
537 * Returns html
539 * @param integer $indent
540 * @param array $extraargs any extra data that is needed to print the list item
541 * may be used by sub class.
542 * @return string html
544 public function to_html($indent = 0, $extraargs = array()) {
545 if (!$this->display) {
546 return '';
548 $tabs = str_repeat("\t", $indent);
550 if (isset($this->children)) {
551 $childrenhtml = $this->children->to_html($indent+1, $extraargs);
552 } else {
553 $childrenhtml = '';
555 return $this->item_html($extraargs).'&nbsp;'.(join('', $this->icons)).(($childrenhtml !='')?("\n".$childrenhtml):'');
558 public function set_icon_html($first, $last, $lastitem) {
559 global $CFG;
560 $strmoveup = get_string('moveup');
561 $strmovedown = get_string('movedown');
562 $strmoveleft = get_string('maketoplevelitem', 'question');
564 if (right_to_left()) { // Exchange arrows on RTL
565 $rightarrow = 'left';
566 $leftarrow = 'right';
567 } else {
568 $rightarrow = 'right';
569 $leftarrow = 'left';
572 if (isset($this->parentlist->parentitem)) {
573 $parentitem = $this->parentlist->parentitem;
574 if (isset($parentitem->parentlist->parentitem)) {
575 $action = get_string('makechildof', 'question', $parentitem->parentlist->parentitem->name);
576 } else {
577 $action = $strmoveleft;
579 $url = new moodle_url($this->parentlist->pageurl, (array('sesskey'=>sesskey(), 'left'=>$this->id)));
580 $this->icons['left'] = $this->image_icon($action, $url, $leftarrow);
581 } else {
582 $this->icons['left'] = $this->image_spacer();
585 if (!$first) {
586 $url = new moodle_url($this->parentlist->pageurl, (array('sesskey'=>sesskey(), 'moveup'=>$this->id)));
587 $this->icons['up'] = $this->image_icon($strmoveup, $url, 'up');
588 } else {
589 $this->icons['up'] = $this->image_spacer();
592 if (!$last) {
593 $url = new moodle_url($this->parentlist->pageurl, (array('sesskey'=>sesskey(), 'movedown'=>$this->id)));
594 $this->icons['down'] = $this->image_icon($strmovedown, $url, 'down');
595 } else {
596 $this->icons['down'] = $this->image_spacer();
599 if (!empty($lastitem)) {
600 $makechildof = get_string('makechildof', 'question', $lastitem->name);
601 $url = new moodle_url($this->parentlist->pageurl, (array('sesskey'=>sesskey(), 'right'=>$this->id)));
602 $this->icons['right'] = $this->image_icon($makechildof, $url, $rightarrow);
603 } else {
604 $this->icons['right'] = $this->image_spacer();
608 public function image_icon($action, $url, $icon) {
609 global $OUTPUT;
610 return '<a title="' . s($action) .'" href="'.$url.'">' .
611 $OUTPUT->pix_icon('t/' . $icon, $action) . '</a> ';
614 public function image_spacer() {
615 global $OUTPUT;
616 return $OUTPUT->spacer();
620 * Recurse down tree creating list_items, called from moodle_list::list_from_records
622 * @param array $records
623 * @param array $children
624 * @param integer $thisrecordid
626 public function create_children(&$records, &$children, $thisrecordid) {
627 //keys where value is $thisrecordid
628 $thischildren = array_keys($children, $thisrecordid);
629 foreach ($thischildren as $child) {
630 $thisclass = get_class($this);
631 $newlistitem = new $thisclass($records[$child], $this->children, $this->attributes);
632 $this->children->add_item($newlistitem);
633 $newlistitem->create_children($records, $children, $records[$child]->id);
637 public function set_parent($parent) {
638 $this->parentlist = $parent;