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) {
25 $file = @file
($CFG->dirroot
.'/blocks/'.$blockname.'/block_'.$blockname.'.php'); // ignore errors when file does not exist
30 foreach($file as $line) {
31 // If you find MoodleBlock (appearing in the class declaration) it's not compatible
32 if(strpos($line, 'MoodleBlock')) {
35 // But if we find a { it means the class declaration is over, so it's compatible
36 else if(strpos($line, '{')) {
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) {
49 static $constructors = array();
51 if(!class_exists($classname)) {
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);
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)) {
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)) {
98 $classname = 'block_'.$blockname;
99 $retval = new $classname;
100 if($instance !== NULL) {
101 $retval->_load_instance($instance);
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) {
111 if(empty($blockname)) {
115 $classname = 'block_'.$blockname;
117 if(class_exists($classname)) {
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)) {
156 if(($pageformat = $page->get_format_name()) == NULL) {
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');
174 foreach($formats as $format => $allowed) {
175 $thisformat = '^'.str_replace('*', '[^-]*', $format).'.*$';
176 if(ereg($thisformat, $pageformat)) {
177 if(($scount = substr_count($format, '-')) > $depth) {
183 if($accept === NULL) {
184 $accept = !empty($formats['all']);
189 function blocks_delete_instance($instance,$pinned=false) {
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);
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);
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)) {
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
) {
232 if(!$record = blocks_get_record($instance->blockid
)) {
235 if(!$obj = block_instance($record->name
, $instance)) {
238 if(!$obj->is_empty()) {
240 // for blocks_print_group()
241 $instance->rec
= $record;
242 $instance->obj
= $obj;
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) {
255 if(empty($pageblocks[$position])) {
256 $pageblocks[$position] = array();
260 $maxweight = max(array_keys($pageblocks[$position]));
263 foreach ($pageblocks[$position] as $instance) {
264 if (!empty($instance->pinned
)) {
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
);
279 $block = $instance->rec
;
283 // Block doesn't exist! We should delete this instance!
287 if(!$block->visible
) {
288 // Disabled by the admin
292 if (empty($instance->obj
)) {
293 if (!$obj = block_instance($block->name
, $instance)) {
298 $obj = $instance->obj
;
301 $editalways = $page->edit_always();
303 if (($isediting && empty($instance->pinned
)) ||
!empty($editalways)) {
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
)) {
322 $obj->_print_shadow();
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) {
344 if(empty($instances) ||
!is_array($instances)) {
348 $blocks = blocks_get_record();
350 foreach($instances as $instance) {
351 if(!$instance->visible
) {
355 if (!array_key_exists($instance->blockid
, $blocks)) {
356 // Block doesn't exist! We should delete this instance!
360 if(!$blocks[$instance->blockid
]->visible
) {
363 $pref = block_method_result($blocks[$instance->blockid
]->name
, 'preferred_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) {
385 return (isset($cache[$blockid])?
$cache[$blockid] : false);
388 function blocks_find_block($blockid, $blocksarray) {
389 if (empty($blocksarray)) {
392 foreach($blocksarray as $blockgroup) {
393 if (empty($blockgroup)) {
396 foreach($blockgroup as $instance) {
397 if($instance->blockid
== $blockid) {
405 function blocks_find_instance($instanceid, $blocksarray) {
406 foreach($blocksarray as $subarray) {
407 foreach($subarray as $instance) {
408 if($instance->id
== $instanceid) {
416 // Simple entry point for anyone that wants to use blocks
417 function blocks_setup(&$PAGE,$pinned=BLOCKS_PINNED_FALSE
) {
419 case BLOCKS_PINNED_TRUE
:
420 $pageblocks = blocks_get_pinned($PAGE);
422 case BLOCKS_PINNED_BOTH
:
423 $pageblocks = blocks_get_by_page_pinned($PAGE);
425 case BLOCKS_PINNED_FALSE
:
427 $pageblocks = blocks_get_by_page($PAGE);
430 blocks_execute_url_action($PAGE, $pageblocks,($pinned==BLOCKS_PINNED_TRUE
));
434 function blocks_execute_action($page, &$pageblocks, $blockaction, $instanceorid, $pinned=false, $redirect=true) {
437 if (is_int($instanceorid)) {
438 $blockid = $instanceorid;
439 } else if (is_object($instanceorid)) {
440 $instance = $instanceorid;
443 switch($blockaction) {
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) {
455 // First of all check to see if the block wants to be edited
456 if(!$blockobject->user_can_edit()) {
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.
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) {
482 if(!$blockobject->instance_config_save($data,$pinned)) {
483 error('Error saving block configuration');
485 // And nothing more, continue with displaying the page
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() .'">';
497 foreach($hiddendata as $name => $val) {
498 echo '<input type="hidden" name="'. $name .'" value="'. $val .'" />';
501 $blockobject->instance_config_print();
505 $CFG->pagepath
= 'blocks/' . $block->name
;
507 die(); // Do not go on with the other page-related stuff
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);
518 update_record('block_instance', $instance);
522 if(empty($instance)) {
523 error('Invalid block instance for '. $blockaction);
525 blocks_delete_instance($instance, $pinned);
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);
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];
550 if (!empty($pinned)) {
551 update_record('block_pinned', $other);
553 update_record('block_instance', $other);
557 if (!empty($pinned)) {
558 update_record('block_pinned', $instance);
560 update_record('block_instance', $instance);
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);
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];
587 if (!empty($pinned)) {
588 update_record('block_pinned', $other);
590 update_record('block_instance', $other);
594 if (!empty($pinned)) {
595 update_record('block_pinned', $instance);
597 update_record('block_instance', $instance);
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);
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);
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
632 if(!$block->multiple
&& blocks_find_block($blockid, $pageblocks) !== false) {
633 // If no multiples are allowed and we already have one, return now
637 if(!block_method_result($block->name
, 'user_can_addto', $page)) {
638 // If the block doesn't want to be added...
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 .'\'';
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);
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();
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()) {
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) {
709 // If it's staying where it is, don't do anything, unless overridden
710 if(($newpos == $instance->position
)&& $checkPos) {
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
;
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);
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){
740 if($instance->weight
== $newweight)
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;
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;
764 blocks_execute_repositioning($instance,$newpos,$newweight,$pinned,false);
767 function blocks_get_pinned($page) {
771 if (method_exists($page,'edit_always')) {
772 if ($page->edit_always()) {
777 $blocks = get_records_select('block_pinned', 'pagetype = \''. $page->get_type() .'\''.(($visible) ?
'AND visible = 1' : ''), 'position, weight');
779 $positions = $page->blocks_get_positions();
782 foreach($positions as $key => $position) {
783 $arr[$position] = array();
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;
801 function blocks_get_by_page_pinned($page) {
802 $pinned = blocks_get_pinned($page);
803 $user = blocks_get_by_page($page);
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)) {
818 foreach ($blocks as $block) {
819 $pinned[$pos][$weights[$pos]] = $block;
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();
831 foreach($positions as $key => $position) {
832 $arr[$position] = array();
839 foreach($blocks as $block) {
840 $arr[$block->position
][$block->weight
] = $block;
846 //This function prints the block to admin blocks as necessary
847 function blocks_print_adminblock(&$page, &$pageblocks) {
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) {
861 if(!$blockobject->user_can_addto($page)) {
864 $menu[$block->id
] = $blockobject->get_title();
868 $target = $page->url_get_full(array('sesskey' => $USER->sesskey
, 'blockaction' => 'add'));
869 $content = popup_form($target.'&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) {
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
;
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]);
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);
936 function upgrade_blocks_db($continueto) {
937 /// This function upgrades the blocks tables, if necessary
938 /// It's called from admin/index.php
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, ' ', ' ');
951 print_heading('blocks');
954 /// Both old .sql files and new install.xml are supported
955 /// but we priorize install.xml (XMLDB) if present
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
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);
971 error('Upgrade of blocks system failed! (Could not update version in config table)');
974 error('Blocks tables could NOT be set up successfully!');
978 /// Upgrading code starts here
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
985 if (is_readable($CFG->dirroot
. '/blocks/db/upgrade.php')) {
986 include_once($CFG->dirroot
. '/blocks/db/upgrade.php'); // defines new upgrading function
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>');
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)) {
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) {
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');
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);
1031 error('Upgrade of blocks system failed! (Could not update version in config table)');
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) {
1050 $blocktitles = array();
1051 $invalidblocks = array();
1052 $validblocks = 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;
1061 $first_install = false;
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
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;
1088 $fullblock = $CFG->dirroot
.'/blocks/'. $blockname;
1090 if ( is_readable($fullblock.'/block_'.$blockname.'.php')) {
1091 include_once($fullblock.'/block_'.$blockname.'.php');
1093 $notices[] = 'Block '. $blockname .': '. $fullblock .'/block_'. $blockname .'.php was not readable';
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
1104 if ( @is_readable
($fullblock .'/db/upgrade.php')) {
1105 include_once($fullblock .'/db/upgrade.php'); // defines new upgrading function
1110 $classname = 'block_'.$blockname;
1111 if(!class_exists($classname)) {
1112 $notices[] = 'Block '. $blockname .': '. $classname .' not implemented';
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)) {
1122 $notices[] = 'Block '. $blockname .': class does not have a constructor';
1123 $invalidblocks[] = $blockname;
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';
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';
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.';
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
) {
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, ' ', ' ');
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)) {
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) {
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');
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');
1204 notify('Upgrading block '. $block->name
.' from '. $currblock->version
.' to '. $block->version
.' FAILED!');
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, ' ', ' ');
1234 $updated_blocks = true;
1235 upgrade_log_start();
1236 print_heading($block->name
);
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
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
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');
1262 error($block->name
.' block could not be added to the block list!');
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) {
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);