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