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