Merged from 1.7
[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) {
d23157d8 274
66c7e47b 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;
d23157d8 328 if(!empty($COURSE->javascriptportal)) {
329 $COURSE->javascriptportal->currentblocksection = $position;
330 }
1345403a 331 $obj->_print_block();
9b4b78fd 332 }
d23157d8 333 if (!empty($COURSE->javascriptportal)
334 && (empty($instance->pinned) || !$instance->pinned)) {
335 $COURSE->javascriptportal->block_add('inst'.$instance->id, !$instance->visible);
336 }
337 } // End foreach
338
66492322 339
0a0bb380 340 if ($page->blocks_default_position() == $position && $page->user_is_editing()) {
66492322 341 blocks_print_adminblock($page, $pageblocks);
342 }
0f3fe4b6 343}
344
c8e0b579 345// This iterates over an array of blocks and calculates the preferred width
346// Parameter passed by reference for speed; it's not modified.
347function blocks_preferred_width(&$instances) {
0f3fe4b6 348 $width = 0;
349
9b4b78fd 350 if(empty($instances) || !is_array($instances)) {
0f3fe4b6 351 return 0;
352 }
ff6191b7 353
354 $blocks = blocks_get_record();
355
9b4b78fd 356 foreach($instances as $instance) {
357 if(!$instance->visible) {
fe78a3dc 358 continue;
0c9c6363 359 }
ff6191b7 360
f809df70 361 if (!array_key_exists($instance->blockid, $blocks)) {
362 // Block doesn't exist! We should delete this instance!
363 continue;
364 }
365
ff6191b7 366 if(!$blocks[$instance->blockid]->visible) {
9b687320 367 continue;
368 }
ff6191b7 369 $pref = block_method_result($blocks[$instance->blockid]->name, 'preferred_width');
9b4b78fd 370 if($pref === NULL) {
371 continue;
372 }
373 if($pref > $width) {
374 $width = $pref;
0f3fe4b6 375 }
376 }
377 return $width;
378}
379
9b4b78fd 380function blocks_get_record($blockid = NULL, $invalidate = false) {
381 static $cache = NULL;
0f3fe4b6 382
9b4b78fd 383 if($invalidate || empty($cache)) {
eca3b01f 384 $cache = get_records('block');
9b4b78fd 385 }
0f3fe4b6 386
9b4b78fd 387 if($blockid === NULL) {
388 return $cache;
389 }
0f3fe4b6 390
9b4b78fd 391 return (isset($cache[$blockid])? $cache[$blockid] : false);
392}
393
394function blocks_find_block($blockid, $blocksarray) {
0d6b9d4f 395 if (empty($blocksarray)) {
396 return false;
397 }
9b4b78fd 398 foreach($blocksarray as $blockgroup) {
0d6b9d4f 399 if (empty($blockgroup)) {
400 continue;
401 }
9b4b78fd 402 foreach($blockgroup as $instance) {
403 if($instance->blockid == $blockid) {
404 return $instance;
405 }
406 }
407 }
408 return false;
409}
410
411function blocks_find_instance($instanceid, $blocksarray) {
412 foreach($blocksarray as $subarray) {
413 foreach($subarray as $instance) {
414 if($instance->id == $instanceid) {
415 return $instance;
416 }
417 }
418 }
419 return false;
420}
421
ec79d3e4 422// Simple entry point for anyone that wants to use blocks
ee6055eb 423function blocks_setup(&$PAGE,$pinned=BLOCKS_PINNED_FALSE) {
424 switch ($pinned) {
425 case BLOCKS_PINNED_TRUE:
426 $pageblocks = blocks_get_pinned($PAGE);
427 break;
428 case BLOCKS_PINNED_BOTH:
429 $pageblocks = blocks_get_by_page_pinned($PAGE);
430 break;
431 case BLOCKS_PINNED_FALSE:
432 default:
433 $pageblocks = blocks_get_by_page($PAGE);
434 break;
435 }
436 blocks_execute_url_action($PAGE, $pageblocks,($pinned==BLOCKS_PINNED_TRUE));
ec79d3e4 437 return $pageblocks;
438}
439
b1631fef 440function blocks_execute_action($page, &$pageblocks, $blockaction, $instanceorid, $pinned=false, $redirect=true) {
9b4b78fd 441 global $CFG;
442
a9c75a9c 443 if (is_int($instanceorid)) {
9b4b78fd 444 $blockid = $instanceorid;
a9c75a9c 445 } else if (is_object($instanceorid)) {
9b4b78fd 446 $instance = $instanceorid;
447 }
0f3fe4b6 448
449 switch($blockaction) {
9b4b78fd 450 case 'config':
f032aa7a 451 global $USER;
9b4b78fd 452 $block = blocks_get_record($instance->blockid);
e82d6cac 453 // Hacky hacky tricky stuff to get the original human readable block title,
454 // even if the block has configured its title to be something else.
455 // Create the object WITHOUT instance data.
456 $blockobject = block_instance($block->name);
9b4b78fd 457 if ($blockobject === false) {
11306331 458 break;
459 }
460
461 // First of all check to see if the block wants to be edited
462 if(!$blockobject->user_can_edit()) {
463 break;
9b4b78fd 464 }
11306331 465
e82d6cac 466 // Now get the title and AFTER that load up the instance
467 $blocktitle = $blockobject->get_title();
468 $blockobject->_load_instance($instance);
469
9b4b78fd 470 optional_param('submitted', 0, PARAM_INT);
471
27ec21a0 472 // Define the data we're going to silently include in the instance config form here,
9b4b78fd 473 // so we can strip them from the submitted data BEFORE serializing it.
474 $hiddendata = array(
475 'sesskey' => $USER->sesskey,
9b4b78fd 476 'instanceid' => $instance->id,
477 'blockaction' => 'config'
478 );
f032aa7a 479
480 // To this data, add anything the page itself needs to display
481 $hiddendata = array_merge($hiddendata, $page->url_get_parameters());
9b4b78fd 482
483 if($data = data_submitted()) {
484 $remove = array_keys($hiddendata);
485 foreach($remove as $item) {
486 unset($data->$item);
0f3fe4b6 487 }
0d6b9d4f 488 if(!$blockobject->instance_config_save($data,$pinned)) {
9b4b78fd 489 error('Error saving block configuration');
0f3fe4b6 490 }
9b4b78fd 491 // And nothing more, continue with displaying the page
0f3fe4b6 492 }
9b4b78fd 493 else {
f032aa7a 494 // We need to show the config screen, so we highjack the display logic and then die
e82d6cac 495 $strheading = get_string('blockconfiga', 'moodle', $blocktitle);
edb42f09 496 $page->print_header(get_string('pageheaderconfigablock', 'moodle'), array($strheading => ''));
b9709905 497
498 echo '<div class="block-config" id="'.$block->name.'">'; /// Make CSS easier
499
edb42f09 500 print_heading($strheading);
f032aa7a 501 echo '<form method="post" action="'. $page->url_get_path() .'">';
9b4b78fd 502 echo '<p>';
503 foreach($hiddendata as $name => $val) {
27ec21a0 504 echo '<input type="hidden" name="'. $name .'" value="'. $val .'" />';
0f3fe4b6 505 }
9b4b78fd 506 echo '</p>';
507 $blockobject->instance_config_print();
508 echo '</form>';
b9709905 509
510 echo '</div>';
a2c28054 511 $CFG->pagepath = 'blocks/' . $block->name;
9b4b78fd 512 print_footer();
f032aa7a 513 die(); // Do not go on with the other page-related stuff
0f3fe4b6 514 }
515 break;
9b4b78fd 516 case 'toggle':
517 if(empty($instance)) {
518 error('Invalid block instance for '.$blockaction);
0f3fe4b6 519 }
9b4b78fd 520 $instance->visible = ($instance->visible) ? 0 : 1;
0d6b9d4f 521 if (!empty($pinned)) {
522 update_record('block_pinned', $instance);
523 } else {
524 update_record('block_instance', $instance);
525 }
9b4b78fd 526 break;
527 case 'delete':
528 if(empty($instance)) {
a9c75a9c 529 error('Invalid block instance for '. $blockaction);
0f3fe4b6 530 }
0d6b9d4f 531 blocks_delete_instance($instance, $pinned);
0f3fe4b6 532 break;
533 case 'moveup':
9b4b78fd 534 if(empty($instance)) {
a9c75a9c 535 error('Invalid block instance for '. $blockaction);
9b4b78fd 536 }
f032aa7a 537
538 if($instance->weight == 0) {
539 // The block is the first one, so a move "up" probably means it changes position
540 // Where is the instance going to be moved?
541 $newpos = $page->blocks_move_position($instance, BLOCK_MOVE_UP);
6b853ff4 542 $newweight = (empty($pageblocks[$newpos]) ? 0 : max(array_keys($pageblocks[$newpos])) + 1);
f032aa7a 543
0d6b9d4f 544 blocks_execute_repositioning($instance, $newpos, $newweight, $pinned);
89a5baab 545 }
f032aa7a 546 else {
547 // The block is just moving upwards in the same position.
548 // This configuration will make sure that even if somehow the weights
549 // become not continuous, block move operations will eventually bring
550 // the situation back to normal without printing any warnings.
551 if(!empty($pageblocks[$instance->position][$instance->weight - 1])) {
552 $other = $pageblocks[$instance->position][$instance->weight - 1];
553 }
554 if(!empty($other)) {
555 ++$other->weight;
0d6b9d4f 556 if (!empty($pinned)) {
557 update_record('block_pinned', $other);
558 } else {
559 update_record('block_instance', $other);
560 }
f032aa7a 561 }
562 --$instance->weight;
0d6b9d4f 563 if (!empty($pinned)) {
564 update_record('block_pinned', $instance);
565 } else {
566 update_record('block_instance', $instance);
567 }
0f3fe4b6 568 }
569 break;
570 case 'movedown':
9b4b78fd 571 if(empty($instance)) {
a9c75a9c 572 error('Invalid block instance for '. $blockaction);
9b4b78fd 573 }
f032aa7a 574
575 if($instance->weight == max(array_keys($pageblocks[$instance->position]))) {
576 // The block is the last one, so a move "down" probably means it changes position
577 // Where is the instance going to be moved?
578 $newpos = $page->blocks_move_position($instance, BLOCK_MOVE_DOWN);
6b853ff4 579 $newweight = (empty($pageblocks[$newpos]) ? 0 : max(array_keys($pageblocks[$newpos])) + 1);
f032aa7a 580
0d6b9d4f 581 blocks_execute_repositioning($instance, $newpos, $newweight, $pinned);
89a5baab 582 }
f032aa7a 583 else {
584 // The block is just moving downwards in the same position.
585 // This configuration will make sure that even if somehow the weights
586 // become not continuous, block move operations will eventually bring
587 // the situation back to normal without printing any warnings.
588 if(!empty($pageblocks[$instance->position][$instance->weight + 1])) {
589 $other = $pageblocks[$instance->position][$instance->weight + 1];
590 }
591 if(!empty($other)) {
592 --$other->weight;
0d6b9d4f 593 if (!empty($pinned)) {
594 update_record('block_pinned', $other);
595 } else {
596 update_record('block_instance', $other);
597 }
f032aa7a 598 }
599 ++$instance->weight;
0d6b9d4f 600 if (!empty($pinned)) {
601 update_record('block_pinned', $instance);
602 } else {
603 update_record('block_instance', $instance);
604 }
0f3fe4b6 605 }
606 break;
9b4b78fd 607 case 'moveleft':
608 if(empty($instance)) {
a9c75a9c 609 error('Invalid block instance for '. $blockaction);
9b4b78fd 610 }
f032aa7a 611
612 // Where is the instance going to be moved?
613 $newpos = $page->blocks_move_position($instance, BLOCK_MOVE_LEFT);
6b853ff4 614 $newweight = (empty($pageblocks[$newpos]) ? 0 : max(array_keys($pageblocks[$newpos])) + 1);
f032aa7a 615
0d6b9d4f 616 blocks_execute_repositioning($instance, $newpos, $newweight, $pinned);
0f3fe4b6 617 break;
9b4b78fd 618 case 'moveright':
619 if(empty($instance)) {
a9c75a9c 620 error('Invalid block instance for '. $blockaction);
9b4b78fd 621 }
f032aa7a 622
623 // Where is the instance going to be moved?
624 $newpos = $page->blocks_move_position($instance, BLOCK_MOVE_RIGHT);
6b853ff4 625 $newweight = (empty($pageblocks[$newpos]) ? 0 : max(array_keys($pageblocks[$newpos])) + 1);
f032aa7a 626
0d6b9d4f 627 blocks_execute_repositioning($instance, $newpos, $newweight, $pinned);
9b4b78fd 628 break;
629 case 'add':
630 // Add a new instance of this block, if allowed
631 $block = blocks_get_record($blockid);
0f3fe4b6 632
3cacefda 633 if(empty($block) || !$block->visible) {
634 // Only allow adding if the block exists and is enabled
11306331 635 break;
9b4b78fd 636 }
0f3fe4b6 637
89a5baab 638 if(!$block->multiple && blocks_find_block($blockid, $pageblocks) !== false) {
639 // If no multiples are allowed and we already have one, return now
11306331 640 break;
641 }
642
643 if(!block_method_result($block->name, 'user_can_addto', $page)) {
644 // If the block doesn't want to be added...
645 break;
89a5baab 646 }
647
f032aa7a 648 $newpos = $page->blocks_default_position();
0d6b9d4f 649 if (!empty($pinned)) {
650 $sql = 'SELECT 1, max(weight) + 1 AS nextfree FROM '. $CFG->prefix .'block_pinned WHERE '
651 .' pagetype = \''. $page->get_type() .'\' AND position = \''. $newpos .'\'';
652 } else {
653 $sql = 'SELECT 1, max(weight) + 1 AS nextfree FROM '. $CFG->prefix .'block_instance WHERE pageid = '. $page->get_id()
654 .' AND pagetype = \''. $page->get_type() .'\' AND position = \''. $newpos .'\'';
655 }
656 $weight = get_record_sql($sql);
9b4b78fd 657
658 $newinstance = new stdClass;
659 $newinstance->blockid = $blockid;
0d6b9d4f 660 if (empty($pinned)) {
661 $newinstance->pageid = $page->get_id();
662 }
f032aa7a 663 $newinstance->pagetype = $page->get_type();
664 $newinstance->position = $newpos;
ff679897 665 $newinstance->weight = empty($weight->nextfree) ? 0 : $weight->nextfree;
9b4b78fd 666 $newinstance->visible = 1;
667 $newinstance->configdata = '';
0d6b9d4f 668 if (!empty($pinned)) {
669 $newinstance->id = insert_record('block_pinned', $newinstance);
670 } else {
671 $newinstance->id = insert_record('block_instance', $newinstance);
672 }
b33dd23a 673
674 // If the new instance was created, allow it to do additional setup
675 if($newinstance && ($obj = block_instance($block->name, $newinstance))) {
676 // Return value ignored
677 $obj->instance_create();
678 }
679
9b4b78fd 680 break;
681 }
f032aa7a 682
b1631fef 683 if ($redirect) {
684 // In order to prevent accidental duplicate actions, redirect to a page with a clean url
685 redirect($page->url_get_full());
686 }
f032aa7a 687}
688
da71112b 689// You can use this to get the blocks to respond to URL actions without much hassle
0d6b9d4f 690function blocks_execute_url_action(&$PAGE, &$pageblocks,$pinned=false) {
02cc05a7 691 $blockaction = optional_param('blockaction', '', PARAM_ALPHA);
da71112b 692
3edc57e1 693 if (empty($blockaction) || !$PAGE->user_allowed_editing() || !confirm_sesskey()) {
da71112b 694 return;
695 }
696
697 $instanceid = optional_param('instanceid', 0, PARAM_INT);
698 $blockid = optional_param('blockid', 0, PARAM_INT);
699
700 if (!empty($blockid)) {
0d6b9d4f 701 blocks_execute_action($PAGE, $pageblocks, strtolower($blockaction), $blockid, $pinned);
da71112b 702
703 }
704 else if (!empty($instanceid)) {
705 $instance = blocks_find_instance($instanceid, $pageblocks);
0d6b9d4f 706 blocks_execute_action($PAGE, $pageblocks, strtolower($blockaction), $instance, $pinned);
da71112b 707 }
708}
709
f032aa7a 710// This shouldn't be used externally at all, it's here for use by blocks_execute_action()
711// in order to reduce code repetition.
c4308cfa 712function blocks_execute_repositioning(&$instance, $newpos, $newweight, $pinned=false, $checkPos=true) {
f032aa7a 713 global $CFG;
714
c4308cfa 715 // If it's staying where it is, don't do anything, unless overridden
d23157d8 716 if (($newpos == $instance->position) && $checkPos) {
f032aa7a 717 return;
718 }
719
720 // Close the weight gap we 'll leave behind
0d6b9d4f 721 if (!empty($pinned)) {
d23157d8 722 $sql = 'UPDATE '. $CFG->prefix .'block_instance SET weight = weight - 1 '.
723 'WHERE pagetype = \''. $instance->pagetype.
724 '\' AND position = \'' .$instance->position.
725 '\' AND weight > '. $instance->weight;
0d6b9d4f 726 } else {
d23157d8 727 $sql = 'UPDATE '. $CFG->prefix .'block_instance SET weight = weight - 1 '.
728 'WHERE pagetype = \''. $instance->pagetype.
729 '\' AND pageid = '. $instance->pageid .
730 ' AND position = \'' .$instance->position.
731 '\' AND weight > '. $instance->weight;
0d6b9d4f 732 }
733 execute_sql($sql,false);
f032aa7a 734
735 $instance->position = $newpos;
736 $instance->weight = $newweight;
737
0d6b9d4f 738 if (!empty($pinned)) {
739 update_record('block_pinned', $instance);
740 } else {
741 update_record('block_instance', $instance);
742 }
743}
744
e028ed34 745//like blocks_execute_repositiong except completely atomic, handles all aspects of the positioning
746function blocks_execute_repositioning_atomic(&$instance, $newpos, $newweight, $pinned=false){
747 global $CFG;
c4308cfa 748
d23157d8 749 if ($instance->weight == $newweight) {
c4308cfa 750 return false;
d23157d8 751 }
e028ed34 752
753 //make room for block insert
754 if (!empty($pinned)) {
d23157d8 755 $sql = 'UPDATE '. $CFG->prefix .'block_instance SET weight = weight + 1 '.
756 'WHERE pagetype = \''. $instance->pagetype.
757 '\' AND position = \'' .$newpos.
758 '\' AND weight >= '. $newweight;
e028ed34 759 } else {
d23157d8 760 $sql = 'UPDATE '. $CFG->prefix .'block_instance SET weight = weight + 1 '.
761 'WHERE pagetype = \''. $instance->pagetype.
762 '\' AND pageid = '. $instance->pageid.
763 ' AND position = \'' .$newpos.
764 '\' AND weight >= '. $newweight;
77e65ff7 765 }
e028ed34 766 execute_sql($sql,false);
767
c4308cfa 768 //adjusts the wieghts for changes in the weight list
d23157d8 769 if ($newweight < $instance->weight) {
c4308cfa 770 $instance->weight+=2;
d23157d8 771 } else {
c4308cfa 772 $newweight--;
773 }
e028ed34 774
c4308cfa 775 //reposition blocks
776 blocks_execute_repositioning($instance,$newpos,$newweight,$pinned,false);
e028ed34 777}
778
d23157d8 779
780/**
781 * Returns an array consisting of 2 arrays:
782 * 1) Array of pinned blocks for position BLOCK_POS_LEFT
783 * 2) Array of pinned blocks for position BLOCK_POS_RIGHT
784 */
0d6b9d4f 785function blocks_get_pinned($page) {
786
787 $visible = true;
788
789 if (method_exists($page,'edit_always')) {
790 if ($page->edit_always()) {
791 $visible = false;
792 }
793 }
794
d23157d8 795 $blocks = get_records_select('block_pinned', 'pagetype = \''. $page->get_type() .
796 '\''.(($visible) ? 'AND visible = 1' : ''), 'position, weight');
0d6b9d4f 797
798 $positions = $page->blocks_get_positions();
799 $arr = array();
800
801 foreach($positions as $key => $position) {
802 $arr[$position] = array();
803 }
804
805 if(empty($blocks)) {
806 return $arr;
807 }
808
809 foreach($blocks as $block) {
810 $block->pinned = true; // so we know we can't move it.
ddf1935f 811 // make up an instanceid if we can..
812 $block->pageid = $page->get_id();
0d6b9d4f 813 $arr[$block->position][$block->weight] = $block;
814 }
815
816 return $arr;
817}
818
819
d23157d8 820/**
821 * Similar to blocks_get_by_page(), except that, the array returned includes
822 * pinned blocks as well. Pinned blocks are always appended before normal
823 * block instances.
824 */
0d6b9d4f 825function blocks_get_by_page_pinned($page) {
826 $pinned = blocks_get_pinned($page);
827 $user = blocks_get_by_page($page);
828
829 $weights = array();
830
831 foreach ($pinned as $pos => $arr) {
832 $weights[$pos] = count($arr);
833 }
834
835 foreach ($user as $pos => $blocks) {
836 if (!array_key_exists($pos,$pinned)) {
837 $pinned[$pos] = array();
838 }
839 if (!array_key_exists($pos,$weights)) {
840 $weights[$pos] = 0;
841 }
77e65ff7 842 foreach ($blocks as $block) {
0d6b9d4f 843 $pinned[$pos][$weights[$pos]] = $block;
844 $weights[$pos]++;
845 }
846 }
847 return $pinned;
0f3fe4b6 848}
849
d23157d8 850
851/**
852 * Returns an array of blocks for the page. Pinned blocks are excluded.
853 */
9b4b78fd 854function blocks_get_by_page($page) {
d23157d8 855 $blocks = get_records_select('block_instance', "pageid = '". $page->get_id() .
856 "' AND pagetype = '". $page->get_type() ."'", 'position, weight');
f032aa7a 857
858 $positions = $page->blocks_get_positions();
859 $arr = array();
860 foreach($positions as $key => $position) {
861 $arr[$position] = array();
862 }
0f3fe4b6 863
9b4b78fd 864 if(empty($blocks)) {
865 return $arr;
866 }
0f3fe4b6 867
77e65ff7 868 foreach($blocks as $block) {
9b4b78fd 869 $arr[$block->position][$block->weight] = $block;
0f3fe4b6 870 }
d23157d8 871 return $arr;
9b4b78fd 872}
0f3fe4b6 873
d23157d8 874
9b4b78fd 875//This function prints the block to admin blocks as necessary
c1d8705f 876function blocks_print_adminblock(&$page, &$pageblocks) {
9b4b78fd 877 global $USER;
0f3fe4b6 878
c1d8705f 879 $missingblocks = blocks_get_missing($page, $pageblocks);
880
9b4b78fd 881 if (!empty($missingblocks)) {
c1d8705f 882 $strblocks = get_string('blocks');
883 $stradd = get_string('add');
9b4b78fd 884 foreach ($missingblocks as $blockid) {
885 $block = blocks_get_record($blockid);
9b4b78fd 886 $blockobject = block_instance($block->name);
887 if ($blockobject === false) {
888 continue;
889 }
11306331 890 if(!$blockobject->user_can_addto($page)) {
891 continue;
892 }
9b4b78fd 893 $menu[$block->id] = $blockobject->get_title();
894 }
4a4c30d2 895 asort($menu);
0f3fe4b6 896
f032aa7a 897 $target = $page->url_get_full(array('sesskey' => $USER->sesskey, 'blockaction' => 'add'));
898 $content = popup_form($target.'&amp;blockid=', $menu, 'add_block', '', $stradd .'...', '', '', true);
afd8402c 899 print_side_block($strblocks, $content, NULL, NULL, NULL, array('class' => 'block_adminblock'));
0f3fe4b6 900 }
0f3fe4b6 901}
902
9b4b78fd 903function blocks_repopulate_page($page) {
904 global $CFG;
5b224948 905
9b4b78fd 906 $allblocks = blocks_get_record();
907
908 if(empty($allblocks)) {
909 error('Could not retrieve blocks from the database');
910 }
911
f032aa7a 912 // Assemble the information to correlate block names to ids
9b4b78fd 913 $idforname = array();
914 foreach($allblocks as $block) {
915 $idforname[$block->name] = $block->id;
916 }
917
f032aa7a 918 /// If the site override has been defined, it is the only valid one.
919 if (!empty($CFG->defaultblocks_override)) {
920 $blocknames = $CFG->defaultblocks_override;
921 }
922 else {
923 $blocknames = $page->blocks_get_default();
924 }
925
926 $positions = $page->blocks_get_positions();
927 $posblocks = explode(':', $blocknames);
928
929 // Now one array holds the names of the positions, and the other one holds the blocks
930 // that are going to go in each position. Luckily for us, both arrays are numerically
931 // indexed and the indexes match, so we can work straight away... but CAREFULLY!
9b4b78fd 932
f032aa7a 933 // Ready to start creating block instances, but first drop any existing ones
934 delete_records('block_instance', 'pageid', $page->get_id(), 'pagetype', $page->get_type());
935
936 // Here we slyly count $posblocks and NOT $positions. This can actually make a difference
937 // if the textual representation has undefined slots in the end. So we only work with as many
938 // positions were retrieved, not with all the page says it has available.
939 $numpositions = count($posblocks);
940 for($i = 0; $i < $numpositions; ++$i) {
941 $position = $positions[$i];
942 $blocknames = explode(',', $posblocks[$i]);
9b4b78fd 943 $weight = 0;
944 foreach($blocknames as $blockname) {
945 $newinstance = new stdClass;
946 $newinstance->blockid = $idforname[$blockname];
f032aa7a 947 $newinstance->pageid = $page->get_id();
948 $newinstance->pagetype = $page->get_type();
9b4b78fd 949 $newinstance->position = $position;
950 $newinstance->weight = $weight;
951 $newinstance->visible = 1;
952 $newinstance->configdata = '';
3cacefda 953
954 if(!empty($newinstance->blockid)) {
955 // Only add block if it was recognized
956 insert_record('block_instance', $newinstance);
957 ++$weight;
958 }
0f3fe4b6 959 }
960 }
9b4b78fd 961
962 return true;
0f3fe4b6 963}
964
965function upgrade_blocks_db($continueto) {
966/// This function upgrades the blocks tables, if necessary
967/// It's called from admin/index.php
968
969 global $CFG, $db;
970
a9c75a9c 971 require_once ($CFG->dirroot .'/blocks/version.php'); // Get code versions
0f3fe4b6 972
973 if (empty($CFG->blocks_version)) { // Blocks have never been installed.
a9c75a9c 974 $strdatabaseupgrades = get_string('databaseupgrades');
a36f058e 975 print_header($strdatabaseupgrades, $strdatabaseupgrades, $strdatabaseupgrades, '',
976 '<script type="text/javascript" src="' . $CFG->wwwroot . '/lib/scroll_to_errors.js"></script>',
977 false, '&nbsp;', '&nbsp;');
0f3fe4b6 978
583fad99 979 upgrade_log_start();
1164af7c 980 print_heading('blocks');
0f3fe4b6 981 $db->debug=true;
1164af7c 982
983 /// Both old .sql files and new install.xml are supported
984 /// but we priorize install.xml (XMLDB) if present
985 $status = false;
db8bd7a6 986 if (file_exists($CFG->dirroot . '/blocks/db/install.xml')) {
1164af7c 987 $status = install_from_xmldb_file($CFG->dirroot . '/blocks/db/install.xml'); //New method
988 } else if (file_exists($CFG->dirroot . '/blocks/db/' . $CFG->dbtype . '.sql')) {
989 $status = modify_database($CFG->dirroot . '/blocks/db/' . $CFG->dbtype . '.sql'); //Old method
990 }
991
992 $db->debug = false;
993 if ($status) {
a9c75a9c 994 if (set_config('blocks_version', $blocks_version)) {
c7a9e293 995 notify(get_string('databasesuccess'), 'notifysuccess');
8549af11 996 notify(get_string('databaseupgradeblocks', '', $blocks_version), 'notifysuccess');
0f3fe4b6 997 print_continue($continueto);
998 exit;
999 } else {
a9c75a9c 1000 error('Upgrade of blocks system failed! (Could not update version in config table)');
0f3fe4b6 1001 }
1002 } else {
a9c75a9c 1003 error('Blocks tables could NOT be set up successfully!');
0f3fe4b6 1004 }
1005 }
1006
1164af7c 1007/// Upgrading code starts here
1008 $oldupgrade = false;
1009 $newupgrade = false;
1010 if (is_readable($CFG->dirroot . '/blocks/db/' . $CFG->dbtype . '.php')) {
1011 include_once($CFG->dirroot . '/blocks/db/' . $CFG->dbtype . '.php'); // defines old upgrading function
1012 $oldupgrade = true;
1013 }
db8bd7a6 1014 if (is_readable($CFG->dirroot . '/blocks/db/upgrade.php')) {
1164af7c 1015 include_once($CFG->dirroot . '/blocks/db/upgrade.php'); // defines new upgrading function
1016 $newupgrade = true;
1017 }
0f3fe4b6 1018
1019 if ($blocks_version > $CFG->blocks_version) { // Upgrade tables
a9c75a9c 1020 $strdatabaseupgrades = get_string('databaseupgrades');
a36f058e 1021 print_header($strdatabaseupgrades, $strdatabaseupgrades, $strdatabaseupgrades, '',
1022 '<script type="text/javascript" src="' . $CFG->wwwroot . '/lib/scroll_to_errors.js"></script>');
583fad99 1023
1024 upgrade_log_start();
1164af7c 1025 print_heading('blocks');
1026
1027 /// Run de old and new upgrade functions for the module
1028 $oldupgrade_function = 'blocks_upgrade';
1029 $newupgrade_function = 'xmldb_blocks_upgrade';
1030
1031 /// First, the old function if exists
1032 $oldupgrade_status = true;
1033 if ($oldupgrade && function_exists($oldupgrade_function)) {
1034 $db->debug = true;
1035 $oldupgrade_status = $oldupgrade_function($CFG->blocks_version);
1036 } else if ($oldupgrade) {
1037 notify ('Upgrade function ' . $oldupgrade_function . ' was not available in ' .
1038 '/blocks/db/' . $CFG->dbtype . '.php');
1039 }
0f3fe4b6 1040
1164af7c 1041 /// Then, the new function if exists and the old one was ok
1042 $newupgrade_status = true;
1043 if ($newupgrade && function_exists($newupgrade_function) && $oldupgrade_status) {
1044 $db->debug = true;
1045 $newupgrade_status = $newupgrade_function($CFG->blocks_version);
1046 } else if ($newupgrade) {
1047 notify ('Upgrade function ' . $newupgrade_function . ' was not available in ' .
1048 '/blocks/db/upgrade.php');
1049 }
1050
1051 $db->debug=false;
1052 /// Now analyze upgrade results
1053 if ($oldupgrade_status && $newupgrade_status) { // No upgrading failed
a9c75a9c 1054 if (set_config('blocks_version', $blocks_version)) {
c7a9e293 1055 notify(get_string('databasesuccess'), 'notifysuccess');
8549af11 1056 notify(get_string('databaseupgradeblocks', '', $blocks_version), 'notifysuccess');
0f3fe4b6 1057 print_continue($continueto);
1058 exit;
1059 } else {
a9c75a9c 1060 error('Upgrade of blocks system failed! (Could not update version in config table)');
0f3fe4b6 1061 }
1062 } else {
a9c75a9c 1063 error('Upgrade failed! See blocks/version.php');
0f3fe4b6 1064 }
1065
1066 } else if ($blocks_version < $CFG->blocks_version) {
583fad99 1067 upgrade_log_start();
b011f733 1068 notify('WARNING!!! The Blocks version you are using is OLDER than the version that made these databases!');
0f3fe4b6 1069 }
1164af7c 1070 upgrade_log_finish();
0f3fe4b6 1071}
1072
1073//This function finds all available blocks and install them
1074//into blocks table or do all the upgrade process if newer
1075function upgrade_blocks_plugins($continueto) {
1076
790647b9 1077 global $CFG, $db;
0f3fe4b6 1078
1079 $blocktitles = array();
1080 $invalidblocks = array();
1081 $validblocks = array();
1082 $notices = array();
1083
1084 //Count the number of blocks in db
9b4b78fd 1085 $blockcount = count_records('block');
0f3fe4b6 1086 //If there isn't records. This is the first install, so I remember it
1087 if ($blockcount == 0) {
1088 $first_install = true;
1089 } else {
1090 $first_install = false;
1091 }
1092
1093 $site = get_site();
1094
9b4b78fd 1095 if (!$blocks = get_list_of_plugins('blocks', 'db') ) {
a9c75a9c 1096 error('No blocks installed!');
0f3fe4b6 1097 }
1098
a9c75a9c 1099 include_once($CFG->dirroot .'/blocks/moodleblock.class.php');
e89d741a 1100 if(!class_exists('block_base')) {
1101 error('Class block_base is not defined or file not found for /blocks/moodleblock.class.php');
0f3fe4b6 1102 }
1103
1104 foreach ($blocks as $blockname) {
1105
a9c75a9c 1106 if ($blockname == 'NEWBLOCK') { // Someone has unzipped the template, ignore it
0f3fe4b6 1107 continue;
1108 }
1109
61abc65b 1110 if(!block_is_compatible($blockname)) {
1111 // This is an old-style block
1112 //$notices[] = 'Block '. $blockname .' is not compatible with the current version of Mooodle and needs to be updated by a programmer.';
1113 $invalidblocks[] = $blockname;
1114 continue;
1115 }
f10306b9 1116
a9c75a9c 1117 $fullblock = $CFG->dirroot .'/blocks/'. $blockname;
0f3fe4b6 1118
9b4b78fd 1119 if ( is_readable($fullblock.'/block_'.$blockname.'.php')) {
1120 include_once($fullblock.'/block_'.$blockname.'.php');
0f3fe4b6 1121 } else {
a9c75a9c 1122 $notices[] = 'Block '. $blockname .': '. $fullblock .'/block_'. $blockname .'.php was not readable';
0f3fe4b6 1123 continue;
1124 }
1125
790647b9 1126 $oldupgrade = false;
1127 $newupgrade = false;
a9c75a9c 1128 if ( @is_dir($fullblock .'/db/')) {
1129 if ( @is_readable($fullblock .'/db/'. $CFG->dbtype .'.php')) {
790647b9 1130 include_once($fullblock .'/db/'. $CFG->dbtype .'.php'); // defines old upgrading function
1131 $oldupgrade = true;
828c4e09 1132 }
790647b9 1133 if ( @is_readable($fullblock .'/db/upgrade.php')) {
1134 include_once($fullblock .'/db/upgrade.php'); // defines new upgrading function
1135 $newupgrade = true;
1136 }
1137 }
1138
e89d741a 1139 $classname = 'block_'.$blockname;
0f3fe4b6 1140 if(!class_exists($classname)) {
a9c75a9c 1141 $notices[] = 'Block '. $blockname .': '. $classname .' not implemented';
0f3fe4b6 1142 continue;
1143 }
1144
9b4b78fd 1145 // Here is the place to see if the block implements a constructor (old style),
1146 // an init() function (new style) or nothing at all (error time).
1147
33bee34c 1148 $constructor = get_class_constructor($classname);
1149 if(empty($constructor)) {
0f3fe4b6 1150 // No constructor
a9c75a9c 1151 $notices[] = 'Block '. $blockname .': class does not have a constructor';
0f3fe4b6 1152 $invalidblocks[] = $blockname;
1153 continue;
1154 }
1155
9b4b78fd 1156 $block = new stdClass; // This may be used to update the db below
1157 $blockobj = new $classname; // This is what we 'll be testing
0f3fe4b6 1158
e89d741a 1159 // Inherits from block_base?
1160 if(!is_subclass_of($blockobj, 'block_base')) {
1161 $notices[] = 'Block '. $blockname .': class does not inherit from block_base';
0f3fe4b6 1162 continue;
1163 }
1164
1165 // OK, it's as we all hoped. For further tests, the object will do them itself.
1166 if(!$blockobj->_self_test()) {
a9c75a9c 1167 $notices[] = 'Block '. $blockname .': self test failed';
0f3fe4b6 1168 continue;
1169 }
1170 $block->version = $blockobj->get_version();
1171
1172 if (!isset($block->version)) {
a9c75a9c 1173 $notices[] = 'Block '. $blockname .': has no version support. It must be updated by a programmer.';
0f3fe4b6 1174 continue;
1175 }
1176
1177 $block->name = $blockname; // The name MUST match the directory
1178 $blocktitle = $blockobj->get_title();
1179
9b4b78fd 1180 if ($currblock = get_record('block', 'name', $block->name)) {
0f3fe4b6 1181 if ($currblock->version == $block->version) {
1182 // do nothing
1183 } else if ($currblock->version < $block->version) {
1184 if (empty($updated_blocks)) {
a9c75a9c 1185 $strblocksetup = get_string('blocksetup');
a36f058e 1186 print_header($strblocksetup, $strblocksetup, $strblocksetup, '',
1187 '<script type="text/javascript" src="' . $CFG->wwwroot . '/lib/scroll_to_errors.js"></script>',
1188 false, '&nbsp;', '&nbsp;');
0f3fe4b6 1189 }
790647b9 1190 $updated_blocks = true;
583fad99 1191 upgrade_log_start();
b88f7004 1192 print_heading('New version of '.$blocktitle.' ('.$block->name.') exists');
790647b9 1193 @set_time_limit(0); // To allow slow databases to complete the long SQL
1194
1195 /// Run de old and new upgrade functions for the module
1196 $oldupgrade_function = $block->name .'_upgrade';
32ac8473 1197 $newupgrade_function = 'xmldb_block_' . $block->name .'_upgrade';
790647b9 1198
1199 /// First, the old function if exists
1200 $oldupgrade_status = true;
1201 if ($oldupgrade && function_exists($oldupgrade_function)) {
1202 $db->debug = true;
1203 $oldupgrade_status = $oldupgrade_function($currblock->version, $block);
1204 } else if ($oldupgrade) {
1205 notify ('Upgrade function ' . $oldupgrade_function . ' was not available in ' .
1206 $fullblock . '/db/' . $CFG->dbtype . '.php');
b88f7004 1207 }
790647b9 1208
1209 /// Then, the new function if exists and the old one was ok
1210 $newupgrade_status = true;
1211 if ($newupgrade && function_exists($newupgrade_function) && $oldupgrade_status) {
1212 $db->debug = true;
1213 $newupgrade_status = $newupgrade_function($currblock->version, $block);
1214 } else if ($newupgrade) {
1215 notify ('Upgrade function ' . $newupgrade_function . ' was not available in ' .
1216 $fullblock . '/db/upgrade.php');
bbbf2d40 1217 }
790647b9 1218
1219 $db->debug=false;
1220 /// Now analyze upgrade results
1221 if ($oldupgrade_status && $newupgrade_status) { // No upgrading failed
9b4b78fd 1222 // OK so far, now update the block record
b88f7004 1223 $block->id = $currblock->id;
9b4b78fd 1224 if (! update_record('block', $block)) {
a9c75a9c 1225 error('Could not update block '. $block->name .' record in block table!');
0f3fe4b6 1226 }
48f6bcdd 1227 $component = 'block/'.$block->name;
1228 if (!update_capabilities($component)) {
790647b9 1229 error('Could not update '.$block->name.' capabilities!');
1230 }
c7a9e293 1231 notify(get_string('blocksuccess', '', $blocktitle), 'notifysuccess');
790647b9 1232 } else {
1233 notify('Upgrading block '. $block->name .' from '. $currblock->version .' to '. $block->version .' FAILED!');
0f3fe4b6 1234 }
790647b9 1235 echo '<hr />';
0f3fe4b6 1236 } else {
583fad99 1237 upgrade_log_start();
a9c75a9c 1238 error('Version mismatch: block '. $block->name .' can\'t downgrade '. $currblock->version .' -> '. $block->version .'!');
0f3fe4b6 1239 }
1240
1241 } else { // block not installed yet, so install it
1242
9b4b78fd 1243 // If it allows multiples, start with it enabled
1244 $block->multiple = $blockobj->instance_allow_multiple();
f9648e77 1245 if (!empty($blockobj->cron)) {
1246 $block->cron = $blockobj->cron;
1247 }
9b4b78fd 1248
0f3fe4b6 1249 // [pj] Normally this would be inline in the if, but we need to
1250 // check for NULL (necessary for 4.0.5 <= PHP < 4.2.0)
1251 $conflictblock = array_search($blocktitle, $blocktitles);
1252 if($conflictblock !== false && $conflictblock !== NULL) {
0f3fe4b6 1253 // Duplicate block titles are not allowed, they confuse people
1254 // AND PHP's associative arrays ;)
1255 error('<strong>Naming conflict</strong>: block <strong>'.$block->name.'</strong> has the same title with an existing block, <strong>'.$conflictblock.'</strong>!');
1256 }
1257 if (empty($updated_blocks)) {
a9c75a9c 1258 $strblocksetup = get_string('blocksetup');
a36f058e 1259 print_header($strblocksetup, $strblocksetup, $strblocksetup, '',
1260 '<script type="text/javascript" src="' . $CFG->wwwroot . '/lib/scroll_to_errors.js"></script>',
1261 false, '&nbsp;', '&nbsp;');
0f3fe4b6 1262 }
790647b9 1263 $updated_blocks = true;
583fad99 1264 upgrade_log_start();
0f3fe4b6 1265 print_heading($block->name);
0f3fe4b6 1266 $db->debug = true;
a71bfa1c 1267 @set_time_limit(0); // To allow slow databases to complete the long SQL
790647b9 1268
1269 /// Both old .sql files and new install.xml are supported
1270 /// but we priorize install.xml (XMLDB) if present
1271 $status = false;
db8bd7a6 1272 if (file_exists($fullblock . '/db/install.xml')) {
790647b9 1273 $status = install_from_xmldb_file($fullblock . '/db/install.xml'); //New method
1274 } else if (file_exists($fullblock .'/db/'. $CFG->dbtype .'.sql')) {
1275 $status = modify_database($fullblock .'/db/'. $CFG->dbtype .'.sql'); //Old method
1276 } else {
1277 $status = true;
1278 }
1279
1280 $db->debug = false;
1281 if ($status) {
9b4b78fd 1282 if ($block->id = insert_record('block', $block)) {
44c55d46 1283 $blockobj->after_install();
48f6bcdd 1284 $component = 'block/'.$block->name;
1285 if (!update_capabilities($component)) {
790647b9 1286 notify('Could not set up '.$block->name.' capabilities!');
1287 }
c7a9e293 1288 notify(get_string('blocksuccess', '', $blocktitle), 'notifysuccess');
a9c75a9c 1289 echo '<hr />';
0f3fe4b6 1290 } else {
a9c75a9c 1291 error($block->name .' block could not be added to the block list!');
0f3fe4b6 1292 }
1293 } else {
a9c75a9c 1294 error('Block '. $block->name .' tables could NOT be set up successfully!');
0f3fe4b6 1295 }
1296 }
1297
1298 $blocktitles[$block->name] = $blocktitle;
1299 }
1300
1301 if(!empty($notices)) {
583fad99 1302 upgrade_log_start();
0f3fe4b6 1303 foreach($notices as $notice) {
1304 notify($notice);
1305 }
1306 }
1307
9b4b78fd 1308 // Finally, if we are in the first_install of BLOCKS (this means that we are
1309 // upgrading from Moodle < 1.3), put blocks in all existing courses.
0f3fe4b6 1310 if ($first_install) {
583fad99 1311 upgrade_log_start();
0f3fe4b6 1312 //Iterate over each course
9b4b78fd 1313 if ($courses = get_records('course')) {
0f3fe4b6 1314 foreach ($courses as $course) {
7542a4e5 1315 $page = page_create_object(PAGE_COURSE_VIEW, $course->id);
9b4b78fd 1316 blocks_repopulate_page($page);
0f3fe4b6 1317 }
1318 }
1319 }
1320
e02c35b2 1321 if (!empty($CFG->siteblocksadded)) { /// This is a once-off hack to make a proper upgrade
583fad99 1322 upgrade_log_start();
7542a4e5 1323 $page = page_create_object(PAGE_COURSE_VIEW, SITEID);
9b4b78fd 1324 blocks_repopulate_page($page);
e02c35b2 1325 delete_records('config', 'name', 'siteblocksadded');
1326 }
1327
583fad99 1328 upgrade_log_finish();
1329
0f3fe4b6 1330 if (!empty($updated_blocks)) {
1331 print_continue($continueto);
1332 die;
1333 }
1334}
1335
f10306b9 1336?>