Utilizing page_id_and_class(), make a factory function page_create_instance()
[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) {
1345403a 75 $retval->_load_instance($instance);
9b4b78fd 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
febeb161 85 include_once($CFG->dirroot.'/blocks/moodleblock.class.php');
e89d741a 86 $classname = 'block_'.$blockname;
febeb161 87 include_once($CFG->dirroot.'/blocks/'.$blockname.'/block_'.$blockname.'.php');
0f3fe4b6 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() );
1345403a 224 $obj->_add_edit_controls($options);
9b4b78fd 225 }
0f3fe4b6 226
9b4b78fd 227 if(!$instance->visible) {
228 if($isediting) {
1345403a 229 $obj->_print_shadow();
0f3fe4b6 230 }
231 }
9b4b78fd 232 else {
1345403a 233 $obj->_print_block();
9b4b78fd 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)) {
c6a2a401 266 $cache = get_records('block', '', '', 'name');
9b4b78fd 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
da71112b 481// You can use this to get the blocks to respond to URL actions without much hassle
482function blocks_execute_url_action(&$PAGE, &$pageblocks) {
483 $blockaction = optional_param('blockaction');
484
3edc57e1 485 if (empty($blockaction) || !$PAGE->user_allowed_editing() || !confirm_sesskey()) {
da71112b 486 return;
487 }
488
489 $instanceid = optional_param('instanceid', 0, PARAM_INT);
490 $blockid = optional_param('blockid', 0, PARAM_INT);
491
492 if (!empty($blockid)) {
493 blocks_execute_action($PAGE, $pageblocks, strtolower($blockaction), $blockid);
494
495 }
496 else if (!empty($instanceid)) {
497 $instance = blocks_find_instance($instanceid, $pageblocks);
498 blocks_execute_action($PAGE, $pageblocks, strtolower($blockaction), $instance);
499 }
500}
501
f032aa7a 502// This shouldn't be used externally at all, it's here for use by blocks_execute_action()
503// in order to reduce code repetition.
504function blocks_execute_repositioning(&$instance, $newpos, $newweight) {
505 global $CFG;
506
507 // If it's staying where it is, don't do anything
508 if($newpos == $instance->position) {
509 return;
510 }
511
512 // Close the weight gap we 'll leave behind
513 execute_sql('UPDATE '. $CFG->prefix .'block_instance SET weight = weight - 1 WHERE pagetype = \''. $instance->pagetype.
514 '\' AND pageid = '. $instance->pageid .' AND position = \'' .$instance->position.
515 '\' AND weight > '. $instance->weight,
516 false);
517
518 $instance->position = $newpos;
519 $instance->weight = $newweight;
520
521 update_record('block_instance', $instance);
0f3fe4b6 522}
523
9b4b78fd 524function blocks_get_by_page($page) {
f032aa7a 525 $blocks = get_records_select('block_instance', 'pageid = '. $page->get_id() .' AND pagetype = \''. $page->get_type() .'\'', 'position, weight');
526
527 $positions = $page->blocks_get_positions();
528 $arr = array();
529 foreach($positions as $key => $position) {
530 $arr[$position] = array();
531 }
0f3fe4b6 532
9b4b78fd 533 if(empty($blocks)) {
534 return $arr;
535 }
0f3fe4b6 536
9b4b78fd 537 foreach($blocks as $block) {
538 $arr[$block->position][$block->weight] = $block;
0f3fe4b6 539 }
540
9b4b78fd 541 return $arr;
542}
0f3fe4b6 543
9b4b78fd 544//This function prints the block to admin blocks as necessary
545function blocks_print_adminblock($page, $missingblocks) {
546 global $USER;
0f3fe4b6 547
9b4b78fd 548 $strblocks = get_string('blocks');
549 $stradd = get_string('add');
550 if (!empty($missingblocks)) {
551 foreach ($missingblocks as $blockid) {
552 $block = blocks_get_record($blockid);
9b4b78fd 553 $blockobject = block_instance($block->name);
554 if ($blockobject === false) {
555 continue;
556 }
557 $menu[$block->id] = $blockobject->get_title();
558 }
0f3fe4b6 559
f032aa7a 560 $target = $page->url_get_full(array('sesskey' => $USER->sesskey, 'blockaction' => 'add'));
561 $content = popup_form($target.'&amp;blockid=', $menu, 'add_block', '', $stradd .'...', '', '', true);
562 $content = '<div style="text-align: center;">'. $content .'</div>';
9b4b78fd 563 print_side_block($strblocks, $content, NULL, NULL, NULL);
0f3fe4b6 564 }
0f3fe4b6 565}
566
9b4b78fd 567function blocks_repopulate_page($page) {
568 global $CFG;
5b224948 569
9b4b78fd 570 $allblocks = blocks_get_record();
571
572 if(empty($allblocks)) {
573 error('Could not retrieve blocks from the database');
574 }
575
f032aa7a 576 // Assemble the information to correlate block names to ids
9b4b78fd 577 $idforname = array();
578 foreach($allblocks as $block) {
579 $idforname[$block->name] = $block->id;
580 }
581
f032aa7a 582 /// If the site override has been defined, it is the only valid one.
583 if (!empty($CFG->defaultblocks_override)) {
584 $blocknames = $CFG->defaultblocks_override;
585 }
586 else {
587 $blocknames = $page->blocks_get_default();
588 }
589
590 $positions = $page->blocks_get_positions();
591 $posblocks = explode(':', $blocknames);
592
593 // Now one array holds the names of the positions, and the other one holds the blocks
594 // that are going to go in each position. Luckily for us, both arrays are numerically
595 // indexed and the indexes match, so we can work straight away... but CAREFULLY!
9b4b78fd 596
f032aa7a 597 // Ready to start creating block instances, but first drop any existing ones
598 delete_records('block_instance', 'pageid', $page->get_id(), 'pagetype', $page->get_type());
599
600 // Here we slyly count $posblocks and NOT $positions. This can actually make a difference
601 // if the textual representation has undefined slots in the end. So we only work with as many
602 // positions were retrieved, not with all the page says it has available.
603 $numpositions = count($posblocks);
604 for($i = 0; $i < $numpositions; ++$i) {
605 $position = $positions[$i];
606 $blocknames = explode(',', $posblocks[$i]);
9b4b78fd 607 $weight = 0;
608 foreach($blocknames as $blockname) {
609 $newinstance = new stdClass;
610 $newinstance->blockid = $idforname[$blockname];
f032aa7a 611 $newinstance->pageid = $page->get_id();
612 $newinstance->pagetype = $page->get_type();
9b4b78fd 613 $newinstance->position = $position;
614 $newinstance->weight = $weight;
615 $newinstance->visible = 1;
616 $newinstance->configdata = '';
3cacefda 617
618 if(!empty($newinstance->blockid)) {
619 // Only add block if it was recognized
620 insert_record('block_instance', $newinstance);
621 ++$weight;
622 }
0f3fe4b6 623 }
624 }
9b4b78fd 625
626 return true;
0f3fe4b6 627}
628
629function upgrade_blocks_db($continueto) {
630/// This function upgrades the blocks tables, if necessary
631/// It's called from admin/index.php
632
633 global $CFG, $db;
634
a9c75a9c 635 require_once ($CFG->dirroot .'/blocks/version.php'); // Get code versions
0f3fe4b6 636
637 if (empty($CFG->blocks_version)) { // Blocks have never been installed.
a9c75a9c 638 $strdatabaseupgrades = get_string('databaseupgrades');
0f3fe4b6 639 print_header($strdatabaseupgrades, $strdatabaseupgrades, $strdatabaseupgrades,
a9c75a9c 640 '', '', false, '&nbsp;', '&nbsp;');
0f3fe4b6 641
642 $db->debug=true;
a9c75a9c 643 if (modify_database($CFG->dirroot .'/blocks/db/'. $CFG->dbtype .'.sql')) {
0f3fe4b6 644 $db->debug = false;
a9c75a9c 645 if (set_config('blocks_version', $blocks_version)) {
646 notify(get_string('databasesuccess'), 'green');
647 notify(get_string('databaseupgradeblocks', '', $blocks_version));
0f3fe4b6 648 print_continue($continueto);
649 exit;
650 } else {
a9c75a9c 651 error('Upgrade of blocks system failed! (Could not update version in config table)');
0f3fe4b6 652 }
653 } else {
a9c75a9c 654 error('Blocks tables could NOT be set up successfully!');
0f3fe4b6 655 }
656 }
657
658
659 if ($blocks_version > $CFG->blocks_version) { // Upgrade tables
a9c75a9c 660 $strdatabaseupgrades = get_string('databaseupgrades');
0f3fe4b6 661 print_header($strdatabaseupgrades, $strdatabaseupgrades, $strdatabaseupgrades);
662
a9c75a9c 663 require_once ($CFG->dirroot .'/blocks/db/'. $CFG->dbtype .'.php');
0f3fe4b6 664
665 $db->debug=true;
666 if (blocks_upgrade($CFG->blocks_version)) {
667 $db->debug=false;
a9c75a9c 668 if (set_config('blocks_version', $blocks_version)) {
669 notify(get_string('databasesuccess'), 'green');
670 notify(get_string('databaseupgradeblocks', '', $blocks_version));
0f3fe4b6 671 print_continue($continueto);
672 exit;
673 } else {
a9c75a9c 674 error('Upgrade of blocks system failed! (Could not update version in config table)');
0f3fe4b6 675 }
676 } else {
677 $db->debug=false;
a9c75a9c 678 error('Upgrade failed! See blocks/version.php');
0f3fe4b6 679 }
680
681 } else if ($blocks_version < $CFG->blocks_version) {
a9c75a9c 682 notify('WARNING!!! The code you are using is OLDER than the version that made these databases!');
0f3fe4b6 683 }
684}
685
686//This function finds all available blocks and install them
687//into blocks table or do all the upgrade process if newer
688function upgrade_blocks_plugins($continueto) {
689
690 global $CFG;
691
692 $blocktitles = array();
693 $invalidblocks = array();
694 $validblocks = array();
695 $notices = array();
696
697 //Count the number of blocks in db
9b4b78fd 698 $blockcount = count_records('block');
0f3fe4b6 699 //If there isn't records. This is the first install, so I remember it
700 if ($blockcount == 0) {
701 $first_install = true;
702 } else {
703 $first_install = false;
704 }
705
706 $site = get_site();
707
9b4b78fd 708 if (!$blocks = get_list_of_plugins('blocks', 'db') ) {
a9c75a9c 709 error('No blocks installed!');
0f3fe4b6 710 }
711
a9c75a9c 712 include_once($CFG->dirroot .'/blocks/moodleblock.class.php');
e89d741a 713 if(!class_exists('block_base')) {
714 error('Class block_base is not defined or file not found for /blocks/moodleblock.class.php');
0f3fe4b6 715 }
716
717 foreach ($blocks as $blockname) {
718
a9c75a9c 719 if ($blockname == 'NEWBLOCK') { // Someone has unzipped the template, ignore it
0f3fe4b6 720 continue;
721 }
722
a9c75a9c 723 $fullblock = $CFG->dirroot .'/blocks/'. $blockname;
0f3fe4b6 724
9b4b78fd 725 if ( is_readable($fullblock.'/block_'.$blockname.'.php')) {
726 include_once($fullblock.'/block_'.$blockname.'.php');
0f3fe4b6 727 } else {
a9c75a9c 728 $notices[] = 'Block '. $blockname .': '. $fullblock .'/block_'. $blockname .'.php was not readable';
0f3fe4b6 729 continue;
730 }
731
a9c75a9c 732 if ( @is_dir($fullblock .'/db/')) {
733 if ( @is_readable($fullblock .'/db/'. $CFG->dbtype .'.php')) {
89a5baab 734 include_once($fullblock .'/db/'. $CFG->dbtype .'.php'); // defines upgrading function
828c4e09 735 } else {
a9c75a9c 736 $notices[] ='Block '. $blockname .': '. $fullblock .'/db/'. $CFG->dbtype .'.php was not readable';
828c4e09 737 continue;
738 }
0f3fe4b6 739 }
740
e89d741a 741 $classname = 'block_'.$blockname;
0f3fe4b6 742 if(!class_exists($classname)) {
a9c75a9c 743 $notices[] = 'Block '. $blockname .': '. $classname .' not implemented';
0f3fe4b6 744 continue;
745 }
746
9b4b78fd 747 // Here is the place to see if the block implements a constructor (old style),
748 // an init() function (new style) or nothing at all (error time).
749
33bee34c 750 $constructor = get_class_constructor($classname);
751 if(empty($constructor)) {
0f3fe4b6 752 // No constructor
a9c75a9c 753 $notices[] = 'Block '. $blockname .': class does not have a constructor';
0f3fe4b6 754 $invalidblocks[] = $blockname;
755 continue;
756 }
9b4b78fd 757 $methods = get_class_methods($classname);
758 if(!in_array('init', $methods)) {
759 // This is an old-style block
a9c75a9c 760 $notices[] = 'Block '. $blockname .' is an old style block and needs to be updated by a programmer.';
9b4b78fd 761 $invalidblocks[] = $blockname;
762 continue;
763 }
0f3fe4b6 764
9b4b78fd 765 $block = new stdClass; // This may be used to update the db below
766 $blockobj = new $classname; // This is what we 'll be testing
0f3fe4b6 767
e89d741a 768 // Inherits from block_base?
769 if(!is_subclass_of($blockobj, 'block_base')) {
770 $notices[] = 'Block '. $blockname .': class does not inherit from block_base';
0f3fe4b6 771 continue;
772 }
773
774 // OK, it's as we all hoped. For further tests, the object will do them itself.
775 if(!$blockobj->_self_test()) {
a9c75a9c 776 $notices[] = 'Block '. $blockname .': self test failed';
0f3fe4b6 777 continue;
778 }
779 $block->version = $blockobj->get_version();
780
781 if (!isset($block->version)) {
a9c75a9c 782 $notices[] = 'Block '. $blockname .': has no version support. It must be updated by a programmer.';
0f3fe4b6 783 continue;
784 }
785
786 $block->name = $blockname; // The name MUST match the directory
787 $blocktitle = $blockobj->get_title();
788
9b4b78fd 789 if ($currblock = get_record('block', 'name', $block->name)) {
0f3fe4b6 790 if ($currblock->version == $block->version) {
791 // do nothing
792 } else if ($currblock->version < $block->version) {
793 if (empty($updated_blocks)) {
a9c75a9c 794 $strblocksetup = get_string('blocksetup');
795 print_header($strblocksetup, $strblocksetup, $strblocksetup, '', '', false, '&nbsp;', '&nbsp;');
0f3fe4b6 796 }
b88f7004 797 print_heading('New version of '.$blocktitle.' ('.$block->name.') exists');
798 $upgrade_function = $block->name.'_upgrade';
0f3fe4b6 799 if (function_exists($upgrade_function)) {
800 $db->debug=true;
801 if ($upgrade_function($currblock->version, $block)) {
b88f7004 802
803 $upgradesuccess = true;
0f3fe4b6 804 } else {
b88f7004 805 $upgradesuccess = false;
806 }
807 $db->debug=false;
808 }
809 else {
810 $upgradesuccess = true;
811 }
812 if(!$upgradesuccess) {
a9c75a9c 813 notify('Upgrading block '. $block->name .' from '. $currblock->version .' to '. $block->version .' FAILED!');
b88f7004 814 }
815 else {
9b4b78fd 816 // OK so far, now update the block record
b88f7004 817 $block->id = $currblock->id;
9b4b78fd 818 if (! update_record('block', $block)) {
a9c75a9c 819 error('Could not update block '. $block->name .' record in block table!');
0f3fe4b6 820 }
b88f7004 821 notify(get_string('blocksuccess', '', $blocktitle), 'green');
822 echo '<hr />';
0f3fe4b6 823 }
824 $updated_blocks = true;
825 } else {
a9c75a9c 826 error('Version mismatch: block '. $block->name .' can\'t downgrade '. $currblock->version .' -> '. $block->version .'!');
0f3fe4b6 827 }
828
829 } else { // block not installed yet, so install it
830
9b4b78fd 831 // If it allows multiples, start with it enabled
832 $block->multiple = $blockobj->instance_allow_multiple();
833
0f3fe4b6 834 // [pj] Normally this would be inline in the if, but we need to
835 // check for NULL (necessary for 4.0.5 <= PHP < 4.2.0)
836 $conflictblock = array_search($blocktitle, $blocktitles);
837 if($conflictblock !== false && $conflictblock !== NULL) {
0f3fe4b6 838 // Duplicate block titles are not allowed, they confuse people
839 // AND PHP's associative arrays ;)
840 error('<strong>Naming conflict</strong>: block <strong>'.$block->name.'</strong> has the same title with an existing block, <strong>'.$conflictblock.'</strong>!');
841 }
842 if (empty($updated_blocks)) {
a9c75a9c 843 $strblocksetup = get_string('blocksetup');
844 print_header($strblocksetup, $strblocksetup, $strblocksetup, '', '', false, '&nbsp;', '&nbsp;');
0f3fe4b6 845 }
846 print_heading($block->name);
847 $updated_blocks = true;
848 $db->debug = true;
a71bfa1c 849 @set_time_limit(0); // To allow slow databases to complete the long SQL
a9c75a9c 850 if (!is_dir($fullblock .'/db/') || modify_database($fullblock .'/db/'. $CFG->dbtype .'.sql')) {
0f3fe4b6 851 $db->debug = false;
9b4b78fd 852 if ($block->id = insert_record('block', $block)) {
0f3fe4b6 853 notify(get_string('blocksuccess', '', $blocktitle), 'green');
a9c75a9c 854 echo '<hr />';
0f3fe4b6 855 } else {
a9c75a9c 856 error($block->name .' block could not be added to the block list!');
0f3fe4b6 857 }
858 } else {
a9c75a9c 859 error('Block '. $block->name .' tables could NOT be set up successfully!');
0f3fe4b6 860 }
861 }
862
863 $blocktitles[$block->name] = $blocktitle;
864 }
865
866 if(!empty($notices)) {
867 foreach($notices as $notice) {
868 notify($notice);
869 }
870 }
871
9b4b78fd 872 // Finally, if we are in the first_install of BLOCKS (this means that we are
873 // upgrading from Moodle < 1.3), put blocks in all existing courses.
0f3fe4b6 874 if ($first_install) {
875 //Iterate over each course
9b4b78fd 876 if ($courses = get_records('course')) {
0f3fe4b6 877 foreach ($courses as $course) {
7542a4e5 878 $page = page_create_object(PAGE_COURSE_VIEW, $course->id);
9b4b78fd 879 blocks_repopulate_page($page);
0f3fe4b6 880 }
881 }
882 }
883
e02c35b2 884 if (!empty($CFG->siteblocksadded)) { /// This is a once-off hack to make a proper upgrade
7542a4e5 885 $page = page_create_object(PAGE_COURSE_VIEW, SITEID);
9b4b78fd 886 blocks_repopulate_page($page);
e02c35b2 887 delete_records('config', 'name', 'siteblocksadded');
888 }
889
0f3fe4b6 890 if (!empty($updated_blocks)) {
891 print_continue($continueto);
892 die;
893 }
894}
895
0f3fe4b6 896?>