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