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