MDL-24699 minimalistic fix for the missing mnet host id when updating local user...
[moodle.git] / lib / blocklib.php
blob8cd5a12b71037d70f9d6f00f29ffff4281758bf0
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) {
172 $accept = NULL;
173 $depth = -1;
174 if ($formats = block_method_result($name, 'applicable_formats')) {
175 foreach($formats as $format => $allowed) {
176 $thisformat = '^'.str_replace('*', '[^-]*', $format).'.*$';
177 if(ereg($thisformat, $pageformat)) {
178 if(($scount = substr_count($format, '-')) > $depth) {
179 $depth = $scount;
180 $accept = $allowed;
185 if($accept === NULL) {
186 $accept = !empty($formats['all']);
188 return $accept;
191 function blocks_delete_instance($instance,$pinned=false) {
192 global $CFG;
194 // Get the block object and call instance_delete() if possible
195 if($record = blocks_get_record($instance->blockid)) {
196 if($obj = block_instance($record->name, $instance)) {
197 // Return value ignored
198 $obj->instance_delete();
202 if (!empty($pinned)) {
203 delete_records('block_pinned', 'id', $instance->id);
204 // And now, decrement the weight of all blocks after this one
205 execute_sql('UPDATE '.$CFG->prefix.'block_pinned SET weight = weight - 1 WHERE pagetype = \''.$instance->pagetype.
206 '\' AND position = \''.$instance->position.
207 '\' AND weight > '.$instance->weight, false);
208 } else {
209 // Now kill the db record;
210 delete_records('block_instance', 'id', $instance->id);
211 delete_context(CONTEXT_BLOCK, $instance->id);
212 // And now, decrement the weight of all blocks after this one
213 execute_sql('UPDATE '.$CFG->prefix.'block_instance SET weight = weight - 1 WHERE pagetype = \''.$instance->pagetype.
214 '\' AND pageid = '.$instance->pageid.' AND position = \''.$instance->position.
215 '\' AND weight > '.$instance->weight, false);
217 return true;
220 // Accepts an array of block instances and checks to see if any of them have content to display
221 // (causing them to calculate their content in the process). Returns true or false. Parameter passed
222 // by reference for speed; the array is actually not modified.
223 function blocks_have_content(&$pageblocks, $position) {
225 if (empty($pageblocks) || !is_array($pageblocks) || !array_key_exists($position,$pageblocks)) {
226 return false;
228 // use a for() loop to get references to the array elements
229 // foreach() cannot fetch references in PHP v4.x
230 for ($n=0; $n<count($pageblocks[$position]);$n++) {
231 $instance = &$pageblocks[$position][$n];
232 if (empty($instance->visible)) {
233 continue;
235 if(!$record = blocks_get_record($instance->blockid)) {
236 continue;
238 if (empty($record->visible)) {
239 continue;
241 if(!$obj = block_instance($record->name, $instance)) {
242 continue;
244 if(!$obj->is_empty()) {
245 // cache rec and obj
246 // for blocks_print_group()
247 $instance->rec = $record;
248 $instance->obj = $obj;
249 return true;
253 return false;
256 // This function prints one group of blocks in a page
257 // Parameters passed by reference for speed; they are not modified.
258 function blocks_print_group(&$page, &$pageblocks, $position) {
259 global $COURSE, $CFG, $USER;
260 $isediting = $page->user_is_editing();
262 if (empty($pageblocks[$position])) {
263 $groupblocks = array();
264 $maxweight = 0;
265 } else {
266 $groupblocks = $pageblocks[$position];
267 $maxweight = max(array_keys($groupblocks));
269 if (!empty($CFG->ajaxcapable) && $CFG->ajaxcapable && !empty($COURSE->javascriptportal) && $isediting) {
270 $COURSE->javascriptportal->currentblocksection = $position;
271 $COURSE->javascriptportal->block_add($position.'inst0', FALSE);
274 foreach ($groupblocks as $instance) {
275 if (!empty($instance->pinned)) {
276 $maxweight--;
280 foreach($groupblocks as $instance) {
281 // $instance may have ->rec and ->obj
282 // cached from when we walked $pageblocks
283 // in blocks_have_content()
284 if (empty($instance->rec)) {
285 if (empty($instance->blockid)) {
286 continue; // Can't do anything
288 $block = blocks_get_record($instance->blockid);
289 } else {
290 $block = $instance->rec;
293 if (empty($block)) {
294 // Block doesn't exist! We should delete this instance!
295 continue;
298 if (empty($block->visible)) {
299 // Disabled by the admin
300 continue;
303 if (empty($instance->obj)) {
304 if (!$obj = block_instance($block->name, $instance)) {
305 // Invalid block
306 continue;
308 } else {
309 $obj = $instance->obj;
312 $editalways = $page->edit_always();
315 if (($isediting && empty($instance->pinned)) || !empty($editalways)) {
316 $options = 0;
317 // 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:
318 // the first block might still be able to move up if the page says so (i.e., it will change position)
319 $options |= BLOCK_MOVE_UP * ($instance->weight != 0 || ($page->blocks_move_position($instance, BLOCK_MOVE_UP) != $instance->position));
320 // Same thing for downward movement
321 $options |= BLOCK_MOVE_DOWN * ($instance->weight != $maxweight || ($page->blocks_move_position($instance, BLOCK_MOVE_DOWN) != $instance->position));
322 // For left and right movements, it's up to the page to tell us whether they are allowed
323 $options |= BLOCK_MOVE_RIGHT * ($page->blocks_move_position($instance, BLOCK_MOVE_RIGHT) != $instance->position);
324 $options |= BLOCK_MOVE_LEFT * ($page->blocks_move_position($instance, BLOCK_MOVE_LEFT ) != $instance->position);
325 // Finally, the block can be configured if the block class either allows multiple instances, or if it specifically
326 // allows instance configuration (multiple instances override that one). It doesn't have anything to do with what the
327 // administrator has allowed for this block in the site admin options.
328 $options |= BLOCK_CONFIGURE * ( $obj->instance_allow_multiple() || $obj->instance_allow_config() );
329 $obj->_add_edit_controls($options);
332 if (!$instance->visible && empty($COURSE->javascriptportal)) {
333 if ($isediting) {
334 $obj->_print_shadow();
336 } else {
337 global $COURSE;
338 if(!empty($COURSE->javascriptportal)) {
339 $COURSE->javascriptportal->currentblocksection = $position;
341 $obj->_print_block();
343 if (!empty($COURSE->javascriptportal)
344 && (empty($instance->pinned) || !$instance->pinned)) {
345 $COURSE->javascriptportal->block_add('inst'.$instance->id, !$instance->visible);
347 } // End foreach
349 // Check if
350 // we are on the default position/side AND
351 // we're editing the page AND
352 // (
353 // we have the capability to manage blocks OR
354 // we are in myMoodle page AND have the capibility to manage myMoodle blocks
355 // )
357 // for constant PAGE_MY_MOODLE
358 include_once($CFG->dirroot.'/my/pagelib.php');
360 $coursecontext = get_context_instance(CONTEXT_COURSE, $COURSE->id);
361 $myownblogpage = (isset($page->filtertype) && isset($page->filterselect) && $page->type=='blog-view' && $page->filtertype=='user' && $page->filterselect == $USER->id);
363 $managecourseblocks = has_capability('moodle/site:manageblocks', $coursecontext);
364 $editmymoodle = $page->type == PAGE_MY_MOODLE && has_capability('moodle/my:manageblocks', $coursecontext);
366 if ($page->blocks_default_position() == $position &&
367 $page->user_is_editing() &&
368 ($managecourseblocks || $editmymoodle || $myownblogpage || defined('ADMIN_STICKYBLOCKS'))) {
370 print_side_block(NULL,NULL, NULL, NULL, NULL, array('id'=> BLOCK_POS_RIGHT.'inst0', 'class'=>'tempblockhandler'));
371 blocks_print_adminblock($page, $pageblocks);
372 } else if ($page->user_is_editing() &&
373 ($managecourseblocks || $editmymoodle || $myownblogpage || defined('ADMIN_STICKYBLOCKS'))) {
374 print_side_block(NULL,NULL, NULL, NULL, NULL, array('id'=> BLOCK_POS_LEFT.'inst0', 'class'=>'tempblockhandler'));
378 // This iterates over an array of blocks and calculates the preferred width
379 // Parameter passed by reference for speed; it's not modified.
380 function blocks_preferred_width(&$instances) {
381 $width = 0;
383 if(empty($instances) || !is_array($instances)) {
384 return 0;
387 $blocks = blocks_get_record();
389 foreach($instances as $instance) {
390 if(!$instance->visible) {
391 continue;
394 if (!array_key_exists($instance->blockid, $blocks)) {
395 // Block doesn't exist! We should delete this instance!
396 continue;
399 if(!$blocks[$instance->blockid]->visible) {
400 continue;
402 $pref = block_method_result($blocks[$instance->blockid]->name, 'preferred_width');
403 if($pref === NULL) {
404 continue;
406 if($pref > $width) {
407 $width = $pref;
410 return $width;
413 function blocks_get_record($blockid = NULL, $invalidate = false) {
414 static $cache = NULL;
416 if($invalidate || empty($cache)) {
417 $cache = get_records('block');
420 if($blockid === NULL) {
421 return $cache;
424 return (isset($cache[$blockid])? $cache[$blockid] : false);
427 function blocks_find_block($blockid, $blocksarray) {
428 if (empty($blocksarray)) {
429 return false;
431 foreach($blocksarray as $blockgroup) {
432 if (empty($blockgroup)) {
433 continue;
435 foreach($blockgroup as $instance) {
436 if($instance->blockid == $blockid) {
437 return $instance;
441 return false;
444 function blocks_find_instance($instanceid, $blocksarray) {
445 foreach($blocksarray as $subarray) {
446 foreach($subarray as $instance) {
447 if($instance->id == $instanceid) {
448 return $instance;
452 return false;
455 // Simple entry point for anyone that wants to use blocks
456 function blocks_setup(&$PAGE,$pinned=BLOCKS_PINNED_FALSE) {
457 switch ($pinned) {
458 case BLOCKS_PINNED_TRUE:
459 $pageblocks = blocks_get_pinned($PAGE);
460 break;
461 case BLOCKS_PINNED_BOTH:
462 $pageblocks = blocks_get_by_page_pinned($PAGE);
463 break;
464 case BLOCKS_PINNED_FALSE:
465 default:
466 $pageblocks = blocks_get_by_page($PAGE);
467 break;
469 blocks_execute_url_action($PAGE, $pageblocks,($pinned==BLOCKS_PINNED_TRUE));
470 return $pageblocks;
473 function blocks_execute_action($page, &$pageblocks, $blockaction, $instanceorid, $pinned=false, $redirect=true) {
474 global $CFG;
476 if (is_int($instanceorid)) {
477 $blockid = $instanceorid;
478 } else if (is_object($instanceorid)) {
479 $instance = $instanceorid;
482 switch($blockaction) {
483 case 'config':
484 global $USER;
485 $block = blocks_get_record($instance->blockid);
486 // Hacky hacky tricky stuff to get the original human readable block title,
487 // even if the block has configured its title to be something else.
488 // Create the object WITHOUT instance data.
489 $blockobject = block_instance($block->name);
490 if ($blockobject === false) {
491 break;
494 // First of all check to see if the block wants to be edited
495 if(!$blockobject->user_can_edit()) {
496 break;
499 // Now get the title and AFTER that load up the instance
500 $blocktitle = $blockobject->get_title();
501 $blockobject->_load_instance($instance);
503 optional_param('submitted', 0, PARAM_INT);
505 // Define the data we're going to silently include in the instance config form here,
506 // so we can strip them from the submitted data BEFORE serializing it.
507 $hiddendata = array(
508 'sesskey' => $USER->sesskey,
509 'instanceid' => $instance->id,
510 'blockaction' => 'config'
513 // To this data, add anything the page itself needs to display
514 $hiddendata = array_merge($hiddendata, $page->url_get_parameters());
516 if ($data = data_submitted()) {
517 $remove = array_keys($hiddendata);
518 foreach($remove as $item) {
519 unset($data->$item);
521 if(!$blockobject->instance_config_save($data,$pinned)) {
522 error('Error saving block configuration');
524 // And nothing more, continue with displaying the page
526 else {
527 // We need to show the config screen, so we highjack the display logic and then die
528 $strheading = get_string('blockconfiga', 'moodle', $blocktitle);
529 $page->print_header(get_string('pageheaderconfigablock', 'moodle'), array($strheading => ''));
531 echo '<div class="block-config" id="'.$block->name.'">'; /// Make CSS easier
533 print_heading($strheading);
534 echo '<form method="post" name="block-config" action="'. $page->url_get_path() .'">';
535 echo '<p>';
536 foreach($hiddendata as $name => $val) {
537 echo '<input type="hidden" name="'. $name .'" value="'. $val .'" />';
539 echo '</p>';
540 $blockobject->instance_config_print();
541 echo '</form>';
543 echo '</div>';
544 $CFG->pagepath = 'blocks/' . $block->name;
545 print_footer();
546 die(); // Do not go on with the other page-related stuff
548 break;
549 case 'toggle':
550 if(empty($instance)) {
551 error('Invalid block instance for '.$blockaction);
553 $instance->visible = ($instance->visible) ? 0 : 1;
554 if (!empty($pinned)) {
555 update_record('block_pinned', $instance);
556 } else {
557 update_record('block_instance', $instance);
559 break;
560 case 'delete':
561 if(empty($instance)) {
562 error('Invalid block instance for '. $blockaction);
564 blocks_delete_instance($instance, $pinned);
565 break;
566 case 'moveup':
567 if (empty($instance)) {
568 error('Invalid block instance for '. $blockaction);
571 if ($instance->weight == 0) {
572 // The block is the first one, so a move "up" probably means it changes position
573 // Where is the instance going to be moved?
574 $newpos = $page->blocks_move_position($instance, BLOCK_MOVE_UP);
575 $newweight = (empty($pageblocks[$newpos]) ? 0 : max(array_keys($pageblocks[$newpos])) + 1);
577 blocks_execute_repositioning($instance, $newpos, $newweight, $pinned);
578 } else {
579 // The block is just moving upwards in the same position.
580 // This configuration will make sure that even if somehow the weights
581 // become not continuous, block move operations will eventually bring
582 // the situation back to normal without printing any warnings.
583 if (!empty($pageblocks[$instance->position][$instance->weight - 1])) {
584 //define instance's position in the array
585 foreach ($pageblocks[$instance->position] as $instancekeysindex => $index ){
586 if ($pageblocks[$instance->position][$instancekeysindex]->id == $instance->id){
587 $instanceindex = $instancekeysindex;
590 $other = $pageblocks[$instance->position][$instanceindex - 1];
592 if (!empty($other)) {
593 ++$other->weight;
594 if (!empty($pinned)) {
595 update_record('block_pinned', $other);
596 } else {
597 update_record('block_instance', $other);
600 --$instance->weight;
601 if (!empty($pinned)) {
602 update_record('block_pinned', $instance);
603 } else {
604 update_record('block_instance', $instance);
607 break;
608 case 'movedown':
609 if (empty($instance)) {
610 error('Invalid block instance for '. $blockaction);
612 if ($instance->weight == max(array_keys($pageblocks[$instance->position]))) {
613 // The block is the last one, so a move "down" probably means it changes position
614 // Where is the instance going to be moved?
615 $newpos = $page->blocks_move_position($instance, BLOCK_MOVE_DOWN);
616 $newweight = (empty($pageblocks[$newpos]) ? 0 : max(array_keys($pageblocks[$newpos])) + 1);
618 blocks_execute_repositioning($instance, $newpos, $newweight, $pinned);
620 else {
621 // The block is just moving downwards in the same position.
622 // This configuration will make sure that even if somehow the weights
623 // become not continuous, block move operations will eventually bring
624 // the situation back to normal without printing any warnings.
625 if (!empty($pageblocks[$instance->position][$instance->weight + 1])) {
626 //define instance's position in the array
627 foreach ($pageblocks[$instance->position] as $instancekeysindex => $index ){
628 if ($pageblocks[$instance->position][$instancekeysindex]->id == $instance->id){
629 $instanceindex = $instancekeysindex;
632 $other = $pageblocks[$instance->position][$instanceindex + 1];
634 if (!empty($other)) {
635 --$other->weight;
636 if (!empty($pinned)) {
637 update_record('block_pinned', $other);
638 } else {
639 update_record('block_instance', $other);
642 ++$instance->weight;
643 if (!empty($pinned)) {
644 update_record('block_pinned', $instance);
645 } else {
646 update_record('block_instance', $instance);
649 break;
650 case 'moveleft':
651 if(empty($instance)) {
652 error('Invalid block instance for '. $blockaction);
654 // Where is the instance going to be moved?
655 $newpos = $page->blocks_move_position($instance, BLOCK_MOVE_LEFT);
656 $newweight = 0;
658 if (!empty($pinned) && !empty($pageblocks[$newpos]) ){
659 $newweight = $pageblocks[$newpos][max(array_keys($pageblocks[$newpos])) ]->weight + 1;
660 } else if(!empty($pageblocks[$newpos]) && (!array_key_exists('pinned', $pageblocks[$newpos][max(array_keys($pageblocks[$newpos]))])) ){
661 $newweight = $pageblocks[$newpos][max(array_keys($pageblocks[$newpos])) ]->weight + 1;
663 blocks_execute_repositioning($instance, $newpos, $newweight, $pinned);
664 break;
665 case 'moveright':
666 if(empty($instance)) {
667 error('Invalid block instance for '. $blockaction);
670 // Where is the instance going to be moved?
671 $newpos = $page->blocks_move_position($instance, BLOCK_MOVE_RIGHT);
672 $newweight = 0;
674 if (!empty($pinned) && !empty($pageblocks[$newpos]) ){
675 $newweight = $pageblocks[$newpos][max(array_keys($pageblocks[$newpos])) ]->weight + 1;
676 }else if(!empty($pageblocks[$newpos]) && (!array_key_exists('pinned', $pageblocks[$newpos][max(array_keys($pageblocks[$newpos]))])) ){
677 $newweight = $pageblocks[$newpos][max(array_keys($pageblocks[$newpos])) ]->weight + 1;
679 blocks_execute_repositioning($instance, $newpos, $newweight, $pinned);
680 break;
681 case 'add':
682 // Add a new instance of this block, if allowed
683 $block = blocks_get_record($blockid);
685 if(empty($block) || !$block->visible) {
686 // Only allow adding if the block exists and is enabled
687 break;
690 if(!$block->multiple && blocks_find_block($blockid, $pageblocks) !== false) {
691 // If no multiples are allowed and we already have one, return now
692 break;
695 if(!block_method_result($block->name, 'user_can_addto', $page)) {
696 // If the block doesn't want to be added...
697 break;
700 $newpos = $page->blocks_default_position();
701 if (!empty($pinned)) {
702 $sql = 'SELECT 1, max(weight) + 1 AS nextfree FROM '. $CFG->prefix .'block_pinned WHERE '
703 .' pagetype = \''. $page->get_type() .'\' AND position = \''. $newpos .'\'';
704 } else {
705 $sql = 'SELECT 1, max(weight) + 1 AS nextfree FROM '. $CFG->prefix .'block_instance WHERE pageid = '. $page->get_id()
706 .' AND pagetype = \''. $page->get_type() .'\' AND position = \''. $newpos .'\'';
708 $weight = get_record_sql($sql);
710 $newinstance = new stdClass;
711 $newinstance->blockid = $blockid;
712 if (empty($pinned)) {
713 $newinstance->pageid = $page->get_id();
715 $newinstance->pagetype = $page->get_type();
716 $newinstance->position = $newpos;
717 $newinstance->weight = empty($weight->nextfree) ? 0 : $weight->nextfree;
718 $newinstance->visible = 1;
719 $newinstance->configdata = '';
720 if (!empty($pinned)) {
721 $newinstance->id = insert_record('block_pinned', $newinstance);
722 } else {
723 $newinstance->id = insert_record('block_instance', $newinstance);
726 // If the new instance was created, allow it to do additional setup
727 if($newinstance && ($obj = block_instance($block->name, $newinstance))) {
728 // Return value ignored
729 $obj->instance_create();
732 break;
735 if ($redirect) {
736 // In order to prevent accidental duplicate actions, redirect to a page with a clean url
737 redirect($page->url_get_full());
741 // You can use this to get the blocks to respond to URL actions without much hassle
742 function blocks_execute_url_action(&$PAGE, &$pageblocks,$pinned=false) {
743 $blockaction = optional_param('blockaction', '', PARAM_ALPHA);
745 if (empty($blockaction) || !$PAGE->user_allowed_editing() || !confirm_sesskey()) {
746 return;
749 $instanceid = optional_param('instanceid', 0, PARAM_INT);
750 $blockid = optional_param('blockid', 0, PARAM_INT);
752 if (!empty($blockid)) {
753 blocks_execute_action($PAGE, $pageblocks, strtolower($blockaction), $blockid, $pinned);
756 else if (!empty($instanceid)) {
757 $instance = blocks_find_instance($instanceid, $pageblocks);
758 blocks_execute_action($PAGE, $pageblocks, strtolower($blockaction), $instance, $pinned);
762 // This shouldn't be used externally at all, it's here for use by blocks_execute_action()
763 // in order to reduce code repetition.
764 function blocks_execute_repositioning(&$instance, $newpos, $newweight, $pinned=false) {
765 global $CFG;
767 // If it's staying where it is, don't do anything, unless overridden
768 if ($newpos == $instance->position) {
769 return;
772 // Close the weight gap we 'll leave behind
773 if (!empty($pinned)) {
774 $sql = 'UPDATE '. $CFG->prefix .'block_pinned SET weight = weight - 1 '.
775 'WHERE pagetype = \''. $instance->pagetype.
776 '\' AND position = \'' .$instance->position.
777 '\' AND weight > '. $instance->weight;
778 } else {
779 $sql = 'UPDATE '. $CFG->prefix .'block_instance SET weight = weight - 1 '.
780 'WHERE pagetype = \''. $instance->pagetype.
781 '\' AND pageid = '. $instance->pageid .
782 ' AND position = \'' .$instance->position.
783 '\' AND weight > '. $instance->weight;
785 execute_sql($sql,false);
787 $instance->position = $newpos;
788 $instance->weight = $newweight;
790 if (!empty($pinned)) {
791 update_record('block_pinned', $instance);
792 } else {
793 update_record('block_instance', $instance);
799 * Moves a block to the new position (column) and weight (sort order).
800 * @param $instance - The block instance to be moved.
801 * @param $destpos - BLOCK_POS_LEFT or BLOCK_POS_RIGHT. The destination column.
802 * @param $destweight - The destination sort order. If NULL, we add to the end
803 * of the destination column.
804 * @param $pinned - Are we moving pinned blocks? We can only move pinned blocks
805 * to a new position withing the pinned list. Likewise, we
806 * can only moved non-pinned blocks to a new position within
807 * the non-pinned list.
808 * @return boolean (success or failure).
810 function blocks_move_block($page, &$instance, $destpos, $destweight=NULL, $pinned=false) {
811 global $CFG;
813 if ($pinned) {
814 $blocklist = blocks_get_pinned($page);
815 } else {
816 $blocklist = blocks_get_by_page($page);
819 if ($blocklist[$instance->position][$instance->weight]->id != $instance->id) {
820 // The source block instance is not where we think it is.
821 return false;
824 // First we close the gap that will be left behind when we take out the
825 // block from it's current column.
826 if ($pinned) {
827 $closegapsql = "UPDATE {$CFG->prefix}block_pinned
828 SET weight = weight - 1
829 WHERE weight > '$instance->weight'
830 AND position = '$instance->position'
831 AND pagetype = '$instance->pagetype'";
832 } else {
833 $closegapsql = "UPDATE {$CFG->prefix}block_instance
834 SET weight = weight - 1
835 WHERE weight > '$instance->weight'
836 AND position = '$instance->position'
837 AND pagetype = '$instance->pagetype'
838 AND pageid = '$instance->pageid'";
840 if (!execute_sql($closegapsql, false)) {
841 return false;
844 // Now let's make space for the block being moved.
845 if ($pinned) {
846 $opengapsql = "UPDATE {$CFG->prefix}block_pinned
847 SET weight = weight + 1
848 WHERE weight >= '$destweight'
849 AND position = '$destpos'
850 AND pagetype = '$instance->pagetype'";
851 } else {
852 $opengapsql = "UPDATE {$CFG->prefix}block_instance
853 SET weight = weight + 1
854 WHERE weight >= '$destweight'
855 AND position = '$destpos'
856 AND pagetype = '$instance->pagetype'
857 AND pageid = '$instance->pageid'";
859 if (!execute_sql($opengapsql, false)) {
860 return false;
863 // Move the block.
864 $instance->position = $destpos;
865 $instance->weight = $destweight;
867 if ($pinned) {
868 $table = 'block_pinned';
869 } else {
870 $table = 'block_instance';
872 return update_record($table, $instance);
877 * Returns an array consisting of 2 arrays:
878 * 1) Array of pinned blocks for position BLOCK_POS_LEFT
879 * 2) Array of pinned blocks for position BLOCK_POS_RIGHT
881 function blocks_get_pinned($page) {
883 $visible = true;
885 if (method_exists($page,'edit_always')) {
886 if ($page->edit_always()) {
887 $visible = false;
891 $blocks = get_records_select('block_pinned', 'pagetype = \''. $page->get_type() .
892 '\''.(($visible) ? 'AND visible = 1' : ''), 'position, weight');
894 $positions = $page->blocks_get_positions();
895 $arr = array();
897 foreach($positions as $key => $position) {
898 $arr[$position] = array();
901 if(empty($blocks)) {
902 return $arr;
905 foreach($blocks as $block) {
906 $block->pinned = true; // so we know we can't move it.
907 // make up an instanceid if we can..
908 $block->pageid = $page->get_id();
909 $arr[$block->position][$block->weight] = $block;
912 return $arr;
917 * Similar to blocks_get_by_page(), except that, the array returned includes
918 * pinned blocks as well. Pinned blocks are always appended before normal
919 * block instances.
921 function blocks_get_by_page_pinned($page) {
922 $pinned = blocks_get_pinned($page);
923 $user = blocks_get_by_page($page);
925 $weights = array();
927 foreach ($pinned as $pos => $arr) {
928 $weights[$pos] = count($arr);
931 foreach ($user as $pos => $blocks) {
932 if (!array_key_exists($pos,$pinned)) {
933 $pinned[$pos] = array();
935 if (!array_key_exists($pos,$weights)) {
936 $weights[$pos] = 0;
938 foreach ($blocks as $block) {
939 $pinned[$pos][$weights[$pos]] = $block;
940 $weights[$pos]++;
943 return $pinned;
948 * Returns an array of blocks for the page. Pinned blocks are excluded.
950 function blocks_get_by_page($page) {
951 $blocks = get_records_select('block_instance', "pageid = '". $page->get_id() .
952 "' AND pagetype = '". $page->get_type() ."'", 'position, weight');
954 $positions = $page->blocks_get_positions();
955 $arr = array();
956 foreach($positions as $key => $position) {
957 $arr[$position] = array();
960 if(empty($blocks)) {
961 return $arr;
964 foreach($blocks as $block) {
965 $arr[$block->position][$block->weight] = $block;
967 return $arr;
971 //This function prints the block to admin blocks as necessary
972 function blocks_print_adminblock(&$page, &$pageblocks) {
973 global $USER;
975 $missingblocks = blocks_get_missing($page, $pageblocks);
977 if (!empty($missingblocks)) {
978 $strblocks = '<div class="title"><h2>';
979 $strblocks .= get_string('blocks');
980 $strblocks .= '</h2></div>';
981 $stradd = get_string('add');
982 foreach ($missingblocks as $blockid) {
983 $block = blocks_get_record($blockid);
984 $blockobject = block_instance($block->name);
985 if ($blockobject === false) {
986 continue;
988 if(!$blockobject->user_can_addto($page)) {
989 continue;
991 $menu[$block->id] = $blockobject->get_title();
993 asort($menu);
995 $target = $page->url_get_full(array('sesskey' => $USER->sesskey, 'blockaction' => 'add'));
996 $content = popup_form($target.'&amp;blockid=', $menu, 'add_block', '', $stradd .'...', '', '', true);
997 print_side_block($strblocks, $content, NULL, NULL, NULL, array('class' => 'block_adminblock'));
1002 * Delete all the blocks from a particular page.
1004 * @param string $pagetype the page type.
1005 * @param integer $pageid the page id.
1006 * @return success of failure.
1008 function blocks_delete_all_on_page($pagetype, $pageid) {
1009 if ($instances = get_records_select('block_instance', "pageid = $pageid AND pagetype = '$pagetype'")) {
1010 foreach ($instances as $instance) {
1011 delete_context(CONTEXT_BLOCK, $instance->id); // Ingore any failures here.
1014 return delete_records('block_instance', 'pageid', $pageid, 'pagetype', $pagetype);
1017 // Dispite what this function is called, it seems to be mostly used to populate
1018 // the default blocks when a new course (or whatever) is created.
1019 function blocks_repopulate_page($page) {
1020 global $CFG;
1022 $allblocks = blocks_get_record();
1024 if(empty($allblocks)) {
1025 error('Could not retrieve blocks from the database');
1028 // Assemble the information to correlate block names to ids
1029 $idforname = array();
1030 foreach($allblocks as $block) {
1031 $idforname[$block->name] = $block->id;
1034 /// If the site override has been defined, it is the only valid one.
1035 if (!empty($CFG->defaultblocks_override)) {
1036 $blocknames = $CFG->defaultblocks_override;
1038 else {
1039 $blocknames = $page->blocks_get_default();
1042 $positions = $page->blocks_get_positions();
1043 $posblocks = explode(':', $blocknames);
1045 // Now one array holds the names of the positions, and the other one holds the blocks
1046 // that are going to go in each position. Luckily for us, both arrays are numerically
1047 // indexed and the indexes match, so we can work straight away... but CAREFULLY!
1049 // Ready to start creating block instances, but first drop any existing ones
1050 blocks_delete_all_on_page($page->get_type(), $page->get_id());
1052 // Here we slyly count $posblocks and NOT $positions. This can actually make a difference
1053 // if the textual representation has undefined slots in the end. So we only work with as many
1054 // positions were retrieved, not with all the page says it has available.
1055 $numpositions = count($posblocks);
1056 for($i = 0; $i < $numpositions; ++$i) {
1057 $position = $positions[$i];
1058 $blocknames = explode(',', $posblocks[$i]);
1059 $weight = 0;
1060 foreach($blocknames as $blockname) {
1061 $newinstance = new stdClass;
1062 $newinstance->blockid = $idforname[$blockname];
1063 $newinstance->pageid = $page->get_id();
1064 $newinstance->pagetype = $page->get_type();
1065 $newinstance->position = $position;
1066 $newinstance->weight = $weight;
1067 $newinstance->visible = 1;
1068 $newinstance->configdata = '';
1070 if(!empty($newinstance->blockid)) {
1071 // Only add block if it was recognized
1072 insert_record('block_instance', $newinstance);
1073 ++$weight;
1078 return true;
1081 function upgrade_blocks_db($continueto) {
1082 /// This function upgrades the blocks tables, if necessary
1083 /// It's called from admin/index.php
1085 global $CFG, $db;
1087 require_once ($CFG->dirroot .'/blocks/version.php'); // Get code versions
1089 if (empty($CFG->blocks_version)) { // Blocks have never been installed.
1090 $strdatabaseupgrades = get_string('databaseupgrades');
1091 print_header($strdatabaseupgrades, $strdatabaseupgrades,
1092 build_navigation(array(array('name' => $strdatabaseupgrades, 'link' => null, 'type' => 'misc'))), '',
1093 upgrade_get_javascript(), false, '&nbsp;', '&nbsp;');
1095 upgrade_log_start();
1096 print_heading('blocks');
1097 $db->debug=true;
1099 /// Both old .sql files and new install.xml are supported
1100 /// but we priorize install.xml (XMLDB) if present
1101 $status = false;
1102 if (file_exists($CFG->dirroot . '/blocks/db/install.xml')) {
1103 $status = install_from_xmldb_file($CFG->dirroot . '/blocks/db/install.xml'); //New method
1104 } else if (file_exists($CFG->dirroot . '/blocks/db/' . $CFG->dbtype . '.sql')) {
1105 $status = modify_database($CFG->dirroot . '/blocks/db/' . $CFG->dbtype . '.sql'); //Old method
1108 $db->debug = false;
1109 if ($status) {
1110 if (set_config('blocks_version', $blocks_version)) {
1111 notify(get_string('databasesuccess'), 'notifysuccess');
1112 notify(get_string('databaseupgradeblocks', '', $blocks_version), 'notifysuccess');
1113 print_continue($continueto);
1114 print_footer('none');
1115 exit;
1116 } else {
1117 error('Upgrade of blocks system failed! (Could not update version in config table)');
1119 } else {
1120 error('Blocks tables could NOT be set up successfully!');
1124 /// Upgrading code starts here
1125 $oldupgrade = false;
1126 $newupgrade = false;
1127 if (is_readable($CFG->dirroot . '/blocks/db/' . $CFG->dbtype . '.php')) {
1128 include_once($CFG->dirroot . '/blocks/db/' . $CFG->dbtype . '.php'); // defines old upgrading function
1129 $oldupgrade = true;
1131 if (is_readable($CFG->dirroot . '/blocks/db/upgrade.php')) {
1132 include_once($CFG->dirroot . '/blocks/db/upgrade.php'); // defines new upgrading function
1133 $newupgrade = true;
1136 if ($blocks_version > $CFG->blocks_version) { // Upgrade tables
1137 $strdatabaseupgrades = get_string('databaseupgrades');
1138 print_header($strdatabaseupgrades, $strdatabaseupgrades,
1139 build_navigation(array(array('name' => $strdatabaseupgrades, 'link' => null, 'type' => 'misc'))), '', upgrade_get_javascript());
1141 upgrade_log_start();
1142 print_heading('blocks');
1144 /// Run de old and new upgrade functions for the module
1145 $oldupgrade_function = 'blocks_upgrade';
1146 $newupgrade_function = 'xmldb_blocks_upgrade';
1148 /// First, the old function if exists
1149 $oldupgrade_status = true;
1150 if ($oldupgrade && function_exists($oldupgrade_function)) {
1151 $db->debug = true;
1152 $oldupgrade_status = $oldupgrade_function($CFG->blocks_version);
1153 } else if ($oldupgrade) {
1154 notify ('Upgrade function ' . $oldupgrade_function . ' was not available in ' .
1155 '/blocks/db/' . $CFG->dbtype . '.php');
1158 /// Then, the new function if exists and the old one was ok
1159 $newupgrade_status = true;
1160 if ($newupgrade && function_exists($newupgrade_function) && $oldupgrade_status) {
1161 $db->debug = true;
1162 $newupgrade_status = $newupgrade_function($CFG->blocks_version);
1163 } else if ($newupgrade) {
1164 notify ('Upgrade function ' . $newupgrade_function . ' was not available in ' .
1165 '/blocks/db/upgrade.php');
1168 $db->debug=false;
1169 /// Now analyze upgrade results
1170 if ($oldupgrade_status && $newupgrade_status) { // No upgrading failed
1171 if (set_config('blocks_version', $blocks_version)) {
1172 notify(get_string('databasesuccess'), 'notifysuccess');
1173 notify(get_string('databaseupgradeblocks', '', $blocks_version), 'notifysuccess');
1174 print_continue($continueto);
1175 print_footer('none');
1176 exit;
1177 } else {
1178 error('Upgrade of blocks system failed! (Could not update version in config table)');
1180 } else {
1181 error('Upgrade failed! See blocks/version.php');
1184 } else if ($blocks_version < $CFG->blocks_version) {
1185 upgrade_log_start();
1186 notify('WARNING!!! The Blocks version you are using is OLDER than the version that made these databases!');
1188 upgrade_log_finish();
1191 //This function finds all available blocks and install them
1192 //into blocks table or do all the upgrade process if newer
1193 function upgrade_blocks_plugins($continueto) {
1195 global $CFG, $db;
1197 $blocktitles = array();
1198 $invalidblocks = array();
1199 $validblocks = array();
1200 $notices = array();
1202 //Count the number of blocks in db
1203 $blockcount = count_records('block');
1204 //If there isn't records. This is the first install, so I remember it
1205 if ($blockcount == 0) {
1206 $first_install = true;
1207 } else {
1208 $first_install = false;
1211 $site = get_site();
1213 if (!$blocks = get_list_of_plugins('blocks', 'db') ) {
1214 error('No blocks installed!');
1217 include_once($CFG->dirroot .'/blocks/moodleblock.class.php');
1218 if(!class_exists('block_base')) {
1219 error('Class block_base is not defined or file not found for /blocks/moodleblock.class.php');
1222 foreach ($blocks as $blockname) {
1224 if ($blockname == 'NEWBLOCK') { // Someone has unzipped the template, ignore it
1225 continue;
1228 if(!block_is_compatible($blockname)) {
1229 // This is an old-style block
1230 //$notices[] = 'Block '. $blockname .' is not compatible with the current version of Mooodle and needs to be updated by a programmer.';
1231 $invalidblocks[] = $blockname;
1232 continue;
1235 $fullblock = $CFG->dirroot .'/blocks/'. $blockname;
1237 if ( is_readable($fullblock.'/block_'.$blockname.'.php')) {
1238 include_once($fullblock.'/block_'.$blockname.'.php');
1239 } else {
1240 $notices[] = 'Block '. $blockname .': '. $fullblock .'/block_'. $blockname .'.php was not readable';
1241 continue;
1244 $oldupgrade = false;
1245 $newupgrade = false;
1246 if ( @is_dir($fullblock .'/db/')) {
1247 if ( @is_readable($fullblock .'/db/'. $CFG->dbtype .'.php')) {
1248 include_once($fullblock .'/db/'. $CFG->dbtype .'.php'); // defines old upgrading function
1249 $oldupgrade = true;
1251 if ( @is_readable($fullblock .'/db/upgrade.php')) {
1252 include_once($fullblock .'/db/upgrade.php'); // defines new upgrading function
1253 $newupgrade = true;
1257 $classname = 'block_'.$blockname;
1258 if(!class_exists($classname)) {
1259 $notices[] = 'Block '. $blockname .': '. $classname .' not implemented';
1260 continue;
1263 // Here is the place to see if the block implements a constructor (old style),
1264 // an init() function (new style) or nothing at all (error time).
1266 $constructor = get_class_constructor($classname);
1267 if(empty($constructor)) {
1268 // No constructor
1269 $notices[] = 'Block '. $blockname .': class does not have a constructor';
1270 $invalidblocks[] = $blockname;
1271 continue;
1274 $block = new stdClass; // This may be used to update the db below
1275 $blockobj = new $classname; // This is what we 'll be testing
1277 // Inherits from block_base?
1278 if(!is_subclass_of($blockobj, 'block_base')) {
1279 $notices[] = 'Block '. $blockname .': class does not inherit from block_base';
1280 continue;
1283 // OK, it's as we all hoped. For further tests, the object will do them itself.
1284 if(!$blockobj->_self_test()) {
1285 $notices[] = 'Block '. $blockname .': self test failed';
1286 continue;
1288 $block->version = $blockobj->get_version();
1290 if (!isset($block->version)) {
1291 $notices[] = 'Block '. $blockname .': has no version support. It must be updated by a programmer.';
1292 continue;
1295 $block->name = $blockname; // The name MUST match the directory
1296 $blocktitle = $blockobj->get_title();
1298 if ($currblock = get_record('block', 'name', $block->name)) {
1299 if ($currblock->version == $block->version) {
1300 // do nothing
1301 } else if ($currblock->version < $block->version) {
1302 if (empty($updated_blocks)) {
1303 $strblocksetup = get_string('blocksetup');
1304 print_header($strblocksetup, $strblocksetup,
1305 build_navigation(array(array('name' => $strblocksetup, 'link' => null, 'type' => 'misc'))), '',
1306 upgrade_get_javascript(), false, '&nbsp;', '&nbsp;');
1308 $updated_blocks = true;
1309 upgrade_log_start();
1310 print_heading('New version of '.$blocktitle.' ('.$block->name.') exists');
1311 @set_time_limit(0); // To allow slow databases to complete the long SQL
1313 /// Run de old and new upgrade functions for the module
1314 $oldupgrade_function = $block->name .'_upgrade';
1315 $newupgrade_function = 'xmldb_block_' . $block->name .'_upgrade';
1317 /// First, the old function if exists
1318 $oldupgrade_status = true;
1319 if ($oldupgrade && function_exists($oldupgrade_function)) {
1320 $db->debug = true;
1321 $oldupgrade_status = $oldupgrade_function($currblock->version, $block);
1322 } else if ($oldupgrade) {
1323 notify ('Upgrade function ' . $oldupgrade_function . ' was not available in ' .
1324 $fullblock . '/db/' . $CFG->dbtype . '.php');
1327 /// Then, the new function if exists and the old one was ok
1328 $newupgrade_status = true;
1329 if ($newupgrade && function_exists($newupgrade_function) && $oldupgrade_status) {
1330 $db->debug = true;
1331 $newupgrade_status = $newupgrade_function($currblock->version, $block);
1332 } else if ($newupgrade) {
1333 notify ('Upgrade function ' . $newupgrade_function . ' was not available in ' .
1334 $fullblock . '/db/upgrade.php');
1337 $db->debug=false;
1338 /// Now analyze upgrade results
1339 if ($oldupgrade_status && $newupgrade_status) { // No upgrading failed
1341 // Set the block cron on upgrade
1342 $block->cron = !empty($blockobj->cron) ? $blockobj->cron : 0;
1344 // OK so far, now update the block record
1345 $block->id = $currblock->id;
1346 if (! update_record('block', $block)) {
1347 error('Could not update block '. $block->name .' record in block table!');
1349 $component = 'block/'.$block->name;
1350 if (!update_capabilities($component)) {
1351 error('Could not update '.$block->name.' capabilities!');
1354 events_update_definition($component);
1355 notify(get_string('blocksuccess', '', $blocktitle), 'notifysuccess');
1356 } else {
1357 notify('Upgrading block '. $block->name .' from '. $currblock->version .' to '. $block->version .' FAILED!');
1359 echo '<hr />';
1360 } else {
1361 upgrade_log_start();
1362 error('Version mismatch: block '. $block->name .' can\'t downgrade '. $currblock->version .' -> '. $block->version .'!');
1365 } else { // block not installed yet, so install it
1367 // If it allows multiples, start with it enabled
1368 if ($blockobj->instance_allow_multiple()) {
1369 $block->multiple = 1;
1372 // Set the block cron on install
1373 $block->cron = !empty($blockobj->cron) ? $blockobj->cron : 0;
1375 // [pj] Normally this would be inline in the if, but we need to
1376 // check for NULL (necessary for 4.0.5 <= PHP < 4.2.0)
1377 $conflictblock = array_search($blocktitle, $blocktitles);
1378 if($conflictblock !== false && $conflictblock !== NULL) {
1379 // Duplicate block titles are not allowed, they confuse people
1380 // AND PHP's associative arrays ;)
1381 error('<strong>Naming conflict</strong>: block <strong>'.$block->name.'</strong> has the same title with an existing block, <strong>'.$conflictblock.'</strong>!');
1383 if (empty($updated_blocks)) {
1384 $strblocksetup = get_string('blocksetup');
1385 print_header($strblocksetup, $strblocksetup,
1386 build_navigation(array(array('name' => $strblocksetup, 'link' => null, 'type' => 'misc'))), '',
1387 upgrade_get_javascript(), false, '&nbsp;', '&nbsp;');
1389 $updated_blocks = true;
1390 upgrade_log_start();
1391 print_heading($block->name);
1392 $db->debug = true;
1393 @set_time_limit(0); // To allow slow databases to complete the long SQL
1395 /// Both old .sql files and new install.xml are supported
1396 /// but we priorize install.xml (XMLDB) if present
1397 $status = false;
1398 if (file_exists($fullblock . '/db/install.xml')) {
1399 $status = install_from_xmldb_file($fullblock . '/db/install.xml'); //New method
1400 } else if (file_exists($fullblock .'/db/'. $CFG->dbtype .'.sql')) {
1401 $status = modify_database($fullblock .'/db/'. $CFG->dbtype .'.sql'); //Old method
1402 } else {
1403 $status = true;
1406 $db->debug = false;
1407 if ($status) {
1408 if ($block->id = insert_record('block', $block)) {
1409 $blockobj->after_install();
1410 $component = 'block/'.$block->name;
1411 if (!update_capabilities($component)) {
1412 notify('Could not set up '.$block->name.' capabilities!');
1415 events_update_definition($component);
1416 notify(get_string('blocksuccess', '', $blocktitle), 'notifysuccess');
1417 echo '<hr />';
1418 } else {
1419 error($block->name .' block could not be added to the block list!');
1421 } else {
1422 error('Block '. $block->name .' tables could NOT be set up successfully!');
1426 $blocktitles[$block->name] = $blocktitle;
1429 if(!empty($notices)) {
1430 upgrade_log_start();
1431 foreach($notices as $notice) {
1432 notify($notice);
1436 // Finally, if we are in the first_install of BLOCKS (this means that we are
1437 // upgrading from Moodle < 1.3), put blocks in all existing courses.
1438 if ($first_install) {
1439 upgrade_log_start();
1440 //Iterate over each course
1441 if ($courses = get_records('course')) {
1442 foreach ($courses as $course) {
1443 $page = page_create_object(PAGE_COURSE_VIEW, $course->id);
1444 blocks_repopulate_page($page);
1449 if (!empty($CFG->siteblocksadded)) { /// This is a once-off hack to make a proper upgrade
1450 upgrade_log_start();
1451 $page = page_create_object(PAGE_COURSE_VIEW, SITEID);
1452 blocks_repopulate_page($page);
1453 delete_records('config', 'name', 'siteblocksadded');
1456 upgrade_log_finish();
1458 if (!empty($updated_blocks)) {
1459 print_continue($continueto);
1460 print_footer('none');
1461 die;