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