MDL-23726 fixed phpdocs - credit goes to Henning Bostelmann
[moodle.git] / lib / blocklib.php
blobdea39de3e6a49b69641452b10b1075bb0b87182b
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(!$obj = block_instance($record->name, $instance)) {
239 continue;
241 if(!$obj->is_empty()) {
242 // cache rec and obj
243 // for blocks_print_group()
244 $instance->rec = $record;
245 $instance->obj = $obj;
246 return true;
250 return false;
253 // This function prints one group of blocks in a page
254 // Parameters passed by reference for speed; they are not modified.
255 function blocks_print_group(&$page, &$pageblocks, $position) {
256 global $COURSE, $CFG, $USER;
257 $isediting = $page->user_is_editing();
259 if (empty($pageblocks[$position])) {
260 $groupblocks = array();
261 $maxweight = 0;
262 } else {
263 $groupblocks = $pageblocks[$position];
264 $maxweight = max(array_keys($groupblocks));
266 if (!empty($CFG->ajaxcapable) && $CFG->ajaxcapable && !empty($COURSE->javascriptportal) && $isediting) {
267 $COURSE->javascriptportal->currentblocksection = $position;
268 $COURSE->javascriptportal->block_add($position.'inst0', FALSE);
271 foreach ($groupblocks as $instance) {
272 if (!empty($instance->pinned)) {
273 $maxweight--;
277 foreach($groupblocks as $instance) {
278 // $instance may have ->rec and ->obj
279 // cached from when we walked $pageblocks
280 // in blocks_have_content()
281 if (empty($instance->rec)) {
282 if (empty($instance->blockid)) {
283 continue; // Can't do anything
285 $block = blocks_get_record($instance->blockid);
286 } else {
287 $block = $instance->rec;
290 if (empty($block)) {
291 // Block doesn't exist! We should delete this instance!
292 continue;
295 if (empty($block->visible)) {
296 // Disabled by the admin
297 continue;
300 if (empty($instance->obj)) {
301 if (!$obj = block_instance($block->name, $instance)) {
302 // Invalid block
303 continue;
305 } else {
306 $obj = $instance->obj;
309 $editalways = $page->edit_always();
312 if (($isediting && empty($instance->pinned)) || !empty($editalways)) {
313 $options = 0;
314 // 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:
315 // the first block might still be able to move up if the page says so (i.e., it will change position)
316 $options |= BLOCK_MOVE_UP * ($instance->weight != 0 || ($page->blocks_move_position($instance, BLOCK_MOVE_UP) != $instance->position));
317 // Same thing for downward movement
318 $options |= BLOCK_MOVE_DOWN * ($instance->weight != $maxweight || ($page->blocks_move_position($instance, BLOCK_MOVE_DOWN) != $instance->position));
319 // For left and right movements, it's up to the page to tell us whether they are allowed
320 $options |= BLOCK_MOVE_RIGHT * ($page->blocks_move_position($instance, BLOCK_MOVE_RIGHT) != $instance->position);
321 $options |= BLOCK_MOVE_LEFT * ($page->blocks_move_position($instance, BLOCK_MOVE_LEFT ) != $instance->position);
322 // Finally, the block can be configured if the block class either allows multiple instances, or if it specifically
323 // allows instance configuration (multiple instances override that one). It doesn't have anything to do with what the
324 // administrator has allowed for this block in the site admin options.
325 $options |= BLOCK_CONFIGURE * ( $obj->instance_allow_multiple() || $obj->instance_allow_config() );
326 $obj->_add_edit_controls($options);
329 if (!$instance->visible && empty($COURSE->javascriptportal)) {
330 if ($isediting) {
331 $obj->_print_shadow();
333 } else {
334 global $COURSE;
335 if(!empty($COURSE->javascriptportal)) {
336 $COURSE->javascriptportal->currentblocksection = $position;
338 $obj->_print_block();
340 if (!empty($COURSE->javascriptportal)
341 && (empty($instance->pinned) || !$instance->pinned)) {
342 $COURSE->javascriptportal->block_add('inst'.$instance->id, !$instance->visible);
344 } // End foreach
346 // Check if
347 // we are on the default position/side AND
348 // we're editing the page AND
349 // (
350 // we have the capability to manage blocks OR
351 // we are in myMoodle page AND have the capibility to manage myMoodle blocks
352 // )
354 // for constant PAGE_MY_MOODLE
355 include_once($CFG->dirroot.'/my/pagelib.php');
357 $coursecontext = get_context_instance(CONTEXT_COURSE, $COURSE->id);
358 $myownblogpage = (isset($page->filtertype) && isset($page->filterselect) && $page->type=='blog-view' && $page->filtertype=='user' && $page->filterselect == $USER->id);
360 $managecourseblocks = has_capability('moodle/site:manageblocks', $coursecontext);
361 $editmymoodle = $page->type == PAGE_MY_MOODLE && has_capability('moodle/my:manageblocks', $coursecontext);
363 if ($page->blocks_default_position() == $position &&
364 $page->user_is_editing() &&
365 ($managecourseblocks || $editmymoodle || $myownblogpage || defined('ADMIN_STICKYBLOCKS'))) {
367 print_side_block(NULL,NULL, NULL, NULL, NULL, array('id'=> BLOCK_POS_RIGHT.'inst0', 'class'=>'tempblockhandler'));
368 blocks_print_adminblock($page, $pageblocks);
369 } else if ($page->user_is_editing() &&
370 ($managecourseblocks || $editmymoodle || $myownblogpage || defined('ADMIN_STICKYBLOCKS'))) {
371 print_side_block(NULL,NULL, NULL, NULL, NULL, array('id'=> BLOCK_POS_LEFT.'inst0', 'class'=>'tempblockhandler'));
375 // This iterates over an array of blocks and calculates the preferred width
376 // Parameter passed by reference for speed; it's not modified.
377 function blocks_preferred_width(&$instances) {
378 $width = 0;
380 if(empty($instances) || !is_array($instances)) {
381 return 0;
384 $blocks = blocks_get_record();
386 foreach($instances as $instance) {
387 if(!$instance->visible) {
388 continue;
391 if (!array_key_exists($instance->blockid, $blocks)) {
392 // Block doesn't exist! We should delete this instance!
393 continue;
396 if(!$blocks[$instance->blockid]->visible) {
397 continue;
399 $pref = block_method_result($blocks[$instance->blockid]->name, 'preferred_width');
400 if($pref === NULL) {
401 continue;
403 if($pref > $width) {
404 $width = $pref;
407 return $width;
410 function blocks_get_record($blockid = NULL, $invalidate = false) {
411 static $cache = NULL;
413 if($invalidate || empty($cache)) {
414 $cache = get_records('block');
417 if($blockid === NULL) {
418 return $cache;
421 return (isset($cache[$blockid])? $cache[$blockid] : false);
424 function blocks_find_block($blockid, $blocksarray) {
425 if (empty($blocksarray)) {
426 return false;
428 foreach($blocksarray as $blockgroup) {
429 if (empty($blockgroup)) {
430 continue;
432 foreach($blockgroup as $instance) {
433 if($instance->blockid == $blockid) {
434 return $instance;
438 return false;
441 function blocks_find_instance($instanceid, $blocksarray) {
442 foreach($blocksarray as $subarray) {
443 foreach($subarray as $instance) {
444 if($instance->id == $instanceid) {
445 return $instance;
449 return false;
452 // Simple entry point for anyone that wants to use blocks
453 function blocks_setup(&$PAGE,$pinned=BLOCKS_PINNED_FALSE) {
454 switch ($pinned) {
455 case BLOCKS_PINNED_TRUE:
456 $pageblocks = blocks_get_pinned($PAGE);
457 break;
458 case BLOCKS_PINNED_BOTH:
459 $pageblocks = blocks_get_by_page_pinned($PAGE);
460 break;
461 case BLOCKS_PINNED_FALSE:
462 default:
463 $pageblocks = blocks_get_by_page($PAGE);
464 break;
466 blocks_execute_url_action($PAGE, $pageblocks,($pinned==BLOCKS_PINNED_TRUE));
467 return $pageblocks;
470 function blocks_execute_action($page, &$pageblocks, $blockaction, $instanceorid, $pinned=false, $redirect=true) {
471 global $CFG;
473 if (is_int($instanceorid)) {
474 $blockid = $instanceorid;
475 } else if (is_object($instanceorid)) {
476 $instance = $instanceorid;
479 switch($blockaction) {
480 case 'config':
481 global $USER;
482 $block = blocks_get_record($instance->blockid);
483 // Hacky hacky tricky stuff to get the original human readable block title,
484 // even if the block has configured its title to be something else.
485 // Create the object WITHOUT instance data.
486 $blockobject = block_instance($block->name);
487 if ($blockobject === false) {
488 break;
491 // First of all check to see if the block wants to be edited
492 if(!$blockobject->user_can_edit()) {
493 break;
496 // Now get the title and AFTER that load up the instance
497 $blocktitle = $blockobject->get_title();
498 $blockobject->_load_instance($instance);
500 optional_param('submitted', 0, PARAM_INT);
502 // Define the data we're going to silently include in the instance config form here,
503 // so we can strip them from the submitted data BEFORE serializing it.
504 $hiddendata = array(
505 'sesskey' => $USER->sesskey,
506 'instanceid' => $instance->id,
507 'blockaction' => 'config'
510 // To this data, add anything the page itself needs to display
511 $hiddendata = array_merge($hiddendata, $page->url_get_parameters());
513 if ($data = data_submitted()) {
514 $remove = array_keys($hiddendata);
515 foreach($remove as $item) {
516 unset($data->$item);
518 if(!$blockobject->instance_config_save($data,$pinned)) {
519 error('Error saving block configuration');
521 // And nothing more, continue with displaying the page
523 else {
524 // We need to show the config screen, so we highjack the display logic and then die
525 $strheading = get_string('blockconfiga', 'moodle', $blocktitle);
526 $page->print_header(get_string('pageheaderconfigablock', 'moodle'), array($strheading => ''));
528 echo '<div class="block-config" id="'.$block->name.'">'; /// Make CSS easier
530 print_heading($strheading);
531 echo '<form method="post" name="block-config" action="'. $page->url_get_path() .'">';
532 echo '<p>';
533 foreach($hiddendata as $name => $val) {
534 echo '<input type="hidden" name="'. $name .'" value="'. $val .'" />';
536 echo '</p>';
537 $blockobject->instance_config_print();
538 echo '</form>';
540 echo '</div>';
541 $CFG->pagepath = 'blocks/' . $block->name;
542 print_footer();
543 die(); // Do not go on with the other page-related stuff
545 break;
546 case 'toggle':
547 if(empty($instance)) {
548 error('Invalid block instance for '.$blockaction);
550 $instance->visible = ($instance->visible) ? 0 : 1;
551 if (!empty($pinned)) {
552 update_record('block_pinned', $instance);
553 } else {
554 update_record('block_instance', $instance);
556 break;
557 case 'delete':
558 if(empty($instance)) {
559 error('Invalid block instance for '. $blockaction);
561 blocks_delete_instance($instance, $pinned);
562 break;
563 case 'moveup':
564 if (empty($instance)) {
565 error('Invalid block instance for '. $blockaction);
568 if ($instance->weight == 0) {
569 // The block is the first one, so a move "up" probably means it changes position
570 // Where is the instance going to be moved?
571 $newpos = $page->blocks_move_position($instance, BLOCK_MOVE_UP);
572 $newweight = (empty($pageblocks[$newpos]) ? 0 : max(array_keys($pageblocks[$newpos])) + 1);
574 blocks_execute_repositioning($instance, $newpos, $newweight, $pinned);
575 } else {
576 // The block is just moving upwards in the same position.
577 // This configuration will make sure that even if somehow the weights
578 // become not continuous, block move operations will eventually bring
579 // the situation back to normal without printing any warnings.
580 if (!empty($pageblocks[$instance->position][$instance->weight - 1])) {
581 //define instance's position in the array
582 foreach ($pageblocks[$instance->position] as $instancekeysindex => $index ){
583 if ($pageblocks[$instance->position][$instancekeysindex]->id == $instance->id){
584 $instanceindex = $instancekeysindex;
587 $other = $pageblocks[$instance->position][$instanceindex - 1];
589 if (!empty($other)) {
590 ++$other->weight;
591 if (!empty($pinned)) {
592 update_record('block_pinned', $other);
593 } else {
594 update_record('block_instance', $other);
597 --$instance->weight;
598 if (!empty($pinned)) {
599 update_record('block_pinned', $instance);
600 } else {
601 update_record('block_instance', $instance);
604 break;
605 case 'movedown':
606 if (empty($instance)) {
607 error('Invalid block instance for '. $blockaction);
609 if ($instance->weight == max(array_keys($pageblocks[$instance->position]))) {
610 // The block is the last one, so a move "down" probably means it changes position
611 // Where is the instance going to be moved?
612 $newpos = $page->blocks_move_position($instance, BLOCK_MOVE_DOWN);
613 $newweight = (empty($pageblocks[$newpos]) ? 0 : max(array_keys($pageblocks[$newpos])) + 1);
615 blocks_execute_repositioning($instance, $newpos, $newweight, $pinned);
617 else {
618 // The block is just moving downwards in the same position.
619 // This configuration will make sure that even if somehow the weights
620 // become not continuous, block move operations will eventually bring
621 // the situation back to normal without printing any warnings.
622 if (!empty($pageblocks[$instance->position][$instance->weight + 1])) {
623 //define instance's position in the array
624 foreach ($pageblocks[$instance->position] as $instancekeysindex => $index ){
625 if ($pageblocks[$instance->position][$instancekeysindex]->id == $instance->id){
626 $instanceindex = $instancekeysindex;
629 $other = $pageblocks[$instance->position][$instanceindex + 1];
631 if (!empty($other)) {
632 --$other->weight;
633 if (!empty($pinned)) {
634 update_record('block_pinned', $other);
635 } else {
636 update_record('block_instance', $other);
639 ++$instance->weight;
640 if (!empty($pinned)) {
641 update_record('block_pinned', $instance);
642 } else {
643 update_record('block_instance', $instance);
646 break;
647 case 'moveleft':
648 if(empty($instance)) {
649 error('Invalid block instance for '. $blockaction);
651 // Where is the instance going to be moved?
652 $newpos = $page->blocks_move_position($instance, BLOCK_MOVE_LEFT);
653 $newweight = 0;
655 if (!empty($pinned) && !empty($pageblocks[$newpos]) ){
656 $newweight = $pageblocks[$newpos][max(array_keys($pageblocks[$newpos])) ]->weight + 1;
657 } else if(!empty($pageblocks[$newpos]) && (!array_key_exists('pinned', $pageblocks[$newpos][max(array_keys($pageblocks[$newpos]))])) ){
658 $newweight = $pageblocks[$newpos][max(array_keys($pageblocks[$newpos])) ]->weight + 1;
660 blocks_execute_repositioning($instance, $newpos, $newweight, $pinned);
661 break;
662 case 'moveright':
663 if(empty($instance)) {
664 error('Invalid block instance for '. $blockaction);
667 // Where is the instance going to be moved?
668 $newpos = $page->blocks_move_position($instance, BLOCK_MOVE_RIGHT);
669 $newweight = 0;
671 if (!empty($pinned) && !empty($pageblocks[$newpos]) ){
672 $newweight = $pageblocks[$newpos][max(array_keys($pageblocks[$newpos])) ]->weight + 1;
673 }else if(!empty($pageblocks[$newpos]) && (!array_key_exists('pinned', $pageblocks[$newpos][max(array_keys($pageblocks[$newpos]))])) ){
674 $newweight = $pageblocks[$newpos][max(array_keys($pageblocks[$newpos])) ]->weight + 1;
676 blocks_execute_repositioning($instance, $newpos, $newweight, $pinned);
677 break;
678 case 'add':
679 // Add a new instance of this block, if allowed
680 $block = blocks_get_record($blockid);
682 if(empty($block) || !$block->visible) {
683 // Only allow adding if the block exists and is enabled
684 break;
687 if(!$block->multiple && blocks_find_block($blockid, $pageblocks) !== false) {
688 // If no multiples are allowed and we already have one, return now
689 break;
692 if(!block_method_result($block->name, 'user_can_addto', $page)) {
693 // If the block doesn't want to be added...
694 break;
697 $newpos = $page->blocks_default_position();
698 if (!empty($pinned)) {
699 $sql = 'SELECT 1, max(weight) + 1 AS nextfree FROM '. $CFG->prefix .'block_pinned WHERE '
700 .' pagetype = \''. $page->get_type() .'\' AND position = \''. $newpos .'\'';
701 } else {
702 $sql = 'SELECT 1, max(weight) + 1 AS nextfree FROM '. $CFG->prefix .'block_instance WHERE pageid = '. $page->get_id()
703 .' AND pagetype = \''. $page->get_type() .'\' AND position = \''. $newpos .'\'';
705 $weight = get_record_sql($sql);
707 $newinstance = new stdClass;
708 $newinstance->blockid = $blockid;
709 if (empty($pinned)) {
710 $newinstance->pageid = $page->get_id();
712 $newinstance->pagetype = $page->get_type();
713 $newinstance->position = $newpos;
714 $newinstance->weight = empty($weight->nextfree) ? 0 : $weight->nextfree;
715 $newinstance->visible = 1;
716 $newinstance->configdata = '';
717 if (!empty($pinned)) {
718 $newinstance->id = insert_record('block_pinned', $newinstance);
719 } else {
720 $newinstance->id = insert_record('block_instance', $newinstance);
723 // If the new instance was created, allow it to do additional setup
724 if($newinstance && ($obj = block_instance($block->name, $newinstance))) {
725 // Return value ignored
726 $obj->instance_create();
729 break;
732 if ($redirect) {
733 // In order to prevent accidental duplicate actions, redirect to a page with a clean url
734 redirect($page->url_get_full());
738 // You can use this to get the blocks to respond to URL actions without much hassle
739 function blocks_execute_url_action(&$PAGE, &$pageblocks,$pinned=false) {
740 $blockaction = optional_param('blockaction', '', PARAM_ALPHA);
742 if (empty($blockaction) || !$PAGE->user_allowed_editing() || !confirm_sesskey()) {
743 return;
746 $instanceid = optional_param('instanceid', 0, PARAM_INT);
747 $blockid = optional_param('blockid', 0, PARAM_INT);
749 if (!empty($blockid)) {
750 blocks_execute_action($PAGE, $pageblocks, strtolower($blockaction), $blockid, $pinned);
753 else if (!empty($instanceid)) {
754 $instance = blocks_find_instance($instanceid, $pageblocks);
755 blocks_execute_action($PAGE, $pageblocks, strtolower($blockaction), $instance, $pinned);
759 // This shouldn't be used externally at all, it's here for use by blocks_execute_action()
760 // in order to reduce code repetition.
761 function blocks_execute_repositioning(&$instance, $newpos, $newweight, $pinned=false) {
762 global $CFG;
764 // If it's staying where it is, don't do anything, unless overridden
765 if ($newpos == $instance->position) {
766 return;
769 // Close the weight gap we 'll leave behind
770 if (!empty($pinned)) {
771 $sql = 'UPDATE '. $CFG->prefix .'block_pinned SET weight = weight - 1 '.
772 'WHERE pagetype = \''. $instance->pagetype.
773 '\' AND position = \'' .$instance->position.
774 '\' AND weight > '. $instance->weight;
775 } else {
776 $sql = 'UPDATE '. $CFG->prefix .'block_instance SET weight = weight - 1 '.
777 'WHERE pagetype = \''. $instance->pagetype.
778 '\' AND pageid = '. $instance->pageid .
779 ' AND position = \'' .$instance->position.
780 '\' AND weight > '. $instance->weight;
782 execute_sql($sql,false);
784 $instance->position = $newpos;
785 $instance->weight = $newweight;
787 if (!empty($pinned)) {
788 update_record('block_pinned', $instance);
789 } else {
790 update_record('block_instance', $instance);
796 * Moves a block to the new position (column) and weight (sort order).
797 * @param $instance - The block instance to be moved.
798 * @param $destpos - BLOCK_POS_LEFT or BLOCK_POS_RIGHT. The destination column.
799 * @param $destweight - The destination sort order. If NULL, we add to the end
800 * of the destination column.
801 * @param $pinned - Are we moving pinned blocks? We can only move pinned blocks
802 * to a new position withing the pinned list. Likewise, we
803 * can only moved non-pinned blocks to a new position within
804 * the non-pinned list.
805 * @return boolean (success or failure).
807 function blocks_move_block($page, &$instance, $destpos, $destweight=NULL, $pinned=false) {
808 global $CFG;
810 if ($pinned) {
811 $blocklist = blocks_get_pinned($page);
812 } else {
813 $blocklist = blocks_get_by_page($page);
816 if ($blocklist[$instance->position][$instance->weight]->id != $instance->id) {
817 // The source block instance is not where we think it is.
818 return false;
821 // First we close the gap that will be left behind when we take out the
822 // block from it's current column.
823 if ($pinned) {
824 $closegapsql = "UPDATE {$CFG->prefix}block_pinned
825 SET weight = weight - 1
826 WHERE weight > '$instance->weight'
827 AND position = '$instance->position'
828 AND pagetype = '$instance->pagetype'";
829 } else {
830 $closegapsql = "UPDATE {$CFG->prefix}block_instance
831 SET weight = weight - 1
832 WHERE weight > '$instance->weight'
833 AND position = '$instance->position'
834 AND pagetype = '$instance->pagetype'
835 AND pageid = '$instance->pageid'";
837 if (!execute_sql($closegapsql, false)) {
838 return false;
841 // Now let's make space for the block being moved.
842 if ($pinned) {
843 $opengapsql = "UPDATE {$CFG->prefix}block_pinned
844 SET weight = weight + 1
845 WHERE weight >= '$destweight'
846 AND position = '$destpos'
847 AND pagetype = '$instance->pagetype'";
848 } else {
849 $opengapsql = "UPDATE {$CFG->prefix}block_instance
850 SET weight = weight + 1
851 WHERE weight >= '$destweight'
852 AND position = '$destpos'
853 AND pagetype = '$instance->pagetype'
854 AND pageid = '$instance->pageid'";
856 if (!execute_sql($opengapsql, false)) {
857 return false;
860 // Move the block.
861 $instance->position = $destpos;
862 $instance->weight = $destweight;
864 if ($pinned) {
865 $table = 'block_pinned';
866 } else {
867 $table = 'block_instance';
869 return update_record($table, $instance);
874 * Returns an array consisting of 2 arrays:
875 * 1) Array of pinned blocks for position BLOCK_POS_LEFT
876 * 2) Array of pinned blocks for position BLOCK_POS_RIGHT
878 function blocks_get_pinned($page) {
880 $visible = true;
882 if (method_exists($page,'edit_always')) {
883 if ($page->edit_always()) {
884 $visible = false;
888 $blocks = get_records_select('block_pinned', 'pagetype = \''. $page->get_type() .
889 '\''.(($visible) ? 'AND visible = 1' : ''), 'position, weight');
891 $positions = $page->blocks_get_positions();
892 $arr = array();
894 foreach($positions as $key => $position) {
895 $arr[$position] = array();
898 if(empty($blocks)) {
899 return $arr;
902 foreach($blocks as $block) {
903 $block->pinned = true; // so we know we can't move it.
904 // make up an instanceid if we can..
905 $block->pageid = $page->get_id();
906 $arr[$block->position][$block->weight] = $block;
909 return $arr;
914 * Similar to blocks_get_by_page(), except that, the array returned includes
915 * pinned blocks as well. Pinned blocks are always appended before normal
916 * block instances.
918 function blocks_get_by_page_pinned($page) {
919 $pinned = blocks_get_pinned($page);
920 $user = blocks_get_by_page($page);
922 $weights = array();
924 foreach ($pinned as $pos => $arr) {
925 $weights[$pos] = count($arr);
928 foreach ($user as $pos => $blocks) {
929 if (!array_key_exists($pos,$pinned)) {
930 $pinned[$pos] = array();
932 if (!array_key_exists($pos,$weights)) {
933 $weights[$pos] = 0;
935 foreach ($blocks as $block) {
936 $pinned[$pos][$weights[$pos]] = $block;
937 $weights[$pos]++;
940 return $pinned;
945 * Returns an array of blocks for the page. Pinned blocks are excluded.
947 function blocks_get_by_page($page) {
948 $blocks = get_records_select('block_instance', "pageid = '". $page->get_id() .
949 "' AND pagetype = '". $page->get_type() ."'", 'position, weight');
951 $positions = $page->blocks_get_positions();
952 $arr = array();
953 foreach($positions as $key => $position) {
954 $arr[$position] = array();
957 if(empty($blocks)) {
958 return $arr;
961 foreach($blocks as $block) {
962 $arr[$block->position][$block->weight] = $block;
964 return $arr;
968 //This function prints the block to admin blocks as necessary
969 function blocks_print_adminblock(&$page, &$pageblocks) {
970 global $USER;
972 $missingblocks = blocks_get_missing($page, $pageblocks);
974 if (!empty($missingblocks)) {
975 $strblocks = '<div class="title"><h2>';
976 $strblocks .= get_string('blocks');
977 $strblocks .= '</h2></div>';
978 $stradd = get_string('add');
979 foreach ($missingblocks as $blockid) {
980 $block = blocks_get_record($blockid);
981 $blockobject = block_instance($block->name);
982 if ($blockobject === false) {
983 continue;
985 if(!$blockobject->user_can_addto($page)) {
986 continue;
988 $menu[$block->id] = $blockobject->get_title();
990 asort($menu);
992 $target = $page->url_get_full(array('sesskey' => $USER->sesskey, 'blockaction' => 'add'));
993 $content = popup_form($target.'&amp;blockid=', $menu, 'add_block', '', $stradd .'...', '', '', true);
994 print_side_block($strblocks, $content, NULL, NULL, NULL, array('class' => 'block_adminblock'));
999 * Delete all the blocks from a particular page.
1001 * @param string $pagetype the page type.
1002 * @param integer $pageid the page id.
1003 * @return success of failure.
1005 function blocks_delete_all_on_page($pagetype, $pageid) {
1006 if ($instances = get_records_select('block_instance', "pageid = $pageid AND pagetype = '$pagetype'")) {
1007 foreach ($instances as $instance) {
1008 delete_context(CONTEXT_BLOCK, $instance->id); // Ingore any failures here.
1011 return delete_records('block_instance', 'pageid', $pageid, 'pagetype', $pagetype);
1014 // Dispite what this function is called, it seems to be mostly used to populate
1015 // the default blocks when a new course (or whatever) is created.
1016 function blocks_repopulate_page($page) {
1017 global $CFG;
1019 $allblocks = blocks_get_record();
1021 if(empty($allblocks)) {
1022 error('Could not retrieve blocks from the database');
1025 // Assemble the information to correlate block names to ids
1026 $idforname = array();
1027 foreach($allblocks as $block) {
1028 $idforname[$block->name] = $block->id;
1031 /// If the site override has been defined, it is the only valid one.
1032 if (!empty($CFG->defaultblocks_override)) {
1033 $blocknames = $CFG->defaultblocks_override;
1035 else {
1036 $blocknames = $page->blocks_get_default();
1039 $positions = $page->blocks_get_positions();
1040 $posblocks = explode(':', $blocknames);
1042 // Now one array holds the names of the positions, and the other one holds the blocks
1043 // that are going to go in each position. Luckily for us, both arrays are numerically
1044 // indexed and the indexes match, so we can work straight away... but CAREFULLY!
1046 // Ready to start creating block instances, but first drop any existing ones
1047 blocks_delete_all_on_page($page->get_type(), $page->get_id());
1049 // Here we slyly count $posblocks and NOT $positions. This can actually make a difference
1050 // if the textual representation has undefined slots in the end. So we only work with as many
1051 // positions were retrieved, not with all the page says it has available.
1052 $numpositions = count($posblocks);
1053 for($i = 0; $i < $numpositions; ++$i) {
1054 $position = $positions[$i];
1055 $blocknames = explode(',', $posblocks[$i]);
1056 $weight = 0;
1057 foreach($blocknames as $blockname) {
1058 $newinstance = new stdClass;
1059 $newinstance->blockid = $idforname[$blockname];
1060 $newinstance->pageid = $page->get_id();
1061 $newinstance->pagetype = $page->get_type();
1062 $newinstance->position = $position;
1063 $newinstance->weight = $weight;
1064 $newinstance->visible = 1;
1065 $newinstance->configdata = '';
1067 if(!empty($newinstance->blockid)) {
1068 // Only add block if it was recognized
1069 insert_record('block_instance', $newinstance);
1070 ++$weight;
1075 return true;
1078 function upgrade_blocks_db($continueto) {
1079 /// This function upgrades the blocks tables, if necessary
1080 /// It's called from admin/index.php
1082 global $CFG, $db;
1084 require_once ($CFG->dirroot .'/blocks/version.php'); // Get code versions
1086 if (empty($CFG->blocks_version)) { // Blocks have never been installed.
1087 $strdatabaseupgrades = get_string('databaseupgrades');
1088 print_header($strdatabaseupgrades, $strdatabaseupgrades,
1089 build_navigation(array(array('name' => $strdatabaseupgrades, 'link' => null, 'type' => 'misc'))), '',
1090 upgrade_get_javascript(), false, '&nbsp;', '&nbsp;');
1092 upgrade_log_start();
1093 print_heading('blocks');
1094 $db->debug=true;
1096 /// Both old .sql files and new install.xml are supported
1097 /// but we priorize install.xml (XMLDB) if present
1098 $status = false;
1099 if (file_exists($CFG->dirroot . '/blocks/db/install.xml')) {
1100 $status = install_from_xmldb_file($CFG->dirroot . '/blocks/db/install.xml'); //New method
1101 } else if (file_exists($CFG->dirroot . '/blocks/db/' . $CFG->dbtype . '.sql')) {
1102 $status = modify_database($CFG->dirroot . '/blocks/db/' . $CFG->dbtype . '.sql'); //Old method
1105 $db->debug = false;
1106 if ($status) {
1107 if (set_config('blocks_version', $blocks_version)) {
1108 notify(get_string('databasesuccess'), 'notifysuccess');
1109 notify(get_string('databaseupgradeblocks', '', $blocks_version), 'notifysuccess');
1110 print_continue($continueto);
1111 print_footer('none');
1112 exit;
1113 } else {
1114 error('Upgrade of blocks system failed! (Could not update version in config table)');
1116 } else {
1117 error('Blocks tables could NOT be set up successfully!');
1121 /// Upgrading code starts here
1122 $oldupgrade = false;
1123 $newupgrade = false;
1124 if (is_readable($CFG->dirroot . '/blocks/db/' . $CFG->dbtype . '.php')) {
1125 include_once($CFG->dirroot . '/blocks/db/' . $CFG->dbtype . '.php'); // defines old upgrading function
1126 $oldupgrade = true;
1128 if (is_readable($CFG->dirroot . '/blocks/db/upgrade.php')) {
1129 include_once($CFG->dirroot . '/blocks/db/upgrade.php'); // defines new upgrading function
1130 $newupgrade = true;
1133 if ($blocks_version > $CFG->blocks_version) { // Upgrade tables
1134 $strdatabaseupgrades = get_string('databaseupgrades');
1135 print_header($strdatabaseupgrades, $strdatabaseupgrades,
1136 build_navigation(array(array('name' => $strdatabaseupgrades, 'link' => null, 'type' => 'misc'))), '', upgrade_get_javascript());
1138 upgrade_log_start();
1139 print_heading('blocks');
1141 /// Run de old and new upgrade functions for the module
1142 $oldupgrade_function = 'blocks_upgrade';
1143 $newupgrade_function = 'xmldb_blocks_upgrade';
1145 /// First, the old function if exists
1146 $oldupgrade_status = true;
1147 if ($oldupgrade && function_exists($oldupgrade_function)) {
1148 $db->debug = true;
1149 $oldupgrade_status = $oldupgrade_function($CFG->blocks_version);
1150 } else if ($oldupgrade) {
1151 notify ('Upgrade function ' . $oldupgrade_function . ' was not available in ' .
1152 '/blocks/db/' . $CFG->dbtype . '.php');
1155 /// Then, the new function if exists and the old one was ok
1156 $newupgrade_status = true;
1157 if ($newupgrade && function_exists($newupgrade_function) && $oldupgrade_status) {
1158 $db->debug = true;
1159 $newupgrade_status = $newupgrade_function($CFG->blocks_version);
1160 } else if ($newupgrade) {
1161 notify ('Upgrade function ' . $newupgrade_function . ' was not available in ' .
1162 '/blocks/db/upgrade.php');
1165 $db->debug=false;
1166 /// Now analyze upgrade results
1167 if ($oldupgrade_status && $newupgrade_status) { // No upgrading failed
1168 if (set_config('blocks_version', $blocks_version)) {
1169 notify(get_string('databasesuccess'), 'notifysuccess');
1170 notify(get_string('databaseupgradeblocks', '', $blocks_version), 'notifysuccess');
1171 print_continue($continueto);
1172 print_footer('none');
1173 exit;
1174 } else {
1175 error('Upgrade of blocks system failed! (Could not update version in config table)');
1177 } else {
1178 error('Upgrade failed! See blocks/version.php');
1181 } else if ($blocks_version < $CFG->blocks_version) {
1182 upgrade_log_start();
1183 notify('WARNING!!! The Blocks version you are using is OLDER than the version that made these databases!');
1185 upgrade_log_finish();
1188 //This function finds all available blocks and install them
1189 //into blocks table or do all the upgrade process if newer
1190 function upgrade_blocks_plugins($continueto) {
1192 global $CFG, $db;
1194 $blocktitles = array();
1195 $invalidblocks = array();
1196 $validblocks = array();
1197 $notices = array();
1199 //Count the number of blocks in db
1200 $blockcount = count_records('block');
1201 //If there isn't records. This is the first install, so I remember it
1202 if ($blockcount == 0) {
1203 $first_install = true;
1204 } else {
1205 $first_install = false;
1208 $site = get_site();
1210 if (!$blocks = get_list_of_plugins('blocks', 'db') ) {
1211 error('No blocks installed!');
1214 include_once($CFG->dirroot .'/blocks/moodleblock.class.php');
1215 if(!class_exists('block_base')) {
1216 error('Class block_base is not defined or file not found for /blocks/moodleblock.class.php');
1219 foreach ($blocks as $blockname) {
1221 if ($blockname == 'NEWBLOCK') { // Someone has unzipped the template, ignore it
1222 continue;
1225 if(!block_is_compatible($blockname)) {
1226 // This is an old-style block
1227 //$notices[] = 'Block '. $blockname .' is not compatible with the current version of Mooodle and needs to be updated by a programmer.';
1228 $invalidblocks[] = $blockname;
1229 continue;
1232 $fullblock = $CFG->dirroot .'/blocks/'. $blockname;
1234 if ( is_readable($fullblock.'/block_'.$blockname.'.php')) {
1235 include_once($fullblock.'/block_'.$blockname.'.php');
1236 } else {
1237 $notices[] = 'Block '. $blockname .': '. $fullblock .'/block_'. $blockname .'.php was not readable';
1238 continue;
1241 $oldupgrade = false;
1242 $newupgrade = false;
1243 if ( @is_dir($fullblock .'/db/')) {
1244 if ( @is_readable($fullblock .'/db/'. $CFG->dbtype .'.php')) {
1245 include_once($fullblock .'/db/'. $CFG->dbtype .'.php'); // defines old upgrading function
1246 $oldupgrade = true;
1248 if ( @is_readable($fullblock .'/db/upgrade.php')) {
1249 include_once($fullblock .'/db/upgrade.php'); // defines new upgrading function
1250 $newupgrade = true;
1254 $classname = 'block_'.$blockname;
1255 if(!class_exists($classname)) {
1256 $notices[] = 'Block '. $blockname .': '. $classname .' not implemented';
1257 continue;
1260 // Here is the place to see if the block implements a constructor (old style),
1261 // an init() function (new style) or nothing at all (error time).
1263 $constructor = get_class_constructor($classname);
1264 if(empty($constructor)) {
1265 // No constructor
1266 $notices[] = 'Block '. $blockname .': class does not have a constructor';
1267 $invalidblocks[] = $blockname;
1268 continue;
1271 $block = new stdClass; // This may be used to update the db below
1272 $blockobj = new $classname; // This is what we 'll be testing
1274 // Inherits from block_base?
1275 if(!is_subclass_of($blockobj, 'block_base')) {
1276 $notices[] = 'Block '. $blockname .': class does not inherit from block_base';
1277 continue;
1280 // OK, it's as we all hoped. For further tests, the object will do them itself.
1281 if(!$blockobj->_self_test()) {
1282 $notices[] = 'Block '. $blockname .': self test failed';
1283 continue;
1285 $block->version = $blockobj->get_version();
1287 if (!isset($block->version)) {
1288 $notices[] = 'Block '. $blockname .': has no version support. It must be updated by a programmer.';
1289 continue;
1292 $block->name = $blockname; // The name MUST match the directory
1293 $blocktitle = $blockobj->get_title();
1295 if ($currblock = get_record('block', 'name', $block->name)) {
1296 if ($currblock->version == $block->version) {
1297 // do nothing
1298 } else if ($currblock->version < $block->version) {
1299 if (empty($updated_blocks)) {
1300 $strblocksetup = get_string('blocksetup');
1301 print_header($strblocksetup, $strblocksetup,
1302 build_navigation(array(array('name' => $strblocksetup, 'link' => null, 'type' => 'misc'))), '',
1303 upgrade_get_javascript(), false, '&nbsp;', '&nbsp;');
1305 $updated_blocks = true;
1306 upgrade_log_start();
1307 print_heading('New version of '.$blocktitle.' ('.$block->name.') exists');
1308 @set_time_limit(0); // To allow slow databases to complete the long SQL
1310 /// Run de old and new upgrade functions for the module
1311 $oldupgrade_function = $block->name .'_upgrade';
1312 $newupgrade_function = 'xmldb_block_' . $block->name .'_upgrade';
1314 /// First, the old function if exists
1315 $oldupgrade_status = true;
1316 if ($oldupgrade && function_exists($oldupgrade_function)) {
1317 $db->debug = true;
1318 $oldupgrade_status = $oldupgrade_function($currblock->version, $block);
1319 } else if ($oldupgrade) {
1320 notify ('Upgrade function ' . $oldupgrade_function . ' was not available in ' .
1321 $fullblock . '/db/' . $CFG->dbtype . '.php');
1324 /// Then, the new function if exists and the old one was ok
1325 $newupgrade_status = true;
1326 if ($newupgrade && function_exists($newupgrade_function) && $oldupgrade_status) {
1327 $db->debug = true;
1328 $newupgrade_status = $newupgrade_function($currblock->version, $block);
1329 } else if ($newupgrade) {
1330 notify ('Upgrade function ' . $newupgrade_function . ' was not available in ' .
1331 $fullblock . '/db/upgrade.php');
1334 $db->debug=false;
1335 /// Now analyze upgrade results
1336 if ($oldupgrade_status && $newupgrade_status) { // No upgrading failed
1338 // Set the block cron on upgrade
1339 $block->cron = !empty($blockobj->cron) ? $blockobj->cron : 0;
1341 // OK so far, now update the block record
1342 $block->id = $currblock->id;
1343 if (! update_record('block', $block)) {
1344 error('Could not update block '. $block->name .' record in block table!');
1346 $component = 'block/'.$block->name;
1347 if (!update_capabilities($component)) {
1348 error('Could not update '.$block->name.' capabilities!');
1351 events_update_definition($component);
1352 notify(get_string('blocksuccess', '', $blocktitle), 'notifysuccess');
1353 } else {
1354 notify('Upgrading block '. $block->name .' from '. $currblock->version .' to '. $block->version .' FAILED!');
1356 echo '<hr />';
1357 } else {
1358 upgrade_log_start();
1359 error('Version mismatch: block '. $block->name .' can\'t downgrade '. $currblock->version .' -> '. $block->version .'!');
1362 } else { // block not installed yet, so install it
1364 // If it allows multiples, start with it enabled
1365 if ($blockobj->instance_allow_multiple()) {
1366 $block->multiple = 1;
1369 // Set the block cron on install
1370 $block->cron = !empty($blockobj->cron) ? $blockobj->cron : 0;
1372 // [pj] Normally this would be inline in the if, but we need to
1373 // check for NULL (necessary for 4.0.5 <= PHP < 4.2.0)
1374 $conflictblock = array_search($blocktitle, $blocktitles);
1375 if($conflictblock !== false && $conflictblock !== NULL) {
1376 // Duplicate block titles are not allowed, they confuse people
1377 // AND PHP's associative arrays ;)
1378 error('<strong>Naming conflict</strong>: block <strong>'.$block->name.'</strong> has the same title with an existing block, <strong>'.$conflictblock.'</strong>!');
1380 if (empty($updated_blocks)) {
1381 $strblocksetup = get_string('blocksetup');
1382 print_header($strblocksetup, $strblocksetup,
1383 build_navigation(array(array('name' => $strblocksetup, 'link' => null, 'type' => 'misc'))), '',
1384 upgrade_get_javascript(), false, '&nbsp;', '&nbsp;');
1386 $updated_blocks = true;
1387 upgrade_log_start();
1388 print_heading($block->name);
1389 $db->debug = true;
1390 @set_time_limit(0); // To allow slow databases to complete the long SQL
1392 /// Both old .sql files and new install.xml are supported
1393 /// but we priorize install.xml (XMLDB) if present
1394 $status = false;
1395 if (file_exists($fullblock . '/db/install.xml')) {
1396 $status = install_from_xmldb_file($fullblock . '/db/install.xml'); //New method
1397 } else if (file_exists($fullblock .'/db/'. $CFG->dbtype .'.sql')) {
1398 $status = modify_database($fullblock .'/db/'. $CFG->dbtype .'.sql'); //Old method
1399 } else {
1400 $status = true;
1403 $db->debug = false;
1404 if ($status) {
1405 if ($block->id = insert_record('block', $block)) {
1406 $blockobj->after_install();
1407 $component = 'block/'.$block->name;
1408 if (!update_capabilities($component)) {
1409 notify('Could not set up '.$block->name.' capabilities!');
1412 events_update_definition($component);
1413 notify(get_string('blocksuccess', '', $blocktitle), 'notifysuccess');
1414 echo '<hr />';
1415 } else {
1416 error($block->name .' block could not be added to the block list!');
1418 } else {
1419 error('Block '. $block->name .' tables could NOT be set up successfully!');
1423 $blocktitles[$block->name] = $blocktitle;
1426 if(!empty($notices)) {
1427 upgrade_log_start();
1428 foreach($notices as $notice) {
1429 notify($notice);
1433 // Finally, if we are in the first_install of BLOCKS (this means that we are
1434 // upgrading from Moodle < 1.3), put blocks in all existing courses.
1435 if ($first_install) {
1436 upgrade_log_start();
1437 //Iterate over each course
1438 if ($courses = get_records('course')) {
1439 foreach ($courses as $course) {
1440 $page = page_create_object(PAGE_COURSE_VIEW, $course->id);
1441 blocks_repopulate_page($page);
1446 if (!empty($CFG->siteblocksadded)) { /// This is a once-off hack to make a proper upgrade
1447 upgrade_log_start();
1448 $page = page_create_object(PAGE_COURSE_VIEW, SITEID);
1449 blocks_repopulate_page($page);
1450 delete_records('config', 'name', 'siteblocksadded');
1453 upgrade_log_finish();
1455 if (!empty($updated_blocks)) {
1456 print_continue($continueto);
1457 print_footer('none');
1458 die;