Course/import.php should check for teacher
[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
f032aa7a 14require_once($CFG->libdir.'/pagelib.php');
0f3fe4b6 15
33bee34c 16// Returns the case-sensitive name of the class' constructor function. This includes both
17// PHP5- and PHP4-style constructors. If no appropriate constructor can be found, returns NULL.
18// If there is no such class, returns boolean false.
19function get_class_constructor($classname) {
20 // Caching
21 static $constructors = array();
22
23 if(!class_exists($classname)) {
24 return false;
25 }
26
27 // Tests indicate this doesn't hurt even in PHP5.
28 $classname = strtolower($classname);
29
30 // Return cached value, if exists
31 if(isset($constructors[$classname])) {
32 return $constructors[$classname];
33 }
34
35 // Get a list of methods. After examining several different ways of
36 // doing the check, (is_callable, method_exists, function_exists etc)
37 // it seems that this is the most reliable one.
38 $methods = get_class_methods($classname);
39
40 // PHP5 constructor?
41 if(phpversion() >= '5') {
42 if(in_array('__construct', $methods)) {
43 return $constructors[$classname] = '__construct';
44 }
45 }
46
47 // If we have PHP5 but no magic constructor, we have to lowercase the methods
48 $methods = array_map('strtolower', $methods);
49
50 if(in_array($classname, $methods)) {
51 return $constructors[$classname] = $classname;
52 }
53
54 return $constructors[$classname] = NULL;
55}
56
0f3fe4b6 57//This function retrieves a method-defined property of a class WITHOUT instantiating an object
58//It seems that the only way to use the :: operator with variable class names is eval() :(
59//For caveats with this technique, see the PHP docs on operator ::
60function block_method_result($blockname, $method) {
61 if(!block_load_class($blockname)) {
62 return NULL;
63 }
e89d741a 64 return eval('return block_'.$blockname.'::'.$method.'();');
0f3fe4b6 65}
66
67//This function creates a new object of the specified block class
9b4b78fd 68function block_instance($blockname, $instance = NULL) {
0f3fe4b6 69 if(!block_load_class($blockname)) {
70 return false;
71 }
e89d741a 72 $classname = 'block_'.$blockname;
f032aa7a 73 $retval = new $classname;
9b4b78fd 74 if($instance !== NULL) {
1345403a 75 $retval->_load_instance($instance);
9b4b78fd 76 }
77 return $retval;
0f3fe4b6 78}
79
80//This function loads the necessary class files for a block
81//Whenever you want to load a block, use this first
82function block_load_class($blockname) {
83 global $CFG;
84
c7a9e293 85 if (empty($blockname)) {
86 return false;
87 }
88
febeb161 89 include_once($CFG->dirroot.'/blocks/moodleblock.class.php');
e89d741a 90 $classname = 'block_'.$blockname;
febeb161 91 include_once($CFG->dirroot.'/blocks/'.$blockname.'/block_'.$blockname.'.php');
0f3fe4b6 92
93 // After all this, return value indicating success or failure
94 return class_exists($classname);
95}
96
c8e0b579 97// This function returns an array with the IDs of any blocks that you can add to your page.
98// Parameters are passed by reference for speed; they are not modified at all.
99function blocks_get_missing(&$page, &$pageblocks) {
f032aa7a 100
101 $missingblocks = array();
102 $allblocks = blocks_get_record();
103 $pageformat = $page->get_format_name();
104
105 if(!empty($allblocks)) {
106 foreach($allblocks as $block) {
107 if($block->visible && (!blocks_find_block($block->id, $pageblocks) || $block->multiple)) {
108 // And if it's applicable for display in this format...
5bbbe0be 109 if(blocks_name_allowed_in_format($block->name, $pageformat)) {
8a47e075 110 // ...add it to the missing blocks
f032aa7a 111 $missingblocks[] = $block->id;
112 }
113 }
114 }
115 }
116 return $missingblocks;
117}
118
119function blocks_remove_inappropriate($page) {
120 $pageblocks = blocks_get_by_page($page);
121
122 if(empty($pageblocks)) {
123 return;
124 }
125
126 if(($pageformat = $page->get_format_name()) == NULL) {
127 return;
128 }
129
130 foreach($pageblocks as $position) {
131 foreach($position as $instance) {
132 $block = blocks_get_record($instance->blockid);
5bbbe0be 133 if(!blocks_name_allowed_in_format($block->name, $pageformat)) {
8a47e075 134 blocks_delete_instance($instance);
f032aa7a 135 }
136 }
137 }
138}
139
5bbbe0be 140function blocks_name_allowed_in_format($name, $pageformat) {
141 $formats = block_method_result($name, 'applicable_formats');
142 $accept = NULL;
143 $depth = -1;
144 foreach($formats as $format => $allowed) {
145 $thisformat = '^'.str_replace('*', '[^-]*', $format).'.*$';
146 if(ereg($thisformat, $pageformat)) {
147 if(($scount = substr_count($format, '-')) > $depth) {
148 $depth = $scount;
149 $accept = $allowed;
150 }
151 }
152 }
153 if($accept === NULL) {
154 $accept = !empty($formats['all']);
155 }
156 return $accept;
157}
158
f032aa7a 159function blocks_delete_instance($instance) {
160 global $CFG;
161
162 delete_records('block_instance', 'id', $instance->id);
163 // And now, decrement the weight of all blocks after this one
164 execute_sql('UPDATE '.$CFG->prefix.'block_instance SET weight = weight - 1 WHERE pagetype = \''.$instance->pagetype.
165 '\' AND pageid = '.$instance->pageid.' AND position = \''.$instance->position.
166 '\' AND weight > '.$instance->weight, false);
167}
168
c8e0b579 169// Accepts an array of block instances and checks to see if any of them have content to display
170// (causing them to calculate their content in the process). Returns true or false. Parameter passed
171// by reference for speed; the array is actually not modified.
172function blocks_have_content(&$instances) {
9b4b78fd 173 foreach($instances as $instance) {
7933cc6b 174 if (!$instance->visible) {
175 continue;
176 }
177 if (!$record = blocks_get_record($instance->blockid)) {
178 continue;
179 }
180 if (!$obj = block_instance($record->name, $instance)) {
9b4b78fd 181 continue;
182 }
9b4b78fd 183 $content = $obj->get_content();
184 $type = $obj->get_content_type();
185 switch($type) {
186 case BLOCK_TYPE_LIST:
187 if(!empty($content->items) || !empty($content->footer)) {
188 return true;
189 }
190 break;
191 case BLOCK_TYPE_TEXT:
192 case BLOCK_TYPE_NUKE:
193 if(!empty($content->text) || !empty($content->footer)) {
194 return true;
195 }
196 break;
0f3fe4b6 197 }
198 }
9b4b78fd 199
0f3fe4b6 200 return false;
201}
202
c8e0b579 203// This function prints one group of blocks in a page
204// Parameters passed by reference for speed; they are not modified.
205function blocks_print_group(&$page, &$instances) {
9b4b78fd 206
207 if(empty($instances)) {
208 return;
209 }
0f3fe4b6 210
f032aa7a 211 $isediting = $page->user_is_editing();
0f3fe4b6 212
9b4b78fd 213 $maxweight = max(array_keys($instances));
0f3fe4b6 214
9b4b78fd 215 foreach($instances as $instance) {
216 $block = blocks_get_record($instance->blockid);
217 if(!$block->visible) {
218 // Disabled by the admin
219 continue;
220 }
0f3fe4b6 221
ab0e4dd4 222 if (!$obj = block_instance($block->name, $instance)) {
223 // Invalid block
224 continue;
225 }
0f3fe4b6 226
f032aa7a 227 if ($isediting) {
9b4b78fd 228 $options = 0;
f032aa7a 229 // 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:
230 // the first block might still be able to move up if the page says so (i.e., it will change position)
231 $options |= BLOCK_MOVE_UP * ($instance->weight != 0 || ($page->blocks_move_position($instance, BLOCK_MOVE_UP) != $instance->position));
232 // Same thing for downward movement
233 $options |= BLOCK_MOVE_DOWN * ($instance->weight != $maxweight || ($page->blocks_move_position($instance, BLOCK_MOVE_DOWN) != $instance->position));
234 // For left and right movements, it's up to the page to tell us whether they are allowed
235 $options |= BLOCK_MOVE_RIGHT * ($page->blocks_move_position($instance, BLOCK_MOVE_RIGHT) != $instance->position);
236 $options |= BLOCK_MOVE_LEFT * ($page->blocks_move_position($instance, BLOCK_MOVE_LEFT ) != $instance->position);
237 // Finally, the block can be configured if the block class either allows multiple instances, or if it specifically
238 // allows instance configuration (multiple instances override that one). It doesn't have anything to do with what the
239 // administrator has allowed for this block in the site admin options.
240 $options |= BLOCK_CONFIGURE * ( $obj->instance_allow_multiple() || $obj->instance_allow_config() );
1345403a 241 $obj->_add_edit_controls($options);
9b4b78fd 242 }
0f3fe4b6 243
9b4b78fd 244 if(!$instance->visible) {
245 if($isediting) {
1345403a 246 $obj->_print_shadow();
0f3fe4b6 247 }
248 }
9b4b78fd 249 else {
1345403a 250 $obj->_print_block();
9b4b78fd 251 }
0f3fe4b6 252 }
253}
254
c8e0b579 255// This iterates over an array of blocks and calculates the preferred width
256// Parameter passed by reference for speed; it's not modified.
257function blocks_preferred_width(&$instances) {
0f3fe4b6 258 $width = 0;
259
9b4b78fd 260 if(empty($instances) || !is_array($instances)) {
0f3fe4b6 261 return 0;
262 }
9b4b78fd 263 foreach($instances as $instance) {
264 if(!$instance->visible) {
fe78a3dc 265 continue;
0c9c6363 266 }
9b4b78fd 267 $block = blocks_get_record($instance->blockid);
268 $pref = block_method_result($block->name, 'preferred_width');
269 if($pref === NULL) {
270 continue;
271 }
272 if($pref > $width) {
273 $width = $pref;
0f3fe4b6 274 }
275 }
276 return $width;
277}
278
9b4b78fd 279function blocks_get_record($blockid = NULL, $invalidate = false) {
280 static $cache = NULL;
0f3fe4b6 281
9b4b78fd 282 if($invalidate || empty($cache)) {
eca3b01f 283 $cache = get_records('block');
9b4b78fd 284 }
0f3fe4b6 285
9b4b78fd 286 if($blockid === NULL) {
287 return $cache;
288 }
0f3fe4b6 289
9b4b78fd 290 return (isset($cache[$blockid])? $cache[$blockid] : false);
291}
292
293function blocks_find_block($blockid, $blocksarray) {
294 foreach($blocksarray as $blockgroup) {
295 foreach($blockgroup as $instance) {
296 if($instance->blockid == $blockid) {
297 return $instance;
298 }
299 }
300 }
301 return false;
302}
303
304function blocks_find_instance($instanceid, $blocksarray) {
305 foreach($blocksarray as $subarray) {
306 foreach($subarray as $instance) {
307 if($instance->id == $instanceid) {
308 return $instance;
309 }
310 }
311 }
312 return false;
313}
314
ec79d3e4 315// Simple entry point for anyone that wants to use blocks
316function blocks_setup(&$PAGE) {
317 $pageblocks = blocks_get_by_page($PAGE);
318 blocks_execute_url_action($PAGE, $pageblocks);
319 return $pageblocks;
320}
321
9b4b78fd 322function blocks_execute_action($page, &$pageblocks, $blockaction, $instanceorid) {
323 global $CFG;
324
a9c75a9c 325 if (is_int($instanceorid)) {
9b4b78fd 326 $blockid = $instanceorid;
a9c75a9c 327 } else if (is_object($instanceorid)) {
9b4b78fd 328 $instance = $instanceorid;
329 }
0f3fe4b6 330
331 switch($blockaction) {
9b4b78fd 332 case 'config':
f032aa7a 333 global $USER;
9b4b78fd 334 $block = blocks_get_record($instance->blockid);
e82d6cac 335 // Hacky hacky tricky stuff to get the original human readable block title,
336 // even if the block has configured its title to be something else.
337 // Create the object WITHOUT instance data.
338 $blockobject = block_instance($block->name);
9b4b78fd 339 if ($blockobject === false) {
340 continue;
341 }
e82d6cac 342 // Now get the title and AFTER that load up the instance
343 $blocktitle = $blockobject->get_title();
344 $blockobject->_load_instance($instance);
345
9b4b78fd 346 optional_param('submitted', 0, PARAM_INT);
347
27ec21a0 348 // Define the data we're going to silently include in the instance config form here,
9b4b78fd 349 // so we can strip them from the submitted data BEFORE serializing it.
350 $hiddendata = array(
351 'sesskey' => $USER->sesskey,
9b4b78fd 352 'instanceid' => $instance->id,
353 'blockaction' => 'config'
354 );
f032aa7a 355
356 // To this data, add anything the page itself needs to display
357 $hiddendata = array_merge($hiddendata, $page->url_get_parameters());
9b4b78fd 358
359 if($data = data_submitted()) {
360 $remove = array_keys($hiddendata);
361 foreach($remove as $item) {
362 unset($data->$item);
0f3fe4b6 363 }
9b4b78fd 364 if(!$blockobject->instance_config_save($data)) {
365 error('Error saving block configuration');
0f3fe4b6 366 }
9b4b78fd 367 // And nothing more, continue with displaying the page
0f3fe4b6 368 }
9b4b78fd 369 else {
f032aa7a 370 // We need to show the config screen, so we highjack the display logic and then die
e82d6cac 371 $strheading = get_string('blockconfiga', 'moodle', $blocktitle);
edb42f09 372 $page->print_header(get_string('pageheaderconfigablock', 'moodle'), array($strheading => ''));
373 print_heading($strheading);
f032aa7a 374 echo '<form method="post" action="'. $page->url_get_path() .'">';
9b4b78fd 375 echo '<p>';
376 foreach($hiddendata as $name => $val) {
27ec21a0 377 echo '<input type="hidden" name="'. $name .'" value="'. $val .'" />';
0f3fe4b6 378 }
9b4b78fd 379 echo '</p>';
380 $blockobject->instance_config_print();
381 echo '</form>';
382 print_footer();
f032aa7a 383 die(); // Do not go on with the other page-related stuff
0f3fe4b6 384 }
385 break;
9b4b78fd 386 case 'toggle':
387 if(empty($instance)) {
388 error('Invalid block instance for '.$blockaction);
0f3fe4b6 389 }
9b4b78fd 390 $instance->visible = ($instance->visible) ? 0 : 1;
391 update_record('block_instance', $instance);
392 break;
393 case 'delete':
394 if(empty($instance)) {
a9c75a9c 395 error('Invalid block instance for '. $blockaction);
0f3fe4b6 396 }
9b4b78fd 397 blocks_delete_instance($instance);
0f3fe4b6 398 break;
399 case 'moveup':
9b4b78fd 400 if(empty($instance)) {
a9c75a9c 401 error('Invalid block instance for '. $blockaction);
9b4b78fd 402 }
f032aa7a 403
404 if($instance->weight == 0) {
405 // The block is the first one, so a move "up" probably means it changes position
406 // Where is the instance going to be moved?
407 $newpos = $page->blocks_move_position($instance, BLOCK_MOVE_UP);
6b853ff4 408 $newweight = (empty($pageblocks[$newpos]) ? 0 : max(array_keys($pageblocks[$newpos])) + 1);
f032aa7a 409
410 blocks_execute_repositioning($instance, $newpos, $newweight);
89a5baab 411 }
f032aa7a 412 else {
413 // The block is just moving upwards in the same position.
414 // This configuration will make sure that even if somehow the weights
415 // become not continuous, block move operations will eventually bring
416 // the situation back to normal without printing any warnings.
417 if(!empty($pageblocks[$instance->position][$instance->weight - 1])) {
418 $other = $pageblocks[$instance->position][$instance->weight - 1];
419 }
420 if(!empty($other)) {
421 ++$other->weight;
422 update_record('block_instance', $other);
423 }
424 --$instance->weight;
425 update_record('block_instance', $instance);
0f3fe4b6 426 }
427 break;
428 case 'movedown':
9b4b78fd 429 if(empty($instance)) {
a9c75a9c 430 error('Invalid block instance for '. $blockaction);
9b4b78fd 431 }
f032aa7a 432
433 if($instance->weight == max(array_keys($pageblocks[$instance->position]))) {
434 // The block is the last one, so a move "down" probably means it changes position
435 // Where is the instance going to be moved?
436 $newpos = $page->blocks_move_position($instance, BLOCK_MOVE_DOWN);
6b853ff4 437 $newweight = (empty($pageblocks[$newpos]) ? 0 : max(array_keys($pageblocks[$newpos])) + 1);
f032aa7a 438
439 blocks_execute_repositioning($instance, $newpos, $newweight);
89a5baab 440 }
f032aa7a 441 else {
442 // The block is just moving downwards in the same position.
443 // This configuration will make sure that even if somehow the weights
444 // become not continuous, block move operations will eventually bring
445 // the situation back to normal without printing any warnings.
446 if(!empty($pageblocks[$instance->position][$instance->weight + 1])) {
447 $other = $pageblocks[$instance->position][$instance->weight + 1];
448 }
449 if(!empty($other)) {
450 --$other->weight;
451 update_record('block_instance', $other);
452 }
453 ++$instance->weight;
454 update_record('block_instance', $instance);
0f3fe4b6 455 }
456 break;
9b4b78fd 457 case 'moveleft':
458 if(empty($instance)) {
a9c75a9c 459 error('Invalid block instance for '. $blockaction);
9b4b78fd 460 }
f032aa7a 461
462 // Where is the instance going to be moved?
463 $newpos = $page->blocks_move_position($instance, BLOCK_MOVE_LEFT);
6b853ff4 464 $newweight = (empty($pageblocks[$newpos]) ? 0 : max(array_keys($pageblocks[$newpos])) + 1);
f032aa7a 465
466 blocks_execute_repositioning($instance, $newpos, $newweight);
0f3fe4b6 467 break;
9b4b78fd 468 case 'moveright':
469 if(empty($instance)) {
a9c75a9c 470 error('Invalid block instance for '. $blockaction);
9b4b78fd 471 }
f032aa7a 472
473 // Where is the instance going to be moved?
474 $newpos = $page->blocks_move_position($instance, BLOCK_MOVE_RIGHT);
6b853ff4 475 $newweight = (empty($pageblocks[$newpos]) ? 0 : max(array_keys($pageblocks[$newpos])) + 1);
f032aa7a 476
477 blocks_execute_repositioning($instance, $newpos, $newweight);
9b4b78fd 478 break;
479 case 'add':
480 // Add a new instance of this block, if allowed
481 $block = blocks_get_record($blockid);
0f3fe4b6 482
3cacefda 483 if(empty($block) || !$block->visible) {
484 // Only allow adding if the block exists and is enabled
9b4b78fd 485 return false;
486 }
0f3fe4b6 487
89a5baab 488 if(!$block->multiple && blocks_find_block($blockid, $pageblocks) !== false) {
489 // If no multiples are allowed and we already have one, return now
490 return false;
491 }
492
f032aa7a 493 $newpos = $page->blocks_default_position();
494 $weight = get_record_sql('SELECT 1, max(weight) + 1 AS nextfree FROM '. $CFG->prefix .'block_instance WHERE pageid = '. $page->get_id() .' AND pagetype = \''. $page->get_type() .'\' AND position = \''. $newpos .'\'');
9b4b78fd 495
496 $newinstance = new stdClass;
497 $newinstance->blockid = $blockid;
f032aa7a 498 $newinstance->pageid = $page->get_id();
499 $newinstance->pagetype = $page->get_type();
500 $newinstance->position = $newpos;
ff679897 501 $newinstance->weight = empty($weight->nextfree) ? 0 : $weight->nextfree;
9b4b78fd 502 $newinstance->visible = 1;
503 $newinstance->configdata = '';
504 insert_record('block_instance', $newinstance);
505 break;
506 }
f032aa7a 507
508 // In order to prevent accidental duplicate actions, redirect to a page with a clean url
509 redirect($page->url_get_full());
510}
511
da71112b 512// You can use this to get the blocks to respond to URL actions without much hassle
513function blocks_execute_url_action(&$PAGE, &$pageblocks) {
514 $blockaction = optional_param('blockaction');
515
3edc57e1 516 if (empty($blockaction) || !$PAGE->user_allowed_editing() || !confirm_sesskey()) {
da71112b 517 return;
518 }
519
520 $instanceid = optional_param('instanceid', 0, PARAM_INT);
521 $blockid = optional_param('blockid', 0, PARAM_INT);
522
523 if (!empty($blockid)) {
524 blocks_execute_action($PAGE, $pageblocks, strtolower($blockaction), $blockid);
525
526 }
527 else if (!empty($instanceid)) {
528 $instance = blocks_find_instance($instanceid, $pageblocks);
529 blocks_execute_action($PAGE, $pageblocks, strtolower($blockaction), $instance);
530 }
531}
532
f032aa7a 533// This shouldn't be used externally at all, it's here for use by blocks_execute_action()
534// in order to reduce code repetition.
535function blocks_execute_repositioning(&$instance, $newpos, $newweight) {
536 global $CFG;
537
538 // If it's staying where it is, don't do anything
539 if($newpos == $instance->position) {
540 return;
541 }
542
543 // Close the weight gap we 'll leave behind
544 execute_sql('UPDATE '. $CFG->prefix .'block_instance SET weight = weight - 1 WHERE pagetype = \''. $instance->pagetype.
545 '\' AND pageid = '. $instance->pageid .' AND position = \'' .$instance->position.
546 '\' AND weight > '. $instance->weight,
547 false);
548
549 $instance->position = $newpos;
550 $instance->weight = $newweight;
551
552 update_record('block_instance', $instance);
0f3fe4b6 553}
554
9b4b78fd 555function blocks_get_by_page($page) {
f032aa7a 556 $blocks = get_records_select('block_instance', 'pageid = '. $page->get_id() .' AND pagetype = \''. $page->get_type() .'\'', 'position, weight');
557
558 $positions = $page->blocks_get_positions();
559 $arr = array();
560 foreach($positions as $key => $position) {
561 $arr[$position] = array();
562 }
0f3fe4b6 563
9b4b78fd 564 if(empty($blocks)) {
565 return $arr;
566 }
0f3fe4b6 567
9b4b78fd 568 foreach($blocks as $block) {
569 $arr[$block->position][$block->weight] = $block;
0f3fe4b6 570 }
571
9b4b78fd 572 return $arr;
573}
0f3fe4b6 574
9b4b78fd 575//This function prints the block to admin blocks as necessary
c1d8705f 576function blocks_print_adminblock(&$page, &$pageblocks) {
9b4b78fd 577 global $USER;
0f3fe4b6 578
c1d8705f 579 $missingblocks = blocks_get_missing($page, $pageblocks);
580
9b4b78fd 581 if (!empty($missingblocks)) {
c1d8705f 582 $strblocks = get_string('blocks');
583 $stradd = get_string('add');
9b4b78fd 584 foreach ($missingblocks as $blockid) {
585 $block = blocks_get_record($blockid);
9b4b78fd 586 $blockobject = block_instance($block->name);
587 if ($blockobject === false) {
588 continue;
589 }
590 $menu[$block->id] = $blockobject->get_title();
591 }
4a4c30d2 592 asort($menu);
0f3fe4b6 593
f032aa7a 594 $target = $page->url_get_full(array('sesskey' => $USER->sesskey, 'blockaction' => 'add'));
595 $content = popup_form($target.'&amp;blockid=', $menu, 'add_block', '', $stradd .'...', '', '', true);
afd8402c 596 print_side_block($strblocks, $content, NULL, NULL, NULL, array('class' => 'block_adminblock'));
0f3fe4b6 597 }
0f3fe4b6 598}
599
9b4b78fd 600function blocks_repopulate_page($page) {
601 global $CFG;
5b224948 602
9b4b78fd 603 $allblocks = blocks_get_record();
604
605 if(empty($allblocks)) {
606 error('Could not retrieve blocks from the database');
607 }
608
f032aa7a 609 // Assemble the information to correlate block names to ids
9b4b78fd 610 $idforname = array();
611 foreach($allblocks as $block) {
612 $idforname[$block->name] = $block->id;
613 }
614
f032aa7a 615 /// If the site override has been defined, it is the only valid one.
616 if (!empty($CFG->defaultblocks_override)) {
617 $blocknames = $CFG->defaultblocks_override;
618 }
619 else {
620 $blocknames = $page->blocks_get_default();
621 }
622
623 $positions = $page->blocks_get_positions();
624 $posblocks = explode(':', $blocknames);
625
626 // Now one array holds the names of the positions, and the other one holds the blocks
627 // that are going to go in each position. Luckily for us, both arrays are numerically
628 // indexed and the indexes match, so we can work straight away... but CAREFULLY!
9b4b78fd 629
f032aa7a 630 // Ready to start creating block instances, but first drop any existing ones
631 delete_records('block_instance', 'pageid', $page->get_id(), 'pagetype', $page->get_type());
632
633 // Here we slyly count $posblocks and NOT $positions. This can actually make a difference
634 // if the textual representation has undefined slots in the end. So we only work with as many
635 // positions were retrieved, not with all the page says it has available.
636 $numpositions = count($posblocks);
637 for($i = 0; $i < $numpositions; ++$i) {
638 $position = $positions[$i];
639 $blocknames = explode(',', $posblocks[$i]);
9b4b78fd 640 $weight = 0;
641 foreach($blocknames as $blockname) {
642 $newinstance = new stdClass;
643 $newinstance->blockid = $idforname[$blockname];
f032aa7a 644 $newinstance->pageid = $page->get_id();
645 $newinstance->pagetype = $page->get_type();
9b4b78fd 646 $newinstance->position = $position;
647 $newinstance->weight = $weight;
648 $newinstance->visible = 1;
649 $newinstance->configdata = '';
3cacefda 650
651 if(!empty($newinstance->blockid)) {
652 // Only add block if it was recognized
653 insert_record('block_instance', $newinstance);
654 ++$weight;
655 }
0f3fe4b6 656 }
657 }
9b4b78fd 658
659 return true;
0f3fe4b6 660}
661
662function upgrade_blocks_db($continueto) {
663/// This function upgrades the blocks tables, if necessary
664/// It's called from admin/index.php
665
666 global $CFG, $db;
667
a9c75a9c 668 require_once ($CFG->dirroot .'/blocks/version.php'); // Get code versions
0f3fe4b6 669
670 if (empty($CFG->blocks_version)) { // Blocks have never been installed.
a9c75a9c 671 $strdatabaseupgrades = get_string('databaseupgrades');
0f3fe4b6 672 print_header($strdatabaseupgrades, $strdatabaseupgrades, $strdatabaseupgrades,
a9c75a9c 673 '', '', false, '&nbsp;', '&nbsp;');
0f3fe4b6 674
675 $db->debug=true;
a9c75a9c 676 if (modify_database($CFG->dirroot .'/blocks/db/'. $CFG->dbtype .'.sql')) {
0f3fe4b6 677 $db->debug = false;
a9c75a9c 678 if (set_config('blocks_version', $blocks_version)) {
c7a9e293 679 notify(get_string('databasesuccess'), 'notifysuccess');
a9c75a9c 680 notify(get_string('databaseupgradeblocks', '', $blocks_version));
0f3fe4b6 681 print_continue($continueto);
682 exit;
683 } else {
a9c75a9c 684 error('Upgrade of blocks system failed! (Could not update version in config table)');
0f3fe4b6 685 }
686 } else {
a9c75a9c 687 error('Blocks tables could NOT be set up successfully!');
0f3fe4b6 688 }
689 }
690
691
692 if ($blocks_version > $CFG->blocks_version) { // Upgrade tables
a9c75a9c 693 $strdatabaseupgrades = get_string('databaseupgrades');
0f3fe4b6 694 print_header($strdatabaseupgrades, $strdatabaseupgrades, $strdatabaseupgrades);
695
a9c75a9c 696 require_once ($CFG->dirroot .'/blocks/db/'. $CFG->dbtype .'.php');
0f3fe4b6 697
698 $db->debug=true;
699 if (blocks_upgrade($CFG->blocks_version)) {
700 $db->debug=false;
a9c75a9c 701 if (set_config('blocks_version', $blocks_version)) {
c7a9e293 702 notify(get_string('databasesuccess'), 'notifysuccess');
a9c75a9c 703 notify(get_string('databaseupgradeblocks', '', $blocks_version));
0f3fe4b6 704 print_continue($continueto);
705 exit;
706 } else {
a9c75a9c 707 error('Upgrade of blocks system failed! (Could not update version in config table)');
0f3fe4b6 708 }
709 } else {
710 $db->debug=false;
a9c75a9c 711 error('Upgrade failed! See blocks/version.php');
0f3fe4b6 712 }
713
714 } else if ($blocks_version < $CFG->blocks_version) {
a9c75a9c 715 notify('WARNING!!! The code you are using is OLDER than the version that made these databases!');
0f3fe4b6 716 }
717}
718
719//This function finds all available blocks and install them
720//into blocks table or do all the upgrade process if newer
721function upgrade_blocks_plugins($continueto) {
722
723 global $CFG;
724
725 $blocktitles = array();
726 $invalidblocks = array();
727 $validblocks = array();
728 $notices = array();
729
730 //Count the number of blocks in db
9b4b78fd 731 $blockcount = count_records('block');
0f3fe4b6 732 //If there isn't records. This is the first install, so I remember it
733 if ($blockcount == 0) {
734 $first_install = true;
735 } else {
736 $first_install = false;
737 }
738
739 $site = get_site();
740
9b4b78fd 741 if (!$blocks = get_list_of_plugins('blocks', 'db') ) {
a9c75a9c 742 error('No blocks installed!');
0f3fe4b6 743 }
744
a9c75a9c 745 include_once($CFG->dirroot .'/blocks/moodleblock.class.php');
e89d741a 746 if(!class_exists('block_base')) {
747 error('Class block_base is not defined or file not found for /blocks/moodleblock.class.php');
0f3fe4b6 748 }
749
750 foreach ($blocks as $blockname) {
751
a9c75a9c 752 if ($blockname == 'NEWBLOCK') { // Someone has unzipped the template, ignore it
0f3fe4b6 753 continue;
754 }
755
a9c75a9c 756 $fullblock = $CFG->dirroot .'/blocks/'. $blockname;
0f3fe4b6 757
9b4b78fd 758 if ( is_readable($fullblock.'/block_'.$blockname.'.php')) {
759 include_once($fullblock.'/block_'.$blockname.'.php');
0f3fe4b6 760 } else {
a9c75a9c 761 $notices[] = 'Block '. $blockname .': '. $fullblock .'/block_'. $blockname .'.php was not readable';
0f3fe4b6 762 continue;
763 }
764
a9c75a9c 765 if ( @is_dir($fullblock .'/db/')) {
766 if ( @is_readable($fullblock .'/db/'. $CFG->dbtype .'.php')) {
89a5baab 767 include_once($fullblock .'/db/'. $CFG->dbtype .'.php'); // defines upgrading function
828c4e09 768 } else {
a9c75a9c 769 $notices[] ='Block '. $blockname .': '. $fullblock .'/db/'. $CFG->dbtype .'.php was not readable';
828c4e09 770 continue;
771 }
0f3fe4b6 772 }
773
e89d741a 774 $classname = 'block_'.$blockname;
0f3fe4b6 775 if(!class_exists($classname)) {
a9c75a9c 776 $notices[] = 'Block '. $blockname .': '. $classname .' not implemented';
0f3fe4b6 777 continue;
778 }
779
9b4b78fd 780 // Here is the place to see if the block implements a constructor (old style),
781 // an init() function (new style) or nothing at all (error time).
782
33bee34c 783 $constructor = get_class_constructor($classname);
784 if(empty($constructor)) {
0f3fe4b6 785 // No constructor
a9c75a9c 786 $notices[] = 'Block '. $blockname .': class does not have a constructor';
0f3fe4b6 787 $invalidblocks[] = $blockname;
788 continue;
789 }
9b4b78fd 790 $methods = get_class_methods($classname);
791 if(!in_array('init', $methods)) {
792 // This is an old-style block
a9c75a9c 793 $notices[] = 'Block '. $blockname .' is an old style block and needs to be updated by a programmer.';
9b4b78fd 794 $invalidblocks[] = $blockname;
795 continue;
796 }
0f3fe4b6 797
9b4b78fd 798 $block = new stdClass; // This may be used to update the db below
799 $blockobj = new $classname; // This is what we 'll be testing
0f3fe4b6 800
e89d741a 801 // Inherits from block_base?
802 if(!is_subclass_of($blockobj, 'block_base')) {
803 $notices[] = 'Block '. $blockname .': class does not inherit from block_base';
0f3fe4b6 804 continue;
805 }
806
807 // OK, it's as we all hoped. For further tests, the object will do them itself.
808 if(!$blockobj->_self_test()) {
a9c75a9c 809 $notices[] = 'Block '. $blockname .': self test failed';
0f3fe4b6 810 continue;
811 }
812 $block->version = $blockobj->get_version();
813
814 if (!isset($block->version)) {
a9c75a9c 815 $notices[] = 'Block '. $blockname .': has no version support. It must be updated by a programmer.';
0f3fe4b6 816 continue;
817 }
818
819 $block->name = $blockname; // The name MUST match the directory
820 $blocktitle = $blockobj->get_title();
821
9b4b78fd 822 if ($currblock = get_record('block', 'name', $block->name)) {
0f3fe4b6 823 if ($currblock->version == $block->version) {
824 // do nothing
825 } else if ($currblock->version < $block->version) {
826 if (empty($updated_blocks)) {
a9c75a9c 827 $strblocksetup = get_string('blocksetup');
828 print_header($strblocksetup, $strblocksetup, $strblocksetup, '', '', false, '&nbsp;', '&nbsp;');
0f3fe4b6 829 }
b88f7004 830 print_heading('New version of '.$blocktitle.' ('.$block->name.') exists');
831 $upgrade_function = $block->name.'_upgrade';
0f3fe4b6 832 if (function_exists($upgrade_function)) {
833 $db->debug=true;
834 if ($upgrade_function($currblock->version, $block)) {
b88f7004 835
836 $upgradesuccess = true;
0f3fe4b6 837 } else {
b88f7004 838 $upgradesuccess = false;
839 }
840 $db->debug=false;
841 }
842 else {
843 $upgradesuccess = true;
844 }
845 if(!$upgradesuccess) {
a9c75a9c 846 notify('Upgrading block '. $block->name .' from '. $currblock->version .' to '. $block->version .' FAILED!');
b88f7004 847 }
848 else {
9b4b78fd 849 // OK so far, now update the block record
b88f7004 850 $block->id = $currblock->id;
9b4b78fd 851 if (! update_record('block', $block)) {
a9c75a9c 852 error('Could not update block '. $block->name .' record in block table!');
0f3fe4b6 853 }
c7a9e293 854 notify(get_string('blocksuccess', '', $blocktitle), 'notifysuccess');
b88f7004 855 echo '<hr />';
0f3fe4b6 856 }
857 $updated_blocks = true;
858 } else {
a9c75a9c 859 error('Version mismatch: block '. $block->name .' can\'t downgrade '. $currblock->version .' -> '. $block->version .'!');
0f3fe4b6 860 }
861
862 } else { // block not installed yet, so install it
863
9b4b78fd 864 // If it allows multiples, start with it enabled
865 $block->multiple = $blockobj->instance_allow_multiple();
866
0f3fe4b6 867 // [pj] Normally this would be inline in the if, but we need to
868 // check for NULL (necessary for 4.0.5 <= PHP < 4.2.0)
869 $conflictblock = array_search($blocktitle, $blocktitles);
870 if($conflictblock !== false && $conflictblock !== NULL) {
0f3fe4b6 871 // Duplicate block titles are not allowed, they confuse people
872 // AND PHP's associative arrays ;)
873 error('<strong>Naming conflict</strong>: block <strong>'.$block->name.'</strong> has the same title with an existing block, <strong>'.$conflictblock.'</strong>!');
874 }
875 if (empty($updated_blocks)) {
a9c75a9c 876 $strblocksetup = get_string('blocksetup');
877 print_header($strblocksetup, $strblocksetup, $strblocksetup, '', '', false, '&nbsp;', '&nbsp;');
0f3fe4b6 878 }
879 print_heading($block->name);
880 $updated_blocks = true;
881 $db->debug = true;
a71bfa1c 882 @set_time_limit(0); // To allow slow databases to complete the long SQL
a9c75a9c 883 if (!is_dir($fullblock .'/db/') || modify_database($fullblock .'/db/'. $CFG->dbtype .'.sql')) {
0f3fe4b6 884 $db->debug = false;
9b4b78fd 885 if ($block->id = insert_record('block', $block)) {
c7a9e293 886 notify(get_string('blocksuccess', '', $blocktitle), 'notifysuccess');
a9c75a9c 887 echo '<hr />';
0f3fe4b6 888 } else {
a9c75a9c 889 error($block->name .' block could not be added to the block list!');
0f3fe4b6 890 }
891 } else {
a9c75a9c 892 error('Block '. $block->name .' tables could NOT be set up successfully!');
0f3fe4b6 893 }
894 }
895
896 $blocktitles[$block->name] = $blocktitle;
897 }
898
899 if(!empty($notices)) {
900 foreach($notices as $notice) {
901 notify($notice);
902 }
903 }
904
9b4b78fd 905 // Finally, if we are in the first_install of BLOCKS (this means that we are
906 // upgrading from Moodle < 1.3), put blocks in all existing courses.
0f3fe4b6 907 if ($first_install) {
908 //Iterate over each course
9b4b78fd 909 if ($courses = get_records('course')) {
0f3fe4b6 910 foreach ($courses as $course) {
7542a4e5 911 $page = page_create_object(PAGE_COURSE_VIEW, $course->id);
9b4b78fd 912 blocks_repopulate_page($page);
0f3fe4b6 913 }
914 }
915 }
916
e02c35b2 917 if (!empty($CFG->siteblocksadded)) { /// This is a once-off hack to make a proper upgrade
7542a4e5 918 $page = page_create_object(PAGE_COURSE_VIEW, SITEID);
9b4b78fd 919 blocks_repopulate_page($page);
e02c35b2 920 delete_records('config', 'name', 'siteblocksadded');
921 }
922
0f3fe4b6 923 if (!empty($updated_blocks)) {
924 print_continue($continueto);
925 die;
926 }
927}
928
0f3fe4b6 929?>