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