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