Dan's fix from MDL-7263
[moodle.git] / lib / blocklib.php
blobc49a1971b10e4cec72e2e4c554767668d7ee84f6
1 <?php //$Id$
3 //This library includes all the necessary stuff to use blocks in course pages
5 define('BLOCK_MOVE_LEFT', 0x01);
6 define('BLOCK_MOVE_RIGHT', 0x02);
7 define('BLOCK_MOVE_UP', 0x04);
8 define('BLOCK_MOVE_DOWN', 0x08);
9 define('BLOCK_CONFIGURE', 0x10);
11 define('BLOCK_POS_LEFT', 'l');
12 define('BLOCK_POS_RIGHT', 'r');
14 define('BLOCKS_PINNED_TRUE',0);
15 define('BLOCKS_PINNED_FALSE',1);
16 define('BLOCKS_PINNED_BOTH',2);
18 require_once($CFG->libdir.'/pagelib.php');
19 require_once($CFG->dirroot.'/course/lib.php'); // needed to solve all those: Call to undefined function: print_recent_activity() when adding Recent Activity
21 // Returns false if this block is incompatible with the current version of Moodle.
22 function block_is_compatible($blockname) {
23 global $CFG;
25 $file = @file($CFG->dirroot.'/blocks/'.$blockname.'/block_'.$blockname.'.php'); // ignore errors when file does not exist
26 if(empty($file)) {
27 return NULL;
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;
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;
41 return NULL;
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.
47 function get_class_constructor($classname) {
48 // Caching
49 static $constructors = array();
51 if(!class_exists($classname)) {
52 return false;
55 // Tests indicate this doesn't hurt even in PHP5.
56 $classname = strtolower($classname);
58 // Return cached value, if exists
59 if(isset($constructors[$classname])) {
60 return $constructors[$classname];
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);
68 // PHP5 constructor?
69 if(phpversion() >= '5') {
70 if(in_array('__construct', $methods)) {
71 return $constructors[$classname] = '__construct';
75 // If we have PHP5 but no magic constructor, we have to lowercase the methods
76 $methods = array_map('strtolower', $methods);
78 if(in_array($classname, $methods)) {
79 return $constructors[$classname] = $classname;
82 return $constructors[$classname] = NULL;
85 //This function retrieves a method-defined property of a class WITHOUT instantiating an object
86 function block_method_result($blockname, $method, $param = NULL) {
87 if(!block_load_class($blockname)) {
88 return NULL;
90 return call_user_func(array('block_'.$blockname, $method), $param);
93 //This function creates a new object of the specified block class
94 function block_instance($blockname, $instance = NULL) {
95 if(!block_load_class($blockname)) {
96 return false;
98 $classname = 'block_'.$blockname;
99 $retval = new $classname;
100 if($instance !== NULL) {
101 $retval->_load_instance($instance);
103 return $retval;
106 //This function loads the necessary class files for a block
107 //Whenever you want to load a block, use this first
108 function block_load_class($blockname) {
109 global $CFG;
111 if(empty($blockname)) {
112 return false;
115 $classname = 'block_'.$blockname;
117 if(class_exists($classname)) {
118 return true;
121 require_once($CFG->dirroot.'/blocks/moodleblock.class.php');
122 @include_once($CFG->dirroot.'/blocks/'.$blockname.'/block_'.$blockname.'.php'); // do not throw errors if block code not present
124 return class_exists($classname);
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.
129 function blocks_get_missing(&$page, &$pageblocks) {
131 $missingblocks = array();
132 $allblocks = blocks_get_record();
133 $pageformat = $page->get_format_name();
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...
139 if(blocks_name_allowed_in_format($block->name, $pageformat)) {
140 // ...add it to the missing blocks
141 $missingblocks[] = $block->id;
146 return $missingblocks;
149 function blocks_remove_inappropriate($page) {
150 $pageblocks = blocks_get_by_page($page);
152 if(empty($pageblocks)) {
153 return;
156 if(($pageformat = $page->get_format_name()) == NULL) {
157 return;
160 foreach($pageblocks as $position) {
161 foreach($position as $instance) {
162 $block = blocks_get_record($instance->blockid);
163 if(!blocks_name_allowed_in_format($block->name, $pageformat)) {
164 blocks_delete_instance($instance);
170 function 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;
183 if($accept === NULL) {
184 $accept = !empty($formats['all']);
186 return $accept;
189 function blocks_delete_instance($instance,$pinned=false) {
190 global $CFG;
192 // Get the block object and call instance_delete() if possible
193 if(!$record = blocks_get_record($instance->blockid)) {
194 if(!$obj = block_instance($record->name, $instance)) {
195 // Return value ignored
196 $obj->instance_delete();
200 if (!empty($pinned)) {
201 delete_records('block_pinned', 'id', $instance->id);
202 // And now, decrement the weight of all blocks after this one
203 execute_sql('UPDATE '.$CFG->prefix.'block_pinned SET weight = weight - 1 WHERE pagetype = \''.$instance->pagetype.
204 '\' AND position = \''.$instance->position.
205 '\' AND weight > '.$instance->weight, false);
206 } else {
207 // Now kill the db record;
208 delete_records('block_instance', 'id', $instance->id);
209 // And now, decrement the weight of all blocks after this one
210 execute_sql('UPDATE '.$CFG->prefix.'block_instance SET weight = weight - 1 WHERE pagetype = \''.$instance->pagetype.
211 '\' AND pageid = '.$instance->pageid.' AND position = \''.$instance->position.
212 '\' AND weight > '.$instance->weight, false);
214 return true;
217 // Accepts an array of block instances and checks to see if any of them have content to display
218 // (causing them to calculate their content in the process). Returns true or false. Parameter passed
219 // by reference for speed; the array is actually not modified.
220 function blocks_have_content(&$pageblocks, $position) {
222 if (empty($pageblocks) || !is_array($pageblocks) || !array_key_exists($position,$pageblocks)) {
223 return false;
225 // use a for() loop to get references to the array elements
226 // foreach() cannot fetch references in PHP v4.x
227 for ($n=0; $n<count($pageblocks[$position]);$n++) {
228 $instance = &$pageblocks[$position][$n];
229 if(!$instance->visible) {
230 continue;
232 if(!$record = blocks_get_record($instance->blockid)) {
233 continue;
235 if(!$obj = block_instance($record->name, $instance)) {
236 continue;
238 if(!$obj->is_empty()) {
239 // cache rec and obj
240 // for blocks_print_group()
241 $instance->rec = $record;
242 $instance->obj = $obj;
243 return true;
247 return false;
250 // This function prints one group of blocks in a page
251 // Parameters passed by reference for speed; they are not modified.
252 function blocks_print_group(&$page, &$pageblocks, $position) {
253 global $COURSE;
255 if(empty($pageblocks[$position])) {
256 $pageblocks[$position] = array();
257 $maxweight = 0;
259 else {
260 $maxweight = max(array_keys($pageblocks[$position]));
263 foreach ($pageblocks[$position] as $instance) {
264 if (!empty($instance->pinned)) {
265 $maxweight--;
269 $isediting = $page->user_is_editing();
271 foreach($pageblocks[$position] as $instance) {
273 // $instance may have ->rec and ->obj
274 // cached from when we walked $pageblocks
275 // in blocks_have_content()
276 if (empty($instance->rec)) {
277 $block = blocks_get_record($instance->blockid);
278 } else {
279 $block = $instance->rec;
282 if (empty($block)) {
283 // Block doesn't exist! We should delete this instance!
284 continue;
287 if(!$block->visible) {
288 // Disabled by the admin
289 continue;
292 if (empty($instance->obj)) {
293 if (!$obj = block_instance($block->name, $instance)) {
294 // Invalid block
295 continue;
297 } else {
298 $obj = $instance->obj;
301 $editalways = $page->edit_always();
303 if (($isediting && empty($instance->pinned)) || !empty($editalways)) {
304 $options = 0;
305 // 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:
306 // the first block might still be able to move up if the page says so (i.e., it will change position)
307 $options |= BLOCK_MOVE_UP * ($instance->weight != 0 || ($page->blocks_move_position($instance, BLOCK_MOVE_UP) != $instance->position));
308 // Same thing for downward movement
309 $options |= BLOCK_MOVE_DOWN * ($instance->weight != $maxweight || ($page->blocks_move_position($instance, BLOCK_MOVE_DOWN) != $instance->position));
310 // For left and right movements, it's up to the page to tell us whether they are allowed
311 $options |= BLOCK_MOVE_RIGHT * ($page->blocks_move_position($instance, BLOCK_MOVE_RIGHT) != $instance->position);
312 $options |= BLOCK_MOVE_LEFT * ($page->blocks_move_position($instance, BLOCK_MOVE_LEFT ) != $instance->position);
313 // Finally, the block can be configured if the block class either allows multiple instances, or if it specifically
314 // allows instance configuration (multiple instances override that one). It doesn't have anything to do with what the
315 // administrator has allowed for this block in the site admin options.
316 $options |= BLOCK_CONFIGURE * ( $obj->instance_allow_multiple() || $obj->instance_allow_config() );
317 $obj->_add_edit_controls($options);
320 if (!$instance->visible && empty($COURSE->javascriptportal)) {
321 if ($isediting) {
322 $obj->_print_shadow();
324 } else {
325 global $COURSE;
326 if(!empty($COURSE->javascriptportal))
327 $COURSE->javascriptportal->currentblocksection = $position;
328 $obj->_print_block();
333 if ($page->blocks_default_position() == $position && $page->user_is_editing()) {
334 blocks_print_adminblock($page, $pageblocks);
339 // This iterates over an array of blocks and calculates the preferred width
340 // Parameter passed by reference for speed; it's not modified.
341 function blocks_preferred_width(&$instances) {
342 $width = 0;
344 if(empty($instances) || !is_array($instances)) {
345 return 0;
348 $blocks = blocks_get_record();
350 foreach($instances as $instance) {
351 if(!$instance->visible) {
352 continue;
355 if (!array_key_exists($instance->blockid, $blocks)) {
356 // Block doesn't exist! We should delete this instance!
357 continue;
360 if(!$blocks[$instance->blockid]->visible) {
361 continue;
363 $pref = block_method_result($blocks[$instance->blockid]->name, 'preferred_width');
364 if($pref === NULL) {
365 continue;
367 if($pref > $width) {
368 $width = $pref;
371 return $width;
374 function blocks_get_record($blockid = NULL, $invalidate = false) {
375 static $cache = NULL;
377 if($invalidate || empty($cache)) {
378 $cache = get_records('block');
381 if($blockid === NULL) {
382 return $cache;
385 return (isset($cache[$blockid])? $cache[$blockid] : false);
388 function blocks_find_block($blockid, $blocksarray) {
389 if (empty($blocksarray)) {
390 return false;
392 foreach($blocksarray as $blockgroup) {
393 if (empty($blockgroup)) {
394 continue;
396 foreach($blockgroup as $instance) {
397 if($instance->blockid == $blockid) {
398 return $instance;
402 return false;
405 function blocks_find_instance($instanceid, $blocksarray) {
406 foreach($blocksarray as $subarray) {
407 foreach($subarray as $instance) {
408 if($instance->id == $instanceid) {
409 return $instance;
413 return false;
416 // Simple entry point for anyone that wants to use blocks
417 function blocks_setup(&$PAGE,$pinned=BLOCKS_PINNED_FALSE) {
418 switch ($pinned) {
419 case BLOCKS_PINNED_TRUE:
420 $pageblocks = blocks_get_pinned($PAGE);
421 break;
422 case BLOCKS_PINNED_BOTH:
423 $pageblocks = blocks_get_by_page_pinned($PAGE);
424 break;
425 case BLOCKS_PINNED_FALSE:
426 default:
427 $pageblocks = blocks_get_by_page($PAGE);
428 break;
430 blocks_execute_url_action($PAGE, $pageblocks,($pinned==BLOCKS_PINNED_TRUE));
431 return $pageblocks;
434 function blocks_execute_action($page, &$pageblocks, $blockaction, $instanceorid, $pinned=false, $redirect=true) {
435 global $CFG;
437 if (is_int($instanceorid)) {
438 $blockid = $instanceorid;
439 } else if (is_object($instanceorid)) {
440 $instance = $instanceorid;
443 switch($blockaction) {
444 case 'config':
445 global $USER;
446 $block = blocks_get_record($instance->blockid);
447 // Hacky hacky tricky stuff to get the original human readable block title,
448 // even if the block has configured its title to be something else.
449 // Create the object WITHOUT instance data.
450 $blockobject = block_instance($block->name);
451 if ($blockobject === false) {
452 break;
455 // First of all check to see if the block wants to be edited
456 if(!$blockobject->user_can_edit()) {
457 break;
460 // Now get the title and AFTER that load up the instance
461 $blocktitle = $blockobject->get_title();
462 $blockobject->_load_instance($instance);
464 optional_param('submitted', 0, PARAM_INT);
466 // Define the data we're going to silently include in the instance config form here,
467 // so we can strip them from the submitted data BEFORE serializing it.
468 $hiddendata = array(
469 'sesskey' => $USER->sesskey,
470 'instanceid' => $instance->id,
471 'blockaction' => 'config'
474 // To this data, add anything the page itself needs to display
475 $hiddendata = array_merge($hiddendata, $page->url_get_parameters());
477 if($data = data_submitted()) {
478 $remove = array_keys($hiddendata);
479 foreach($remove as $item) {
480 unset($data->$item);
482 if(!$blockobject->instance_config_save($data,$pinned)) {
483 error('Error saving block configuration');
485 // And nothing more, continue with displaying the page
487 else {
488 // We need to show the config screen, so we highjack the display logic and then die
489 $strheading = get_string('blockconfiga', 'moodle', $blocktitle);
490 $page->print_header(get_string('pageheaderconfigablock', 'moodle'), array($strheading => ''));
492 echo '<div class="block-config" id="'.$block->name.'">'; /// Make CSS easier
494 print_heading($strheading);
495 echo '<form method="post" action="'. $page->url_get_path() .'">';
496 echo '<p>';
497 foreach($hiddendata as $name => $val) {
498 echo '<input type="hidden" name="'. $name .'" value="'. $val .'" />';
500 echo '</p>';
501 $blockobject->instance_config_print();
502 echo '</form>';
504 echo '</div>';
505 $CFG->pagepath = 'blocks/' . $block->name;
506 print_footer();
507 die(); // Do not go on with the other page-related stuff
509 break;
510 case 'toggle':
511 if(empty($instance)) {
512 error('Invalid block instance for '.$blockaction);
514 $instance->visible = ($instance->visible) ? 0 : 1;
515 if (!empty($pinned)) {
516 update_record('block_pinned', $instance);
517 } else {
518 update_record('block_instance', $instance);
520 break;
521 case 'delete':
522 if(empty($instance)) {
523 error('Invalid block instance for '. $blockaction);
525 blocks_delete_instance($instance, $pinned);
526 break;
527 case 'moveup':
528 if(empty($instance)) {
529 error('Invalid block instance for '. $blockaction);
532 if($instance->weight == 0) {
533 // The block is the first one, so a move "up" probably means it changes position
534 // Where is the instance going to be moved?
535 $newpos = $page->blocks_move_position($instance, BLOCK_MOVE_UP);
536 $newweight = (empty($pageblocks[$newpos]) ? 0 : max(array_keys($pageblocks[$newpos])) + 1);
538 blocks_execute_repositioning($instance, $newpos, $newweight, $pinned);
540 else {
541 // The block is just moving upwards in the same position.
542 // This configuration will make sure that even if somehow the weights
543 // become not continuous, block move operations will eventually bring
544 // the situation back to normal without printing any warnings.
545 if(!empty($pageblocks[$instance->position][$instance->weight - 1])) {
546 $other = $pageblocks[$instance->position][$instance->weight - 1];
548 if(!empty($other)) {
549 ++$other->weight;
550 if (!empty($pinned)) {
551 update_record('block_pinned', $other);
552 } else {
553 update_record('block_instance', $other);
556 --$instance->weight;
557 if (!empty($pinned)) {
558 update_record('block_pinned', $instance);
559 } else {
560 update_record('block_instance', $instance);
563 break;
564 case 'movedown':
565 if(empty($instance)) {
566 error('Invalid block instance for '. $blockaction);
569 if($instance->weight == max(array_keys($pageblocks[$instance->position]))) {
570 // The block is the last one, so a move "down" probably means it changes position
571 // Where is the instance going to be moved?
572 $newpos = $page->blocks_move_position($instance, BLOCK_MOVE_DOWN);
573 $newweight = (empty($pageblocks[$newpos]) ? 0 : max(array_keys($pageblocks[$newpos])) + 1);
575 blocks_execute_repositioning($instance, $newpos, $newweight, $pinned);
577 else {
578 // The block is just moving downwards in the same position.
579 // This configuration will make sure that even if somehow the weights
580 // become not continuous, block move operations will eventually bring
581 // the situation back to normal without printing any warnings.
582 if(!empty($pageblocks[$instance->position][$instance->weight + 1])) {
583 $other = $pageblocks[$instance->position][$instance->weight + 1];
585 if(!empty($other)) {
586 --$other->weight;
587 if (!empty($pinned)) {
588 update_record('block_pinned', $other);
589 } else {
590 update_record('block_instance', $other);
593 ++$instance->weight;
594 if (!empty($pinned)) {
595 update_record('block_pinned', $instance);
596 } else {
597 update_record('block_instance', $instance);
600 break;
601 case 'moveleft':
602 if(empty($instance)) {
603 error('Invalid block instance for '. $blockaction);
606 // Where is the instance going to be moved?
607 $newpos = $page->blocks_move_position($instance, BLOCK_MOVE_LEFT);
608 $newweight = (empty($pageblocks[$newpos]) ? 0 : max(array_keys($pageblocks[$newpos])) + 1);
610 blocks_execute_repositioning($instance, $newpos, $newweight, $pinned);
611 break;
612 case 'moveright':
613 if(empty($instance)) {
614 error('Invalid block instance for '. $blockaction);
617 // Where is the instance going to be moved?
618 $newpos = $page->blocks_move_position($instance, BLOCK_MOVE_RIGHT);
619 $newweight = (empty($pageblocks[$newpos]) ? 0 : max(array_keys($pageblocks[$newpos])) + 1);
621 blocks_execute_repositioning($instance, $newpos, $newweight, $pinned);
622 break;
623 case 'add':
624 // Add a new instance of this block, if allowed
625 $block = blocks_get_record($blockid);
627 if(empty($block) || !$block->visible) {
628 // Only allow adding if the block exists and is enabled
629 break;
632 if(!$block->multiple && blocks_find_block($blockid, $pageblocks) !== false) {
633 // If no multiples are allowed and we already have one, return now
634 break;
637 if(!block_method_result($block->name, 'user_can_addto', $page)) {
638 // If the block doesn't want to be added...
639 break;
642 $newpos = $page->blocks_default_position();
643 if (!empty($pinned)) {
644 $sql = 'SELECT 1, max(weight) + 1 AS nextfree FROM '. $CFG->prefix .'block_pinned WHERE '
645 .' pagetype = \''. $page->get_type() .'\' AND position = \''. $newpos .'\'';
646 } else {
647 $sql = 'SELECT 1, max(weight) + 1 AS nextfree FROM '. $CFG->prefix .'block_instance WHERE pageid = '. $page->get_id()
648 .' AND pagetype = \''. $page->get_type() .'\' AND position = \''. $newpos .'\'';
650 $weight = get_record_sql($sql);
652 $newinstance = new stdClass;
653 $newinstance->blockid = $blockid;
654 if (empty($pinned)) {
655 $newinstance->pageid = $page->get_id();
657 $newinstance->pagetype = $page->get_type();
658 $newinstance->position = $newpos;
659 $newinstance->weight = empty($weight->nextfree) ? 0 : $weight->nextfree;
660 $newinstance->visible = 1;
661 $newinstance->configdata = '';
662 if (!empty($pinned)) {
663 $newinstance->id = insert_record('block_pinned', $newinstance);
664 } else {
665 $newinstance->id = insert_record('block_instance', $newinstance);
668 // If the new instance was created, allow it to do additional setup
669 if($newinstance && ($obj = block_instance($block->name, $newinstance))) {
670 // Return value ignored
671 $obj->instance_create();
674 break;
677 if ($redirect) {
678 // In order to prevent accidental duplicate actions, redirect to a page with a clean url
679 redirect($page->url_get_full());
683 // You can use this to get the blocks to respond to URL actions without much hassle
684 function blocks_execute_url_action(&$PAGE, &$pageblocks,$pinned=false) {
685 $blockaction = optional_param('blockaction', '', PARAM_ALPHA);
687 if (empty($blockaction) || !$PAGE->user_allowed_editing() || !confirm_sesskey()) {
688 return;
691 $instanceid = optional_param('instanceid', 0, PARAM_INT);
692 $blockid = optional_param('blockid', 0, PARAM_INT);
694 if (!empty($blockid)) {
695 blocks_execute_action($PAGE, $pageblocks, strtolower($blockaction), $blockid, $pinned);
698 else if (!empty($instanceid)) {
699 $instance = blocks_find_instance($instanceid, $pageblocks);
700 blocks_execute_action($PAGE, $pageblocks, strtolower($blockaction), $instance, $pinned);
704 // This shouldn't be used externally at all, it's here for use by blocks_execute_action()
705 // in order to reduce code repetition.
706 function blocks_execute_repositioning(&$instance, $newpos, $newweight, $pinned=false, $checkPos=true) {
707 global $CFG;
709 // If it's staying where it is, don't do anything, unless overridden
710 if(($newpos == $instance->position)&& $checkPos) {
711 return;
714 // Close the weight gap we 'll leave behind
715 if (!empty($pinned)) {
716 $sql = 'UPDATE '. $CFG->prefix .'block_instance SET weight = weight - 1 WHERE pagetype = \''. $instance->pagetype.
717 '\' AND position = \'' .$instance->position.
718 '\' AND weight > '. $instance->weight;
719 } else {
720 $sql = 'UPDATE '. $CFG->prefix .'block_instance SET weight = weight - 1 WHERE pagetype = \''. $instance->pagetype.
721 '\' AND pageid = '. $instance->pageid .' AND position = \'' .$instance->position.
722 '\' AND weight > '. $instance->weight;
724 execute_sql($sql,false);
726 $instance->position = $newpos;
727 $instance->weight = $newweight;
729 if (!empty($pinned)) {
730 update_record('block_pinned', $instance);
731 } else {
732 update_record('block_instance', $instance);
736 //like blocks_execute_repositiong except completely atomic, handles all aspects of the positioning
737 function blocks_execute_repositioning_atomic(&$instance, $newpos, $newweight, $pinned=false){
738 global $CFG;
740 if($instance->weight == $newweight)
741 return false;
743 //make room for block insert
744 if (!empty($pinned)) {
745 $sql = 'UPDATE '. $CFG->prefix .'block_instance SET weight = weight + 1 WHERE pagetype = \''. $instance->pagetype.
746 '\' AND position = \'' .$newpos.
747 '\' AND weight >= '. $newweight;
748 } else {
749 $sql = 'UPDATE '. $CFG->prefix .'block_instance SET weight = weight + 1 WHERE pagetype = \''. $instance->pagetype.
750 '\' AND pageid = '. $instance->pageid .' AND position = \'' .$newpos.
751 '\' AND weight >= '. $newweight;
753 execute_sql($sql,false);
755 //adjusts the wieghts for changes in the weight list
756 if($newweight < $instance->weight){
757 $instance->weight+=2;
758 }else{
759 $newweight--;
763 //reposition blocks
764 blocks_execute_repositioning($instance,$newpos,$newweight,$pinned,false);
767 function blocks_get_pinned($page) {
769 $visible = true;
771 if (method_exists($page,'edit_always')) {
772 if ($page->edit_always()) {
773 $visible = false;
777 $blocks = get_records_select('block_pinned', 'pagetype = \''. $page->get_type() .'\''.(($visible) ? 'AND visible = 1' : ''), 'position, weight');
779 $positions = $page->blocks_get_positions();
780 $arr = array();
782 foreach($positions as $key => $position) {
783 $arr[$position] = array();
786 if(empty($blocks)) {
787 return $arr;
790 foreach($blocks as $block) {
791 $block->pinned = true; // so we know we can't move it.
792 // make up an instanceid if we can..
793 $block->pageid = $page->get_id();
794 $arr[$block->position][$block->weight] = $block;
797 return $arr;
801 function blocks_get_by_page_pinned($page) {
802 $pinned = blocks_get_pinned($page);
803 $user = blocks_get_by_page($page);
805 $weights = array();
807 foreach ($pinned as $pos => $arr) {
808 $weights[$pos] = count($arr);
811 foreach ($user as $pos => $blocks) {
812 if (!array_key_exists($pos,$pinned)) {
813 $pinned[$pos] = array();
815 if (!array_key_exists($pos,$weights)) {
816 $weights[$pos] = 0;
818 foreach ($blocks as $block) {
819 $pinned[$pos][$weights[$pos]] = $block;
820 $weights[$pos]++;
823 return $pinned;
826 function blocks_get_by_page($page) {
827 $blocks = get_records_select('block_instance', "pageid = '". $page->get_id() ."' AND pagetype = '". $page->get_type() ."'", 'position, weight');
829 $positions = $page->blocks_get_positions();
830 $arr = array();
831 foreach($positions as $key => $position) {
832 $arr[$position] = array();
835 if(empty($blocks)) {
836 return $arr;
839 foreach($blocks as $block) {
840 $arr[$block->position][$block->weight] = $block;
843 return $arr;
846 //This function prints the block to admin blocks as necessary
847 function blocks_print_adminblock(&$page, &$pageblocks) {
848 global $USER;
850 $missingblocks = blocks_get_missing($page, $pageblocks);
852 if (!empty($missingblocks)) {
853 $strblocks = get_string('blocks');
854 $stradd = get_string('add');
855 foreach ($missingblocks as $blockid) {
856 $block = blocks_get_record($blockid);
857 $blockobject = block_instance($block->name);
858 if ($blockobject === false) {
859 continue;
861 if(!$blockobject->user_can_addto($page)) {
862 continue;
864 $menu[$block->id] = $blockobject->get_title();
866 asort($menu);
868 $target = $page->url_get_full(array('sesskey' => $USER->sesskey, 'blockaction' => 'add'));
869 $content = popup_form($target.'&amp;blockid=', $menu, 'add_block', '', $stradd .'...', '', '', true);
870 print_side_block($strblocks, $content, NULL, NULL, NULL, array('class' => 'block_adminblock'));
874 function blocks_repopulate_page($page) {
875 global $CFG;
877 $allblocks = blocks_get_record();
879 if(empty($allblocks)) {
880 error('Could not retrieve blocks from the database');
883 // Assemble the information to correlate block names to ids
884 $idforname = array();
885 foreach($allblocks as $block) {
886 $idforname[$block->name] = $block->id;
889 /// If the site override has been defined, it is the only valid one.
890 if (!empty($CFG->defaultblocks_override)) {
891 $blocknames = $CFG->defaultblocks_override;
893 else {
894 $blocknames = $page->blocks_get_default();
897 $positions = $page->blocks_get_positions();
898 $posblocks = explode(':', $blocknames);
900 // Now one array holds the names of the positions, and the other one holds the blocks
901 // that are going to go in each position. Luckily for us, both arrays are numerically
902 // indexed and the indexes match, so we can work straight away... but CAREFULLY!
904 // Ready to start creating block instances, but first drop any existing ones
905 delete_records('block_instance', 'pageid', $page->get_id(), 'pagetype', $page->get_type());
907 // Here we slyly count $posblocks and NOT $positions. This can actually make a difference
908 // if the textual representation has undefined slots in the end. So we only work with as many
909 // positions were retrieved, not with all the page says it has available.
910 $numpositions = count($posblocks);
911 for($i = 0; $i < $numpositions; ++$i) {
912 $position = $positions[$i];
913 $blocknames = explode(',', $posblocks[$i]);
914 $weight = 0;
915 foreach($blocknames as $blockname) {
916 $newinstance = new stdClass;
917 $newinstance->blockid = $idforname[$blockname];
918 $newinstance->pageid = $page->get_id();
919 $newinstance->pagetype = $page->get_type();
920 $newinstance->position = $position;
921 $newinstance->weight = $weight;
922 $newinstance->visible = 1;
923 $newinstance->configdata = '';
925 if(!empty($newinstance->blockid)) {
926 // Only add block if it was recognized
927 insert_record('block_instance', $newinstance);
928 ++$weight;
933 return true;
936 function upgrade_blocks_db($continueto) {
937 /// This function upgrades the blocks tables, if necessary
938 /// It's called from admin/index.php
940 global $CFG, $db;
942 require_once ($CFG->dirroot .'/blocks/version.php'); // Get code versions
944 if (empty($CFG->blocks_version)) { // Blocks have never been installed.
945 $strdatabaseupgrades = get_string('databaseupgrades');
946 print_header($strdatabaseupgrades, $strdatabaseupgrades, $strdatabaseupgrades, '',
947 '<script type="text/javascript" src="' . $CFG->wwwroot . '/lib/scroll_to_errors.js"></script>',
948 false, '&nbsp;', '&nbsp;');
950 upgrade_log_start();
951 print_heading('blocks');
952 $db->debug=true;
954 /// Both old .sql files and new install.xml are supported
955 /// but we priorize install.xml (XMLDB) if present
956 $status = false;
957 if (file_exists($CFG->dirroot . '/blocks/db/install.xml')) {
958 $status = install_from_xmldb_file($CFG->dirroot . '/blocks/db/install.xml'); //New method
959 } else if (file_exists($CFG->dirroot . '/blocks/db/' . $CFG->dbtype . '.sql')) {
960 $status = modify_database($CFG->dirroot . '/blocks/db/' . $CFG->dbtype . '.sql'); //Old method
963 $db->debug = false;
964 if ($status) {
965 if (set_config('blocks_version', $blocks_version)) {
966 notify(get_string('databasesuccess'), 'notifysuccess');
967 notify(get_string('databaseupgradeblocks', '', $blocks_version), 'notifysuccess');
968 print_continue($continueto);
969 exit;
970 } else {
971 error('Upgrade of blocks system failed! (Could not update version in config table)');
973 } else {
974 error('Blocks tables could NOT be set up successfully!');
978 /// Upgrading code starts here
979 $oldupgrade = false;
980 $newupgrade = false;
981 if (is_readable($CFG->dirroot . '/blocks/db/' . $CFG->dbtype . '.php')) {
982 include_once($CFG->dirroot . '/blocks/db/' . $CFG->dbtype . '.php'); // defines old upgrading function
983 $oldupgrade = true;
985 if (is_readable($CFG->dirroot . '/blocks/db/upgrade.php')) {
986 include_once($CFG->dirroot . '/blocks/db/upgrade.php'); // defines new upgrading function
987 $newupgrade = true;
990 if ($blocks_version > $CFG->blocks_version) { // Upgrade tables
991 $strdatabaseupgrades = get_string('databaseupgrades');
992 print_header($strdatabaseupgrades, $strdatabaseupgrades, $strdatabaseupgrades, '',
993 '<script type="text/javascript" src="' . $CFG->wwwroot . '/lib/scroll_to_errors.js"></script>');
995 upgrade_log_start();
996 print_heading('blocks');
998 /// Run de old and new upgrade functions for the module
999 $oldupgrade_function = 'blocks_upgrade';
1000 $newupgrade_function = 'xmldb_blocks_upgrade';
1002 /// First, the old function if exists
1003 $oldupgrade_status = true;
1004 if ($oldupgrade && function_exists($oldupgrade_function)) {
1005 $db->debug = true;
1006 $oldupgrade_status = $oldupgrade_function($CFG->blocks_version);
1007 } else if ($oldupgrade) {
1008 notify ('Upgrade function ' . $oldupgrade_function . ' was not available in ' .
1009 '/blocks/db/' . $CFG->dbtype . '.php');
1012 /// Then, the new function if exists and the old one was ok
1013 $newupgrade_status = true;
1014 if ($newupgrade && function_exists($newupgrade_function) && $oldupgrade_status) {
1015 $db->debug = true;
1016 $newupgrade_status = $newupgrade_function($CFG->blocks_version);
1017 } else if ($newupgrade) {
1018 notify ('Upgrade function ' . $newupgrade_function . ' was not available in ' .
1019 '/blocks/db/upgrade.php');
1022 $db->debug=false;
1023 /// Now analyze upgrade results
1024 if ($oldupgrade_status && $newupgrade_status) { // No upgrading failed
1025 if (set_config('blocks_version', $blocks_version)) {
1026 notify(get_string('databasesuccess'), 'notifysuccess');
1027 notify(get_string('databaseupgradeblocks', '', $blocks_version), 'notifysuccess');
1028 print_continue($continueto);
1029 exit;
1030 } else {
1031 error('Upgrade of blocks system failed! (Could not update version in config table)');
1033 } else {
1034 error('Upgrade failed! See blocks/version.php');
1037 } else if ($blocks_version < $CFG->blocks_version) {
1038 upgrade_log_start();
1039 notify('WARNING!!! The Blocks version you are using is OLDER than the version that made these databases!');
1041 upgrade_log_finish();
1044 //This function finds all available blocks and install them
1045 //into blocks table or do all the upgrade process if newer
1046 function upgrade_blocks_plugins($continueto) {
1048 global $CFG, $db;
1050 $blocktitles = array();
1051 $invalidblocks = array();
1052 $validblocks = array();
1053 $notices = array();
1055 //Count the number of blocks in db
1056 $blockcount = count_records('block');
1057 //If there isn't records. This is the first install, so I remember it
1058 if ($blockcount == 0) {
1059 $first_install = true;
1060 } else {
1061 $first_install = false;
1064 $site = get_site();
1066 if (!$blocks = get_list_of_plugins('blocks', 'db') ) {
1067 error('No blocks installed!');
1070 include_once($CFG->dirroot .'/blocks/moodleblock.class.php');
1071 if(!class_exists('block_base')) {
1072 error('Class block_base is not defined or file not found for /blocks/moodleblock.class.php');
1075 foreach ($blocks as $blockname) {
1077 if ($blockname == 'NEWBLOCK') { // Someone has unzipped the template, ignore it
1078 continue;
1081 if(!block_is_compatible($blockname)) {
1082 // This is an old-style block
1083 //$notices[] = 'Block '. $blockname .' is not compatible with the current version of Mooodle and needs to be updated by a programmer.';
1084 $invalidblocks[] = $blockname;
1085 continue;
1088 $fullblock = $CFG->dirroot .'/blocks/'. $blockname;
1090 if ( is_readable($fullblock.'/block_'.$blockname.'.php')) {
1091 include_once($fullblock.'/block_'.$blockname.'.php');
1092 } else {
1093 $notices[] = 'Block '. $blockname .': '. $fullblock .'/block_'. $blockname .'.php was not readable';
1094 continue;
1097 $oldupgrade = false;
1098 $newupgrade = false;
1099 if ( @is_dir($fullblock .'/db/')) {
1100 if ( @is_readable($fullblock .'/db/'. $CFG->dbtype .'.php')) {
1101 include_once($fullblock .'/db/'. $CFG->dbtype .'.php'); // defines old upgrading function
1102 $oldupgrade = true;
1104 if ( @is_readable($fullblock .'/db/upgrade.php')) {
1105 include_once($fullblock .'/db/upgrade.php'); // defines new upgrading function
1106 $newupgrade = true;
1110 $classname = 'block_'.$blockname;
1111 if(!class_exists($classname)) {
1112 $notices[] = 'Block '. $blockname .': '. $classname .' not implemented';
1113 continue;
1116 // Here is the place to see if the block implements a constructor (old style),
1117 // an init() function (new style) or nothing at all (error time).
1119 $constructor = get_class_constructor($classname);
1120 if(empty($constructor)) {
1121 // No constructor
1122 $notices[] = 'Block '. $blockname .': class does not have a constructor';
1123 $invalidblocks[] = $blockname;
1124 continue;
1127 $block = new stdClass; // This may be used to update the db below
1128 $blockobj = new $classname; // This is what we 'll be testing
1130 // Inherits from block_base?
1131 if(!is_subclass_of($blockobj, 'block_base')) {
1132 $notices[] = 'Block '. $blockname .': class does not inherit from block_base';
1133 continue;
1136 // OK, it's as we all hoped. For further tests, the object will do them itself.
1137 if(!$blockobj->_self_test()) {
1138 $notices[] = 'Block '. $blockname .': self test failed';
1139 continue;
1141 $block->version = $blockobj->get_version();
1143 if (!isset($block->version)) {
1144 $notices[] = 'Block '. $blockname .': has no version support. It must be updated by a programmer.';
1145 continue;
1148 $block->name = $blockname; // The name MUST match the directory
1149 $blocktitle = $blockobj->get_title();
1151 if ($currblock = get_record('block', 'name', $block->name)) {
1152 if ($currblock->version == $block->version) {
1153 // do nothing
1154 } else if ($currblock->version < $block->version) {
1155 if (empty($updated_blocks)) {
1156 $strblocksetup = get_string('blocksetup');
1157 print_header($strblocksetup, $strblocksetup, $strblocksetup, '',
1158 '<script type="text/javascript" src="' . $CFG->wwwroot . '/lib/scroll_to_errors.js"></script>',
1159 false, '&nbsp;', '&nbsp;');
1161 $updated_blocks = true;
1162 upgrade_log_start();
1163 print_heading('New version of '.$blocktitle.' ('.$block->name.') exists');
1164 @set_time_limit(0); // To allow slow databases to complete the long SQL
1166 /// Run de old and new upgrade functions for the module
1167 $oldupgrade_function = $block->name .'_upgrade';
1168 $newupgrade_function = 'xmldb_block_' . $block->name .'_upgrade';
1170 /// First, the old function if exists
1171 $oldupgrade_status = true;
1172 if ($oldupgrade && function_exists($oldupgrade_function)) {
1173 $db->debug = true;
1174 $oldupgrade_status = $oldupgrade_function($currblock->version, $block);
1175 } else if ($oldupgrade) {
1176 notify ('Upgrade function ' . $oldupgrade_function . ' was not available in ' .
1177 $fullblock . '/db/' . $CFG->dbtype . '.php');
1180 /// Then, the new function if exists and the old one was ok
1181 $newupgrade_status = true;
1182 if ($newupgrade && function_exists($newupgrade_function) && $oldupgrade_status) {
1183 $db->debug = true;
1184 $newupgrade_status = $newupgrade_function($currblock->version, $block);
1185 } else if ($newupgrade) {
1186 notify ('Upgrade function ' . $newupgrade_function . ' was not available in ' .
1187 $fullblock . '/db/upgrade.php');
1190 $db->debug=false;
1191 /// Now analyze upgrade results
1192 if ($oldupgrade_status && $newupgrade_status) { // No upgrading failed
1193 // OK so far, now update the block record
1194 $block->id = $currblock->id;
1195 if (! update_record('block', $block)) {
1196 error('Could not update block '. $block->name .' record in block table!');
1198 $component = 'block/'.$block->name;
1199 if (!update_capabilities($component)) {
1200 error('Could not update '.$block->name.' capabilities!');
1202 notify(get_string('blocksuccess', '', $blocktitle), 'notifysuccess');
1203 } else {
1204 notify('Upgrading block '. $block->name .' from '. $currblock->version .' to '. $block->version .' FAILED!');
1206 echo '<hr />';
1207 } else {
1208 upgrade_log_start();
1209 error('Version mismatch: block '. $block->name .' can\'t downgrade '. $currblock->version .' -> '. $block->version .'!');
1212 } else { // block not installed yet, so install it
1214 // If it allows multiples, start with it enabled
1215 $block->multiple = $blockobj->instance_allow_multiple();
1216 if (!empty($blockobj->cron)) {
1217 $block->cron = $blockobj->cron;
1220 // [pj] Normally this would be inline in the if, but we need to
1221 // check for NULL (necessary for 4.0.5 <= PHP < 4.2.0)
1222 $conflictblock = array_search($blocktitle, $blocktitles);
1223 if($conflictblock !== false && $conflictblock !== NULL) {
1224 // Duplicate block titles are not allowed, they confuse people
1225 // AND PHP's associative arrays ;)
1226 error('<strong>Naming conflict</strong>: block <strong>'.$block->name.'</strong> has the same title with an existing block, <strong>'.$conflictblock.'</strong>!');
1228 if (empty($updated_blocks)) {
1229 $strblocksetup = get_string('blocksetup');
1230 print_header($strblocksetup, $strblocksetup, $strblocksetup, '',
1231 '<script type="text/javascript" src="' . $CFG->wwwroot . '/lib/scroll_to_errors.js"></script>',
1232 false, '&nbsp;', '&nbsp;');
1234 $updated_blocks = true;
1235 upgrade_log_start();
1236 print_heading($block->name);
1237 $db->debug = true;
1238 @set_time_limit(0); // To allow slow databases to complete the long SQL
1240 /// Both old .sql files and new install.xml are supported
1241 /// but we priorize install.xml (XMLDB) if present
1242 $status = false;
1243 if (file_exists($fullblock . '/db/install.xml')) {
1244 $status = install_from_xmldb_file($fullblock . '/db/install.xml'); //New method
1245 } else if (file_exists($fullblock .'/db/'. $CFG->dbtype .'.sql')) {
1246 $status = modify_database($fullblock .'/db/'. $CFG->dbtype .'.sql'); //Old method
1247 } else {
1248 $status = true;
1251 $db->debug = false;
1252 if ($status) {
1253 if ($block->id = insert_record('block', $block)) {
1254 $blockobj->after_install();
1255 $component = 'block/'.$block->name;
1256 if (!update_capabilities($component)) {
1257 notify('Could not set up '.$block->name.' capabilities!');
1259 notify(get_string('blocksuccess', '', $blocktitle), 'notifysuccess');
1260 echo '<hr />';
1261 } else {
1262 error($block->name .' block could not be added to the block list!');
1264 } else {
1265 error('Block '. $block->name .' tables could NOT be set up successfully!');
1269 $blocktitles[$block->name] = $blocktitle;
1272 if(!empty($notices)) {
1273 upgrade_log_start();
1274 foreach($notices as $notice) {
1275 notify($notice);
1279 // Finally, if we are in the first_install of BLOCKS (this means that we are
1280 // upgrading from Moodle < 1.3), put blocks in all existing courses.
1281 if ($first_install) {
1282 upgrade_log_start();
1283 //Iterate over each course
1284 if ($courses = get_records('course')) {
1285 foreach ($courses as $course) {
1286 $page = page_create_object(PAGE_COURSE_VIEW, $course->id);
1287 blocks_repopulate_page($page);
1292 if (!empty($CFG->siteblocksadded)) { /// This is a once-off hack to make a proper upgrade
1293 upgrade_log_start();
1294 $page = page_create_object(PAGE_COURSE_VIEW, SITEID);
1295 blocks_repopulate_page($page);
1296 delete_records('config', 'name', 'siteblocksadded');
1299 upgrade_log_finish();
1301 if (!empty($updated_blocks)) {
1302 print_continue($continueto);
1303 die;