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