MDL-19976 Changing redirect($url->out()) to redirect($url). NEVER, NEVER use redirect...
[moodle.git] / lib / listlib.php
CommitLineData
ce02a9bf 1<?php
2
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.
14//
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/>.
dac786f3 17
18/**
19 * Classes for displaying and editing a nested list of items.
20 *
21 * Handles functionality for :
22 *
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.
27 *
dac786f3 28 * @package moodlecore
ce02a9bf 29 * @copyright Jamie Pratt
30 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
dac786f3 31 */
32
004ff192 33/**
34 * Clues to reading this code:
35 *
36 * The functions that move things around the tree structure just update the
37 * database - they don't update the in-memory structure, instead they trigger a
38 * page reload so everything is rebuilt from scratch.
ce02a9bf 39 *
40 * @package moodlecore
41 * @copyright Jamie Pratt
42 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
004ff192 43 */
44class moodle_list {
dac786f3 45 var $attributes;
46 var $listitemclassname = 'list_item';
47 /**
48 * An array of $listitemclassname objects.
dac786f3 49 * @var array
50 */
51 var $items = array();
52 /**
53 * ol / ul
dac786f3 54 * @var string
55 */
56 var $type;
57 /**
dac786f3 58 * @var list_item or derived class
59 */
850e85b7 60 var $parentitem = null;
dac786f3 61 var $table;
62 var $fieldnamesparent = 'parent';
dac786f3 63 /**
64 * Records from db, only used in top level list.
dac786f3 65 * @var array
66 */
67 var $records = array();
68
69 var $editable;
70
71 /**
72 * Key is child id, value is parent.
dac786f3 73 * @var array
74 */
75 var $childparent;
76
77//------------------------------------------------------
78//vars used for pagination.
79 var $page = 0;// 0 means no pagination
80 var $firstitem = 1;
81 var $lastitem = 999999;
dac786f3 82 var $pagecount;
b0bc5219 83 var $paged = false;
84 var $offset = 0;
dac786f3 85//------------------------------------------------------
86 var $pageurl;
81be5cde 87 var $pageparamname;
dac786f3 88
dac786f3 89 /**
90 * Constructor function
91 *
92 * @param string $type
93 * @param string $attributes
94 * @param boolean $editable
20c55233 95 * @param moodle_url $pageurl url for this page
b0bc5219 96 * @param integer $page if 0 no pagination. (These three params only used in top level list.)
97 * @param string $pageparamname name of url param that is used for passing page no
98 * @param integer $itemsperpage no of top level items.
dac786f3 99 * @return moodle_list
100 */
004ff192 101 function moodle_list($type='ul', $attributes='', $editable = false, $pageurl=null, $page = 0, $pageparamname = 'page', $itemsperpage = 20) {
dac786f3 102 $this->editable = $editable;
103 $this->attributes = $attributes;
104 $this->type = $type;
105 $this->page = $page;
81be5cde 106 $this->pageparamname = $pageparamname;
b0bc5219 107 $this->itemsperpage = $itemsperpage;
004ff192 108 if ($pageurl === null) {
81be5cde 109 $this->pageurl = new moodle_url();
986effb6 110 $this->pageurl->params(array($this->pageparamname => $this->page));
81be5cde 111 } else {
112 $this->pageurl = $pageurl;
dac786f3 113 }
dac786f3 114 }
115
116 /**
117 * Returns html string.
118 *
119 * @param integer $indent depth of indentation.
120 */
004ff192 121 function to_html($indent=0, $extraargs=array()) {
122 if (count($this->items)) {
dac786f3 123 $tabs = str_repeat("\t", $indent);
dac786f3 124 $first = true;
125 $itemiter = 1;
126 $lastitem = '';
b0bc5219 127 $html = '';
dac786f3 128
004ff192 129 foreach ($this->items as $item) {
dac786f3 130 $last = (count($this->items) == $itemiter);
004ff192 131 if ($this->editable) {
b0bc5219 132 $item->set_icon_html($first, $last, $lastitem);
20c55233 133 }
004ff192 134 if ($itemhtml = $item->to_html($indent+1, $extraargs)) {
dac786f3 135 $html .= "$tabs\t<li".((!empty($item->attributes))?(' '.$item->attributes):'').">";
b0bc5219 136 $html .= $itemhtml;
dac786f3 137 $html .= "</li>\n";
138 }
139 $first = false;
140 $lastitem = $item;
141 $itemiter++;
142 }
dac786f3 143 } else {
144 $html = '';
145 }
004ff192 146 if ($html) { //if there are list items to display then wrap them in ul / ol tag.
b0bc5219 147 $tabs = str_repeat("\t", $indent);
148 $html = $tabs.'<'.$this->type.((!empty($this->attributes))?(' '.$this->attributes):'').">\n".$html;
149 $html .= $tabs."</".$this->type.">\n";
150 } else {
151 $html ='';
152 }
dac786f3 153 return $html;
154 }
155
156 /**
157 * Recurse down the tree and find an item by it's id.
158 *
159 * @param integer $id
b0bc5219 160 * @param boolean $suppresserror error if not item found?
dac786f3 161 * @return list_item *copy* or null if item is not found
162 */
004ff192 163 function find_item($id, $suppresserror = false) {
164 if (isset($this->items)) {
165 foreach ($this->items as $key => $child) {
166 if ($child->id == $id) {
dac786f3 167 return $this->items[$key];
168 }
169 }
004ff192 170 foreach (array_keys($this->items) as $key) {
dac786f3 171 $thischild =& $this->items[$key];
172 $ref = $thischild->children->find_item($id, true);//error always reported at top level
004ff192 173 if ($ref !== null) {
dac786f3 174 return $ref;
175 }
176 }
177 }
178
004ff192 179 if (!$suppresserror) {
dac786f3 180 print_error('listnoitem');
181 }
182 return null;
183 }
184
004ff192 185 function add_item(&$item) {
dac786f3 186 $this->items[] =& $item;
187 }
188
004ff192 189 function set_parent(&$parent) {
dac786f3 190 $this->parentitem =& $parent;
191 }
20c55233 192
dac786f3 193 /**
194 * Produces a hierarchical tree of list items from a flat array of records.
195 * 'parent' field is expected to point to a parent record.
196 * records are already sorted.
197 * If the parent field doesn't point to another record in the array then this is
198 * a top level list
20c55233 199 *
b0bc5219 200 * @param integer $offset how many list toplevel items are there in lists before this one
004ff192 201 * @return array(boolean, integer) whether there is more than one page, $offset + how many toplevel items where there in this list.
20c55233 202 *
dac786f3 203 */
004ff192 204 function list_from_records($paged = false, $offset = 0) {
b0bc5219 205 $this->paged = $paged;
206 $this->offset = $offset;
dac786f3 207 $this->get_records();
208 $records = $this->records;
209 $page = $this->page;
210 if (!empty($page)) {
4f8190a5 211 $this->firstitem = ($page - 1) * $this->itemsperpage;
b0bc5219 212 $this->lastitem = $this->firstitem + $this->itemsperpage - 1;
dac786f3 213 }
b0bc5219 214 $itemiter = $offset;
dac786f3 215 //make a simple array which is easier to search
216 $this->childparent = array();
004ff192 217 foreach ($records as $record) {
dac786f3 218 $this->childparent[$record->id] = $record->parent;
219 }
220 //create top level list items and they're responsible for creating their children
004ff192 221 foreach ($records as $record) {
222 if (!array_key_exists($record->parent, $this->childparent)) {
dac786f3 223 //if this record is not a child of another record then
224
b0bc5219 225 $inpage = ($itemiter >= $this->firstitem && $itemiter <= $this->lastitem);
dac786f3 226 //make list item for top level for all items
227 //we need the info about the top level items for reordering peers.
004ff192 228 if ($this->parentitem!==null) {
b0bc5219 229 $newattributes = $this->parentitem->attributes;
230 } else {
231 $newattributes = '';
20c55233 232
b0bc5219 233 }
004ff192 234 $this->items[$itemiter] =& new $this->listitemclassname($record, $this, $newattributes, $inpage);
235 if ($inpage) {
236 $this->items[$itemiter]->create_children($records, $this->childparent, $record->id);
b0bc5219 237 } else {
f6ea3132 238 //don't recurse down the tree for items that are not on this page
20c55233 239 $this->paged = true;
dac786f3 240 }
241 $itemiter++;
242 }
243 }
b0bc5219 244 return array($this->paged, $itemiter);
dac786f3 245 }
246
247 /**
248 * Should be overriden to return an array of records of list items.
249 *
250 */
251 function get_records() {
252 }
253
254 /**
255 * display list of page numbers for navigation
256 */
257 function display_page_numbers() {
b0bc5219 258 $html = '';
259 $topcount = count($this->items);
260 $this->pagecount = (integer) ceil(($topcount + $this->offset)/ QUESTION_PAGE_LENGTH );
004ff192 261 if (!empty($this->page) && ($this->paged)) {
b0bc5219 262 $html = "<div class=\"paging\">".get_string('page').":\n";
dac786f3 263 foreach (range(1,$this->pagecount) as $currentpage) {
264 if ($this->page == $currentpage) {
b0bc5219 265 $html .= " $currentpage \n";
dac786f3 266 }
267 else {
d65cb30f 268 $html .= "<a href=\"".$this->pageurl->out(false, array($this->pageparamname => $currentpage))."\">";
b0bc5219 269 $html .= " $currentpage </a>\n";
dac786f3 270 }
271 }
b0bc5219 272 $html .= "</div>";
dac786f3 273 }
b0bc5219 274 return $html;
dac786f3 275 }
276
277 /**
278 * Returns an array of ids of peers of an item.
279 *
280 * @param int itemid - if given, restrict records to those with this parent id.
281 * @return array peer ids
282 */
283 function get_items_peers($itemid) {
284 $itemref = $this->find_item($itemid);
285 $peerids = $itemref->parentlist->get_child_ids();
286 return $peerids;
287 }
288
289 /**
290 * Returns an array of ids of child items.
291 *
292 * @return array peer ids
293 */
294 function get_child_ids() {
295 $childids = array();
004ff192 296 foreach ($this->items as $child) {
dac786f3 297 $childids[] = $child->id;
298 }
299 return $childids;
300 }
301
302 /**
303 * Move a record up or down
304 *
305 * @param string $direction up / down
306 * @param integer $id
307 */
308 function move_item_up_down($direction, $id) {
309 $peers = $this->get_items_peers($id);
310 $itemkey = array_search($id, $peers);
311 switch ($direction) {
312 case 'down' :
004ff192 313 if (isset($peers[$itemkey+1])) {
dac786f3 314 $olditem = $peers[$itemkey+1];
315 $peers[$itemkey+1] = $id;
316 $peers[$itemkey] = $olditem;
317 } else {
318 print_error('listcantmoveup');
dac786f3 319 }
320 break;
321
322 case 'up' :
004ff192 323 if (isset($peers[$itemkey-1])) {
dac786f3 324 $olditem = $peers[$itemkey-1];
325 $peers[$itemkey-1] = $id;
326 $peers[$itemkey] = $olditem;
327 } else {
328 print_error('listcantmovedown');
329 }
330 break;
331 }
332 $this->reorder_peers($peers);
333 }
d9cde0ed 334
004ff192 335 function reorder_peers($peers) {
336 global $DB;
dac786f3 337 foreach ($peers as $key => $peer) {
004ff192 338 if (!$DB->set_field($this->table, "sortorder", $key, array("id"=>$peer))) {
dac786f3 339 print_error('listupdatefail');
340 }
341 }
342 }
004ff192 343
344 /**
345 * @param integer $id an item index.
346 * @return object the item that used to be the parent of the item moved.
347 */
dac786f3 348 function move_item_left($id) {
d9cde0ed 349 global $DB;
350
dac786f3 351 $item = $this->find_item($id);
004ff192 352 if (!isset($item->parentlist->parentitem->parentlist)) {
dac786f3 353 print_error('listcantmoveleft');
354 } else {
355 $newpeers = $this->get_items_peers($item->parentlist->parentitem->id);
004ff192 356 if (isset($item->parentlist->parentitem->parentlist->parentitem)) {
dac786f3 357 $newparent = $item->parentlist->parentitem->parentlist->parentitem->id;
358 } else {
359 $newparent = 0; // top level item
360 }
d9cde0ed 361 if (!$DB->set_field($this->table, "parent", $newparent, array("id"=>$item->id))) {
dac786f3 362 print_error('listupdatefail');
363 } else {
364 $oldparentkey = array_search($item->parentlist->parentitem->id, $newpeers);
365 $neworder = array_merge(array_slice($newpeers, 0, $oldparentkey+1), array($item->id), array_slice($newpeers, $oldparentkey+1));
366 $this->reorder_peers($neworder);
367 }
368 }
004ff192 369 return $item->parentlist->parentitem;
dac786f3 370 }
004ff192 371
dac786f3 372 /**
373 * Make item with id $id the child of the peer that is just above it in the sort order.
374 *
375 * @param integer $id
376 */
377 function move_item_right($id) {
d9cde0ed 378 global $DB;
379
dac786f3 380 $peers = $this->get_items_peers($id);
381 $itemkey = array_search($id, $peers);
004ff192 382 if (!isset($peers[$itemkey-1])) {
dac786f3 383 print_error('listcantmoveright');
384 } else {
d9cde0ed 385 if (!$DB->set_field($this->table, "parent", $peers[$itemkey-1], array("id"=>$peers[$itemkey]))) {
dac786f3 386 print_error('listupdatefail');
387 } else {
388 $newparent = $this->find_item($peers[$itemkey-1]);
004ff192 389 if (isset($newparent->children)) {
dac786f3 390 $newpeers = $newparent->children->get_child_ids();
391 }
004ff192 392 if ($newpeers) {
dac786f3 393 $newpeers[] = $peers[$itemkey];
394 $this->reorder_peers($newpeers);
395 }
396 }
397 }
398 }
399
400 /**
401 * process any actions.
402 *
403 * @param integer $left id of item to move left
404 * @param integer $right id of item to move right
405 * @param integer $moveup id of item to move up
406 * @param integer $movedown id of item to move down
407 * @return unknown
408 */
004ff192 409 function process_actions($left, $right, $moveup, $movedown) {
850e85b7 410 //should this action be processed by this list object?
004ff192 411 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))) {
850e85b7 412 return false;
413 }
dac786f3 414 if (!empty($left)) {
004ff192 415 $oldparentitem = $this->move_item_left($left);
416 if ($this->item_is_last_on_page($oldparentitem->id)) {
417 // Item has jumped onto the next page, change page when we redirect.
418 $this->page ++;
419 $this->pageurl->params(array($this->pageparamname => $this->page));
420 }
dac786f3 421 } else if (!empty($right)) {
422 $this->move_item_right($right);
004ff192 423 if ($this->item_is_first_on_page($right)) {
424 // Item has jumped onto the previous page, change page when we redirect.
425 $this->page --;
426 $this->pageurl->params(array($this->pageparamname => $this->page));
427 }
dac786f3 428 } else if (!empty($moveup)) {
429 $this->move_item_up_down('up', $moveup);
004ff192 430 if ($this->item_is_first_on_page($moveup)) {
431 // Item has jumped onto the previous page, change page when we redirect.
dac786f3 432 $this->page --;
81be5cde 433 $this->pageurl->params(array($this->pageparamname => $this->page));
dac786f3 434 }
435 } else if (!empty($movedown)) {
436 $this->move_item_up_down('down', $movedown);
004ff192 437 if ($this->item_is_last_on_page($movedown)) {
438 // Item has jumped onto the next page, change page when we redirect.
dac786f3 439 $this->page ++;
81be5cde 440 $this->pageurl->params(array($this->pageparamname => $this->page));
dac786f3 441 }
442 } else {
443 return false;
444 }
445
e42f153c 446 redirect($this->pageurl);
dac786f3 447 }
004ff192 448
449 /**
450 * @param integer $itemid an item id.
451 * @return boolean Is the item with the given id the first top-level item on
452 * the current page?
453 */
454 function item_is_first_on_page($itemid) {
455 return $this->page && isset($this->items[$this->firstitem]) &&
456 $itemid == $this->items[$this->firstitem]->id;
457 }
458
459 /**
460 * @param integer $itemid an item id.
461 * @return boolean Is the item with the given id the last top-level item on
462 * the current page?
463 */
464 function item_is_last_on_page($itemid) {
465 return $this->page && isset($this->items[$this->lastitem]) &&
466 $itemid == $this->items[$this->lastitem]->id;
467 }
dac786f3 468}
469
ce02a9bf 470/**
471 * @package moodlecore
472 * @copyright Jamie Pratt
473 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
474 */
d9cde0ed 475class list_item {
dac786f3 476 /**
477 * id of record, used if list is editable
dac786f3 478 * @var integer
479 */
480 var $id;
481 /**
482 * name of this item, used if list is editable
dac786f3 483 * @var string
484 */
485 var $name;
486 /**
487 * The object or string representing this item.
dac786f3 488 * @var mixed
489 */
490 var $item;
491 var $fieldnamesname = 'name';
492 var $attributes;
b0bc5219 493 var $display;
850e85b7 494 var $icons = array();
dac786f3 495 /**
dac786f3 496 * @var moodle_list
497 */
498 var $parentlist;
499 /**
500 * Set if there are any children of this listitem.
dac786f3 501 * @var moodle_list
502 */
503 var $children;
004ff192 504
dac786f3 505 /**
506 * Constructor
dac786f3 507 * @param mixed $item fragment of html for list item or record
b0bc5219 508 * @param object &$parent reference to parent of this item
dac786f3 509 * @param string $attributes attributes for li tag
b0bc5219 510 * @param boolean $display whether this item is displayed. Some items may be loaded so we have a complete
511 * structure in memory to work with for actions but are not displayed.
dac786f3 512 * @return list_item
513 */
004ff192 514 function list_item($item, &$parent, $attributes='', $display = true) {
dac786f3 515 $this->item = $item;
516 if (is_object($this->item)) {
517 $this->id = $this->item->id;
518 $this->name = $this->item->{$this->fieldnamesname};
519 }
520 $this->set_parent($parent);
521 $this->attributes = $attributes;
522 $parentlistclass = get_class($parent);
b0bc5219 523 $this->children =& new $parentlistclass($parent->type, $parent->attributes, $parent->editable, $parent->pageurl, 0);
dac786f3 524 $this->children->set_parent($this);
b0bc5219 525 $this->display = $display;
dac786f3 526 }
004ff192 527
dac786f3 528 /**
529 * Output the html just for this item. Called by to_html which adds html for children.
530 *
531 */
004ff192 532 function item_html($extraargs = array()) {
533 if (is_string($this->item)) {
dac786f3 534 $html = $this->item;
535 } elseif (is_object($this->item)) {
536 //for debug purposes only. You should create a sub class to
537 //properly handle the record
538 $html = join(', ', (array)$this->item);
539 }
540 return $html;
541 }
004ff192 542
dac786f3 543 /**
544 * Returns html
545 *
546 * @param integer $indent
547 * @param array $extraargs any extra data that is needed to print the list item
548 * may be used by sub class.
549 * @return string html
550 */
004ff192 551 function to_html($indent=0, $extraargs = array()) {
552 if (!$this->display) {
b0bc5219 553 return '';
554 }
dac786f3 555 $tabs = str_repeat("\t", $indent);
556
004ff192 557 if (isset($this->children)) {
dac786f3 558 $childrenhtml = $this->children->to_html($indent+1, $extraargs);
559 } else {
560 $childrenhtml = '';
561 }
850e85b7 562 return $this->item_html($extraargs).'&nbsp;'.(join($this->icons, '')).(($childrenhtml !='')?("\n".$childrenhtml):'');
dac786f3 563 }
564
004ff192 565 function set_icon_html($first, $last, &$lastitem) {
dac786f3 566 global $CFG;
567 $strmoveup = get_string('moveup');
568 $strmovedown = get_string('movedown');
850e85b7 569 $strmoveleft = get_string('maketoplevelitem', 'question');
20c55233 570
dac786f3 571 if (isset($this->parentlist->parentitem)) {
572 $parentitem =& $this->parentlist->parentitem;
004ff192 573 if (isset($parentitem->parentlist->parentitem)) {
dac786f3 574 $action = get_string('makechildof', 'question', $parentitem->parentlist->parentitem->name);
575 } else {
850e85b7 576 $action = $strmoveleft;
dac786f3 577 }
20c55233 578 $this->icons['left'] = $this->image_icon($action, $this->parentlist->pageurl->out_action(array('left'=>$this->id)), 'left');
dac786f3 579 } else {
20c55233 580 $this->icons['left'] = $this->image_spacer();
dac786f3 581 }
582
583 if (!$first) {
20c55233 584 $this->icons['up'] = $this->image_icon($strmoveup, $this->parentlist->pageurl->out_action(array('moveup'=>$this->id)), 'up');
dac786f3 585 } else {
20c55233 586 $this->icons['up'] = $this->image_spacer();
dac786f3 587 }
588
589 if (!$last) {
20c55233 590 $this->icons['down'] = $this->image_icon($strmovedown, $this->parentlist->pageurl->out_action(array('movedown'=>$this->id)), 'down');
dac786f3 591 } else {
20c55233 592 $this->icons['down'] = $this->image_spacer();
dac786f3 593 }
594
595 if (!empty($lastitem)) {
596 $makechildof = get_string('makechildof', 'question', $lastitem->name);
20c55233 597 $this->icons['right'] = $this->image_icon($makechildof, $this->parentlist->pageurl->out_action(array('right'=>$this->id)), 'right');
dac786f3 598 } else {
20c55233 599 $this->icons['right'] = $this->image_spacer();
dac786f3 600 }
850e85b7 601 }
004ff192 602
603 function image_icon($action, $url, $icon) {
a28c9253 604 global $OUTPUT;
b0bc5219 605 return '<a title="' . $action .'" href="'.$url.'">
a28c9253 606 <img src="' . $OUTPUT->old_icon_url('t/'.$icon) . '" class="iconsmall" alt="' . $action. '" /></a> ';
20c55233 607 }
004ff192 608
609 function image_spacer() {
a28c9253 610 global $OUTPUT;
611 return '<img src="' . $OUTPUT->old_icon_url('spacer') . '" class="iconsmall" alt="" />';
dac786f3 612 }
004ff192 613
dac786f3 614 /**
615 * Recurse down tree creating list_items, called from moodle_list::list_from_records
616 *
617 * @param array $records
618 * @param array $children
619 * @param integer $thisrecordid
620 */
004ff192 621 function create_children(&$records, &$children, $thisrecordid) {
dac786f3 622 //keys where value is $thisrecordid
623 $thischildren = array_keys($children, $thisrecordid);
004ff192 624 if (count($thischildren)) {
625 foreach ($thischildren as $child) {
dac786f3 626 $thisclass = get_class($this);
627 $newlistitem =& new $thisclass($records[$child], $this->children, $this->attributes);
004ff192 628 $this->children->add_item($newlistitem);
dac786f3 629 $newlistitem->create_children($records, $children, $records[$child]->id);
630 }
631 }
632 }
004ff192 633
634 function set_parent(&$parent) {
dac786f3 635 $this->parentlist =& $parent;
dac786f3 636 }
dac786f3 637}
b7064779 638?>