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