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