In this theme, peformance info only will be showed if it's enabled.
[moodle.git] / lib / blocklib.php
CommitLineData
dcb1bd3c 1<?php //$Id$
0f3fe4b6 2
3//This library includes all the necessary stuff to use blocks in course pages
4
0f3fe4b6 5define('BLOCK_MOVE_LEFT', 0x01);
6define('BLOCK_MOVE_RIGHT', 0x02);
7define('BLOCK_MOVE_UP', 0x04);
8define('BLOCK_MOVE_DOWN', 0x08);
9b4b78fd 9define('BLOCK_CONFIGURE', 0x10);
0f3fe4b6 10
9b4b78fd 11define('BLOCK_POS_LEFT', 'l');
12define('BLOCK_POS_RIGHT', 'r');
0e9af917 13
ee6055eb 14define('BLOCKS_PINNED_TRUE',0);
15define('BLOCKS_PINNED_FALSE',1);
16define('BLOCKS_PINNED_BOTH',2);
17
f032aa7a 18require_once($CFG->libdir.'/pagelib.php');
0f3fe4b6 19
61abc65b 20
21// Returns false if this block is incompatible with the current version of Moodle.
22function block_is_compatible($blockname) {
23 global $CFG;
24
25 $file = file($CFG->dirroot.'/blocks/'.$blockname.'/block_'.$blockname.'.php');
26 if(empty($file)) {
27 return NULL;
28 }
29
30 foreach($file as $line) {
31 // If you find MoodleBlock (appearing in the class declaration) it's not compatible
32 if(strpos($line, 'MoodleBlock')) {
33 return false;
34 }
35 // But if we find a { it means the class declaration is over, so it's compatible
36 else if(strpos($line, '{')) {
37 return true;
38 }
39 }
40
41 return NULL;
42}
43
33bee34c 44// Returns the case-sensitive name of the class' constructor function. This includes both
45// PHP5- and PHP4-style constructors. If no appropriate constructor can be found, returns NULL.
46// If there is no such class, returns boolean false.
47function get_class_constructor($classname) {
48 // Caching
49 static $constructors = array();
50
51 if(!class_exists($classname)) {
52 return false;
53 }
54
55 // Tests indicate this doesn't hurt even in PHP5.
56 $classname = strtolower($classname);
57
58 // Return cached value, if exists
59 if(isset($constructors[$classname])) {
60 return $constructors[$classname];
61 }
62
63 // Get a list of methods. After examining several different ways of
64 // doing the check, (is_callable, method_exists, function_exists etc)
65 // it seems that this is the most reliable one.
66 $methods = get_class_methods($classname);
67
68 // PHP5 constructor?
69 if(phpversion() >= '5') {
70 if(in_array('__construct', $methods)) {
71 return $constructors[$classname] = '__construct';
72 }
73 }
74
75 // If we have PHP5 but no magic constructor, we have to lowercase the methods
76 $methods = array_map('strtolower', $methods);
77
78 if(in_array($classname, $methods)) {
79 return $constructors[$classname] = $classname;
80 }
81
82 return $constructors[$classname] = NULL;
83}
84
0f3fe4b6 85//This function retrieves a method-defined property of a class WITHOUT instantiating an object
11306331 86function block_method_result($blockname, $method, $param = NULL) {
0f3fe4b6 87 if(!block_load_class($blockname)) {
88 return NULL;
89 }
11306331 90 return call_user_func(array('block_'.$blockname, $method), $param);
0f3fe4b6 91}
92
93//This function creates a new object of the specified block class
9b4b78fd 94function block_instance($blockname, $instance = NULL) {
0f3fe4b6 95 if(!block_load_class($blockname)) {
96 return false;
97 }
e89d741a 98 $classname = 'block_'.$blockname;
f032aa7a 99 $retval = new $classname;
9b4b78fd 100 if($instance !== NULL) {
1345403a 101 $retval->_load_instance($instance);
9b4b78fd 102 }
103 return $retval;
0f3fe4b6 104}
105
106//This function loads the necessary class files for a block
107//Whenever you want to load a block, use this first
108function block_load_class($blockname) {
109 global $CFG;
110
a9033ad5 111 if(empty($blockname)) {
c7a9e293 112 return false;
113 }
114
e89d741a 115 $classname = 'block_'.$blockname;
a9033ad5 116
117 if(class_exists($classname)) {
118 return true;
119 }
120
121 require_once($CFG->dirroot.'/blocks/moodleblock.class.php');
febeb161 122 include_once($CFG->dirroot.'/blocks/'.$blockname.'/block_'.$blockname.'.php');
0f3fe4b6 123
0f3fe4b6 124 return class_exists($classname);
125}
126
c8e0b579 127// This function returns an array with the IDs of any blocks that you can add to your page.
128// Parameters are passed by reference for speed; they are not modified at all.
129function blocks_get_missing(&$page, &$pageblocks) {
f032aa7a 130
131 $missingblocks = array();
132 $allblocks = blocks_get_record();
133 $pageformat = $page->get_format_name();
134
135 if(!empty($allblocks)) {
136 foreach($allblocks as $block) {
137 if($block->visible && (!blocks_find_block($block->id, $pageblocks) || $block->multiple)) {
138 // And if it's applicable for display in this format...
5bbbe0be 139 if(blocks_name_allowed_in_format($block->name, $pageformat)) {
8a47e075 140 // ...add it to the missing blocks
f032aa7a 141 $missingblocks[] = $block->id;
142 }
143 }
144 }
145 }
146 return $missingblocks;
147}
148
149function blocks_remove_inappropriate($page) {
150 $pageblocks = blocks_get_by_page($page);
151
152 if(empty($pageblocks)) {
153 return;
154 }
155
156 if(($pageformat = $page->get_format_name()) == NULL) {
157 return;
158 }
159
160 foreach($pageblocks as $position) {
161 foreach($position as $instance) {
162 $block = blocks_get_record($instance->blockid);
5bbbe0be 163 if(!blocks_name_allowed_in_format($block->name, $pageformat)) {
8a47e075 164 blocks_delete_instance($instance);
f032aa7a 165 }
166 }
167 }
168}
169
5bbbe0be 170function blocks_name_allowed_in_format($name, $pageformat) {
171 $formats = block_method_result($name, 'applicable_formats');
172 $accept = NULL;
173 $depth = -1;
174 foreach($formats as $format => $allowed) {
175 $thisformat = '^'.str_replace('*', '[^-]*', $format).'.*$';
176 if(ereg($thisformat, $pageformat)) {
177 if(($scount = substr_count($format, '-')) > $depth) {
178 $depth = $scount;
179 $accept = $allowed;
180 }
181 }
182 }
183 if($accept === NULL) {
184 $accept = !empty($formats['all']);
185 }
186 return $accept;
187}
188
0d6b9d4f 189function blocks_delete_instance($instance,$pinned=false) {
f032aa7a 190 global $CFG;
191
b33dd23a 192 // Get the block object and call instance_delete() first
193 if(!$record = blocks_get_record($instance->blockid)) {
2e477369 194 return false;
b33dd23a 195 }
196 if(!$obj = block_instance($record->name, $instance)) {
2e477369 197 return false;
b33dd23a 198 }
199
200 // Return value ignored
201 $obj->instance_delete();
0d6b9d4f 202 if (!empty($pinned)) {
203 delete_records('block_pinned', 'id', $instance->id);
204 // And now, decrement the weight of all blocks after this one
205 execute_sql('UPDATE '.$CFG->prefix.'block_pinned SET weight = weight - 1 WHERE pagetype = \''.$instance->pagetype.
206 '\' AND position = \''.$instance->position.
207 '\' AND weight > '.$instance->weight, false);
208 } else {
209 // Now kill the db record;
210 delete_records('block_instance', 'id', $instance->id);
211 // And now, decrement the weight of all blocks after this one
212 execute_sql('UPDATE '.$CFG->prefix.'block_instance SET weight = weight - 1 WHERE pagetype = \''.$instance->pagetype.
213 '\' AND pageid = '.$instance->pageid.' AND position = \''.$instance->position.
214 '\' AND weight > '.$instance->weight, false);
215 }
2e477369 216 return true;
f032aa7a 217}
218
c8e0b579 219// Accepts an array of block instances and checks to see if any of them have content to display
220// (causing them to calculate their content in the process). Returns true or false. Parameter passed
221// by reference for speed; the array is actually not modified.
dffd4bb9 222function blocks_have_content(&$pageblocks, $position) {
0d6b9d4f 223
224 if (empty($pageblocks) || !is_array($pageblocks) || !array_key_exists($position,$pageblocks)) {
225 return false;
226 }
dffd4bb9 227 foreach($pageblocks[$position] as $instance) {
3ef642d9 228 if(!$instance->visible) {
7933cc6b 229 continue;
230 }
3ef642d9 231 if(!$record = blocks_get_record($instance->blockid)) {
7933cc6b 232 continue;
233 }
3ef642d9 234 if(!$obj = block_instance($record->name, $instance)) {
9b4b78fd 235 continue;
236 }
3ef642d9 237 if(!$obj->is_empty()) {
238 return true;
0f3fe4b6 239 }
240 }
9b4b78fd 241
0f3fe4b6 242 return false;
243}
244
c8e0b579 245// This function prints one group of blocks in a page
246// Parameters passed by reference for speed; they are not modified.
66492322 247function blocks_print_group(&$page, &$pageblocks, $position) {
248
249 if(empty($pageblocks[$position])) {
3f052187 250 $pageblocks[$position] = array();
b35fc182 251 $maxweight = 0;
252 }
253 else {
254 $maxweight = max(array_keys($pageblocks[$position]));
9b4b78fd 255 }
3cdc4597 256
257 foreach ($pageblocks[$position] as $instance) {
4374ee2c 258 if (!empty($instance->pinned)) {
259 $maxweight--;
260 }
261 }
0f3fe4b6 262
f032aa7a 263 $isediting = $page->user_is_editing();
0f3fe4b6 264
66492322 265 foreach($pageblocks[$position] as $instance) {
9b4b78fd 266 $block = blocks_get_record($instance->blockid);
267 if(!$block->visible) {
268 // Disabled by the admin
269 continue;
270 }
0f3fe4b6 271
ab0e4dd4 272 if (!$obj = block_instance($block->name, $instance)) {
273 // Invalid block
274 continue;
275 }
0f3fe4b6 276
4374ee2c 277 $editalways = $page->edit_always();
0d6b9d4f 278
279 if (($isediting && empty($instance->pinned)) || !empty($editalways)) {
9b4b78fd 280 $options = 0;
f032aa7a 281 // 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:
282 // the first block might still be able to move up if the page says so (i.e., it will change position)
283 $options |= BLOCK_MOVE_UP * ($instance->weight != 0 || ($page->blocks_move_position($instance, BLOCK_MOVE_UP) != $instance->position));
284 // Same thing for downward movement
285 $options |= BLOCK_MOVE_DOWN * ($instance->weight != $maxweight || ($page->blocks_move_position($instance, BLOCK_MOVE_DOWN) != $instance->position));
286 // For left and right movements, it's up to the page to tell us whether they are allowed
287 $options |= BLOCK_MOVE_RIGHT * ($page->blocks_move_position($instance, BLOCK_MOVE_RIGHT) != $instance->position);
288 $options |= BLOCK_MOVE_LEFT * ($page->blocks_move_position($instance, BLOCK_MOVE_LEFT ) != $instance->position);
289 // Finally, the block can be configured if the block class either allows multiple instances, or if it specifically
290 // allows instance configuration (multiple instances override that one). It doesn't have anything to do with what the
291 // administrator has allowed for this block in the site admin options.
292 $options |= BLOCK_CONFIGURE * ( $obj->instance_allow_multiple() || $obj->instance_allow_config() );
1345403a 293 $obj->_add_edit_controls($options);
9b4b78fd 294 }
0f3fe4b6 295
9b4b78fd 296 if(!$instance->visible) {
297 if($isediting) {
1345403a 298 $obj->_print_shadow();
0f3fe4b6 299 }
300 }
9b4b78fd 301 else {
1345403a 302 $obj->_print_block();
9b4b78fd 303 }
0f3fe4b6 304 }
66492322 305
831cd87f 306 if($page->blocks_default_position() == $position && $page->user_is_editing()) {
66492322 307 blocks_print_adminblock($page, $pageblocks);
308 }
309
0f3fe4b6 310}
311
c8e0b579 312// This iterates over an array of blocks and calculates the preferred width
313// Parameter passed by reference for speed; it's not modified.
314function blocks_preferred_width(&$instances) {
0f3fe4b6 315 $width = 0;
316
9b4b78fd 317 if(empty($instances) || !is_array($instances)) {
0f3fe4b6 318 return 0;
319 }
ff6191b7 320
321 $blocks = blocks_get_record();
322
9b4b78fd 323 foreach($instances as $instance) {
324 if(!$instance->visible) {
fe78a3dc 325 continue;
0c9c6363 326 }
ff6191b7 327
328 if(!$blocks[$instance->blockid]->visible) {
9b687320 329 continue;
330 }
ff6191b7 331 $pref = block_method_result($blocks[$instance->blockid]->name, 'preferred_width');
9b4b78fd 332 if($pref === NULL) {
333 continue;
334 }
335 if($pref > $width) {
336 $width = $pref;
0f3fe4b6 337 }
338 }
339 return $width;
340}
341
9b4b78fd 342function blocks_get_record($blockid = NULL, $invalidate = false) {
343 static $cache = NULL;
0f3fe4b6 344
9b4b78fd 345 if($invalidate || empty($cache)) {
eca3b01f 346 $cache = get_records('block');
9b4b78fd 347 }
0f3fe4b6 348
9b4b78fd 349 if($blockid === NULL) {
350 return $cache;
351 }
0f3fe4b6 352
9b4b78fd 353 return (isset($cache[$blockid])? $cache[$blockid] : false);
354}
355
356function blocks_find_block($blockid, $blocksarray) {
0d6b9d4f 357 if (empty($blocksarray)) {
358 return false;
359 }
9b4b78fd 360 foreach($blocksarray as $blockgroup) {
0d6b9d4f 361 if (empty($blockgroup)) {
362 continue;
363 }
9b4b78fd 364 foreach($blockgroup as $instance) {
365 if($instance->blockid == $blockid) {
366 return $instance;
367 }
368 }
369 }
370 return false;
371}
372
373function blocks_find_instance($instanceid, $blocksarray) {
374 foreach($blocksarray as $subarray) {
375 foreach($subarray as $instance) {
376 if($instance->id == $instanceid) {
377 return $instance;
378 }
379 }
380 }
381 return false;
382}
383
ec79d3e4 384// Simple entry point for anyone that wants to use blocks
ee6055eb 385function blocks_setup(&$PAGE,$pinned=BLOCKS_PINNED_FALSE) {
386 switch ($pinned) {
387 case BLOCKS_PINNED_TRUE:
388 $pageblocks = blocks_get_pinned($PAGE);
389 break;
390 case BLOCKS_PINNED_BOTH:
391 $pageblocks = blocks_get_by_page_pinned($PAGE);
392 break;
393 case BLOCKS_PINNED_FALSE:
394 default:
395 $pageblocks = blocks_get_by_page($PAGE);
396 break;
397 }
398 blocks_execute_url_action($PAGE, $pageblocks,($pinned==BLOCKS_PINNED_TRUE));
ec79d3e4 399 return $pageblocks;
400}
401
0d6b9d4f 402function blocks_execute_action($page, &$pageblocks, $blockaction, $instanceorid, $pinned=false) {
9b4b78fd 403 global $CFG;
404
a9c75a9c 405 if (is_int($instanceorid)) {
9b4b78fd 406 $blockid = $instanceorid;
a9c75a9c 407 } else if (is_object($instanceorid)) {
9b4b78fd 408 $instance = $instanceorid;
409 }
0f3fe4b6 410
411 switch($blockaction) {
9b4b78fd 412 case 'config':
f032aa7a 413 global $USER;
9b4b78fd 414 $block = blocks_get_record($instance->blockid);
e82d6cac 415 // Hacky hacky tricky stuff to get the original human readable block title,
416 // even if the block has configured its title to be something else.
417 // Create the object WITHOUT instance data.
418 $blockobject = block_instance($block->name);
9b4b78fd 419 if ($blockobject === false) {
11306331 420 break;
421 }
422
423 // First of all check to see if the block wants to be edited
424 if(!$blockobject->user_can_edit()) {
425 break;
9b4b78fd 426 }
11306331 427
e82d6cac 428 // Now get the title and AFTER that load up the instance
429 $blocktitle = $blockobject->get_title();
430 $blockobject->_load_instance($instance);
431
9b4b78fd 432 optional_param('submitted', 0, PARAM_INT);
433
27ec21a0 434 // Define the data we're going to silently include in the instance config form here,
9b4b78fd 435 // so we can strip them from the submitted data BEFORE serializing it.
436 $hiddendata = array(
437 'sesskey' => $USER->sesskey,
9b4b78fd 438 'instanceid' => $instance->id,
439 'blockaction' => 'config'
440 );
f032aa7a 441
442 // To this data, add anything the page itself needs to display
443 $hiddendata = array_merge($hiddendata, $page->url_get_parameters());
9b4b78fd 444
445 if($data = data_submitted()) {
446 $remove = array_keys($hiddendata);
447 foreach($remove as $item) {
448 unset($data->$item);
0f3fe4b6 449 }
0d6b9d4f 450 if(!$blockobject->instance_config_save($data,$pinned)) {
9b4b78fd 451 error('Error saving block configuration');
0f3fe4b6 452 }
9b4b78fd 453 // And nothing more, continue with displaying the page
0f3fe4b6 454 }
9b4b78fd 455 else {
f032aa7a 456 // We need to show the config screen, so we highjack the display logic and then die
e82d6cac 457 $strheading = get_string('blockconfiga', 'moodle', $blocktitle);
edb42f09 458 $page->print_header(get_string('pageheaderconfigablock', 'moodle'), array($strheading => ''));
b9709905 459
460 echo '<div class="block-config" id="'.$block->name.'">'; /// Make CSS easier
461
edb42f09 462 print_heading($strheading);
f032aa7a 463 echo '<form method="post" action="'. $page->url_get_path() .'">';
9b4b78fd 464 echo '<p>';
465 foreach($hiddendata as $name => $val) {
27ec21a0 466 echo '<input type="hidden" name="'. $name .'" value="'. $val .'" />';
0f3fe4b6 467 }
9b4b78fd 468 echo '</p>';
469 $blockobject->instance_config_print();
470 echo '</form>';
b9709905 471
472 echo '</div>';
a2c28054 473 $CFG->pagepath = 'blocks/' . $block->name;
9b4b78fd 474 print_footer();
f032aa7a 475 die(); // Do not go on with the other page-related stuff
0f3fe4b6 476 }
477 break;
9b4b78fd 478 case 'toggle':
479 if(empty($instance)) {
480 error('Invalid block instance for '.$blockaction);
0f3fe4b6 481 }
9b4b78fd 482 $instance->visible = ($instance->visible) ? 0 : 1;
0d6b9d4f 483 if (!empty($pinned)) {
484 update_record('block_pinned', $instance);
485 } else {
486 update_record('block_instance', $instance);
487 }
9b4b78fd 488 break;
489 case 'delete':
490 if(empty($instance)) {
a9c75a9c 491 error('Invalid block instance for '. $blockaction);
0f3fe4b6 492 }
0d6b9d4f 493 blocks_delete_instance($instance, $pinned);
0f3fe4b6 494 break;
495 case 'moveup':
9b4b78fd 496 if(empty($instance)) {
a9c75a9c 497 error('Invalid block instance for '. $blockaction);
9b4b78fd 498 }
f032aa7a 499
500 if($instance->weight == 0) {
501 // The block is the first one, so a move "up" probably means it changes position
502 // Where is the instance going to be moved?
503 $newpos = $page->blocks_move_position($instance, BLOCK_MOVE_UP);
6b853ff4 504 $newweight = (empty($pageblocks[$newpos]) ? 0 : max(array_keys($pageblocks[$newpos])) + 1);
f032aa7a 505
0d6b9d4f 506 blocks_execute_repositioning($instance, $newpos, $newweight, $pinned);
89a5baab 507 }
f032aa7a 508 else {
509 // The block is just moving upwards in the same position.
510 // This configuration will make sure that even if somehow the weights
511 // become not continuous, block move operations will eventually bring
512 // the situation back to normal without printing any warnings.
513 if(!empty($pageblocks[$instance->position][$instance->weight - 1])) {
514 $other = $pageblocks[$instance->position][$instance->weight - 1];
515 }
516 if(!empty($other)) {
517 ++$other->weight;
0d6b9d4f 518 if (!empty($pinned)) {
519 update_record('block_pinned', $other);
520 } else {
521 update_record('block_instance', $other);
522 }
f032aa7a 523 }
524 --$instance->weight;
0d6b9d4f 525 if (!empty($pinned)) {
526 update_record('block_pinned', $instance);
527 } else {
528 update_record('block_instance', $instance);
529 }
0f3fe4b6 530 }
531 break;
532 case 'movedown':
9b4b78fd 533 if(empty($instance)) {
a9c75a9c 534 error('Invalid block instance for '. $blockaction);
9b4b78fd 535 }
f032aa7a 536
537 if($instance->weight == max(array_keys($pageblocks[$instance->position]))) {
538 // The block is the last one, so a move "down" probably means it changes position
539 // Where is the instance going to be moved?
540 $newpos = $page->blocks_move_position($instance, BLOCK_MOVE_DOWN);
6b853ff4 541 $newweight = (empty($pageblocks[$newpos]) ? 0 : max(array_keys($pageblocks[$newpos])) + 1);
f032aa7a 542
0d6b9d4f 543 blocks_execute_repositioning($instance, $newpos, $newweight, $pinned);
89a5baab 544 }
f032aa7a 545 else {
546 // The block is just moving downwards in the same position.
547 // This configuration will make sure that even if somehow the weights
548 // become not continuous, block move operations will eventually bring
549 // the situation back to normal without printing any warnings.
550 if(!empty($pageblocks[$instance->position][$instance->weight + 1])) {
551 $other = $pageblocks[$instance->position][$instance->weight + 1];
552 }
553 if(!empty($other)) {
554 --$other->weight;
0d6b9d4f 555 if (!empty($pinned)) {
556 update_record('block_pinned', $other);
557 } else {
558 update_record('block_instance', $other);
559 }
f032aa7a 560 }
561 ++$instance->weight;
0d6b9d4f 562 if (!empty($pinned)) {
563 update_record('block_pinned', $instance);
564 } else {
565 update_record('block_instance', $instance);
566 }
0f3fe4b6 567 }
568 break;
9b4b78fd 569 case 'moveleft':
570 if(empty($instance)) {
a9c75a9c 571 error('Invalid block instance for '. $blockaction);
9b4b78fd 572 }
f032aa7a 573
574 // Where is the instance going to be moved?
575 $newpos = $page->blocks_move_position($instance, BLOCK_MOVE_LEFT);
6b853ff4 576 $newweight = (empty($pageblocks[$newpos]) ? 0 : max(array_keys($pageblocks[$newpos])) + 1);
f032aa7a 577
0d6b9d4f 578 blocks_execute_repositioning($instance, $newpos, $newweight, $pinned);
0f3fe4b6 579 break;
9b4b78fd 580 case 'moveright':
581 if(empty($instance)) {
a9c75a9c 582 error('Invalid block instance for '. $blockaction);
9b4b78fd 583 }
f032aa7a 584
585 // Where is the instance going to be moved?
586 $newpos = $page->blocks_move_position($instance, BLOCK_MOVE_RIGHT);
6b853ff4 587 $newweight = (empty($pageblocks[$newpos]) ? 0 : max(array_keys($pageblocks[$newpos])) + 1);
f032aa7a 588
0d6b9d4f 589 blocks_execute_repositioning($instance, $newpos, $newweight, $pinned);
9b4b78fd 590 break;
591 case 'add':
592 // Add a new instance of this block, if allowed
593 $block = blocks_get_record($blockid);
0f3fe4b6 594
3cacefda 595 if(empty($block) || !$block->visible) {
596 // Only allow adding if the block exists and is enabled
11306331 597 break;
9b4b78fd 598 }
0f3fe4b6 599
89a5baab 600 if(!$block->multiple && blocks_find_block($blockid, $pageblocks) !== false) {
601 // If no multiples are allowed and we already have one, return now
11306331 602 break;
603 }
604
605 if(!block_method_result($block->name, 'user_can_addto', $page)) {
606 // If the block doesn't want to be added...
607 break;
89a5baab 608 }
609
f032aa7a 610 $newpos = $page->blocks_default_position();
0d6b9d4f 611 if (!empty($pinned)) {
612 $sql = 'SELECT 1, max(weight) + 1 AS nextfree FROM '. $CFG->prefix .'block_pinned WHERE '
613 .' pagetype = \''. $page->get_type() .'\' AND position = \''. $newpos .'\'';
614 } else {
615 $sql = 'SELECT 1, max(weight) + 1 AS nextfree FROM '. $CFG->prefix .'block_instance WHERE pageid = '. $page->get_id()
616 .' AND pagetype = \''. $page->get_type() .'\' AND position = \''. $newpos .'\'';
617 }
618 $weight = get_record_sql($sql);
9b4b78fd 619
620 $newinstance = new stdClass;
621 $newinstance->blockid = $blockid;
0d6b9d4f 622 if (empty($pinned)) {
623 $newinstance->pageid = $page->get_id();
624 }
f032aa7a 625 $newinstance->pagetype = $page->get_type();
626 $newinstance->position = $newpos;
ff679897 627 $newinstance->weight = empty($weight->nextfree) ? 0 : $weight->nextfree;
9b4b78fd 628 $newinstance->visible = 1;
629 $newinstance->configdata = '';
0d6b9d4f 630 if (!empty($pinned)) {
631 $newinstance->id = insert_record('block_pinned', $newinstance);
632 } else {
633 $newinstance->id = insert_record('block_instance', $newinstance);
634 }
b33dd23a 635
636 // If the new instance was created, allow it to do additional setup
637 if($newinstance && ($obj = block_instance($block->name, $newinstance))) {
638 // Return value ignored
639 $obj->instance_create();
640 }
641
9b4b78fd 642 break;
643 }
f032aa7a 644
645 // In order to prevent accidental duplicate actions, redirect to a page with a clean url
646 redirect($page->url_get_full());
647}
648
da71112b 649// You can use this to get the blocks to respond to URL actions without much hassle
0d6b9d4f 650function blocks_execute_url_action(&$PAGE, &$pageblocks,$pinned=false) {
da71112b 651 $blockaction = optional_param('blockaction');
652
3edc57e1 653 if (empty($blockaction) || !$PAGE->user_allowed_editing() || !confirm_sesskey()) {
da71112b 654 return;
655 }
656
657 $instanceid = optional_param('instanceid', 0, PARAM_INT);
658 $blockid = optional_param('blockid', 0, PARAM_INT);
659
660 if (!empty($blockid)) {
0d6b9d4f 661 blocks_execute_action($PAGE, $pageblocks, strtolower($blockaction), $blockid, $pinned);
da71112b 662
663 }
664 else if (!empty($instanceid)) {
665 $instance = blocks_find_instance($instanceid, $pageblocks);
0d6b9d4f 666 blocks_execute_action($PAGE, $pageblocks, strtolower($blockaction), $instance, $pinned);
da71112b 667 }
668}
669
f032aa7a 670// This shouldn't be used externally at all, it's here for use by blocks_execute_action()
671// in order to reduce code repetition.
0d6b9d4f 672function blocks_execute_repositioning(&$instance, $newpos, $newweight, $pinned=false) {
f032aa7a 673 global $CFG;
674
675 // If it's staying where it is, don't do anything
676 if($newpos == $instance->position) {
677 return;
678 }
679
680 // Close the weight gap we 'll leave behind
0d6b9d4f 681 if (!empty($pinned)) {
682 $sql = 'UPDATE '. $CFG->prefix .'block_instance SET weight = weight - 1 WHERE pagetype = \''. $instance->pagetype.
683 '\' AND position = \'' .$instance->position.
684 '\' AND weight > '. $instance->weight;
685 } else {
686 $sql = 'UPDATE '. $CFG->prefix .'block_instance SET weight = weight - 1 WHERE pagetype = \''. $instance->pagetype.
f032aa7a 687 '\' AND pageid = '. $instance->pageid .' AND position = \'' .$instance->position.
0d6b9d4f 688 '\' AND weight > '. $instance->weight;
689 }
690 execute_sql($sql,false);
f032aa7a 691
692 $instance->position = $newpos;
693 $instance->weight = $newweight;
694
0d6b9d4f 695 if (!empty($pinned)) {
696 update_record('block_pinned', $instance);
697 } else {
698 update_record('block_instance', $instance);
699 }
700}
701
702function blocks_get_pinned($page) {
703
704 $visible = true;
705
706 if (method_exists($page,'edit_always')) {
707 if ($page->edit_always()) {
708 $visible = false;
709 }
710 }
711
712 $blocks = get_records_select('block_pinned', 'pagetype = \''. $page->get_type() .'\''.(($visible) ? 'AND visible = 1' : ''), 'position, weight');
713
714 $positions = $page->blocks_get_positions();
715 $arr = array();
716
717 foreach($positions as $key => $position) {
718 $arr[$position] = array();
719 }
720
721 if(empty($blocks)) {
722 return $arr;
723 }
724
725 foreach($blocks as $block) {
726 $block->pinned = true; // so we know we can't move it.
ddf1935f 727 // make up an instanceid if we can..
728 $block->pageid = $page->get_id();
0d6b9d4f 729 $arr[$block->position][$block->weight] = $block;
730 }
731
732 return $arr;
733}
734
735
736function blocks_get_by_page_pinned($page) {
737 $pinned = blocks_get_pinned($page);
738 $user = blocks_get_by_page($page);
739
740 $weights = array();
741
742 foreach ($pinned as $pos => $arr) {
743 $weights[$pos] = count($arr);
744 }
745
746 foreach ($user as $pos => $blocks) {
747 if (!array_key_exists($pos,$pinned)) {
748 $pinned[$pos] = array();
749 }
750 if (!array_key_exists($pos,$weights)) {
751 $weights[$pos] = 0;
752 }
753 foreach ($blocks as $block) {
754 $pinned[$pos][$weights[$pos]] = $block;
755 $weights[$pos]++;
756 }
757 }
758 return $pinned;
0f3fe4b6 759}
760
9b4b78fd 761function blocks_get_by_page($page) {
a9b3afb7 762 $blocks = get_records_select('block_instance', "pageid = '". $page->get_id() ."' AND pagetype = '". $page->get_type() ."'", 'position, weight');
f032aa7a 763
764 $positions = $page->blocks_get_positions();
765 $arr = array();
766 foreach($positions as $key => $position) {
767 $arr[$position] = array();
768 }
0f3fe4b6 769
9b4b78fd 770 if(empty($blocks)) {
771 return $arr;
772 }
0f3fe4b6 773
9b4b78fd 774 foreach($blocks as $block) {
775 $arr[$block->position][$block->weight] = $block;
0f3fe4b6 776 }
777
9b4b78fd 778 return $arr;
779}
0f3fe4b6 780
9b4b78fd 781//This function prints the block to admin blocks as necessary
c1d8705f 782function blocks_print_adminblock(&$page, &$pageblocks) {
9b4b78fd 783 global $USER;
0f3fe4b6 784
c1d8705f 785 $missingblocks = blocks_get_missing($page, $pageblocks);
786
9b4b78fd 787 if (!empty($missingblocks)) {
c1d8705f 788 $strblocks = get_string('blocks');
789 $stradd = get_string('add');
9b4b78fd 790 foreach ($missingblocks as $blockid) {
791 $block = blocks_get_record($blockid);
9b4b78fd 792 $blockobject = block_instance($block->name);
793 if ($blockobject === false) {
794 continue;
795 }
11306331 796 if(!$blockobject->user_can_addto($page)) {
797 continue;
798 }
9b4b78fd 799 $menu[$block->id] = $blockobject->get_title();
800 }
4a4c30d2 801 asort($menu);
0f3fe4b6 802
f032aa7a 803 $target = $page->url_get_full(array('sesskey' => $USER->sesskey, 'blockaction' => 'add'));
804 $content = popup_form($target.'&amp;blockid=', $menu, 'add_block', '', $stradd .'...', '', '', true);
afd8402c 805 print_side_block($strblocks, $content, NULL, NULL, NULL, array('class' => 'block_adminblock'));
0f3fe4b6 806 }
0f3fe4b6 807}
808
9b4b78fd 809function blocks_repopulate_page($page) {
810 global $CFG;
5b224948 811
9b4b78fd 812 $allblocks = blocks_get_record();
813
814 if(empty($allblocks)) {
815 error('Could not retrieve blocks from the database');
816 }
817
f032aa7a 818 // Assemble the information to correlate block names to ids
9b4b78fd 819 $idforname = array();
820 foreach($allblocks as $block) {
821 $idforname[$block->name] = $block->id;
822 }
823
f032aa7a 824 /// If the site override has been defined, it is the only valid one.
825 if (!empty($CFG->defaultblocks_override)) {
826 $blocknames = $CFG->defaultblocks_override;
827 }
828 else {
829 $blocknames = $page->blocks_get_default();
830 }
831
832 $positions = $page->blocks_get_positions();
833 $posblocks = explode(':', $blocknames);
834
835 // Now one array holds the names of the positions, and the other one holds the blocks
836 // that are going to go in each position. Luckily for us, both arrays are numerically
837 // indexed and the indexes match, so we can work straight away... but CAREFULLY!
9b4b78fd 838
f032aa7a 839 // Ready to start creating block instances, but first drop any existing ones
840 delete_records('block_instance', 'pageid', $page->get_id(), 'pagetype', $page->get_type());
841
842 // Here we slyly count $posblocks and NOT $positions. This can actually make a difference
843 // if the textual representation has undefined slots in the end. So we only work with as many
844 // positions were retrieved, not with all the page says it has available.
845 $numpositions = count($posblocks);
846 for($i = 0; $i < $numpositions; ++$i) {
847 $position = $positions[$i];
848 $blocknames = explode(',', $posblocks[$i]);
9b4b78fd 849 $weight = 0;
850 foreach($blocknames as $blockname) {
851 $newinstance = new stdClass;
852 $newinstance->blockid = $idforname[$blockname];
f032aa7a 853 $newinstance->pageid = $page->get_id();
854 $newinstance->pagetype = $page->get_type();
9b4b78fd 855 $newinstance->position = $position;
856 $newinstance->weight = $weight;
857 $newinstance->visible = 1;
858 $newinstance->configdata = '';
3cacefda 859
860 if(!empty($newinstance->blockid)) {
861 // Only add block if it was recognized
862 insert_record('block_instance', $newinstance);
863 ++$weight;
864 }
0f3fe4b6 865 }
866 }
9b4b78fd 867
868 return true;
0f3fe4b6 869}
870
871function upgrade_blocks_db($continueto) {
872/// This function upgrades the blocks tables, if necessary
873/// It's called from admin/index.php
874
875 global $CFG, $db;
876
a9c75a9c 877 require_once ($CFG->dirroot .'/blocks/version.php'); // Get code versions
0f3fe4b6 878
879 if (empty($CFG->blocks_version)) { // Blocks have never been installed.
a9c75a9c 880 $strdatabaseupgrades = get_string('databaseupgrades');
0f3fe4b6 881 print_header($strdatabaseupgrades, $strdatabaseupgrades, $strdatabaseupgrades,
a9c75a9c 882 '', '', false, '&nbsp;', '&nbsp;');
0f3fe4b6 883
884 $db->debug=true;
a9c75a9c 885 if (modify_database($CFG->dirroot .'/blocks/db/'. $CFG->dbtype .'.sql')) {
0f3fe4b6 886 $db->debug = false;
a9c75a9c 887 if (set_config('blocks_version', $blocks_version)) {
c7a9e293 888 notify(get_string('databasesuccess'), 'notifysuccess');
a9c75a9c 889 notify(get_string('databaseupgradeblocks', '', $blocks_version));
0f3fe4b6 890 print_continue($continueto);
891 exit;
892 } else {
a9c75a9c 893 error('Upgrade of blocks system failed! (Could not update version in config table)');
0f3fe4b6 894 }
895 } else {
a9c75a9c 896 error('Blocks tables could NOT be set up successfully!');
0f3fe4b6 897 }
898 }
899
900
901 if ($blocks_version > $CFG->blocks_version) { // Upgrade tables
a9c75a9c 902 $strdatabaseupgrades = get_string('databaseupgrades');
0f3fe4b6 903 print_header($strdatabaseupgrades, $strdatabaseupgrades, $strdatabaseupgrades);
904
a9c75a9c 905 require_once ($CFG->dirroot .'/blocks/db/'. $CFG->dbtype .'.php');
0f3fe4b6 906
907 $db->debug=true;
908 if (blocks_upgrade($CFG->blocks_version)) {
909 $db->debug=false;
a9c75a9c 910 if (set_config('blocks_version', $blocks_version)) {
c7a9e293 911 notify(get_string('databasesuccess'), 'notifysuccess');
a9c75a9c 912 notify(get_string('databaseupgradeblocks', '', $blocks_version));
0f3fe4b6 913 print_continue($continueto);
914 exit;
915 } else {
a9c75a9c 916 error('Upgrade of blocks system failed! (Could not update version in config table)');
0f3fe4b6 917 }
918 } else {
919 $db->debug=false;
a9c75a9c 920 error('Upgrade failed! See blocks/version.php');
0f3fe4b6 921 }
922
923 } else if ($blocks_version < $CFG->blocks_version) {
b011f733 924 notify('WARNING!!! The Blocks version you are using is OLDER than the version that made these databases!');
0f3fe4b6 925 }
926}
927
928//This function finds all available blocks and install them
929//into blocks table or do all the upgrade process if newer
930function upgrade_blocks_plugins($continueto) {
931
932 global $CFG;
933
934 $blocktitles = array();
935 $invalidblocks = array();
936 $validblocks = array();
937 $notices = array();
938
939 //Count the number of blocks in db
9b4b78fd 940 $blockcount = count_records('block');
0f3fe4b6 941 //If there isn't records. This is the first install, so I remember it
942 if ($blockcount == 0) {
943 $first_install = true;
944 } else {
945 $first_install = false;
946 }
947
948 $site = get_site();
949
9b4b78fd 950 if (!$blocks = get_list_of_plugins('blocks', 'db') ) {
a9c75a9c 951 error('No blocks installed!');
0f3fe4b6 952 }
953
a9c75a9c 954 include_once($CFG->dirroot .'/blocks/moodleblock.class.php');
e89d741a 955 if(!class_exists('block_base')) {
956 error('Class block_base is not defined or file not found for /blocks/moodleblock.class.php');
0f3fe4b6 957 }
958
959 foreach ($blocks as $blockname) {
960
a9c75a9c 961 if ($blockname == 'NEWBLOCK') { // Someone has unzipped the template, ignore it
0f3fe4b6 962 continue;
963 }
964
61abc65b 965 if(!block_is_compatible($blockname)) {
966 // This is an old-style block
967 //$notices[] = 'Block '. $blockname .' is not compatible with the current version of Mooodle and needs to be updated by a programmer.';
968 $invalidblocks[] = $blockname;
969 continue;
970 }
971
a9c75a9c 972 $fullblock = $CFG->dirroot .'/blocks/'. $blockname;
0f3fe4b6 973
9b4b78fd 974 if ( is_readable($fullblock.'/block_'.$blockname.'.php')) {
975 include_once($fullblock.'/block_'.$blockname.'.php');
0f3fe4b6 976 } else {
a9c75a9c 977 $notices[] = 'Block '. $blockname .': '. $fullblock .'/block_'. $blockname .'.php was not readable';
0f3fe4b6 978 continue;
979 }
980
a9c75a9c 981 if ( @is_dir($fullblock .'/db/')) {
982 if ( @is_readable($fullblock .'/db/'. $CFG->dbtype .'.php')) {
89a5baab 983 include_once($fullblock .'/db/'. $CFG->dbtype .'.php'); // defines upgrading function
828c4e09 984 } else {
7a3290ed 985 //$notices[] ='Block '. $blockname .': '. $fullblock .'/db/'. $CFG->dbtype .'.php was not readable';
828c4e09 986 continue;
987 }
0f3fe4b6 988 }
989
e89d741a 990 $classname = 'block_'.$blockname;
0f3fe4b6 991 if(!class_exists($classname)) {
a9c75a9c 992 $notices[] = 'Block '. $blockname .': '. $classname .' not implemented';
0f3fe4b6 993 continue;
994 }
995
9b4b78fd 996 // Here is the place to see if the block implements a constructor (old style),
997 // an init() function (new style) or nothing at all (error time).
998
33bee34c 999 $constructor = get_class_constructor($classname);
1000 if(empty($constructor)) {
0f3fe4b6 1001 // No constructor
a9c75a9c 1002 $notices[] = 'Block '. $blockname .': class does not have a constructor';
0f3fe4b6 1003 $invalidblocks[] = $blockname;
1004 continue;
1005 }
1006
9b4b78fd 1007 $block = new stdClass; // This may be used to update the db below
1008 $blockobj = new $classname; // This is what we 'll be testing
0f3fe4b6 1009
e89d741a 1010 // Inherits from block_base?
1011 if(!is_subclass_of($blockobj, 'block_base')) {
1012 $notices[] = 'Block '. $blockname .': class does not inherit from block_base';
0f3fe4b6 1013 continue;
1014 }
1015
1016 // OK, it's as we all hoped. For further tests, the object will do them itself.
1017 if(!$blockobj->_self_test()) {
a9c75a9c 1018 $notices[] = 'Block '. $blockname .': self test failed';
0f3fe4b6 1019 continue;
1020 }
1021 $block->version = $blockobj->get_version();
1022
1023 if (!isset($block->version)) {
a9c75a9c 1024 $notices[] = 'Block '. $blockname .': has no version support. It must be updated by a programmer.';
0f3fe4b6 1025 continue;
1026 }
1027
1028 $block->name = $blockname; // The name MUST match the directory
1029 $blocktitle = $blockobj->get_title();
1030
9b4b78fd 1031 if ($currblock = get_record('block', 'name', $block->name)) {
0f3fe4b6 1032 if ($currblock->version == $block->version) {
1033 // do nothing
1034 } else if ($currblock->version < $block->version) {
1035 if (empty($updated_blocks)) {
a9c75a9c 1036 $strblocksetup = get_string('blocksetup');
1037 print_header($strblocksetup, $strblocksetup, $strblocksetup, '', '', false, '&nbsp;', '&nbsp;');
0f3fe4b6 1038 }
b88f7004 1039 print_heading('New version of '.$blocktitle.' ('.$block->name.') exists');
1040 $upgrade_function = $block->name.'_upgrade';
0f3fe4b6 1041 if (function_exists($upgrade_function)) {
1042 $db->debug=true;
1043 if ($upgrade_function($currblock->version, $block)) {
b88f7004 1044
1045 $upgradesuccess = true;
0f3fe4b6 1046 } else {
b88f7004 1047 $upgradesuccess = false;
1048 }
1049 $db->debug=false;
1050 }
1051 else {
1052 $upgradesuccess = true;
1053 }
1054 if(!$upgradesuccess) {
a9c75a9c 1055 notify('Upgrading block '. $block->name .' from '. $currblock->version .' to '. $block->version .' FAILED!');
b88f7004 1056 }
1057 else {
9b4b78fd 1058 // OK so far, now update the block record
b88f7004 1059 $block->id = $currblock->id;
9b4b78fd 1060 if (! update_record('block', $block)) {
a9c75a9c 1061 error('Could not update block '. $block->name .' record in block table!');
0f3fe4b6 1062 }
c7a9e293 1063 notify(get_string('blocksuccess', '', $blocktitle), 'notifysuccess');
b88f7004 1064 echo '<hr />';
0f3fe4b6 1065 }
1066 $updated_blocks = true;
1067 } else {
a9c75a9c 1068 error('Version mismatch: block '. $block->name .' can\'t downgrade '. $currblock->version .' -> '. $block->version .'!');
0f3fe4b6 1069 }
1070
1071 } else { // block not installed yet, so install it
1072
9b4b78fd 1073 // If it allows multiples, start with it enabled
1074 $block->multiple = $blockobj->instance_allow_multiple();
f9648e77 1075 if (!empty($blockobj->cron)) {
1076 $block->cron = $blockobj->cron;
1077 }
9b4b78fd 1078
0f3fe4b6 1079 // [pj] Normally this would be inline in the if, but we need to
1080 // check for NULL (necessary for 4.0.5 <= PHP < 4.2.0)
1081 $conflictblock = array_search($blocktitle, $blocktitles);
1082 if($conflictblock !== false && $conflictblock !== NULL) {
0f3fe4b6 1083 // Duplicate block titles are not allowed, they confuse people
1084 // AND PHP's associative arrays ;)
1085 error('<strong>Naming conflict</strong>: block <strong>'.$block->name.'</strong> has the same title with an existing block, <strong>'.$conflictblock.'</strong>!');
1086 }
1087 if (empty($updated_blocks)) {
a9c75a9c 1088 $strblocksetup = get_string('blocksetup');
1089 print_header($strblocksetup, $strblocksetup, $strblocksetup, '', '', false, '&nbsp;', '&nbsp;');
0f3fe4b6 1090 }
1091 print_heading($block->name);
1092 $updated_blocks = true;
1093 $db->debug = true;
a71bfa1c 1094 @set_time_limit(0); // To allow slow databases to complete the long SQL
a9c75a9c 1095 if (!is_dir($fullblock .'/db/') || modify_database($fullblock .'/db/'. $CFG->dbtype .'.sql')) {
0f3fe4b6 1096 $db->debug = false;
9b4b78fd 1097 if ($block->id = insert_record('block', $block)) {
c7a9e293 1098 notify(get_string('blocksuccess', '', $blocktitle), 'notifysuccess');
a9c75a9c 1099 echo '<hr />';
0f3fe4b6 1100 } else {
a9c75a9c 1101 error($block->name .' block could not be added to the block list!');
0f3fe4b6 1102 }
1103 } else {
a9c75a9c 1104 error('Block '. $block->name .' tables could NOT be set up successfully!');
0f3fe4b6 1105 }
1106 }
1107
1108 $blocktitles[$block->name] = $blocktitle;
1109 }
1110
1111 if(!empty($notices)) {
1112 foreach($notices as $notice) {
1113 notify($notice);
1114 }
1115 }
1116
9b4b78fd 1117 // Finally, if we are in the first_install of BLOCKS (this means that we are
1118 // upgrading from Moodle < 1.3), put blocks in all existing courses.
0f3fe4b6 1119 if ($first_install) {
1120 //Iterate over each course
9b4b78fd 1121 if ($courses = get_records('course')) {
0f3fe4b6 1122 foreach ($courses as $course) {
7542a4e5 1123 $page = page_create_object(PAGE_COURSE_VIEW, $course->id);
9b4b78fd 1124 blocks_repopulate_page($page);
0f3fe4b6 1125 }
1126 }
1127 }
1128
e02c35b2 1129 if (!empty($CFG->siteblocksadded)) { /// This is a once-off hack to make a proper upgrade
7542a4e5 1130 $page = page_create_object(PAGE_COURSE_VIEW, SITEID);
9b4b78fd 1131 blocks_repopulate_page($page);
e02c35b2 1132 delete_records('config', 'name', 'siteblocksadded');
1133 }
1134
0f3fe4b6 1135 if (!empty($updated_blocks)) {
1136 print_continue($continueto);
1137 die;
1138 }
1139}
1140
0f3fe4b6 1141?>