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