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