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