Merge branch 'wip-mdl-31405-new' of git://github.com/rajeshtaneja/moodle
[moodle.git] / lib / listlib.php
blob9cc815b11079faf0146ef02e6bce7f423425b52d
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 * Move a record up or down
303 * @param string $direction up / down
304 * @param integer $id
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) {
310 case 'down' :
311 if (isset($peers[$itemkey+1])) {
312 $olditem = $peers[$itemkey+1];
313 $peers[$itemkey+1] = $id;
314 $peers[$itemkey] = $olditem;
315 } else {
316 print_error('listcantmoveup');
318 break;
320 case 'up' :
321 if (isset($peers[$itemkey-1])) {
322 $olditem = $peers[$itemkey-1];
323 $peers[$itemkey-1] = $id;
324 $peers[$itemkey] = $olditem;
325 } else {
326 print_error('listcantmovedown');
328 break;
330 $this->reorder_peers($peers);
333 public function reorder_peers($peers) {
334 global $DB;
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) {
345 global $DB;
347 $item = $this->find_item($id);
348 if (!isset($item->parentlist->parentitem->parentlist)) {
349 print_error('listcantmoveleft');
350 } else {
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;
354 } else {
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.
368 * @param integer $id
370 public function move_item_right($id) {
371 global $DB;
373 $peers = $this->get_items_peers($id);
374 $itemkey = array_search($id, $peers);
375 if (!isset($peers[$itemkey-1])) {
376 print_error('listcantmoveright');
377 } else {
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();
383 if ($newpeers) {
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
397 * @return unknown
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))) {
402 return false;
404 if (!empty($left)) {
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.
408 $this->page ++;
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.
415 $this->page --;
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.
422 $this->page --;
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.
429 $this->page ++;
430 $this->pageurl->params(array($this->pageparamname => $this->page));
432 } else {
433 return false;
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
442 * the current page?
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
452 * the current page?
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. */
467 public $id;
469 /** @var string name of this item, used if list is editable. */
470 public $name;
472 /** @var mixed The object or string representing this item. */
473 public $item;
474 public $fieldnamesname = 'name';
475 public $attributes;
476 public $display;
477 public $icons = array();
479 /** @var moodle_list */
480 public $parentlist;
482 /** @var moodle_list Set if there are any children of this listitem. */
483 public $children;
486 * Constructor
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.
492 * @return list_item
494 public function __construct($item, $parent, $attributes = '', $display = true) {
495 $this->item = $item;
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)) {
514 $html = $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);
520 return $html;
524 * Returns html
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) {
533 return '';
535 $tabs = str_repeat("\t", $indent);
537 if (isset($this->children)) {
538 $childrenhtml = $this->children->to_html($indent+1, $extraargs);
539 } else {
540 $childrenhtml = '';
542 return $this->item_html($extraargs).'&nbsp;'.(join($this->icons, '')).(($childrenhtml !='')?("\n".$childrenhtml):'');
545 public function set_icon_html($first, $last, $lastitem) {
546 global $CFG;
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';
554 } else {
555 $rightarrow = 'right';
556 $leftarrow = 'left';
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);
563 } else {
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);
568 } else {
569 $this->icons['left'] = $this->image_spacer();
572 if (!$first) {
573 $url = new moodle_url($this->parentlist->pageurl, (array('sesskey'=>sesskey(), 'moveup'=>$this->id)));
574 $this->icons['up'] = $this->image_icon($strmoveup, $url, 'up');
575 } else {
576 $this->icons['up'] = $this->image_spacer();
579 if (!$last) {
580 $url = new moodle_url($this->parentlist->pageurl, (array('sesskey'=>sesskey(), 'movedown'=>$this->id)));
581 $this->icons['down'] = $this->image_icon($strmovedown, $url, 'down');
582 } else {
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);
590 } else {
591 $this->icons['right'] = $this->image_spacer();
595 public function image_icon($action, $url, $icon) {
596 global $OUTPUT;
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() {
602 global $OUTPUT;
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;