dropping studentcanpost in glossary, MDL_7170
[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
ee6055eb 14define('BLOCKS_PINNED_TRUE',0);
15define('BLOCKS_PINNED_FALSE',1);
16define('BLOCKS_PINNED_BOTH',2);
17
f032aa7a 18require_once($CFG->libdir.'/pagelib.php');
8ad22079 19require_once($CFG->dirroot.'/course/lib.php'); // needed to solve all those: Call to undefined function: print_recent_activity() when adding Recent Activity
61abc65b 20
21// Returns false if this block is incompatible with the current version of Moodle.
22function block_is_compatible($blockname) {
23 global $CFG;
24
e9a20759 25 $file = @file($CFG->dirroot.'/blocks/'.$blockname.'/block_'.$blockname.'.php'); // ignore errors when file does not exist
61abc65b 26 if(empty($file)) {
27 return NULL;
28 }
29
30 foreach($file as $line) {
31 // If you find MoodleBlock (appearing in the class declaration) it's not compatible
32 if(strpos($line, 'MoodleBlock')) {
33 return false;
34 }
35 // But if we find a { it means the class declaration is over, so it's compatible
36 else if(strpos($line, '{')) {
37 return true;
38 }
39 }
40
41 return NULL;
42}
43
33bee34c 44// Returns the case-sensitive name of the class' constructor function. This includes both
45// PHP5- and PHP4-style constructors. If no appropriate constructor can be found, returns NULL.
46// If there is no such class, returns boolean false.
47function get_class_constructor($classname) {
48 // Caching
49 static $constructors = array();
50
51 if(!class_exists($classname)) {
52 return false;
53 }
54
55 // Tests indicate this doesn't hurt even in PHP5.
56 $classname = strtolower($classname);
57
58 // Return cached value, if exists
59 if(isset($constructors[$classname])) {
60 return $constructors[$classname];
61 }
62
63 // Get a list of methods. After examining several different ways of
64 // doing the check, (is_callable, method_exists, function_exists etc)
65 // it seems that this is the most reliable one.
66 $methods = get_class_methods($classname);
67
68 // PHP5 constructor?
69 if(phpversion() >= '5') {
70 if(in_array('__construct', $methods)) {
71 return $constructors[$classname] = '__construct';
72 }
73 }
74
75 // If we have PHP5 but no magic constructor, we have to lowercase the methods
76 $methods = array_map('strtolower', $methods);
77
78 if(in_array($classname, $methods)) {
79 return $constructors[$classname] = $classname;
80 }
81
82 return $constructors[$classname] = NULL;
83}
84
0f3fe4b6 85//This function retrieves a method-defined property of a class WITHOUT instantiating an object
11306331 86function block_method_result($blockname, $method, $param = NULL) {
0f3fe4b6 87 if(!block_load_class($blockname)) {
88 return NULL;
89 }
11306331 90 return call_user_func(array('block_'.$blockname, $method), $param);
0f3fe4b6 91}
92
93//This function creates a new object of the specified block class
9b4b78fd 94function block_instance($blockname, $instance = NULL) {
0f3fe4b6 95 if(!block_load_class($blockname)) {
96 return false;
97 }
e89d741a 98 $classname = 'block_'.$blockname;
f032aa7a 99 $retval = new $classname;
9b4b78fd 100 if($instance !== NULL) {
1345403a 101 $retval->_load_instance($instance);
9b4b78fd 102 }
103 return $retval;
0f3fe4b6 104}
105
106//This function loads the necessary class files for a block
107//Whenever you want to load a block, use this first
108function block_load_class($blockname) {
109 global $CFG;
110
a9033ad5 111 if(empty($blockname)) {
c7a9e293 112 return false;
113 }
114
e89d741a 115 $classname = 'block_'.$blockname;
a9033ad5 116
117 if(class_exists($classname)) {
118 return true;
119 }
120
121 require_once($CFG->dirroot.'/blocks/moodleblock.class.php');
e9a20759 122 @include_once($CFG->dirroot.'/blocks/'.$blockname.'/block_'.$blockname.'.php'); // do not throw errors if block code not present
0f3fe4b6 123
0f3fe4b6 124 return class_exists($classname);
125}
126
c8e0b579 127// This function returns an array with the IDs of any blocks that you can add to your page.
128// Parameters are passed by reference for speed; they are not modified at all.
129function blocks_get_missing(&$page, &$pageblocks) {
f032aa7a 130
131 $missingblocks = array();
132 $allblocks = blocks_get_record();
133 $pageformat = $page->get_format_name();
134
135 if(!empty($allblocks)) {
136 foreach($allblocks as $block) {
137 if($block->visible && (!blocks_find_block($block->id, $pageblocks) || $block->multiple)) {
138 // And if it's applicable for display in this format...
5bbbe0be 139 if(blocks_name_allowed_in_format($block->name, $pageformat)) {
8a47e075 140 // ...add it to the missing blocks
f032aa7a 141 $missingblocks[] = $block->id;
142 }
143 }
144 }
145 }
146 return $missingblocks;
147}
148
149function blocks_remove_inappropriate($page) {
150 $pageblocks = blocks_get_by_page($page);
151
152 if(empty($pageblocks)) {
153 return;
154 }
155
156 if(($pageformat = $page->get_format_name()) == NULL) {
157 return;
158 }
159
160 foreach($pageblocks as $position) {
161 foreach($position as $instance) {
162 $block = blocks_get_record($instance->blockid);
5bbbe0be 163 if(!blocks_name_allowed_in_format($block->name, $pageformat)) {
8a47e075 164 blocks_delete_instance($instance);
f032aa7a 165 }
166 }
167 }
168}
169
5bbbe0be 170function blocks_name_allowed_in_format($name, $pageformat) {
171 $formats = block_method_result($name, 'applicable_formats');
172 $accept = NULL;
173 $depth = -1;
1bece917 174 if (isset($formats)) {
175 foreach($formats as $format => $allowed) {
176 $thisformat = '^'.str_replace('*', '[^-]*', $format).'.*$';
177 if(ereg($thisformat, $pageformat)) {
178 if(($scount = substr_count($format, '-')) > $depth) {
179 $depth = $scount;
180 $accept = $allowed;
181 }
182 }
5bbbe0be 183 }
184 }
185 if($accept === NULL) {
186 $accept = !empty($formats['all']);
187 }
188 return $accept;
189}
190
0d6b9d4f 191function blocks_delete_instance($instance,$pinned=false) {
f032aa7a 192 global $CFG;
193
e9a20759 194 // Get the block object and call instance_delete() if possible
b33dd23a 195 if(!$record = blocks_get_record($instance->blockid)) {
e9a20759 196 if(!$obj = block_instance($record->name, $instance)) {
197 // Return value ignored
198 $obj->instance_delete();
199 }
b33dd23a 200 }
201
0d6b9d4f 202 if (!empty($pinned)) {
203 delete_records('block_pinned', 'id', $instance->id);
204 // And now, decrement the weight of all blocks after this one
205 execute_sql('UPDATE '.$CFG->prefix.'block_pinned SET weight = weight - 1 WHERE pagetype = \''.$instance->pagetype.
206 '\' AND position = \''.$instance->position.
207 '\' AND weight > '.$instance->weight, false);
208 } else {
209 // Now kill the db record;
210 delete_records('block_instance', 'id', $instance->id);
211 // And now, decrement the weight of all blocks after this one
212 execute_sql('UPDATE '.$CFG->prefix.'block_instance SET weight = weight - 1 WHERE pagetype = \''.$instance->pagetype.
213 '\' AND pageid = '.$instance->pageid.' AND position = \''.$instance->position.
214 '\' AND weight > '.$instance->weight, false);
215 }
2e477369 216 return true;
f032aa7a 217}
218
c8e0b579 219// Accepts an array of block instances and checks to see if any of them have content to display
220// (causing them to calculate their content in the process). Returns true or false. Parameter passed
221// by reference for speed; the array is actually not modified.
dffd4bb9 222function blocks_have_content(&$pageblocks, $position) {
0d6b9d4f 223
224 if (empty($pageblocks) || !is_array($pageblocks) || !array_key_exists($position,$pageblocks)) {
225 return false;
226 }
66c7e47b 227 // use a for() loop to get references to the array elements
228 // foreach() cannot fetch references in PHP v4.x
229 for ($n=0; $n<count($pageblocks[$position]);$n++) {
230 $instance = &$pageblocks[$position][$n];
3ef642d9 231 if(!$instance->visible) {
7933cc6b 232 continue;
233 }
3ef642d9 234 if(!$record = blocks_get_record($instance->blockid)) {
7933cc6b 235 continue;
236 }
3ef642d9 237 if(!$obj = block_instance($record->name, $instance)) {
9b4b78fd 238 continue;
239 }
3ef642d9 240 if(!$obj->is_empty()) {
66c7e47b 241 // cache rec and obj
242 // for blocks_print_group()
b1a308be 243 $instance->rec = $record;
66c7e47b 244 $instance->obj = $obj;
3ef642d9 245 return true;
0f3fe4b6 246 }
247 }
9b4b78fd 248
0f3fe4b6 249 return false;
250}
251
c8e0b579 252// This function prints one group of blocks in a page
253// Parameters passed by reference for speed; they are not modified.
66492322 254function blocks_print_group(&$page, &$pageblocks, $position) {
0a0bb380 255 global $COURSE;
66492322 256
257 if(empty($pageblocks[$position])) {
3f052187 258 $pageblocks[$position] = array();
b35fc182 259 $maxweight = 0;
260 }
261 else {
262 $maxweight = max(array_keys($pageblocks[$position]));
9b4b78fd 263 }
3cdc4597 264
265 foreach ($pageblocks[$position] as $instance) {
4374ee2c 266 if (!empty($instance->pinned)) {
267 $maxweight--;
268 }
269 }
0f3fe4b6 270
f032aa7a 271 $isediting = $page->user_is_editing();
0f3fe4b6 272
66492322 273 foreach($pageblocks[$position] as $instance) {
66c7e47b 274
275 // $instance may have ->rec and ->obj
276 // cached from when we walked $pageblocks
277 // in blocks_have_content()
278 if (empty($instance->rec)) {
279 $block = blocks_get_record($instance->blockid);
280 } else {
281 $block = $instance->rec;
282 }
f809df70 283
284 if (empty($block)) {
285 // Block doesn't exist! We should delete this instance!
286 continue;
287 }
288
9b4b78fd 289 if(!$block->visible) {
290 // Disabled by the admin
291 continue;
292 }
66c7e47b 293
294 if (empty($instance->obj)) {
295 if (!$obj = block_instance($block->name, $instance)) {
296 // Invalid block
297 continue;
298 }
299 } else {
300 $obj = $instance->obj;
ab0e4dd4 301 }
0f3fe4b6 302
4374ee2c 303 $editalways = $page->edit_always();
0d6b9d4f 304
305 if (($isediting && empty($instance->pinned)) || !empty($editalways)) {
9b4b78fd 306 $options = 0;
f032aa7a 307 // 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:
308 // the first block might still be able to move up if the page says so (i.e., it will change position)
309 $options |= BLOCK_MOVE_UP * ($instance->weight != 0 || ($page->blocks_move_position($instance, BLOCK_MOVE_UP) != $instance->position));
310 // Same thing for downward movement
311 $options |= BLOCK_MOVE_DOWN * ($instance->weight != $maxweight || ($page->blocks_move_position($instance, BLOCK_MOVE_DOWN) != $instance->position));
312 // For left and right movements, it's up to the page to tell us whether they are allowed
313 $options |= BLOCK_MOVE_RIGHT * ($page->blocks_move_position($instance, BLOCK_MOVE_RIGHT) != $instance->position);
314 $options |= BLOCK_MOVE_LEFT * ($page->blocks_move_position($instance, BLOCK_MOVE_LEFT ) != $instance->position);
315 // Finally, the block can be configured if the block class either allows multiple instances, or if it specifically
316 // allows instance configuration (multiple instances override that one). It doesn't have anything to do with what the
317 // administrator has allowed for this block in the site admin options.
318 $options |= BLOCK_CONFIGURE * ( $obj->instance_allow_multiple() || $obj->instance_allow_config() );
1345403a 319 $obj->_add_edit_controls($options);
9b4b78fd 320 }
0f3fe4b6 321
0a0bb380 322 if (!$instance->visible && empty($COURSE->javascriptportal)) {
323 if ($isediting) {
1345403a 324 $obj->_print_shadow();
0f3fe4b6 325 }
0a0bb380 326 } else {
4a1a14c9 327 global $COURSE;
328 if(!empty($COURSE->javascriptportal))
329 $COURSE->javascriptportal->currentblocksection = $position;
1345403a 330 $obj->_print_block();
4a1a14c9 331
9b4b78fd 332 }
0f3fe4b6 333 }
66492322 334
0a0bb380 335 if ($page->blocks_default_position() == $position && $page->user_is_editing()) {
66492322 336 blocks_print_adminblock($page, $pageblocks);
337 }
338
0f3fe4b6 339}
340
c8e0b579 341// This iterates over an array of blocks and calculates the preferred width
342// Parameter passed by reference for speed; it's not modified.
343function blocks_preferred_width(&$instances) {
0f3fe4b6 344 $width = 0;
345
9b4b78fd 346 if(empty($instances) || !is_array($instances)) {
0f3fe4b6 347 return 0;
348 }
ff6191b7 349
350 $blocks = blocks_get_record();
351
9b4b78fd 352 foreach($instances as $instance) {
353 if(!$instance->visible) {
fe78a3dc 354 continue;
0c9c6363 355 }
ff6191b7 356
f809df70 357 if (!array_key_exists($instance->blockid, $blocks)) {
358 // Block doesn't exist! We should delete this instance!
359 continue;
360 }
361
ff6191b7 362 if(!$blocks[$instance->blockid]->visible) {
9b687320 363 continue;
364 }
ff6191b7 365 $pref = block_method_result($blocks[$instance->blockid]->name, 'preferred_width');
9b4b78fd 366 if($pref === NULL) {
367 continue;
368 }
369 if($pref > $width) {
370 $width = $pref;
0f3fe4b6 371 }
372 }
373 return $width;
374}
375
9b4b78fd 376function blocks_get_record($blockid = NULL, $invalidate = false) {
377 static $cache = NULL;
0f3fe4b6 378
9b4b78fd 379 if($invalidate || empty($cache)) {
eca3b01f 380 $cache = get_records('block');
9b4b78fd 381 }
0f3fe4b6 382
9b4b78fd 383 if($blockid === NULL) {
384 return $cache;
385 }
0f3fe4b6 386
9b4b78fd 387 return (isset($cache[$blockid])? $cache[$blockid] : false);
388}
389
390function blocks_find_block($blockid, $blocksarray) {
0d6b9d4f 391 if (empty($blocksarray)) {
392 return false;
393 }
9b4b78fd 394 foreach($blocksarray as $blockgroup) {
0d6b9d4f 395 if (empty($blockgroup)) {
396 continue;
397 }
9b4b78fd 398 foreach($blockgroup as $instance) {
399 if($instance->blockid == $blockid) {
400 return $instance;
401 }
402 }
403 }
404 return false;
405}
406
407function blocks_find_instance($instanceid, $blocksarray) {
408 foreach($blocksarray as $subarray) {
409 foreach($subarray as $instance) {
410 if($instance->id == $instanceid) {
411 return $instance;
412 }
413 }
414 }
415 return false;
416}
417
ec79d3e4 418// Simple entry point for anyone that wants to use blocks
ee6055eb 419function blocks_setup(&$PAGE,$pinned=BLOCKS_PINNED_FALSE) {
420 switch ($pinned) {
421 case BLOCKS_PINNED_TRUE:
422 $pageblocks = blocks_get_pinned($PAGE);
423 break;
424 case BLOCKS_PINNED_BOTH:
425 $pageblocks = blocks_get_by_page_pinned($PAGE);
426 break;
427 case BLOCKS_PINNED_FALSE:
428 default:
429 $pageblocks = blocks_get_by_page($PAGE);
430 break;
431 }
432 blocks_execute_url_action($PAGE, $pageblocks,($pinned==BLOCKS_PINNED_TRUE));
ec79d3e4 433 return $pageblocks;
434}
435
b1631fef 436function blocks_execute_action($page, &$pageblocks, $blockaction, $instanceorid, $pinned=false, $redirect=true) {
9b4b78fd 437 global $CFG;
438
a9c75a9c 439 if (is_int($instanceorid)) {
9b4b78fd 440 $blockid = $instanceorid;
a9c75a9c 441 } else if (is_object($instanceorid)) {
9b4b78fd 442 $instance = $instanceorid;
443 }
0f3fe4b6 444
445 switch($blockaction) {
9b4b78fd 446 case 'config':
f032aa7a 447 global $USER;
9b4b78fd 448 $block = blocks_get_record($instance->blockid);
e82d6cac 449 // Hacky hacky tricky stuff to get the original human readable block title,
450 // even if the block has configured its title to be something else.
451 // Create the object WITHOUT instance data.
452 $blockobject = block_instance($block->name);
9b4b78fd 453 if ($blockobject === false) {
11306331 454 break;
455 }
456
457 // First of all check to see if the block wants to be edited
458 if(!$blockobject->user_can_edit()) {
459 break;
9b4b78fd 460 }
11306331 461
e82d6cac 462 // Now get the title and AFTER that load up the instance
463 $blocktitle = $blockobject->get_title();
464 $blockobject->_load_instance($instance);
465
9b4b78fd 466 optional_param('submitted', 0, PARAM_INT);
467
27ec21a0 468 // Define the data we're going to silently include in the instance config form here,
9b4b78fd 469 // so we can strip them from the submitted data BEFORE serializing it.
470 $hiddendata = array(
471 'sesskey' => $USER->sesskey,
9b4b78fd 472 'instanceid' => $instance->id,
473 'blockaction' => 'config'
474 );
f032aa7a 475
476 // To this data, add anything the page itself needs to display
477 $hiddendata = array_merge($hiddendata, $page->url_get_parameters());
9b4b78fd 478
479 if($data = data_submitted()) {
480 $remove = array_keys($hiddendata);
481 foreach($remove as $item) {
482 unset($data->$item);
0f3fe4b6 483 }
0d6b9d4f 484 if(!$blockobject->instance_config_save($data,$pinned)) {
9b4b78fd 485 error('Error saving block configuration');
0f3fe4b6 486 }
9b4b78fd 487 // And nothing more, continue with displaying the page
0f3fe4b6 488 }
9b4b78fd 489 else {
f032aa7a 490 // We need to show the config screen, so we highjack the display logic and then die
e82d6cac 491 $strheading = get_string('blockconfiga', 'moodle', $blocktitle);
edb42f09 492 $page->print_header(get_string('pageheaderconfigablock', 'moodle'), array($strheading => ''));
b9709905 493
494 echo '<div class="block-config" id="'.$block->name.'">'; /// Make CSS easier
495
edb42f09 496 print_heading($strheading);
f032aa7a 497 echo '<form method="post" action="'. $page->url_get_path() .'">';
9b4b78fd 498 echo '<p>';
499 foreach($hiddendata as $name => $val) {
27ec21a0 500 echo '<input type="hidden" name="'. $name .'" value="'. $val .'" />';
0f3fe4b6 501 }
9b4b78fd 502 echo '</p>';
503 $blockobject->instance_config_print();
504 echo '</form>';
b9709905 505
506 echo '</div>';
a2c28054 507 $CFG->pagepath = 'blocks/' . $block->name;
9b4b78fd 508 print_footer();
f032aa7a 509 die(); // Do not go on with the other page-related stuff
0f3fe4b6 510 }
511 break;
9b4b78fd 512 case 'toggle':
513 if(empty($instance)) {
514 error('Invalid block instance for '.$blockaction);
0f3fe4b6 515 }
9b4b78fd 516 $instance->visible = ($instance->visible) ? 0 : 1;
0d6b9d4f 517 if (!empty($pinned)) {
518 update_record('block_pinned', $instance);
519 } else {
520 update_record('block_instance', $instance);
521 }
9b4b78fd 522 break;
523 case 'delete':
524 if(empty($instance)) {
a9c75a9c 525 error('Invalid block instance for '. $blockaction);
0f3fe4b6 526 }
0d6b9d4f 527 blocks_delete_instance($instance, $pinned);
0f3fe4b6 528 break;
529 case 'moveup':
9b4b78fd 530 if(empty($instance)) {
a9c75a9c 531 error('Invalid block instance for '. $blockaction);
9b4b78fd 532 }
f032aa7a 533
534 if($instance->weight == 0) {
535 // The block is the first one, so a move "up" probably means it changes position
536 // Where is the instance going to be moved?
537 $newpos = $page->blocks_move_position($instance, BLOCK_MOVE_UP);
6b853ff4 538 $newweight = (empty($pageblocks[$newpos]) ? 0 : max(array_keys($pageblocks[$newpos])) + 1);
f032aa7a 539
0d6b9d4f 540 blocks_execute_repositioning($instance, $newpos, $newweight, $pinned);
89a5baab 541 }
f032aa7a 542 else {
543 // The block is just moving upwards in the same position.
544 // This configuration will make sure that even if somehow the weights
545 // become not continuous, block move operations will eventually bring
546 // the situation back to normal without printing any warnings.
547 if(!empty($pageblocks[$instance->position][$instance->weight - 1])) {
548 $other = $pageblocks[$instance->position][$instance->weight - 1];
549 }
550 if(!empty($other)) {
551 ++$other->weight;
0d6b9d4f 552 if (!empty($pinned)) {
553 update_record('block_pinned', $other);
554 } else {
555 update_record('block_instance', $other);
556 }
f032aa7a 557 }
558 --$instance->weight;
0d6b9d4f 559 if (!empty($pinned)) {
560 update_record('block_pinned', $instance);
561 } else {
562 update_record('block_instance', $instance);
563 }
0f3fe4b6 564 }
565 break;
566 case 'movedown':
9b4b78fd 567 if(empty($instance)) {
a9c75a9c 568 error('Invalid block instance for '. $blockaction);
9b4b78fd 569 }
f032aa7a 570
571 if($instance->weight == max(array_keys($pageblocks[$instance->position]))) {
572 // The block is the last one, so a move "down" probably means it changes position
573 // Where is the instance going to be moved?
574 $newpos = $page->blocks_move_position($instance, BLOCK_MOVE_DOWN);
6b853ff4 575 $newweight = (empty($pageblocks[$newpos]) ? 0 : max(array_keys($pageblocks[$newpos])) + 1);
f032aa7a 576
0d6b9d4f 577 blocks_execute_repositioning($instance, $newpos, $newweight, $pinned);
89a5baab 578 }
f032aa7a 579 else {
580 // The block is just moving downwards in the same position.
581 // This configuration will make sure that even if somehow the weights
582 // become not continuous, block move operations will eventually bring
583 // the situation back to normal without printing any warnings.
584 if(!empty($pageblocks[$instance->position][$instance->weight + 1])) {
585 $other = $pageblocks[$instance->position][$instance->weight + 1];
586 }
587 if(!empty($other)) {
588 --$other->weight;
0d6b9d4f 589 if (!empty($pinned)) {
590 update_record('block_pinned', $other);
591 } else {
592 update_record('block_instance', $other);
593 }
f032aa7a 594 }
595 ++$instance->weight;
0d6b9d4f 596 if (!empty($pinned)) {
597 update_record('block_pinned', $instance);
598 } else {
599 update_record('block_instance', $instance);
600 }
0f3fe4b6 601 }
602 break;
9b4b78fd 603 case 'moveleft':
604 if(empty($instance)) {
a9c75a9c 605 error('Invalid block instance for '. $blockaction);
9b4b78fd 606 }
f032aa7a 607
608 // Where is the instance going to be moved?
609 $newpos = $page->blocks_move_position($instance, BLOCK_MOVE_LEFT);
6b853ff4 610 $newweight = (empty($pageblocks[$newpos]) ? 0 : max(array_keys($pageblocks[$newpos])) + 1);
f032aa7a 611
0d6b9d4f 612 blocks_execute_repositioning($instance, $newpos, $newweight, $pinned);
0f3fe4b6 613 break;
9b4b78fd 614 case 'moveright':
615 if(empty($instance)) {
a9c75a9c 616 error('Invalid block instance for '. $blockaction);
9b4b78fd 617 }
f032aa7a 618
619 // Where is the instance going to be moved?
620 $newpos = $page->blocks_move_position($instance, BLOCK_MOVE_RIGHT);
6b853ff4 621 $newweight = (empty($pageblocks[$newpos]) ? 0 : max(array_keys($pageblocks[$newpos])) + 1);
f032aa7a 622
0d6b9d4f 623 blocks_execute_repositioning($instance, $newpos, $newweight, $pinned);
9b4b78fd 624 break;
625 case 'add':
626 // Add a new instance of this block, if allowed
627 $block = blocks_get_record($blockid);
0f3fe4b6 628
3cacefda 629 if(empty($block) || !$block->visible) {
630 // Only allow adding if the block exists and is enabled
11306331 631 break;
9b4b78fd 632 }
0f3fe4b6 633
89a5baab 634 if(!$block->multiple && blocks_find_block($blockid, $pageblocks) !== false) {
635 // If no multiples are allowed and we already have one, return now
11306331 636 break;
637 }
638
639 if(!block_method_result($block->name, 'user_can_addto', $page)) {
640 // If the block doesn't want to be added...
641 break;
89a5baab 642 }
643
f032aa7a 644 $newpos = $page->blocks_default_position();
0d6b9d4f 645 if (!empty($pinned)) {
646 $sql = 'SELECT 1, max(weight) + 1 AS nextfree FROM '. $CFG->prefix .'block_pinned WHERE '
647 .' pagetype = \''. $page->get_type() .'\' AND position = \''. $newpos .'\'';
648 } else {
649 $sql = 'SELECT 1, max(weight) + 1 AS nextfree FROM '. $CFG->prefix .'block_instance WHERE pageid = '. $page->get_id()
650 .' AND pagetype = \''. $page->get_type() .'\' AND position = \''. $newpos .'\'';
651 }
652 $weight = get_record_sql($sql);
9b4b78fd 653
654 $newinstance = new stdClass;
655 $newinstance->blockid = $blockid;
0d6b9d4f 656 if (empty($pinned)) {
657 $newinstance->pageid = $page->get_id();
658 }
f032aa7a 659 $newinstance->pagetype = $page->get_type();
660 $newinstance->position = $newpos;
ff679897 661 $newinstance->weight = empty($weight->nextfree) ? 0 : $weight->nextfree;
9b4b78fd 662 $newinstance->visible = 1;
663 $newinstance->configdata = '';
0d6b9d4f 664 if (!empty($pinned)) {
665 $newinstance->id = insert_record('block_pinned', $newinstance);
666 } else {
667 $newinstance->id = insert_record('block_instance', $newinstance);
668 }
b33dd23a 669
670 // If the new instance was created, allow it to do additional setup
671 if($newinstance && ($obj = block_instance($block->name, $newinstance))) {
672 // Return value ignored
673 $obj->instance_create();
674 }
675
9b4b78fd 676 break;
677 }
f032aa7a 678
b1631fef 679 if ($redirect) {
680 // In order to prevent accidental duplicate actions, redirect to a page with a clean url
681 redirect($page->url_get_full());
682 }
f032aa7a 683}
684
da71112b 685// You can use this to get the blocks to respond to URL actions without much hassle
0d6b9d4f 686function blocks_execute_url_action(&$PAGE, &$pageblocks,$pinned=false) {
02cc05a7 687 $blockaction = optional_param('blockaction', '', PARAM_ALPHA);
da71112b 688
3edc57e1 689 if (empty($blockaction) || !$PAGE->user_allowed_editing() || !confirm_sesskey()) {
da71112b 690 return;
691 }
692
693 $instanceid = optional_param('instanceid', 0, PARAM_INT);
694 $blockid = optional_param('blockid', 0, PARAM_INT);
695
696 if (!empty($blockid)) {
0d6b9d4f 697 blocks_execute_action($PAGE, $pageblocks, strtolower($blockaction), $blockid, $pinned);
da71112b 698
699 }
700 else if (!empty($instanceid)) {
701 $instance = blocks_find_instance($instanceid, $pageblocks);
0d6b9d4f 702 blocks_execute_action($PAGE, $pageblocks, strtolower($blockaction), $instance, $pinned);
da71112b 703 }
704}
705
f032aa7a 706// This shouldn't be used externally at all, it's here for use by blocks_execute_action()
707// in order to reduce code repetition.
c4308cfa 708function blocks_execute_repositioning(&$instance, $newpos, $newweight, $pinned=false, $checkPos=true) {
f032aa7a 709 global $CFG;
710
c4308cfa 711 // If it's staying where it is, don't do anything, unless overridden
712 if(($newpos == $instance->position)&& $checkPos) {
f032aa7a 713 return;
714 }
715
716 // Close the weight gap we 'll leave behind
0d6b9d4f 717 if (!empty($pinned)) {
718 $sql = 'UPDATE '. $CFG->prefix .'block_instance SET weight = weight - 1 WHERE pagetype = \''. $instance->pagetype.
719 '\' AND position = \'' .$instance->position.
720 '\' AND weight > '. $instance->weight;
721 } else {
722 $sql = 'UPDATE '. $CFG->prefix .'block_instance SET weight = weight - 1 WHERE pagetype = \''. $instance->pagetype.
f032aa7a 723 '\' AND pageid = '. $instance->pageid .' AND position = \'' .$instance->position.
0d6b9d4f 724 '\' AND weight > '. $instance->weight;
725 }
726 execute_sql($sql,false);
f032aa7a 727
728 $instance->position = $newpos;
729 $instance->weight = $newweight;
730
0d6b9d4f 731 if (!empty($pinned)) {
732 update_record('block_pinned', $instance);
733 } else {
734 update_record('block_instance', $instance);
735 }
736}
737
e028ed34 738//like blocks_execute_repositiong except completely atomic, handles all aspects of the positioning
739function blocks_execute_repositioning_atomic(&$instance, $newpos, $newweight, $pinned=false){
740 global $CFG;
c4308cfa 741
742 if($instance->weight == $newweight)
743 return false;
e028ed34 744
745 //make room for block insert
746 if (!empty($pinned)) {
747 $sql = 'UPDATE '. $CFG->prefix .'block_instance SET weight = weight + 1 WHERE pagetype = \''. $instance->pagetype.
748 '\' AND position = \'' .$newpos.
749 '\' AND weight >= '. $newweight;
750 } else {
751 $sql = 'UPDATE '. $CFG->prefix .'block_instance SET weight = weight + 1 WHERE pagetype = \''. $instance->pagetype.
752 '\' AND pageid = '. $instance->pageid .' AND position = \'' .$newpos.
753 '\' AND weight >= '. $newweight;
77e65ff7 754 }
e028ed34 755 execute_sql($sql,false);
756
c4308cfa 757 //adjusts the wieghts for changes in the weight list
758 if($newweight < $instance->weight){
759 $instance->weight+=2;
760 }else{
761 $newweight--;
762 }
e028ed34 763
c4308cfa 764
765 //reposition blocks
766 blocks_execute_repositioning($instance,$newpos,$newweight,$pinned,false);
e028ed34 767}
768
0d6b9d4f 769function blocks_get_pinned($page) {
770
771 $visible = true;
772
773 if (method_exists($page,'edit_always')) {
774 if ($page->edit_always()) {
775 $visible = false;
776 }
777 }
778
779 $blocks = get_records_select('block_pinned', 'pagetype = \''. $page->get_type() .'\''.(($visible) ? 'AND visible = 1' : ''), 'position, weight');
780
781 $positions = $page->blocks_get_positions();
782 $arr = array();
783
784 foreach($positions as $key => $position) {
785 $arr[$position] = array();
786 }
787
788 if(empty($blocks)) {
789 return $arr;
790 }
791
792 foreach($blocks as $block) {
793 $block->pinned = true; // so we know we can't move it.
ddf1935f 794 // make up an instanceid if we can..
795 $block->pageid = $page->get_id();
0d6b9d4f 796 $arr[$block->position][$block->weight] = $block;
797 }
798
799 return $arr;
800}
801
802
803function blocks_get_by_page_pinned($page) {
804 $pinned = blocks_get_pinned($page);
805 $user = blocks_get_by_page($page);
806
807 $weights = array();
808
809 foreach ($pinned as $pos => $arr) {
810 $weights[$pos] = count($arr);
811 }
812
813 foreach ($user as $pos => $blocks) {
814 if (!array_key_exists($pos,$pinned)) {
815 $pinned[$pos] = array();
816 }
817 if (!array_key_exists($pos,$weights)) {
818 $weights[$pos] = 0;
819 }
77e65ff7 820 foreach ($blocks as $block) {
0d6b9d4f 821 $pinned[$pos][$weights[$pos]] = $block;
822 $weights[$pos]++;
823 }
824 }
825 return $pinned;
0f3fe4b6 826}
827
9b4b78fd 828function blocks_get_by_page($page) {
a9b3afb7 829 $blocks = get_records_select('block_instance', "pageid = '". $page->get_id() ."' AND pagetype = '". $page->get_type() ."'", 'position, weight');
f032aa7a 830
831 $positions = $page->blocks_get_positions();
832 $arr = array();
833 foreach($positions as $key => $position) {
834 $arr[$position] = array();
835 }
0f3fe4b6 836
9b4b78fd 837 if(empty($blocks)) {
838 return $arr;
839 }
0f3fe4b6 840
77e65ff7 841 foreach($blocks as $block) {
9b4b78fd 842 $arr[$block->position][$block->weight] = $block;
0f3fe4b6 843 }
844
9b4b78fd 845 return $arr;
846}
0f3fe4b6 847
9b4b78fd 848//This function prints the block to admin blocks as necessary
c1d8705f 849function blocks_print_adminblock(&$page, &$pageblocks) {
9b4b78fd 850 global $USER;
0f3fe4b6 851
c1d8705f 852 $missingblocks = blocks_get_missing($page, $pageblocks);
853
9b4b78fd 854 if (!empty($missingblocks)) {
c1d8705f 855 $strblocks = get_string('blocks');
856 $stradd = get_string('add');
9b4b78fd 857 foreach ($missingblocks as $blockid) {
858 $block = blocks_get_record($blockid);
9b4b78fd 859 $blockobject = block_instance($block->name);
860 if ($blockobject === false) {
861 continue;
862 }
11306331 863 if(!$blockobject->user_can_addto($page)) {
864 continue;
865 }
9b4b78fd 866 $menu[$block->id] = $blockobject->get_title();
867 }
4a4c30d2 868 asort($menu);
0f3fe4b6 869
f032aa7a 870 $target = $page->url_get_full(array('sesskey' => $USER->sesskey, 'blockaction' => 'add'));
871 $content = popup_form($target.'&amp;blockid=', $menu, 'add_block', '', $stradd .'...', '', '', true);
afd8402c 872 print_side_block($strblocks, $content, NULL, NULL, NULL, array('class' => 'block_adminblock'));
0f3fe4b6 873 }
0f3fe4b6 874}
875
9b4b78fd 876function blocks_repopulate_page($page) {
877 global $CFG;
5b224948 878
9b4b78fd 879 $allblocks = blocks_get_record();
880
881 if(empty($allblocks)) {
882 error('Could not retrieve blocks from the database');
883 }
884
f032aa7a 885 // Assemble the information to correlate block names to ids
9b4b78fd 886 $idforname = array();
887 foreach($allblocks as $block) {
888 $idforname[$block->name] = $block->id;
889 }
890
f032aa7a 891 /// If the site override has been defined, it is the only valid one.
892 if (!empty($CFG->defaultblocks_override)) {
893 $blocknames = $CFG->defaultblocks_override;
894 }
895 else {
896 $blocknames = $page->blocks_get_default();
897 }
898
899 $positions = $page->blocks_get_positions();
900 $posblocks = explode(':', $blocknames);
901
902 // Now one array holds the names of the positions, and the other one holds the blocks
903 // that are going to go in each position. Luckily for us, both arrays are numerically
904 // indexed and the indexes match, so we can work straight away... but CAREFULLY!
9b4b78fd 905
f032aa7a 906 // Ready to start creating block instances, but first drop any existing ones
907 delete_records('block_instance', 'pageid', $page->get_id(), 'pagetype', $page->get_type());
908
909 // Here we slyly count $posblocks and NOT $positions. This can actually make a difference
910 // if the textual representation has undefined slots in the end. So we only work with as many
911 // positions were retrieved, not with all the page says it has available.
912 $numpositions = count($posblocks);
913 for($i = 0; $i < $numpositions; ++$i) {
914 $position = $positions[$i];
915 $blocknames = explode(',', $posblocks[$i]);
9b4b78fd 916 $weight = 0;
917 foreach($blocknames as $blockname) {
918 $newinstance = new stdClass;
919 $newinstance->blockid = $idforname[$blockname];
f032aa7a 920 $newinstance->pageid = $page->get_id();
921 $newinstance->pagetype = $page->get_type();
9b4b78fd 922 $newinstance->position = $position;
923 $newinstance->weight = $weight;
924 $newinstance->visible = 1;
925 $newinstance->configdata = '';
3cacefda 926
927 if(!empty($newinstance->blockid)) {
928 // Only add block if it was recognized
929 insert_record('block_instance', $newinstance);
930 ++$weight;
931 }
0f3fe4b6 932 }
933 }
9b4b78fd 934
935 return true;
0f3fe4b6 936}
937
938function upgrade_blocks_db($continueto) {
939/// This function upgrades the blocks tables, if necessary
940/// It's called from admin/index.php
941
942 global $CFG, $db;
943
a9c75a9c 944 require_once ($CFG->dirroot .'/blocks/version.php'); // Get code versions
0f3fe4b6 945
946 if (empty($CFG->blocks_version)) { // Blocks have never been installed.
a9c75a9c 947 $strdatabaseupgrades = get_string('databaseupgrades');
a36f058e 948 print_header($strdatabaseupgrades, $strdatabaseupgrades, $strdatabaseupgrades, '',
949 '<script type="text/javascript" src="' . $CFG->wwwroot . '/lib/scroll_to_errors.js"></script>',
950 false, '&nbsp;', '&nbsp;');
0f3fe4b6 951
583fad99 952 upgrade_log_start();
1164af7c 953 print_heading('blocks');
0f3fe4b6 954 $db->debug=true;
1164af7c 955
956 /// Both old .sql files and new install.xml are supported
957 /// but we priorize install.xml (XMLDB) if present
958 $status = false;
db8bd7a6 959 if (file_exists($CFG->dirroot . '/blocks/db/install.xml')) {
1164af7c 960 $status = install_from_xmldb_file($CFG->dirroot . '/blocks/db/install.xml'); //New method
961 } else if (file_exists($CFG->dirroot . '/blocks/db/' . $CFG->dbtype . '.sql')) {
962 $status = modify_database($CFG->dirroot . '/blocks/db/' . $CFG->dbtype . '.sql'); //Old method
963 }
964
965 $db->debug = false;
966 if ($status) {
a9c75a9c 967 if (set_config('blocks_version', $blocks_version)) {
c7a9e293 968 notify(get_string('databasesuccess'), 'notifysuccess');
8549af11 969 notify(get_string('databaseupgradeblocks', '', $blocks_version), 'notifysuccess');
0f3fe4b6 970 print_continue($continueto);
971 exit;
972 } else {
a9c75a9c 973 error('Upgrade of blocks system failed! (Could not update version in config table)');
0f3fe4b6 974 }
975 } else {
a9c75a9c 976 error('Blocks tables could NOT be set up successfully!');
0f3fe4b6 977 }
978 }
979
1164af7c 980/// Upgrading code starts here
981 $oldupgrade = false;
982 $newupgrade = false;
983 if (is_readable($CFG->dirroot . '/blocks/db/' . $CFG->dbtype . '.php')) {
984 include_once($CFG->dirroot . '/blocks/db/' . $CFG->dbtype . '.php'); // defines old upgrading function
985 $oldupgrade = true;
986 }
db8bd7a6 987 if (is_readable($CFG->dirroot . '/blocks/db/upgrade.php')) {
1164af7c 988 include_once($CFG->dirroot . '/blocks/db/upgrade.php'); // defines new upgrading function
989 $newupgrade = true;
990 }
0f3fe4b6 991
992 if ($blocks_version > $CFG->blocks_version) { // Upgrade tables
a9c75a9c 993 $strdatabaseupgrades = get_string('databaseupgrades');
a36f058e 994 print_header($strdatabaseupgrades, $strdatabaseupgrades, $strdatabaseupgrades, '',
995 '<script type="text/javascript" src="' . $CFG->wwwroot . '/lib/scroll_to_errors.js"></script>');
583fad99 996
997 upgrade_log_start();
1164af7c 998 print_heading('blocks');
999
1000 /// Run de old and new upgrade functions for the module
1001 $oldupgrade_function = 'blocks_upgrade';
1002 $newupgrade_function = 'xmldb_blocks_upgrade';
1003
1004 /// First, the old function if exists
1005 $oldupgrade_status = true;
1006 if ($oldupgrade && function_exists($oldupgrade_function)) {
1007 $db->debug = true;
1008 $oldupgrade_status = $oldupgrade_function($CFG->blocks_version);
1009 } else if ($oldupgrade) {
1010 notify ('Upgrade function ' . $oldupgrade_function . ' was not available in ' .
1011 '/blocks/db/' . $CFG->dbtype . '.php');
1012 }
0f3fe4b6 1013
1164af7c 1014 /// Then, the new function if exists and the old one was ok
1015 $newupgrade_status = true;
1016 if ($newupgrade && function_exists($newupgrade_function) && $oldupgrade_status) {
1017 $db->debug = true;
1018 $newupgrade_status = $newupgrade_function($CFG->blocks_version);
1019 } else if ($newupgrade) {
1020 notify ('Upgrade function ' . $newupgrade_function . ' was not available in ' .
1021 '/blocks/db/upgrade.php');
1022 }
1023
1024 $db->debug=false;
1025 /// Now analyze upgrade results
1026 if ($oldupgrade_status && $newupgrade_status) { // No upgrading failed
a9c75a9c 1027 if (set_config('blocks_version', $blocks_version)) {
c7a9e293 1028 notify(get_string('databasesuccess'), 'notifysuccess');
8549af11 1029 notify(get_string('databaseupgradeblocks', '', $blocks_version), 'notifysuccess');
0f3fe4b6 1030 print_continue($continueto);
1031 exit;
1032 } else {
a9c75a9c 1033 error('Upgrade of blocks system failed! (Could not update version in config table)');
0f3fe4b6 1034 }
1035 } else {
a9c75a9c 1036 error('Upgrade failed! See blocks/version.php');
0f3fe4b6 1037 }
1038
1039 } else if ($blocks_version < $CFG->blocks_version) {
583fad99 1040 upgrade_log_start();
b011f733 1041 notify('WARNING!!! The Blocks version you are using is OLDER than the version that made these databases!');
0f3fe4b6 1042 }
1164af7c 1043 upgrade_log_finish();
0f3fe4b6 1044}
1045
1046//This function finds all available blocks and install them
1047//into blocks table or do all the upgrade process if newer
1048function upgrade_blocks_plugins($continueto) {
1049
790647b9 1050 global $CFG, $db;
0f3fe4b6 1051
1052 $blocktitles = array();
1053 $invalidblocks = array();
1054 $validblocks = array();
1055 $notices = array();
1056
1057 //Count the number of blocks in db
9b4b78fd 1058 $blockcount = count_records('block');
0f3fe4b6 1059 //If there isn't records. This is the first install, so I remember it
1060 if ($blockcount == 0) {
1061 $first_install = true;
1062 } else {
1063 $first_install = false;
1064 }
1065
1066 $site = get_site();
1067
9b4b78fd 1068 if (!$blocks = get_list_of_plugins('blocks', 'db') ) {
a9c75a9c 1069 error('No blocks installed!');
0f3fe4b6 1070 }
1071
a9c75a9c 1072 include_once($CFG->dirroot .'/blocks/moodleblock.class.php');
e89d741a 1073 if(!class_exists('block_base')) {
1074 error('Class block_base is not defined or file not found for /blocks/moodleblock.class.php');
0f3fe4b6 1075 }
1076
1077 foreach ($blocks as $blockname) {
1078
a9c75a9c 1079 if ($blockname == 'NEWBLOCK') { // Someone has unzipped the template, ignore it
0f3fe4b6 1080 continue;
1081 }
1082
61abc65b 1083 if(!block_is_compatible($blockname)) {
1084 // This is an old-style block
1085 //$notices[] = 'Block '. $blockname .' is not compatible with the current version of Mooodle and needs to be updated by a programmer.';
1086 $invalidblocks[] = $blockname;
1087 continue;
1088 }
f10306b9 1089
a9c75a9c 1090 $fullblock = $CFG->dirroot .'/blocks/'. $blockname;
0f3fe4b6 1091
9b4b78fd 1092 if ( is_readable($fullblock.'/block_'.$blockname.'.php')) {
1093 include_once($fullblock.'/block_'.$blockname.'.php');
0f3fe4b6 1094 } else {
a9c75a9c 1095 $notices[] = 'Block '. $blockname .': '. $fullblock .'/block_'. $blockname .'.php was not readable';
0f3fe4b6 1096 continue;
1097 }
1098
790647b9 1099 $oldupgrade = false;
1100 $newupgrade = false;
a9c75a9c 1101 if ( @is_dir($fullblock .'/db/')) {
1102 if ( @is_readable($fullblock .'/db/'. $CFG->dbtype .'.php')) {
790647b9 1103 include_once($fullblock .'/db/'. $CFG->dbtype .'.php'); // defines old upgrading function
1104 $oldupgrade = true;
828c4e09 1105 }
790647b9 1106 if ( @is_readable($fullblock .'/db/upgrade.php')) {
1107 include_once($fullblock .'/db/upgrade.php'); // defines new upgrading function
1108 $newupgrade = true;
1109 }
1110 }
1111
e89d741a 1112 $classname = 'block_'.$blockname;
0f3fe4b6 1113 if(!class_exists($classname)) {
a9c75a9c 1114 $notices[] = 'Block '. $blockname .': '. $classname .' not implemented';
0f3fe4b6 1115 continue;
1116 }
1117
9b4b78fd 1118 // Here is the place to see if the block implements a constructor (old style),
1119 // an init() function (new style) or nothing at all (error time).
1120
33bee34c 1121 $constructor = get_class_constructor($classname);
1122 if(empty($constructor)) {
0f3fe4b6 1123 // No constructor
a9c75a9c 1124 $notices[] = 'Block '. $blockname .': class does not have a constructor';
0f3fe4b6 1125 $invalidblocks[] = $blockname;
1126 continue;
1127 }
1128
9b4b78fd 1129 $block = new stdClass; // This may be used to update the db below
1130 $blockobj = new $classname; // This is what we 'll be testing
0f3fe4b6 1131
e89d741a 1132 // Inherits from block_base?
1133 if(!is_subclass_of($blockobj, 'block_base')) {
1134 $notices[] = 'Block '. $blockname .': class does not inherit from block_base';
0f3fe4b6 1135 continue;
1136 }
1137
1138 // OK, it's as we all hoped. For further tests, the object will do them itself.
1139 if(!$blockobj->_self_test()) {
a9c75a9c 1140 $notices[] = 'Block '. $blockname .': self test failed';
0f3fe4b6 1141 continue;
1142 }
1143 $block->version = $blockobj->get_version();
1144
1145 if (!isset($block->version)) {
a9c75a9c 1146 $notices[] = 'Block '. $blockname .': has no version support. It must be updated by a programmer.';
0f3fe4b6 1147 continue;
1148 }
1149
1150 $block->name = $blockname; // The name MUST match the directory
1151 $blocktitle = $blockobj->get_title();
1152
9b4b78fd 1153 if ($currblock = get_record('block', 'name', $block->name)) {
0f3fe4b6 1154 if ($currblock->version == $block->version) {
1155 // do nothing
1156 } else if ($currblock->version < $block->version) {
1157 if (empty($updated_blocks)) {
a9c75a9c 1158 $strblocksetup = get_string('blocksetup');
a36f058e 1159 print_header($strblocksetup, $strblocksetup, $strblocksetup, '',
1160 '<script type="text/javascript" src="' . $CFG->wwwroot . '/lib/scroll_to_errors.js"></script>',
1161 false, '&nbsp;', '&nbsp;');
0f3fe4b6 1162 }
790647b9 1163 $updated_blocks = true;
583fad99 1164 upgrade_log_start();
b88f7004 1165 print_heading('New version of '.$blocktitle.' ('.$block->name.') exists');
790647b9 1166 @set_time_limit(0); // To allow slow databases to complete the long SQL
1167
1168 /// Run de old and new upgrade functions for the module
1169 $oldupgrade_function = $block->name .'_upgrade';
32ac8473 1170 $newupgrade_function = 'xmldb_block_' . $block->name .'_upgrade';
790647b9 1171
1172 /// First, the old function if exists
1173 $oldupgrade_status = true;
1174 if ($oldupgrade && function_exists($oldupgrade_function)) {
1175 $db->debug = true;
1176 $oldupgrade_status = $oldupgrade_function($currblock->version, $block);
1177 } else if ($oldupgrade) {
1178 notify ('Upgrade function ' . $oldupgrade_function . ' was not available in ' .
1179 $fullblock . '/db/' . $CFG->dbtype . '.php');
b88f7004 1180 }
790647b9 1181
1182 /// Then, the new function if exists and the old one was ok
1183 $newupgrade_status = true;
1184 if ($newupgrade && function_exists($newupgrade_function) && $oldupgrade_status) {
1185 $db->debug = true;
1186 $newupgrade_status = $newupgrade_function($currblock->version, $block);
1187 } else if ($newupgrade) {
1188 notify ('Upgrade function ' . $newupgrade_function . ' was not available in ' .
1189 $fullblock . '/db/upgrade.php');
bbbf2d40 1190 }
790647b9 1191
1192 $db->debug=false;
1193 /// Now analyze upgrade results
1194 if ($oldupgrade_status && $newupgrade_status) { // No upgrading failed
9b4b78fd 1195 // OK so far, now update the block record
b88f7004 1196 $block->id = $currblock->id;
9b4b78fd 1197 if (! update_record('block', $block)) {
a9c75a9c 1198 error('Could not update block '. $block->name .' record in block table!');
0f3fe4b6 1199 }
48f6bcdd 1200 $component = 'block/'.$block->name;
1201 if (!update_capabilities($component)) {
790647b9 1202 error('Could not update '.$block->name.' capabilities!');
1203 }
c7a9e293 1204 notify(get_string('blocksuccess', '', $blocktitle), 'notifysuccess');
790647b9 1205 } else {
1206 notify('Upgrading block '. $block->name .' from '. $currblock->version .' to '. $block->version .' FAILED!');
0f3fe4b6 1207 }
790647b9 1208 echo '<hr />';
0f3fe4b6 1209 } else {
583fad99 1210 upgrade_log_start();
a9c75a9c 1211 error('Version mismatch: block '. $block->name .' can\'t downgrade '. $currblock->version .' -> '. $block->version .'!');
0f3fe4b6 1212 }
1213
1214 } else { // block not installed yet, so install it
1215
9b4b78fd 1216 // If it allows multiples, start with it enabled
1217 $block->multiple = $blockobj->instance_allow_multiple();
f9648e77 1218 if (!empty($blockobj->cron)) {
1219 $block->cron = $blockobj->cron;
1220 }
9b4b78fd 1221
0f3fe4b6 1222 // [pj] Normally this would be inline in the if, but we need to
1223 // check for NULL (necessary for 4.0.5 <= PHP < 4.2.0)
1224 $conflictblock = array_search($blocktitle, $blocktitles);
1225 if($conflictblock !== false && $conflictblock !== NULL) {
0f3fe4b6 1226 // Duplicate block titles are not allowed, they confuse people
1227 // AND PHP's associative arrays ;)
1228 error('<strong>Naming conflict</strong>: block <strong>'.$block->name.'</strong> has the same title with an existing block, <strong>'.$conflictblock.'</strong>!');
1229 }
1230 if (empty($updated_blocks)) {
a9c75a9c 1231 $strblocksetup = get_string('blocksetup');
a36f058e 1232 print_header($strblocksetup, $strblocksetup, $strblocksetup, '',
1233 '<script type="text/javascript" src="' . $CFG->wwwroot . '/lib/scroll_to_errors.js"></script>',
1234 false, '&nbsp;', '&nbsp;');
0f3fe4b6 1235 }
790647b9 1236 $updated_blocks = true;
583fad99 1237 upgrade_log_start();
0f3fe4b6 1238 print_heading($block->name);
0f3fe4b6 1239 $db->debug = true;
a71bfa1c 1240 @set_time_limit(0); // To allow slow databases to complete the long SQL
790647b9 1241
1242 /// Both old .sql files and new install.xml are supported
1243 /// but we priorize install.xml (XMLDB) if present
1244 $status = false;
db8bd7a6 1245 if (file_exists($fullblock . '/db/install.xml')) {
790647b9 1246 $status = install_from_xmldb_file($fullblock . '/db/install.xml'); //New method
1247 } else if (file_exists($fullblock .'/db/'. $CFG->dbtype .'.sql')) {
1248 $status = modify_database($fullblock .'/db/'. $CFG->dbtype .'.sql'); //Old method
1249 } else {
1250 $status = true;
1251 }
1252
1253 $db->debug = false;
1254 if ($status) {
9b4b78fd 1255 if ($block->id = insert_record('block', $block)) {
44c55d46 1256 $blockobj->after_install();
48f6bcdd 1257 $component = 'block/'.$block->name;
1258 if (!update_capabilities($component)) {
790647b9 1259 notify('Could not set up '.$block->name.' capabilities!');
1260 }
c7a9e293 1261 notify(get_string('blocksuccess', '', $blocktitle), 'notifysuccess');
a9c75a9c 1262 echo '<hr />';
0f3fe4b6 1263 } else {
a9c75a9c 1264 error($block->name .' block could not be added to the block list!');
0f3fe4b6 1265 }
1266 } else {
a9c75a9c 1267 error('Block '. $block->name .' tables could NOT be set up successfully!');
0f3fe4b6 1268 }
1269 }
1270
1271 $blocktitles[$block->name] = $blocktitle;
1272 }
1273
1274 if(!empty($notices)) {
583fad99 1275 upgrade_log_start();
0f3fe4b6 1276 foreach($notices as $notice) {
1277 notify($notice);
1278 }
1279 }
1280
9b4b78fd 1281 // Finally, if we are in the first_install of BLOCKS (this means that we are
1282 // upgrading from Moodle < 1.3), put blocks in all existing courses.
0f3fe4b6 1283 if ($first_install) {
583fad99 1284 upgrade_log_start();
0f3fe4b6 1285 //Iterate over each course
9b4b78fd 1286 if ($courses = get_records('course')) {
0f3fe4b6 1287 foreach ($courses as $course) {
7542a4e5 1288 $page = page_create_object(PAGE_COURSE_VIEW, $course->id);
9b4b78fd 1289 blocks_repopulate_page($page);
0f3fe4b6 1290 }
1291 }
1292 }
1293
e02c35b2 1294 if (!empty($CFG->siteblocksadded)) { /// This is a once-off hack to make a proper upgrade
583fad99 1295 upgrade_log_start();
7542a4e5 1296 $page = page_create_object(PAGE_COURSE_VIEW, SITEID);
9b4b78fd 1297 blocks_repopulate_page($page);
e02c35b2 1298 delete_records('config', 'name', 'siteblocksadded');
1299 }
1300
583fad99 1301 upgrade_log_finish();
1302
0f3fe4b6 1303 if (!empty($updated_blocks)) {
1304 print_continue($continueto);
1305 die;
1306 }
1307}
1308
f10306b9 1309?>