moodle_page: MDL-12212 clarify some comments
[moodle.git] / lib / blocklib.php
CommitLineData
dcb1bd3c 1<?php //$Id$
0f3fe4b6 2
e8c8cee9 3///////////////////////////////////////////////////////////////////////////
4// //
5// NOTICE OF COPYRIGHT //
6// //
7// Moodle - Modular Object-Oriented Dynamic Learning Environment //
8// http://moodle.org //
9// //
10// Copyright (C) 1999 onwards Martin Dougiamas http://dougiamas.com //
11// //
12// This program is free software; you can redistribute it and/or modify //
13// it under the terms of the GNU General Public License as published by //
14// the Free Software Foundation; either version 2 of the License, or //
15// (at your option) any later version. //
16// //
17// This program is distributed in the hope that it will be useful, //
18// but WITHOUT ANY WARRANTY; without even the implied warranty of //
19// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //
20// GNU General Public License for more details: //
21// //
22// http://www.gnu.org/copyleft/gpl.html //
23// //
24///////////////////////////////////////////////////////////////////////////
25
26/**
27 * This library includes all the necessary stuff to use blocks on pages in Moodle.
28 *
29 * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
30 * @package pages
31 */
0f3fe4b6 32
0f3fe4b6 33define('BLOCK_MOVE_LEFT', 0x01);
34define('BLOCK_MOVE_RIGHT', 0x02);
35define('BLOCK_MOVE_UP', 0x04);
36define('BLOCK_MOVE_DOWN', 0x08);
9b4b78fd 37define('BLOCK_CONFIGURE', 0x10);
0f3fe4b6 38
9b4b78fd 39define('BLOCK_POS_LEFT', 'l');
40define('BLOCK_POS_RIGHT', 'r');
0e9af917 41
ee6055eb 42define('BLOCKS_PINNED_TRUE',0);
43define('BLOCKS_PINNED_FALSE',1);
44define('BLOCKS_PINNED_BOTH',2);
45
f032aa7a 46require_once($CFG->libdir.'/pagelib.php');
61abc65b 47
0f3fe4b6 48//This function retrieves a method-defined property of a class WITHOUT instantiating an object
11306331 49function block_method_result($blockname, $method, $param = NULL) {
0f3fe4b6 50 if(!block_load_class($blockname)) {
51 return NULL;
52 }
11306331 53 return call_user_func(array('block_'.$blockname, $method), $param);
0f3fe4b6 54}
55
56//This function creates a new object of the specified block class
9b4b78fd 57function block_instance($blockname, $instance = NULL) {
0f3fe4b6 58 if(!block_load_class($blockname)) {
59 return false;
60 }
e89d741a 61 $classname = 'block_'.$blockname;
f032aa7a 62 $retval = new $classname;
9b4b78fd 63 if($instance !== NULL) {
1345403a 64 $retval->_load_instance($instance);
9b4b78fd 65 }
66 return $retval;
0f3fe4b6 67}
68
69//This function loads the necessary class files for a block
70//Whenever you want to load a block, use this first
71function block_load_class($blockname) {
72 global $CFG;
73
a9033ad5 74 if(empty($blockname)) {
c7a9e293 75 return false;
76 }
77
e89d741a 78 $classname = 'block_'.$blockname;
a9033ad5 79
80 if(class_exists($classname)) {
81 return true;
82 }
83
84 require_once($CFG->dirroot.'/blocks/moodleblock.class.php');
e9a20759 85 @include_once($CFG->dirroot.'/blocks/'.$blockname.'/block_'.$blockname.'.php'); // do not throw errors if block code not present
0f3fe4b6 86
0f3fe4b6 87 return class_exists($classname);
88}
89
c8e0b579 90// This function returns an array with the IDs of any blocks that you can add to your page.
91// Parameters are passed by reference for speed; they are not modified at all.
92function blocks_get_missing(&$page, &$pageblocks) {
f032aa7a 93
94 $missingblocks = array();
95 $allblocks = blocks_get_record();
d529807a 96 $pageformat = $page->pagetype;
f032aa7a 97
98 if(!empty($allblocks)) {
99 foreach($allblocks as $block) {
100 if($block->visible && (!blocks_find_block($block->id, $pageblocks) || $block->multiple)) {
101 // And if it's applicable for display in this format...
5bbbe0be 102 if(blocks_name_allowed_in_format($block->name, $pageformat)) {
8a47e075 103 // ...add it to the missing blocks
f032aa7a 104 $missingblocks[] = $block->id;
105 }
106 }
107 }
108 }
109 return $missingblocks;
110}
111
112function blocks_remove_inappropriate($page) {
113 $pageblocks = blocks_get_by_page($page);
114
115 if(empty($pageblocks)) {
116 return;
117 }
118
d529807a 119 if(($pageformat = $page->pagetype) == NULL) {
f032aa7a 120 return;
121 }
122
123 foreach($pageblocks as $position) {
124 foreach($position as $instance) {
125 $block = blocks_get_record($instance->blockid);
5bbbe0be 126 if(!blocks_name_allowed_in_format($block->name, $pageformat)) {
8a47e075 127 blocks_delete_instance($instance);
f032aa7a 128 }
129 }
130 }
131}
132
5bbbe0be 133function blocks_name_allowed_in_format($name, $pageformat) {
cd2bc3c9 134 $accept = NULL;
135 $maxdepth = -1;
136 $formats = block_method_result($name, 'applicable_formats');
137 if (!$formats) {
138 $formats = array();
139 }
140 foreach ($formats as $format => $allowed) {
141 $formatregex = '/^'.str_replace('*', '[^-]*', $format).'.*$/';
142 $depth = substr_count($format, '-');
143 if (preg_match($formatregex, $pageformat) && $depth > $maxdepth) {
144 $maxdepth = $depth;
145 $accept = $allowed;
5bbbe0be 146 }
147 }
cd2bc3c9 148 if ($accept === NULL) {
5bbbe0be 149 $accept = !empty($formats['all']);
150 }
151 return $accept;
152}
153
0d6b9d4f 154function blocks_delete_instance($instance,$pinned=false) {
58ff964f 155 global $DB;
f032aa7a 156
e9a20759 157 // Get the block object and call instance_delete() if possible
7fa944ca 158 if($record = blocks_get_record($instance->blockid)) {
159 if($obj = block_instance($record->name, $instance)) {
e9a20759 160 // Return value ignored
161 $obj->instance_delete();
162 }
b33dd23a 163 }
164
0d6b9d4f 165 if (!empty($pinned)) {
66b10689 166 $DB->delete_records('block_pinned_old', array('id'=>$instance->id));
0d6b9d4f 167 // And now, decrement the weight of all blocks after this one
66b10689 168 $sql = "UPDATE {block_pinned_old}
58ff964f 169 SET weight = weight - 1
170 WHERE pagetype = ? AND position = ? AND weight > ?";
171 $params = array($instance->pagetype, $instance->position, $instance->weight);
172 $DB->execute($sql, $params);
0d6b9d4f 173 } else {
174 // Now kill the db record;
66b10689 175 $DB->delete_records('block_instance_old', array('oldid'=>$instance->id));
19f5b2db 176 delete_context(CONTEXT_BLOCK, $instance->id);
0d6b9d4f 177 // And now, decrement the weight of all blocks after this one
66b10689 178 $sql = "UPDATE {block_instance_old}
58ff964f 179 SET weight = weight - 1
180 WHERE pagetype = ? AND pageid = ?
181 AND position = ? AND weight > ?";
182 $params = array($instance->pagetype, $instance->pageid, $instance->position, $instance->weight);
183 $DB->execute($sql, $params);
0d6b9d4f 184 }
2e477369 185 return true;
f032aa7a 186}
187
c8e0b579 188// Accepts an array of block instances and checks to see if any of them have content to display
189// (causing them to calculate their content in the process). Returns true or false. Parameter passed
190// by reference for speed; the array is actually not modified.
dffd4bb9 191function blocks_have_content(&$pageblocks, $position) {
0d6b9d4f 192
193 if (empty($pageblocks) || !is_array($pageblocks) || !array_key_exists($position,$pageblocks)) {
194 return false;
195 }
66c7e47b 196 // use a for() loop to get references to the array elements
197 // foreach() cannot fetch references in PHP v4.x
198 for ($n=0; $n<count($pageblocks[$position]);$n++) {
199 $instance = &$pageblocks[$position][$n];
6b726eb4 200 if (empty($instance->visible)) {
7933cc6b 201 continue;
202 }
3ef642d9 203 if(!$record = blocks_get_record($instance->blockid)) {
7933cc6b 204 continue;
205 }
3ef642d9 206 if(!$obj = block_instance($record->name, $instance)) {
9b4b78fd 207 continue;
208 }
3ef642d9 209 if(!$obj->is_empty()) {
afd1ec02 210 // cache rec and obj
66c7e47b 211 // for blocks_print_group()
b1a308be 212 $instance->rec = $record;
afd1ec02 213 $instance->obj = $obj;
3ef642d9 214 return true;
0f3fe4b6 215 }
216 }
9b4b78fd 217
0f3fe4b6 218 return false;
219}
220
c8e0b579 221// This function prints one group of blocks in a page
222// Parameters passed by reference for speed; they are not modified.
66492322 223function blocks_print_group(&$page, &$pageblocks, $position) {
6ad71d66 224 global $COURSE, $CFG, $USER;
66492322 225
6b726eb4 226 if (empty($pageblocks[$position])) {
227 $groupblocks = array();
b35fc182 228 $maxweight = 0;
6b726eb4 229 } else {
230 $groupblocks = $pageblocks[$position];
231 $maxweight = max(array_keys($groupblocks));
9b4b78fd 232 }
3cdc4597 233
6b726eb4 234
235 foreach ($groupblocks as $instance) {
4374ee2c 236 if (!empty($instance->pinned)) {
237 $maxweight--;
238 }
239 }
0f3fe4b6 240
f032aa7a 241 $isediting = $page->user_is_editing();
6b726eb4 242
243
244 foreach($groupblocks as $instance) {
245
afd1ec02 246
66c7e47b 247 // $instance may have ->rec and ->obj
248 // cached from when we walked $pageblocks
249 // in blocks_have_content()
250 if (empty($instance->rec)) {
6b726eb4 251 if (empty($instance->blockid)) {
252 continue; // Can't do anything
253 }
66c7e47b 254 $block = blocks_get_record($instance->blockid);
255 } else {
256 $block = $instance->rec;
257 }
f809df70 258
259 if (empty($block)) {
260 // Block doesn't exist! We should delete this instance!
261 continue;
262 }
263
6b726eb4 264 if (empty($block->visible)) {
9b4b78fd 265 // Disabled by the admin
266 continue;
267 }
afd1ec02 268
66c7e47b 269 if (empty($instance->obj)) {
270 if (!$obj = block_instance($block->name, $instance)) {
271 // Invalid block
272 continue;
273 }
274 } else {
275 $obj = $instance->obj;
ab0e4dd4 276 }
0f3fe4b6 277
d7f688d4 278 $editalways = false;
0d6b9d4f 279
6b726eb4 280
0d6b9d4f 281 if (($isediting && empty($instance->pinned)) || !empty($editalways)) {
9b4b78fd 282 $options = 0;
f032aa7a 283 // The block can be moved up if it's NOT the first one in its position. If it is, we look at the OR clause:
284 // the first block might still be able to move up if the page says so (i.e., it will change position)
285 $options |= BLOCK_MOVE_UP * ($instance->weight != 0 || ($page->blocks_move_position($instance, BLOCK_MOVE_UP) != $instance->position));
286 // Same thing for downward movement
287 $options |= BLOCK_MOVE_DOWN * ($instance->weight != $maxweight || ($page->blocks_move_position($instance, BLOCK_MOVE_DOWN) != $instance->position));
288 // For left and right movements, it's up to the page to tell us whether they are allowed
289 $options |= BLOCK_MOVE_RIGHT * ($page->blocks_move_position($instance, BLOCK_MOVE_RIGHT) != $instance->position);
290 $options |= BLOCK_MOVE_LEFT * ($page->blocks_move_position($instance, BLOCK_MOVE_LEFT ) != $instance->position);
291 // Finally, the block can be configured if the block class either allows multiple instances, or if it specifically
292 // allows instance configuration (multiple instances override that one). It doesn't have anything to do with what the
293 // administrator has allowed for this block in the site admin options.
294 $options |= BLOCK_CONFIGURE * ( $obj->instance_allow_multiple() || $obj->instance_allow_config() );
1345403a 295 $obj->_add_edit_controls($options);
9b4b78fd 296 }
0f3fe4b6 297
0a0bb380 298 if (!$instance->visible && empty($COURSE->javascriptportal)) {
299 if ($isediting) {
1345403a 300 $obj->_print_shadow();
0f3fe4b6 301 }
0a0bb380 302 } else {
4a1a14c9 303 global $COURSE;
d23157d8 304 if(!empty($COURSE->javascriptportal)) {
305 $COURSE->javascriptportal->currentblocksection = $position;
306 }
1345403a 307 $obj->_print_block();
9b4b78fd 308 }
d23157d8 309 if (!empty($COURSE->javascriptportal)
310 && (empty($instance->pinned) || !$instance->pinned)) {
afd1ec02 311 $COURSE->javascriptportal->block_add('inst'.$instance->id, !$instance->visible);
d23157d8 312 }
313 } // End foreach
314
282c1695 315 // Check if
316 // we are on the default position/side AND
317 // we're editing the page AND
318 // (
319 // we have the capability to manage blocks OR
320 // we are in myMoodle page AND have the capibility to manage myMoodle blocks
321 // )
6ad71d66 322
323 // for constant PAGE_MY_MOODLE
324 include_once($CFG->dirroot.'/my/pagelib.php');
afd1ec02 325
6ad71d66 326 $coursecontext = get_context_instance(CONTEXT_COURSE, $COURSE->id);
d529807a 327 $myownblogpage = (isset($page->filtertype) && isset($page->filterselect) && $page->pagetype=='blog-view' && $page->filtertype=='user' && $page->filterselect == $USER->id);
afd1ec02 328
6ad71d66 329 $managecourseblocks = has_capability('moodle/site:manageblocks', $coursecontext);
d529807a 330 $editmymoodle = $page->pagetype == PAGE_MY_MOODLE && has_capability('moodle/my:manageblocks', $coursecontext);
afd1ec02 331
ad52c04f 332 if ($page->blocks->get_default_position() == $position &&
0be6f678 333 $page->user_is_editing() &&
ee1efe0b 334 ($managecourseblocks || $editmymoodle || $myownblogpage || defined('ADMIN_STICKYBLOCKS'))) {
6ad71d66 335
66492322 336 blocks_print_adminblock($page, $pageblocks);
337 }
0f3fe4b6 338}
339
c8e0b579 340// This iterates over an array of blocks and calculates the preferred width
341// Parameter passed by reference for speed; it's not modified.
342function blocks_preferred_width(&$instances) {
0f3fe4b6 343 $width = 0;
344
9b4b78fd 345 if(empty($instances) || !is_array($instances)) {
0f3fe4b6 346 return 0;
347 }
ff6191b7 348
349 $blocks = blocks_get_record();
350
9b4b78fd 351 foreach($instances as $instance) {
352 if(!$instance->visible) {
fe78a3dc 353 continue;
0c9c6363 354 }
ff6191b7 355
f809df70 356 if (!array_key_exists($instance->blockid, $blocks)) {
357 // Block doesn't exist! We should delete this instance!
358 continue;
359 }
360
ff6191b7 361 if(!$blocks[$instance->blockid]->visible) {
9b687320 362 continue;
363 }
ff6191b7 364 $pref = block_method_result($blocks[$instance->blockid]->name, 'preferred_width');
9b4b78fd 365 if($pref === NULL) {
366 continue;
367 }
368 if($pref > $width) {
369 $width = $pref;
0f3fe4b6 370 }
371 }
372 return $width;
373}
374
9b4b78fd 375function blocks_get_record($blockid = NULL, $invalidate = false) {
58ff964f 376 global $DB;
377
9b4b78fd 378 static $cache = NULL;
0f3fe4b6 379
9b4b78fd 380 if($invalidate || empty($cache)) {
58ff964f 381 $cache = $DB->get_records('block');
9b4b78fd 382 }
0f3fe4b6 383
9b4b78fd 384 if($blockid === NULL) {
385 return $cache;
386 }
0f3fe4b6 387
9b4b78fd 388 return (isset($cache[$blockid])? $cache[$blockid] : false);
389}
390
391function blocks_find_block($blockid, $blocksarray) {
0d6b9d4f 392 if (empty($blocksarray)) {
393 return false;
394 }
9b4b78fd 395 foreach($blocksarray as $blockgroup) {
0d6b9d4f 396 if (empty($blockgroup)) {
397 continue;
398 }
9b4b78fd 399 foreach($blockgroup as $instance) {
400 if($instance->blockid == $blockid) {
401 return $instance;
402 }
403 }
404 }
405 return false;
406}
407
408function blocks_find_instance($instanceid, $blocksarray) {
409 foreach($blocksarray as $subarray) {
410 foreach($subarray as $instance) {
411 if($instance->id == $instanceid) {
412 return $instance;
413 }
414 }
415 }
416 return false;
417}
418
ec79d3e4 419// Simple entry point for anyone that wants to use blocks
ee6055eb 420function blocks_setup(&$PAGE,$pinned=BLOCKS_PINNED_FALSE) {
421 switch ($pinned) {
422 case BLOCKS_PINNED_TRUE:
423 $pageblocks = blocks_get_pinned($PAGE);
424 break;
425 case BLOCKS_PINNED_BOTH:
426 $pageblocks = blocks_get_by_page_pinned($PAGE);
427 break;
428 case BLOCKS_PINNED_FALSE:
429 default:
430 $pageblocks = blocks_get_by_page($PAGE);
431 break;
432 }
433 blocks_execute_url_action($PAGE, $pageblocks,($pinned==BLOCKS_PINNED_TRUE));
ec79d3e4 434 return $pageblocks;
435}
436
b1631fef 437function blocks_execute_action($page, &$pageblocks, $blockaction, $instanceorid, $pinned=false, $redirect=true) {
58ff964f 438 global $CFG, $USER, $DB;
9b4b78fd 439
a9c75a9c 440 if (is_int($instanceorid)) {
9b4b78fd 441 $blockid = $instanceorid;
a9c75a9c 442 } else if (is_object($instanceorid)) {
9b4b78fd 443 $instance = $instanceorid;
444 }
0f3fe4b6 445
446 switch($blockaction) {
9b4b78fd 447 case 'config':
9b4b78fd 448 $block = blocks_get_record($instance->blockid);
e82d6cac 449 // Hacky hacky tricky stuff to get the original human readable block title,
450 // even if the block has configured its title to be something else.
afd1ec02 451 // Create the object WITHOUT instance data.
e82d6cac 452 $blockobject = block_instance($block->name);
9b4b78fd 453 if ($blockobject === false) {
11306331 454 break;
455 }
afd1ec02 456
11306331 457 // First of all check to see if the block wants to be edited
458 if(!$blockobject->user_can_edit()) {
459 break;
9b4b78fd 460 }
11306331 461
e82d6cac 462 // Now get the title and AFTER that load up the instance
463 $blocktitle = $blockobject->get_title();
464 $blockobject->_load_instance($instance);
afd1ec02 465
27ec21a0 466 // Define the data we're going to silently include in the instance config form here,
9b4b78fd 467 // so we can strip them from the submitted data BEFORE serializing it.
468 $hiddendata = array(
19f5b2db 469 'sesskey' => sesskey(),
9b4b78fd 470 'instanceid' => $instance->id,
471 'blockaction' => 'config'
472 );
f032aa7a 473
474 // To this data, add anything the page itself needs to display
ad52c04f 475 $hiddendata = $page->url->params($hiddendata);
9b4b78fd 476
294ce987 477 if ($data = data_submitted()) {
9b4b78fd 478 $remove = array_keys($hiddendata);
479 foreach($remove as $item) {
480 unset($data->$item);
0f3fe4b6 481 }
58ff964f 482 if(!$blockobject->instance_config_save($data, $pinned)) {
e49ef64a 483 print_error('cannotsaveblock');
0f3fe4b6 484 }
9b4b78fd 485 // And nothing more, continue with displaying the page
0f3fe4b6 486 }
9b4b78fd 487 else {
f032aa7a 488 // We need to show the config screen, so we highjack the display logic and then die
e82d6cac 489 $strheading = get_string('blockconfiga', 'moodle', $blocktitle);
edb42f09 490 $page->print_header(get_string('pageheaderconfigablock', 'moodle'), array($strheading => ''));
b9709905 491
492 echo '<div class="block-config" id="'.$block->name.'">'; /// Make CSS easier
0be6f678 493
edb42f09 494 print_heading($strheading);
ad52c04f 495 echo '<form method="post" name="block-config" action="'. $page->url->out(false) .'">';
9b4b78fd 496 echo '<p>';
497 foreach($hiddendata as $name => $val) {
27ec21a0 498 echo '<input type="hidden" name="'. $name .'" value="'. $val .'" />';
0f3fe4b6 499 }
9b4b78fd 500 echo '</p>';
501 $blockobject->instance_config_print();
502 echo '</form>';
b9709905 503
504 echo '</div>';
ad5d5997 505 $PAGE->set_pagetype('blocks-' . $block->name);
9b4b78fd 506 print_footer();
f032aa7a 507 die(); // Do not go on with the other page-related stuff
0f3fe4b6 508 }
509 break;
9b4b78fd 510 case 'toggle':
511 if(empty($instance)) {
e49ef64a 512 print_error('invalidblockinstance', '', '', $blockaction);
0f3fe4b6 513 }
9b4b78fd 514 $instance->visible = ($instance->visible) ? 0 : 1;
0d6b9d4f 515 if (!empty($pinned)) {
66b10689 516 $DB->update_record('block_pinned_old', $instance);
0d6b9d4f 517 } else {
66b10689 518 $DB->update_record('block_instance_old', $instance);
0d6b9d4f 519 }
9b4b78fd 520 break;
521 case 'delete':
522 if(empty($instance)) {
e49ef64a 523 print_error('invalidblockinstance', '', '', $blockaction);
0f3fe4b6 524 }
0d6b9d4f 525 blocks_delete_instance($instance, $pinned);
0f3fe4b6 526 break;
527 case 'moveup':
9b4b78fd 528 if(empty($instance)) {
e49ef64a 529 print_error('invalidblockinstance', '', '', $blockaction);
9b4b78fd 530 }
f032aa7a 531
532 if($instance->weight == 0) {
533 // The block is the first one, so a move "up" probably means it changes position
534 // Where is the instance going to be moved?
535 $newpos = $page->blocks_move_position($instance, BLOCK_MOVE_UP);
6b853ff4 536 $newweight = (empty($pageblocks[$newpos]) ? 0 : max(array_keys($pageblocks[$newpos])) + 1);
f032aa7a 537
0d6b9d4f 538 blocks_execute_repositioning($instance, $newpos, $newweight, $pinned);
89a5baab 539 }
f032aa7a 540 else {
541 // The block is just moving upwards in the same position.
542 // This configuration will make sure that even if somehow the weights
543 // become not continuous, block move operations will eventually bring
544 // the situation back to normal without printing any warnings.
545 if(!empty($pageblocks[$instance->position][$instance->weight - 1])) {
546 $other = $pageblocks[$instance->position][$instance->weight - 1];
547 }
548 if(!empty($other)) {
549 ++$other->weight;
0d6b9d4f 550 if (!empty($pinned)) {
66b10689 551 $DB->update_record('block_pinned_old', $other);
0d6b9d4f 552 } else {
66b10689 553 $DB->update_record('block_instance_old', $other);
afd1ec02 554 }
f032aa7a 555 }
556 --$instance->weight;
0d6b9d4f 557 if (!empty($pinned)) {
66b10689 558 $DB->update_record('block_pinned_old', $instance);
0d6b9d4f 559 } else {
66b10689 560 $DB->update_record('block_instance_old', $instance);
0d6b9d4f 561 }
0f3fe4b6 562 }
563 break;
564 case 'movedown':
9b4b78fd 565 if(empty($instance)) {
e49ef64a 566 print_error('invalidblockinstance', '', '', $blockaction);
9b4b78fd 567 }
f032aa7a 568
569 if($instance->weight == max(array_keys($pageblocks[$instance->position]))) {
570 // The block is the last one, so a move "down" probably means it changes position
571 // Where is the instance going to be moved?
572 $newpos = $page->blocks_move_position($instance, BLOCK_MOVE_DOWN);
6b853ff4 573 $newweight = (empty($pageblocks[$newpos]) ? 0 : max(array_keys($pageblocks[$newpos])) + 1);
f032aa7a 574
0d6b9d4f 575 blocks_execute_repositioning($instance, $newpos, $newweight, $pinned);
89a5baab 576 }
f032aa7a 577 else {
578 // The block is just moving downwards in the same position.
579 // This configuration will make sure that even if somehow the weights
580 // become not continuous, block move operations will eventually bring
581 // the situation back to normal without printing any warnings.
582 if(!empty($pageblocks[$instance->position][$instance->weight + 1])) {
583 $other = $pageblocks[$instance->position][$instance->weight + 1];
584 }
585 if(!empty($other)) {
586 --$other->weight;
0d6b9d4f 587 if (!empty($pinned)) {
66b10689 588 $DB->update_record('block_pinned_old', $other);
0d6b9d4f 589 } else {
66b10689 590 $DB->update_record('block_instance_old', $other);
0d6b9d4f 591 }
f032aa7a 592 }
593 ++$instance->weight;
0d6b9d4f 594 if (!empty($pinned)) {
66b10689 595 $DB->update_record('block_pinned_old', $instance);
0d6b9d4f 596 } else {
66b10689 597 $DB->update_record('block_instance_old', $instance);
0d6b9d4f 598 }
0f3fe4b6 599 }
600 break;
9b4b78fd 601 case 'moveleft':
602 if(empty($instance)) {
e49ef64a 603 print_error('invalidblockinstance', '', '', $blockaction);
9b4b78fd 604 }
f032aa7a 605
606 // Where is the instance going to be moved?
607 $newpos = $page->blocks_move_position($instance, BLOCK_MOVE_LEFT);
6b853ff4 608 $newweight = (empty($pageblocks[$newpos]) ? 0 : max(array_keys($pageblocks[$newpos])) + 1);
f032aa7a 609
0d6b9d4f 610 blocks_execute_repositioning($instance, $newpos, $newweight, $pinned);
0f3fe4b6 611 break;
9b4b78fd 612 case 'moveright':
613 if(empty($instance)) {
e49ef64a 614 print_error('invalidblockinstance', '', '', $blockaction);
9b4b78fd 615 }
f032aa7a 616
617 // Where is the instance going to be moved?
618 $newpos = $page->blocks_move_position($instance, BLOCK_MOVE_RIGHT);
6b853ff4 619 $newweight = (empty($pageblocks[$newpos]) ? 0 : max(array_keys($pageblocks[$newpos])) + 1);
f032aa7a 620
0d6b9d4f 621 blocks_execute_repositioning($instance, $newpos, $newweight, $pinned);
9b4b78fd 622 break;
623 case 'add':
624 // Add a new instance of this block, if allowed
625 $block = blocks_get_record($blockid);
0f3fe4b6 626
3cacefda 627 if(empty($block) || !$block->visible) {
628 // Only allow adding if the block exists and is enabled
11306331 629 break;
9b4b78fd 630 }
0f3fe4b6 631
89a5baab 632 if(!$block->multiple && blocks_find_block($blockid, $pageblocks) !== false) {
633 // If no multiples are allowed and we already have one, return now
11306331 634 break;
635 }
636
637 if(!block_method_result($block->name, 'user_can_addto', $page)) {
638 // If the block doesn't want to be added...
639 break;
89a5baab 640 }
641
ad52c04f 642 $newpos = $page->blocks->get_default_position();
0d6b9d4f 643 if (!empty($pinned)) {
58ff964f 644 $sql = "SELECT 1, MAX(weight) + 1 AS nextfree
66b10689 645 FROM {block_pinned_old}
58ff964f 646 WHERE pagetype = ? AND position = ?";
f230ce19 647 $params = array($page->pagetype, $newpos);
58ff964f 648
0d6b9d4f 649 } else {
58ff964f 650 $sql = "SELECT 1, MAX(weight) + 1 AS nextfree
66b10689 651 FROM {block_instance_old}
58ff964f 652 WHERE pageid = ? AND pagetype = ? AND position = ?";
f230ce19 653 $params = array($page->get_id(), $page->pagetype, $newpos);
0d6b9d4f 654 }
58ff964f 655 $weight = $DB->get_record_sql($sql, $params);
9b4b78fd 656
657 $newinstance = new stdClass;
658 $newinstance->blockid = $blockid;
0d6b9d4f 659 if (empty($pinned)) {
660 $newinstance->pageid = $page->get_id();
661 }
f230ce19 662 $newinstance->pagetype = $page->pagetype;
f032aa7a 663 $newinstance->position = $newpos;
ff679897 664 $newinstance->weight = empty($weight->nextfree) ? 0 : $weight->nextfree;
9b4b78fd 665 $newinstance->visible = 1;
666 $newinstance->configdata = '';
0d6b9d4f 667 if (!empty($pinned)) {
66b10689 668 $newinstance->id = $DB->insert_record('block_pinned_old', $newinstance);
0d6b9d4f 669 } else {
66b10689 670 $newinstance->id = $DB->insert_record('block_instance_old', $newinstance);
0d6b9d4f 671 }
b33dd23a 672
673 // If the new instance was created, allow it to do additional setup
674 if($newinstance && ($obj = block_instance($block->name, $newinstance))) {
675 // Return value ignored
676 $obj->instance_create();
677 }
678
9b4b78fd 679 break;
680 }
f032aa7a 681
b1631fef 682 if ($redirect) {
683 // In order to prevent accidental duplicate actions, redirect to a page with a clean url
ad52c04f 684 redirect($page->url->out());
b1631fef 685 }
f032aa7a 686}
687
da71112b 688// You can use this to get the blocks to respond to URL actions without much hassle
0d6b9d4f 689function blocks_execute_url_action(&$PAGE, &$pageblocks,$pinned=false) {
02cc05a7 690 $blockaction = optional_param('blockaction', '', PARAM_ALPHA);
da71112b 691
3edc57e1 692 if (empty($blockaction) || !$PAGE->user_allowed_editing() || !confirm_sesskey()) {
da71112b 693 return;
694 }
695
696 $instanceid = optional_param('instanceid', 0, PARAM_INT);
697 $blockid = optional_param('blockid', 0, PARAM_INT);
afd1ec02 698
da71112b 699 if (!empty($blockid)) {
0d6b9d4f 700 blocks_execute_action($PAGE, $pageblocks, strtolower($blockaction), $blockid, $pinned);
da71112b 701
702 }
703 else if (!empty($instanceid)) {
704 $instance = blocks_find_instance($instanceid, $pageblocks);
0d6b9d4f 705 blocks_execute_action($PAGE, $pageblocks, strtolower($blockaction), $instance, $pinned);
da71112b 706 }
707}
708
f032aa7a 709// This shouldn't be used externally at all, it's here for use by blocks_execute_action()
710// in order to reduce code repetition.
29ca8b88 711function blocks_execute_repositioning(&$instance, $newpos, $newweight, $pinned=false) {
58ff964f 712 global $DB;
f032aa7a 713
c4308cfa 714 // If it's staying where it is, don't do anything, unless overridden
29ca8b88 715 if ($newpos == $instance->position) {
f032aa7a 716 return;
717 }
718
719 // Close the weight gap we 'll leave behind
0d6b9d4f 720 if (!empty($pinned)) {
66b10689 721 $sql = "UPDATE {block_instance_old}
58ff964f 722 SET weight = weight - 1
723 WHERE pagetype = ? AND position = ? AND weight > ?";
724 $params = array($instance->pagetype, $instance->position, $instance->weight);
725
0d6b9d4f 726 } else {
66b10689 727 $sql = "UPDATE {block_instance_old}
58ff964f 728 SET weight = weight - 1
729 WHERE pagetype = ? AND pageid = ?
730 AND position = ? AND weight > ?";
731 $params = array($instance->pagetype, $instance->pageid, $instance->position, $instance->weight);
0d6b9d4f 732 }
58ff964f 733 $DB->execute($sql, $params);
f032aa7a 734
735 $instance->position = $newpos;
736 $instance->weight = $newweight;
737
0d6b9d4f 738 if (!empty($pinned)) {
66b10689 739 $DB->update_record('block_pinned_old', $instance);
0d6b9d4f 740 } else {
66b10689 741 $DB->update_record('block_instance_old', $instance);
0d6b9d4f 742 }
743}
744
29ca8b88 745
746/**
747 * Moves a block to the new position (column) and weight (sort order).
748 * @param $instance - The block instance to be moved.
749 * @param $destpos - BLOCK_POS_LEFT or BLOCK_POS_RIGHT. The destination column.
750 * @param $destweight - The destination sort order. If NULL, we add to the end
751 * of the destination column.
752 * @param $pinned - Are we moving pinned blocks? We can only move pinned blocks
753 * to a new position withing the pinned list. Likewise, we
754 * can only moved non-pinned blocks to a new position within
755 * the non-pinned list.
756 * @return boolean (success or failure).
757 */
758function blocks_move_block($page, &$instance, $destpos, $destweight=NULL, $pinned=false) {
58ff964f 759 global $CFG, $DB;
afd1ec02 760
29ca8b88 761 if ($pinned) {
762 $blocklist = blocks_get_pinned($page);
763 } else {
764 $blocklist = blocks_get_by_page($page);
765 }
afd1ec02 766
29ca8b88 767 if ($blocklist[$instance->position][$instance->weight]->id != $instance->id) {
768 // The source block instance is not where we think it is.
c4308cfa 769 return false;
d23157d8 770 }
afd1ec02 771
29ca8b88 772 // First we close the gap that will be left behind when we take out the
773 // block from it's current column.
774 if ($pinned) {
66b10689 775 $closegapsql = "UPDATE {block_instance_old}
afd1ec02 776 SET weight = weight - 1
58ff964f 777 WHERE weight > ? AND position = ? AND pagetype = ?";
778 $params = array($instance->weight, $instance->position, $instance->pagetype);
e028ed34 779 } else {
66b10689 780 $closegapsql = "UPDATE {block_instance_old}
afd1ec02 781 SET weight = weight - 1
58ff964f 782 WHERE weight > ? AND position = ?
783 AND pagetype = ? AND pageid = ?";
784 $params = array($instance->weight, $instance->position, $instance->pagetype, $instance->pageid);
29ca8b88 785 }
58ff964f 786 if (!$DB->execute($closegapsql, $params)) {
29ca8b88 787 return false;
77e65ff7 788 }
afd1ec02 789
29ca8b88 790 // Now let's make space for the block being moved.
791 if ($pinned) {
66b10689 792 $opengapsql = "UPDATE {block_instance_old}
afd1ec02 793 SET weight = weight + 1
58ff964f 794 WHERE weight >= ? AND position = ? AND pagetype = ?";
795 $params = array($destweight, $destpos, $instance->pagetype);
d23157d8 796 } else {
66b10689 797 $opengapsql = "UPDATE {block_instance_old}
58ff964f 798 SET weight = weight + 1
799 WHERE weight >= ? AND position = ?
800 AND pagetype = ? AND pageid = ?";
801 $params = array($destweight, $destpos, $instance->pagetype, $instance->pageid);
29ca8b88 802 }
655b09ca 803 if (!$DB->execute($opengapsql, $params)) {
29ca8b88 804 return false;
c4308cfa 805 }
afd1ec02 806
29ca8b88 807 // Move the block.
808 $instance->position = $destpos;
809 $instance->weight = $destweight;
e028ed34 810
29ca8b88 811 if ($pinned) {
66b10689 812 $table = 'block_pinned_old';
29ca8b88 813 } else {
66b10689 814 $table = 'block_instance_old';
29ca8b88 815 }
58ff964f 816 return $DB->update_record($table, $instance);
e028ed34 817}
818
d23157d8 819
820/**
821 * Returns an array consisting of 2 arrays:
822 * 1) Array of pinned blocks for position BLOCK_POS_LEFT
823 * 2) Array of pinned blocks for position BLOCK_POS_RIGHT
824 */
0d6b9d4f 825function blocks_get_pinned($page) {
58ff964f 826 global $DB;
afd1ec02 827
0d6b9d4f 828 $visible = true;
58ff964f 829 $select = "pagetype = ?";
f230ce19 830 $params = array($page->pagetype);
58ff964f 831
832 if ($visible) {
833 $select .= " AND visible = 1";
834 }
835
66b10689 836 $blocks = $DB->get_records_select('block_pinned_old', $select, $params, 'position, weight');
0d6b9d4f 837
ad52c04f 838 $positions = $page->blocks->get_positions();
0d6b9d4f 839 $arr = array();
840
841 foreach($positions as $key => $position) {
842 $arr[$position] = array();
843 }
844
845 if(empty($blocks)) {
846 return $arr;
847 }
848
849 foreach($blocks as $block) {
850 $block->pinned = true; // so we know we can't move it.
ddf1935f 851 // make up an instanceid if we can..
852 $block->pageid = $page->get_id();
0d6b9d4f 853 $arr[$block->position][$block->weight] = $block;
854 }
855
afd1ec02 856 return $arr;
0d6b9d4f 857}
858
859
d23157d8 860/**
861 * Similar to blocks_get_by_page(), except that, the array returned includes
862 * pinned blocks as well. Pinned blocks are always appended before normal
863 * block instances.
864 */
0d6b9d4f 865function blocks_get_by_page_pinned($page) {
866 $pinned = blocks_get_pinned($page);
867 $user = blocks_get_by_page($page);
afd1ec02 868
0d6b9d4f 869 $weights = array();
870
871 foreach ($pinned as $pos => $arr) {
872 $weights[$pos] = count($arr);
873 }
874
875 foreach ($user as $pos => $blocks) {
876 if (!array_key_exists($pos,$pinned)) {
877 $pinned[$pos] = array();
878 }
879 if (!array_key_exists($pos,$weights)) {
880 $weights[$pos] = 0;
881 }
77e65ff7 882 foreach ($blocks as $block) {
0d6b9d4f 883 $pinned[$pos][$weights[$pos]] = $block;
884 $weights[$pos]++;
885 }
886 }
887 return $pinned;
0f3fe4b6 888}
889
d23157d8 890
891/**
892 * Returns an array of blocks for the page. Pinned blocks are excluded.
893 */
9b4b78fd 894function blocks_get_by_page($page) {
58ff964f 895 global $DB;
896
66b10689 897 $blocks = $DB->get_records_select('block_instance_old', "pageid = ? AND ? LIKE (" . $DB->sql_concat('pagetype', "'%'") . ")",
f230ce19 898 array($page->get_id(), $page->pagetype), 'position, weight');
f032aa7a 899
ad52c04f 900 $positions = $page->blocks->get_positions();
f032aa7a 901 $arr = array();
902 foreach($positions as $key => $position) {
903 $arr[$position] = array();
904 }
0f3fe4b6 905
9b4b78fd 906 if(empty($blocks)) {
907 return $arr;
908 }
0f3fe4b6 909
77e65ff7 910 foreach($blocks as $block) {
9b4b78fd 911 $arr[$block->position][$block->weight] = $block;
0f3fe4b6 912 }
d23157d8 913 return $arr;
9b4b78fd 914}
0f3fe4b6 915
d23157d8 916
9b4b78fd 917//This function prints the block to admin blocks as necessary
c1d8705f 918function blocks_print_adminblock(&$page, &$pageblocks) {
9b4b78fd 919 global $USER;
0f3fe4b6 920
c1d8705f 921 $missingblocks = blocks_get_missing($page, $pageblocks);
922
9b4b78fd 923 if (!empty($missingblocks)) {
74fd9ff9 924 $strblocks = '<div class="title"><h2>';
303fe9f4 925 $strblocks .= get_string('blocks');
552adc27 926 $strblocks .= '</h2></div>';
c1d8705f 927 $stradd = get_string('add');
9b4b78fd 928 foreach ($missingblocks as $blockid) {
929 $block = blocks_get_record($blockid);
9b4b78fd 930 $blockobject = block_instance($block->name);
931 if ($blockobject === false) {
932 continue;
933 }
11306331 934 if(!$blockobject->user_can_addto($page)) {
935 continue;
936 }
9b4b78fd 937 $menu[$block->id] = $blockobject->get_title();
938 }
4a4c30d2 939 asort($menu);
0f3fe4b6 940
ad52c04f 941 $target = $page->url->out(array('sesskey' => sesskey(), 'blockaction' => 'add'));
f032aa7a 942 $content = popup_form($target.'&amp;blockid=', $menu, 'add_block', '', $stradd .'...', '', '', true);
afd8402c 943 print_side_block($strblocks, $content, NULL, NULL, NULL, array('class' => 'block_adminblock'));
0f3fe4b6 944 }
0f3fe4b6 945}
946
19f5b2db 947/**
948 * Delete all the blocks from a particular page.
949 *
950 * @param string $pagetype the page type.
951 * @param integer $pageid the page id.
952 * @return success of failure.
953 */
954function blocks_delete_all_on_page($pagetype, $pageid) {
955 global $DB;
66b10689 956 if ($instances = $DB->get_records('block_instance_old', array('pageid' => $pageid, 'pagetype' => $pagetype))) {
19f5b2db 957 foreach ($instances as $instance) {
958 delete_context(CONTEXT_BLOCK, $instance->id); // Ingore any failures here.
959 }
960 }
66b10689 961 return $DB->delete_records('block_instance_old', array('pageid' => $pageid, 'pagetype' => $pagetype));
19f5b2db 962}
963
964// Dispite what this function is called, it seems to be mostly used to populate
965// the default blocks when a new course (or whatever) is created.
9b4b78fd 966function blocks_repopulate_page($page) {
7e0489f4 967 global $CFG, $DB;
5b224948 968
9b4b78fd 969 $allblocks = blocks_get_record();
970
971 if(empty($allblocks)) {
e49ef64a 972 print_error('cannotgetblock');
9b4b78fd 973 }
974
f032aa7a 975 // Assemble the information to correlate block names to ids
9b4b78fd 976 $idforname = array();
977 foreach($allblocks as $block) {
978 $idforname[$block->name] = $block->id;
979 }
980
f032aa7a 981 /// If the site override has been defined, it is the only valid one.
982 if (!empty($CFG->defaultblocks_override)) {
983 $blocknames = $CFG->defaultblocks_override;
984 }
985 else {
986 $blocknames = $page->blocks_get_default();
987 }
afd1ec02 988
ad52c04f 989 $positions = $page->blocks->get_positions();
f032aa7a 990 $posblocks = explode(':', $blocknames);
991
992 // Now one array holds the names of the positions, and the other one holds the blocks
993 // that are going to go in each position. Luckily for us, both arrays are numerically
994 // indexed and the indexes match, so we can work straight away... but CAREFULLY!
9b4b78fd 995
f032aa7a 996 // Ready to start creating block instances, but first drop any existing ones
f230ce19 997 blocks_delete_all_on_page($page->pagetype, $page->get_id());
f032aa7a 998
999 // Here we slyly count $posblocks and NOT $positions. This can actually make a difference
1000 // if the textual representation has undefined slots in the end. So we only work with as many
1001 // positions were retrieved, not with all the page says it has available.
1002 $numpositions = count($posblocks);
1003 for($i = 0; $i < $numpositions; ++$i) {
1004 $position = $positions[$i];
1005 $blocknames = explode(',', $posblocks[$i]);
9b4b78fd 1006 $weight = 0;
1007 foreach($blocknames as $blockname) {
1008 $newinstance = new stdClass;
1009 $newinstance->blockid = $idforname[$blockname];
f032aa7a 1010 $newinstance->pageid = $page->get_id();
f230ce19 1011 $newinstance->pagetype = $page->pagetype;
9b4b78fd 1012 $newinstance->position = $position;
1013 $newinstance->weight = $weight;
1014 $newinstance->visible = 1;
1015 $newinstance->configdata = '';
3cacefda 1016
1017 if(!empty($newinstance->blockid)) {
1018 // Only add block if it was recognized
66b10689 1019 $DB->insert_record('block_instance_old', $newinstance);
3cacefda 1020 ++$weight;
1021 }
0f3fe4b6 1022 }
1023 }
9b4b78fd 1024
1025 return true;
0f3fe4b6 1026}
1027
f10306b9 1028?>