merfed fix for 6178
[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');
0f3fe4b6 19
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
25 $file = file($CFG->dirroot.'/blocks/'.$blockname.'/block_'.$blockname.'.php');
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');
febeb161 122 include_once($CFG->dirroot.'/blocks/'.$blockname.'/block_'.$blockname.'.php');
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) {
171 $formats = block_method_result($name, 'applicable_formats');
172 $accept = NULL;
173 $depth = -1;
174 foreach($formats as $format => $allowed) {
175 $thisformat = '^'.str_replace('*', '[^-]*', $format).'.*$';
176 if(ereg($thisformat, $pageformat)) {
177 if(($scount = substr_count($format, '-')) > $depth) {
178 $depth = $scount;
179 $accept = $allowed;
180 }
181 }
182 }
183 if($accept === NULL) {
184 $accept = !empty($formats['all']);
185 }
186 return $accept;
187}
188
0d6b9d4f 189function blocks_delete_instance($instance,$pinned=false) {
f032aa7a 190 global $CFG;
191
b33dd23a 192 // Get the block object and call instance_delete() first
193 if(!$record = blocks_get_record($instance->blockid)) {
2e477369 194 return false;
b33dd23a 195 }
196 if(!$obj = block_instance($record->name, $instance)) {
2e477369 197 return false;
b33dd23a 198 }
199
200 // Return value ignored
201 $obj->instance_delete();
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) {
255
256 if(empty($pageblocks[$position])) {
3f052187 257 $pageblocks[$position] = array();
b35fc182 258 $maxweight = 0;
259 }
260 else {
261 $maxweight = max(array_keys($pageblocks[$position]));
9b4b78fd 262 }
3cdc4597 263
264 foreach ($pageblocks[$position] as $instance) {
4374ee2c 265 if (!empty($instance->pinned)) {
266 $maxweight--;
267 }
268 }
0f3fe4b6 269
f032aa7a 270 $isediting = $page->user_is_editing();
0f3fe4b6 271
66492322 272 foreach($pageblocks[$position] as $instance) {
66c7e47b 273
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 }
66c7e47b 292
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
9b4b78fd 321 if(!$instance->visible) {
322 if($isediting) {
1345403a 323 $obj->_print_shadow();
0f3fe4b6 324 }
325 }
9b4b78fd 326 else {
1345403a 327 $obj->_print_block();
9b4b78fd 328 }
0f3fe4b6 329 }
66492322 330
831cd87f 331 if($page->blocks_default_position() == $position && $page->user_is_editing()) {
66492322 332 blocks_print_adminblock($page, $pageblocks);
333 }
334
0f3fe4b6 335}
336
c8e0b579 337// This iterates over an array of blocks and calculates the preferred width
338// Parameter passed by reference for speed; it's not modified.
339function blocks_preferred_width(&$instances) {
0f3fe4b6 340 $width = 0;
341
9b4b78fd 342 if(empty($instances) || !is_array($instances)) {
0f3fe4b6 343 return 0;
344 }
ff6191b7 345
346 $blocks = blocks_get_record();
347
9b4b78fd 348 foreach($instances as $instance) {
349 if(!$instance->visible) {
fe78a3dc 350 continue;
0c9c6363 351 }
ff6191b7 352
f809df70 353 if (!array_key_exists($instance->blockid, $blocks)) {
354 // Block doesn't exist! We should delete this instance!
355 continue;
356 }
357
ff6191b7 358 if(!$blocks[$instance->blockid]->visible) {
9b687320 359 continue;
360 }
ff6191b7 361 $pref = block_method_result($blocks[$instance->blockid]->name, 'preferred_width');
9b4b78fd 362 if($pref === NULL) {
363 continue;
364 }
365 if($pref > $width) {
366 $width = $pref;
0f3fe4b6 367 }
368 }
369 return $width;
370}
371
9b4b78fd 372function blocks_get_record($blockid = NULL, $invalidate = false) {
373 static $cache = NULL;
0f3fe4b6 374
9b4b78fd 375 if($invalidate || empty($cache)) {
eca3b01f 376 $cache = get_records('block');
9b4b78fd 377 }
0f3fe4b6 378
9b4b78fd 379 if($blockid === NULL) {
380 return $cache;
381 }
0f3fe4b6 382
9b4b78fd 383 return (isset($cache[$blockid])? $cache[$blockid] : false);
384}
385
386function blocks_find_block($blockid, $blocksarray) {
0d6b9d4f 387 if (empty($blocksarray)) {
388 return false;
389 }
9b4b78fd 390 foreach($blocksarray as $blockgroup) {
0d6b9d4f 391 if (empty($blockgroup)) {
392 continue;
393 }
9b4b78fd 394 foreach($blockgroup as $instance) {
395 if($instance->blockid == $blockid) {
396 return $instance;
397 }
398 }
399 }
400 return false;
401}
402
403function blocks_find_instance($instanceid, $blocksarray) {
404 foreach($blocksarray as $subarray) {
405 foreach($subarray as $instance) {
406 if($instance->id == $instanceid) {
407 return $instance;
408 }
409 }
410 }
411 return false;
412}
413
ec79d3e4 414// Simple entry point for anyone that wants to use blocks
ee6055eb 415function blocks_setup(&$PAGE,$pinned=BLOCKS_PINNED_FALSE) {
416 switch ($pinned) {
417 case BLOCKS_PINNED_TRUE:
418 $pageblocks = blocks_get_pinned($PAGE);
419 break;
420 case BLOCKS_PINNED_BOTH:
421 $pageblocks = blocks_get_by_page_pinned($PAGE);
422 break;
423 case BLOCKS_PINNED_FALSE:
424 default:
425 $pageblocks = blocks_get_by_page($PAGE);
426 break;
427 }
428 blocks_execute_url_action($PAGE, $pageblocks,($pinned==BLOCKS_PINNED_TRUE));
ec79d3e4 429 return $pageblocks;
430}
431
0d6b9d4f 432function blocks_execute_action($page, &$pageblocks, $blockaction, $instanceorid, $pinned=false) {
9b4b78fd 433 global $CFG;
434
a9c75a9c 435 if (is_int($instanceorid)) {
9b4b78fd 436 $blockid = $instanceorid;
a9c75a9c 437 } else if (is_object($instanceorid)) {
9b4b78fd 438 $instance = $instanceorid;
439 }
0f3fe4b6 440
441 switch($blockaction) {
9b4b78fd 442 case 'config':
f032aa7a 443 global $USER;
9b4b78fd 444 $block = blocks_get_record($instance->blockid);
e82d6cac 445 // Hacky hacky tricky stuff to get the original human readable block title,
446 // even if the block has configured its title to be something else.
447 // Create the object WITHOUT instance data.
448 $blockobject = block_instance($block->name);
9b4b78fd 449 if ($blockobject === false) {
11306331 450 break;
451 }
452
453 // First of all check to see if the block wants to be edited
454 if(!$blockobject->user_can_edit()) {
455 break;
9b4b78fd 456 }
11306331 457
e82d6cac 458 // Now get the title and AFTER that load up the instance
459 $blocktitle = $blockobject->get_title();
460 $blockobject->_load_instance($instance);
461
9b4b78fd 462 optional_param('submitted', 0, PARAM_INT);
463
27ec21a0 464 // Define the data we're going to silently include in the instance config form here,
9b4b78fd 465 // so we can strip them from the submitted data BEFORE serializing it.
466 $hiddendata = array(
467 'sesskey' => $USER->sesskey,
9b4b78fd 468 'instanceid' => $instance->id,
469 'blockaction' => 'config'
470 );
f032aa7a 471
472 // To this data, add anything the page itself needs to display
473 $hiddendata = array_merge($hiddendata, $page->url_get_parameters());
9b4b78fd 474
475 if($data = data_submitted()) {
476 $remove = array_keys($hiddendata);
477 foreach($remove as $item) {
478 unset($data->$item);
0f3fe4b6 479 }
0d6b9d4f 480 if(!$blockobject->instance_config_save($data,$pinned)) {
9b4b78fd 481 error('Error saving block configuration');
0f3fe4b6 482 }
9b4b78fd 483 // And nothing more, continue with displaying the page
0f3fe4b6 484 }
9b4b78fd 485 else {
f032aa7a 486 // We need to show the config screen, so we highjack the display logic and then die
e82d6cac 487 $strheading = get_string('blockconfiga', 'moodle', $blocktitle);
edb42f09 488 $page->print_header(get_string('pageheaderconfigablock', 'moodle'), array($strheading => ''));
b9709905 489
490 echo '<div class="block-config" id="'.$block->name.'">'; /// Make CSS easier
491
edb42f09 492 print_heading($strheading);
f032aa7a 493 echo '<form method="post" action="'. $page->url_get_path() .'">';
9b4b78fd 494 echo '<p>';
495 foreach($hiddendata as $name => $val) {
27ec21a0 496 echo '<input type="hidden" name="'. $name .'" value="'. $val .'" />';
0f3fe4b6 497 }
9b4b78fd 498 echo '</p>';
499 $blockobject->instance_config_print();
500 echo '</form>';
b9709905 501
502 echo '</div>';
a2c28054 503 $CFG->pagepath = 'blocks/' . $block->name;
9b4b78fd 504 print_footer();
f032aa7a 505 die(); // Do not go on with the other page-related stuff
0f3fe4b6 506 }
507 break;
9b4b78fd 508 case 'toggle':
509 if(empty($instance)) {
510 error('Invalid block instance for '.$blockaction);
0f3fe4b6 511 }
9b4b78fd 512 $instance->visible = ($instance->visible) ? 0 : 1;
0d6b9d4f 513 if (!empty($pinned)) {
514 update_record('block_pinned', $instance);
515 } else {
516 update_record('block_instance', $instance);
517 }
9b4b78fd 518 break;
519 case 'delete':
520 if(empty($instance)) {
a9c75a9c 521 error('Invalid block instance for '. $blockaction);
0f3fe4b6 522 }
0d6b9d4f 523 blocks_delete_instance($instance, $pinned);
0f3fe4b6 524 break;
525 case 'moveup':
9b4b78fd 526 if(empty($instance)) {
a9c75a9c 527 error('Invalid block instance for '. $blockaction);
9b4b78fd 528 }
f032aa7a 529
530 if($instance->weight == 0) {
531 // The block is the first one, so a move "up" probably means it changes position
532 // Where is the instance going to be moved?
533 $newpos = $page->blocks_move_position($instance, BLOCK_MOVE_UP);
6b853ff4 534 $newweight = (empty($pageblocks[$newpos]) ? 0 : max(array_keys($pageblocks[$newpos])) + 1);
f032aa7a 535
0d6b9d4f 536 blocks_execute_repositioning($instance, $newpos, $newweight, $pinned);
89a5baab 537 }
f032aa7a 538 else {
539 // The block is just moving upwards in the same position.
540 // This configuration will make sure that even if somehow the weights
541 // become not continuous, block move operations will eventually bring
542 // the situation back to normal without printing any warnings.
543 if(!empty($pageblocks[$instance->position][$instance->weight - 1])) {
544 $other = $pageblocks[$instance->position][$instance->weight - 1];
545 }
546 if(!empty($other)) {
547 ++$other->weight;
0d6b9d4f 548 if (!empty($pinned)) {
549 update_record('block_pinned', $other);
550 } else {
551 update_record('block_instance', $other);
552 }
f032aa7a 553 }
554 --$instance->weight;
0d6b9d4f 555 if (!empty($pinned)) {
556 update_record('block_pinned', $instance);
557 } else {
558 update_record('block_instance', $instance);
559 }
0f3fe4b6 560 }
561 break;
562 case 'movedown':
9b4b78fd 563 if(empty($instance)) {
a9c75a9c 564 error('Invalid block instance for '. $blockaction);
9b4b78fd 565 }
f032aa7a 566
567 if($instance->weight == max(array_keys($pageblocks[$instance->position]))) {
568 // The block is the last one, so a move "down" probably means it changes position
569 // Where is the instance going to be moved?
570 $newpos = $page->blocks_move_position($instance, BLOCK_MOVE_DOWN);
6b853ff4 571 $newweight = (empty($pageblocks[$newpos]) ? 0 : max(array_keys($pageblocks[$newpos])) + 1);
f032aa7a 572
0d6b9d4f 573 blocks_execute_repositioning($instance, $newpos, $newweight, $pinned);
89a5baab 574 }
f032aa7a 575 else {
576 // The block is just moving downwards in the same position.
577 // This configuration will make sure that even if somehow the weights
578 // become not continuous, block move operations will eventually bring
579 // the situation back to normal without printing any warnings.
580 if(!empty($pageblocks[$instance->position][$instance->weight + 1])) {
581 $other = $pageblocks[$instance->position][$instance->weight + 1];
582 }
583 if(!empty($other)) {
584 --$other->weight;
0d6b9d4f 585 if (!empty($pinned)) {
586 update_record('block_pinned', $other);
587 } else {
588 update_record('block_instance', $other);
589 }
f032aa7a 590 }
591 ++$instance->weight;
0d6b9d4f 592 if (!empty($pinned)) {
593 update_record('block_pinned', $instance);
594 } else {
595 update_record('block_instance', $instance);
596 }
0f3fe4b6 597 }
598 break;
9b4b78fd 599 case 'moveleft':
600 if(empty($instance)) {
a9c75a9c 601 error('Invalid block instance for '. $blockaction);
9b4b78fd 602 }
f032aa7a 603
604 // Where is the instance going to be moved?
605 $newpos = $page->blocks_move_position($instance, BLOCK_MOVE_LEFT);
6b853ff4 606 $newweight = (empty($pageblocks[$newpos]) ? 0 : max(array_keys($pageblocks[$newpos])) + 1);
f032aa7a 607
0d6b9d4f 608 blocks_execute_repositioning($instance, $newpos, $newweight, $pinned);
0f3fe4b6 609 break;
9b4b78fd 610 case 'moveright':
611 if(empty($instance)) {
a9c75a9c 612 error('Invalid block instance for '. $blockaction);
9b4b78fd 613 }
f032aa7a 614
615 // Where is the instance going to be moved?
616 $newpos = $page->blocks_move_position($instance, BLOCK_MOVE_RIGHT);
6b853ff4 617 $newweight = (empty($pageblocks[$newpos]) ? 0 : max(array_keys($pageblocks[$newpos])) + 1);
f032aa7a 618
0d6b9d4f 619 blocks_execute_repositioning($instance, $newpos, $newweight, $pinned);
9b4b78fd 620 break;
621 case 'add':
622 // Add a new instance of this block, if allowed
623 $block = blocks_get_record($blockid);
0f3fe4b6 624
3cacefda 625 if(empty($block) || !$block->visible) {
626 // Only allow adding if the block exists and is enabled
11306331 627 break;
9b4b78fd 628 }
0f3fe4b6 629
89a5baab 630 if(!$block->multiple && blocks_find_block($blockid, $pageblocks) !== false) {
631 // If no multiples are allowed and we already have one, return now
11306331 632 break;
633 }
634
635 if(!block_method_result($block->name, 'user_can_addto', $page)) {
636 // If the block doesn't want to be added...
637 break;
89a5baab 638 }
639
f032aa7a 640 $newpos = $page->blocks_default_position();
0d6b9d4f 641 if (!empty($pinned)) {
642 $sql = 'SELECT 1, max(weight) + 1 AS nextfree FROM '. $CFG->prefix .'block_pinned WHERE '
643 .' pagetype = \''. $page->get_type() .'\' AND position = \''. $newpos .'\'';
644 } else {
645 $sql = 'SELECT 1, max(weight) + 1 AS nextfree FROM '. $CFG->prefix .'block_instance WHERE pageid = '. $page->get_id()
646 .' AND pagetype = \''. $page->get_type() .'\' AND position = \''. $newpos .'\'';
647 }
648 $weight = get_record_sql($sql);
9b4b78fd 649
650 $newinstance = new stdClass;
651 $newinstance->blockid = $blockid;
0d6b9d4f 652 if (empty($pinned)) {
653 $newinstance->pageid = $page->get_id();
654 }
f032aa7a 655 $newinstance->pagetype = $page->get_type();
656 $newinstance->position = $newpos;
ff679897 657 $newinstance->weight = empty($weight->nextfree) ? 0 : $weight->nextfree;
9b4b78fd 658 $newinstance->visible = 1;
659 $newinstance->configdata = '';
0d6b9d4f 660 if (!empty($pinned)) {
661 $newinstance->id = insert_record('block_pinned', $newinstance);
662 } else {
663 $newinstance->id = insert_record('block_instance', $newinstance);
664 }
b33dd23a 665
666 // If the new instance was created, allow it to do additional setup
667 if($newinstance && ($obj = block_instance($block->name, $newinstance))) {
668 // Return value ignored
669 $obj->instance_create();
670 }
671
9b4b78fd 672 break;
673 }
f032aa7a 674
675 // In order to prevent accidental duplicate actions, redirect to a page with a clean url
676 redirect($page->url_get_full());
677}
678
da71112b 679// You can use this to get the blocks to respond to URL actions without much hassle
0d6b9d4f 680function blocks_execute_url_action(&$PAGE, &$pageblocks,$pinned=false) {
da71112b 681 $blockaction = optional_param('blockaction');
682
3edc57e1 683 if (empty($blockaction) || !$PAGE->user_allowed_editing() || !confirm_sesskey()) {
da71112b 684 return;
685 }
686
687 $instanceid = optional_param('instanceid', 0, PARAM_INT);
688 $blockid = optional_param('blockid', 0, PARAM_INT);
689
690 if (!empty($blockid)) {
0d6b9d4f 691 blocks_execute_action($PAGE, $pageblocks, strtolower($blockaction), $blockid, $pinned);
da71112b 692
693 }
694 else if (!empty($instanceid)) {
695 $instance = blocks_find_instance($instanceid, $pageblocks);
0d6b9d4f 696 blocks_execute_action($PAGE, $pageblocks, strtolower($blockaction), $instance, $pinned);
da71112b 697 }
698}
699
f032aa7a 700// This shouldn't be used externally at all, it's here for use by blocks_execute_action()
701// in order to reduce code repetition.
0d6b9d4f 702function blocks_execute_repositioning(&$instance, $newpos, $newweight, $pinned=false) {
f032aa7a 703 global $CFG;
704
705 // If it's staying where it is, don't do anything
706 if($newpos == $instance->position) {
707 return;
708 }
709
710 // Close the weight gap we 'll leave behind
0d6b9d4f 711 if (!empty($pinned)) {
712 $sql = 'UPDATE '. $CFG->prefix .'block_instance SET weight = weight - 1 WHERE pagetype = \''. $instance->pagetype.
713 '\' AND position = \'' .$instance->position.
714 '\' AND weight > '. $instance->weight;
715 } else {
716 $sql = 'UPDATE '. $CFG->prefix .'block_instance SET weight = weight - 1 WHERE pagetype = \''. $instance->pagetype.
f032aa7a 717 '\' AND pageid = '. $instance->pageid .' AND position = \'' .$instance->position.
0d6b9d4f 718 '\' AND weight > '. $instance->weight;
719 }
720 execute_sql($sql,false);
f032aa7a 721
722 $instance->position = $newpos;
723 $instance->weight = $newweight;
724
0d6b9d4f 725 if (!empty($pinned)) {
726 update_record('block_pinned', $instance);
727 } else {
728 update_record('block_instance', $instance);
729 }
730}
731
732function blocks_get_pinned($page) {
733
734 $visible = true;
735
736 if (method_exists($page,'edit_always')) {
737 if ($page->edit_always()) {
738 $visible = false;
739 }
740 }
741
742 $blocks = get_records_select('block_pinned', 'pagetype = \''. $page->get_type() .'\''.(($visible) ? 'AND visible = 1' : ''), 'position, weight');
743
744 $positions = $page->blocks_get_positions();
745 $arr = array();
746
747 foreach($positions as $key => $position) {
748 $arr[$position] = array();
749 }
750
751 if(empty($blocks)) {
752 return $arr;
753 }
754
755 foreach($blocks as $block) {
756 $block->pinned = true; // so we know we can't move it.
ddf1935f 757 // make up an instanceid if we can..
758 $block->pageid = $page->get_id();
0d6b9d4f 759 $arr[$block->position][$block->weight] = $block;
760 }
761
762 return $arr;
763}
764
765
766function blocks_get_by_page_pinned($page) {
767 $pinned = blocks_get_pinned($page);
768 $user = blocks_get_by_page($page);
769
770 $weights = array();
771
772 foreach ($pinned as $pos => $arr) {
773 $weights[$pos] = count($arr);
774 }
775
776 foreach ($user as $pos => $blocks) {
777 if (!array_key_exists($pos,$pinned)) {
778 $pinned[$pos] = array();
779 }
780 if (!array_key_exists($pos,$weights)) {
781 $weights[$pos] = 0;
782 }
783 foreach ($blocks as $block) {
784 $pinned[$pos][$weights[$pos]] = $block;
785 $weights[$pos]++;
786 }
787 }
788 return $pinned;
0f3fe4b6 789}
790
9b4b78fd 791function blocks_get_by_page($page) {
a9b3afb7 792 $blocks = get_records_select('block_instance', "pageid = '". $page->get_id() ."' AND pagetype = '". $page->get_type() ."'", 'position, weight');
f032aa7a 793
794 $positions = $page->blocks_get_positions();
795 $arr = array();
796 foreach($positions as $key => $position) {
797 $arr[$position] = array();
798 }
0f3fe4b6 799
9b4b78fd 800 if(empty($blocks)) {
801 return $arr;
802 }
0f3fe4b6 803
9b4b78fd 804 foreach($blocks as $block) {
805 $arr[$block->position][$block->weight] = $block;
0f3fe4b6 806 }
807
9b4b78fd 808 return $arr;
809}
0f3fe4b6 810
9b4b78fd 811//This function prints the block to admin blocks as necessary
c1d8705f 812function blocks_print_adminblock(&$page, &$pageblocks) {
9b4b78fd 813 global $USER;
0f3fe4b6 814
c1d8705f 815 $missingblocks = blocks_get_missing($page, $pageblocks);
816
9b4b78fd 817 if (!empty($missingblocks)) {
c1d8705f 818 $strblocks = get_string('blocks');
819 $stradd = get_string('add');
9b4b78fd 820 foreach ($missingblocks as $blockid) {
821 $block = blocks_get_record($blockid);
9b4b78fd 822 $blockobject = block_instance($block->name);
823 if ($blockobject === false) {
824 continue;
825 }
11306331 826 if(!$blockobject->user_can_addto($page)) {
827 continue;
828 }
9b4b78fd 829 $menu[$block->id] = $blockobject->get_title();
830 }
4a4c30d2 831 asort($menu);
0f3fe4b6 832
f032aa7a 833 $target = $page->url_get_full(array('sesskey' => $USER->sesskey, 'blockaction' => 'add'));
834 $content = popup_form($target.'&amp;blockid=', $menu, 'add_block', '', $stradd .'...', '', '', true);
afd8402c 835 print_side_block($strblocks, $content, NULL, NULL, NULL, array('class' => 'block_adminblock'));
0f3fe4b6 836 }
0f3fe4b6 837}
838
9b4b78fd 839function blocks_repopulate_page($page) {
840 global $CFG;
5b224948 841
9b4b78fd 842 $allblocks = blocks_get_record();
843
844 if(empty($allblocks)) {
845 error('Could not retrieve blocks from the database');
846 }
847
f032aa7a 848 // Assemble the information to correlate block names to ids
9b4b78fd 849 $idforname = array();
850 foreach($allblocks as $block) {
851 $idforname[$block->name] = $block->id;
852 }
853
f032aa7a 854 /// If the site override has been defined, it is the only valid one.
855 if (!empty($CFG->defaultblocks_override)) {
856 $blocknames = $CFG->defaultblocks_override;
857 }
858 else {
859 $blocknames = $page->blocks_get_default();
860 }
861
862 $positions = $page->blocks_get_positions();
863 $posblocks = explode(':', $blocknames);
864
865 // Now one array holds the names of the positions, and the other one holds the blocks
866 // that are going to go in each position. Luckily for us, both arrays are numerically
867 // indexed and the indexes match, so we can work straight away... but CAREFULLY!
9b4b78fd 868
f032aa7a 869 // Ready to start creating block instances, but first drop any existing ones
870 delete_records('block_instance', 'pageid', $page->get_id(), 'pagetype', $page->get_type());
871
872 // Here we slyly count $posblocks and NOT $positions. This can actually make a difference
873 // if the textual representation has undefined slots in the end. So we only work with as many
874 // positions were retrieved, not with all the page says it has available.
875 $numpositions = count($posblocks);
876 for($i = 0; $i < $numpositions; ++$i) {
877 $position = $positions[$i];
878 $blocknames = explode(',', $posblocks[$i]);
9b4b78fd 879 $weight = 0;
880 foreach($blocknames as $blockname) {
881 $newinstance = new stdClass;
882 $newinstance->blockid = $idforname[$blockname];
f032aa7a 883 $newinstance->pageid = $page->get_id();
884 $newinstance->pagetype = $page->get_type();
9b4b78fd 885 $newinstance->position = $position;
886 $newinstance->weight = $weight;
887 $newinstance->visible = 1;
888 $newinstance->configdata = '';
3cacefda 889
890 if(!empty($newinstance->blockid)) {
891 // Only add block if it was recognized
892 insert_record('block_instance', $newinstance);
893 ++$weight;
894 }
0f3fe4b6 895 }
896 }
9b4b78fd 897
898 return true;
0f3fe4b6 899}
900
901function upgrade_blocks_db($continueto) {
902/// This function upgrades the blocks tables, if necessary
903/// It's called from admin/index.php
904
905 global $CFG, $db;
906
a9c75a9c 907 require_once ($CFG->dirroot .'/blocks/version.php'); // Get code versions
0f3fe4b6 908
909 if (empty($CFG->blocks_version)) { // Blocks have never been installed.
a9c75a9c 910 $strdatabaseupgrades = get_string('databaseupgrades');
a36f058e 911 print_header($strdatabaseupgrades, $strdatabaseupgrades, $strdatabaseupgrades, '',
912 '<script type="text/javascript" src="' . $CFG->wwwroot . '/lib/scroll_to_errors.js"></script>',
913 false, '&nbsp;', '&nbsp;');
0f3fe4b6 914
915 $db->debug=true;
a9c75a9c 916 if (modify_database($CFG->dirroot .'/blocks/db/'. $CFG->dbtype .'.sql')) {
0f3fe4b6 917 $db->debug = false;
a9c75a9c 918 if (set_config('blocks_version', $blocks_version)) {
c7a9e293 919 notify(get_string('databasesuccess'), 'notifysuccess');
a9c75a9c 920 notify(get_string('databaseupgradeblocks', '', $blocks_version));
0f3fe4b6 921 print_continue($continueto);
922 exit;
923 } else {
a9c75a9c 924 error('Upgrade of blocks system failed! (Could not update version in config table)');
0f3fe4b6 925 }
926 } else {
a9c75a9c 927 error('Blocks tables could NOT be set up successfully!');
0f3fe4b6 928 }
929 }
930
931
932 if ($blocks_version > $CFG->blocks_version) { // Upgrade tables
a9c75a9c 933 $strdatabaseupgrades = get_string('databaseupgrades');
a36f058e 934 print_header($strdatabaseupgrades, $strdatabaseupgrades, $strdatabaseupgrades, '',
935 '<script type="text/javascript" src="' . $CFG->wwwroot . '/lib/scroll_to_errors.js"></script>');
a9c75a9c 936 require_once ($CFG->dirroot .'/blocks/db/'. $CFG->dbtype .'.php');
0f3fe4b6 937
938 $db->debug=true;
939 if (blocks_upgrade($CFG->blocks_version)) {
940 $db->debug=false;
a9c75a9c 941 if (set_config('blocks_version', $blocks_version)) {
c7a9e293 942 notify(get_string('databasesuccess'), 'notifysuccess');
a9c75a9c 943 notify(get_string('databaseupgradeblocks', '', $blocks_version));
0f3fe4b6 944 print_continue($continueto);
945 exit;
946 } else {
a9c75a9c 947 error('Upgrade of blocks system failed! (Could not update version in config table)');
0f3fe4b6 948 }
949 } else {
950 $db->debug=false;
a9c75a9c 951 error('Upgrade failed! See blocks/version.php');
0f3fe4b6 952 }
953
954 } else if ($blocks_version < $CFG->blocks_version) {
b011f733 955 notify('WARNING!!! The Blocks version you are using is OLDER than the version that made these databases!');
0f3fe4b6 956 }
957}
958
959//This function finds all available blocks and install them
960//into blocks table or do all the upgrade process if newer
961function upgrade_blocks_plugins($continueto) {
962
963 global $CFG;
964
965 $blocktitles = array();
966 $invalidblocks = array();
967 $validblocks = array();
968 $notices = array();
969
970 //Count the number of blocks in db
9b4b78fd 971 $blockcount = count_records('block');
0f3fe4b6 972 //If there isn't records. This is the first install, so I remember it
973 if ($blockcount == 0) {
974 $first_install = true;
975 } else {
976 $first_install = false;
977 }
978
979 $site = get_site();
980
9b4b78fd 981 if (!$blocks = get_list_of_plugins('blocks', 'db') ) {
a9c75a9c 982 error('No blocks installed!');
0f3fe4b6 983 }
984
a9c75a9c 985 include_once($CFG->dirroot .'/blocks/moodleblock.class.php');
e89d741a 986 if(!class_exists('block_base')) {
987 error('Class block_base is not defined or file not found for /blocks/moodleblock.class.php');
0f3fe4b6 988 }
989
990 foreach ($blocks as $blockname) {
991
a9c75a9c 992 if ($blockname == 'NEWBLOCK') { // Someone has unzipped the template, ignore it
0f3fe4b6 993 continue;
994 }
995
61abc65b 996 if(!block_is_compatible($blockname)) {
997 // This is an old-style block
998 //$notices[] = 'Block '. $blockname .' is not compatible with the current version of Mooodle and needs to be updated by a programmer.';
999 $invalidblocks[] = $blockname;
1000 continue;
1001 }
1002
a9c75a9c 1003 $fullblock = $CFG->dirroot .'/blocks/'. $blockname;
0f3fe4b6 1004
9b4b78fd 1005 if ( is_readable($fullblock.'/block_'.$blockname.'.php')) {
1006 include_once($fullblock.'/block_'.$blockname.'.php');
0f3fe4b6 1007 } else {
a9c75a9c 1008 $notices[] = 'Block '. $blockname .': '. $fullblock .'/block_'. $blockname .'.php was not readable';
0f3fe4b6 1009 continue;
1010 }
1011
a9c75a9c 1012 if ( @is_dir($fullblock .'/db/')) {
1013 if ( @is_readable($fullblock .'/db/'. $CFG->dbtype .'.php')) {
89a5baab 1014 include_once($fullblock .'/db/'. $CFG->dbtype .'.php'); // defines upgrading function
828c4e09 1015 } else {
7a3290ed 1016 //$notices[] ='Block '. $blockname .': '. $fullblock .'/db/'. $CFG->dbtype .'.php was not readable';
828c4e09 1017 continue;
1018 }
0f3fe4b6 1019 }
1020
e89d741a 1021 $classname = 'block_'.$blockname;
0f3fe4b6 1022 if(!class_exists($classname)) {
a9c75a9c 1023 $notices[] = 'Block '. $blockname .': '. $classname .' not implemented';
0f3fe4b6 1024 continue;
1025 }
1026
9b4b78fd 1027 // Here is the place to see if the block implements a constructor (old style),
1028 // an init() function (new style) or nothing at all (error time).
1029
33bee34c 1030 $constructor = get_class_constructor($classname);
1031 if(empty($constructor)) {
0f3fe4b6 1032 // No constructor
a9c75a9c 1033 $notices[] = 'Block '. $blockname .': class does not have a constructor';
0f3fe4b6 1034 $invalidblocks[] = $blockname;
1035 continue;
1036 }
1037
9b4b78fd 1038 $block = new stdClass; // This may be used to update the db below
1039 $blockobj = new $classname; // This is what we 'll be testing
0f3fe4b6 1040
e89d741a 1041 // Inherits from block_base?
1042 if(!is_subclass_of($blockobj, 'block_base')) {
1043 $notices[] = 'Block '. $blockname .': class does not inherit from block_base';
0f3fe4b6 1044 continue;
1045 }
1046
1047 // OK, it's as we all hoped. For further tests, the object will do them itself.
1048 if(!$blockobj->_self_test()) {
a9c75a9c 1049 $notices[] = 'Block '. $blockname .': self test failed';
0f3fe4b6 1050 continue;
1051 }
1052 $block->version = $blockobj->get_version();
1053
1054 if (!isset($block->version)) {
a9c75a9c 1055 $notices[] = 'Block '. $blockname .': has no version support. It must be updated by a programmer.';
0f3fe4b6 1056 continue;
1057 }
1058
1059 $block->name = $blockname; // The name MUST match the directory
1060 $blocktitle = $blockobj->get_title();
1061
9b4b78fd 1062 if ($currblock = get_record('block', 'name', $block->name)) {
0f3fe4b6 1063 if ($currblock->version == $block->version) {
1064 // do nothing
1065 } else if ($currblock->version < $block->version) {
1066 if (empty($updated_blocks)) {
a9c75a9c 1067 $strblocksetup = get_string('blocksetup');
a36f058e 1068 print_header($strblocksetup, $strblocksetup, $strblocksetup, '',
1069 '<script type="text/javascript" src="' . $CFG->wwwroot . '/lib/scroll_to_errors.js"></script>',
1070 false, '&nbsp;', '&nbsp;');
0f3fe4b6 1071 }
b88f7004 1072 print_heading('New version of '.$blocktitle.' ('.$block->name.') exists');
1073 $upgrade_function = $block->name.'_upgrade';
0f3fe4b6 1074 if (function_exists($upgrade_function)) {
1075 $db->debug=true;
1076 if ($upgrade_function($currblock->version, $block)) {
b88f7004 1077
1078 $upgradesuccess = true;
0f3fe4b6 1079 } else {
b88f7004 1080 $upgradesuccess = false;
1081 }
1082 $db->debug=false;
1083 }
1084 else {
1085 $upgradesuccess = true;
1086 }
1087 if(!$upgradesuccess) {
a9c75a9c 1088 notify('Upgrading block '. $block->name .' from '. $currblock->version .' to '. $block->version .' FAILED!');
b88f7004 1089 }
1090 else {
9b4b78fd 1091 // OK so far, now update the block record
b88f7004 1092 $block->id = $currblock->id;
9b4b78fd 1093 if (! update_record('block', $block)) {
a9c75a9c 1094 error('Could not update block '. $block->name .' record in block table!');
0f3fe4b6 1095 }
c7a9e293 1096 notify(get_string('blocksuccess', '', $blocktitle), 'notifysuccess');
b88f7004 1097 echo '<hr />';
0f3fe4b6 1098 }
1099 $updated_blocks = true;
1100 } else {
a9c75a9c 1101 error('Version mismatch: block '. $block->name .' can\'t downgrade '. $currblock->version .' -> '. $block->version .'!');
0f3fe4b6 1102 }
1103
1104 } else { // block not installed yet, so install it
1105
9b4b78fd 1106 // If it allows multiples, start with it enabled
1107 $block->multiple = $blockobj->instance_allow_multiple();
f9648e77 1108 if (!empty($blockobj->cron)) {
1109 $block->cron = $blockobj->cron;
1110 }
9b4b78fd 1111
0f3fe4b6 1112 // [pj] Normally this would be inline in the if, but we need to
1113 // check for NULL (necessary for 4.0.5 <= PHP < 4.2.0)
1114 $conflictblock = array_search($blocktitle, $blocktitles);
1115 if($conflictblock !== false && $conflictblock !== NULL) {
0f3fe4b6 1116 // Duplicate block titles are not allowed, they confuse people
1117 // AND PHP's associative arrays ;)
1118 error('<strong>Naming conflict</strong>: block <strong>'.$block->name.'</strong> has the same title with an existing block, <strong>'.$conflictblock.'</strong>!');
1119 }
1120 if (empty($updated_blocks)) {
a9c75a9c 1121 $strblocksetup = get_string('blocksetup');
a36f058e 1122 print_header($strblocksetup, $strblocksetup, $strblocksetup, '',
1123 '<script type="text/javascript" src="' . $CFG->wwwroot . '/lib/scroll_to_errors.js"></script>',
1124 false, '&nbsp;', '&nbsp;');
0f3fe4b6 1125 }
1126 print_heading($block->name);
1127 $updated_blocks = true;
1128 $db->debug = true;
a71bfa1c 1129 @set_time_limit(0); // To allow slow databases to complete the long SQL
a9c75a9c 1130 if (!is_dir($fullblock .'/db/') || modify_database($fullblock .'/db/'. $CFG->dbtype .'.sql')) {
0f3fe4b6 1131 $db->debug = false;
9b4b78fd 1132 if ($block->id = insert_record('block', $block)) {
44c55d46 1133 $blockobj->after_install();
c7a9e293 1134 notify(get_string('blocksuccess', '', $blocktitle), 'notifysuccess');
a9c75a9c 1135 echo '<hr />';
0f3fe4b6 1136 } else {
a9c75a9c 1137 error($block->name .' block could not be added to the block list!');
0f3fe4b6 1138 }
1139 } else {
a9c75a9c 1140 error('Block '. $block->name .' tables could NOT be set up successfully!');
0f3fe4b6 1141 }
1142 }
1143
1144 $blocktitles[$block->name] = $blocktitle;
1145 }
1146
1147 if(!empty($notices)) {
1148 foreach($notices as $notice) {
1149 notify($notice);
1150 }
1151 }
1152
9b4b78fd 1153 // Finally, if we are in the first_install of BLOCKS (this means that we are
1154 // upgrading from Moodle < 1.3), put blocks in all existing courses.
0f3fe4b6 1155 if ($first_install) {
1156 //Iterate over each course
9b4b78fd 1157 if ($courses = get_records('course')) {
0f3fe4b6 1158 foreach ($courses as $course) {
7542a4e5 1159 $page = page_create_object(PAGE_COURSE_VIEW, $course->id);
9b4b78fd 1160 blocks_repopulate_page($page);
0f3fe4b6 1161 }
1162 }
1163 }
1164
e02c35b2 1165 if (!empty($CFG->siteblocksadded)) { /// This is a once-off hack to make a proper upgrade
7542a4e5 1166 $page = page_create_object(PAGE_COURSE_VIEW, SITEID);
9b4b78fd 1167 blocks_repopulate_page($page);
e02c35b2 1168 delete_records('config', 'name', 'siteblocksadded');
1169 }
1170
0f3fe4b6 1171 if (!empty($updated_blocks)) {
1172 print_continue($continueto);
1173 die;
1174 }
1175}
1176
44c55d46 1177?>