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