file popup.html was added on branch MOODLE_15_STABLE on 2005-07-07 16:14:38 +0000
[moodle.git] / lib / blocklib.php
blob0f50035e0ce1d7ac7db95cc4539b72ba3d76daa2
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 require_once($CFG->libdir.'/pagelib.php');
17 // Returns false if this block is incompatible with the current version of Moodle.
18 function block_is_compatible($blockname) {
19 global $CFG;
21 $file = file($CFG->dirroot.'/blocks/'.$blockname.'/block_'.$blockname.'.php');
22 if(empty($file)) {
23 return NULL;
26 foreach($file as $line) {
27 // If you find MoodleBlock (appearing in the class declaration) it's not compatible
28 if(strpos($line, 'MoodleBlock')) {
29 return false;
31 // But if we find a { it means the class declaration is over, so it's compatible
32 else if(strpos($line, '{')) {
33 return true;
37 return NULL;
40 // Returns the case-sensitive name of the class' constructor function. This includes both
41 // PHP5- and PHP4-style constructors. If no appropriate constructor can be found, returns NULL.
42 // If there is no such class, returns boolean false.
43 function get_class_constructor($classname) {
44 // Caching
45 static $constructors = array();
47 if(!class_exists($classname)) {
48 return false;
51 // Tests indicate this doesn't hurt even in PHP5.
52 $classname = strtolower($classname);
54 // Return cached value, if exists
55 if(isset($constructors[$classname])) {
56 return $constructors[$classname];
59 // Get a list of methods. After examining several different ways of
60 // doing the check, (is_callable, method_exists, function_exists etc)
61 // it seems that this is the most reliable one.
62 $methods = get_class_methods($classname);
64 // PHP5 constructor?
65 if(phpversion() >= '5') {
66 if(in_array('__construct', $methods)) {
67 return $constructors[$classname] = '__construct';
71 // If we have PHP5 but no magic constructor, we have to lowercase the methods
72 $methods = array_map('strtolower', $methods);
74 if(in_array($classname, $methods)) {
75 return $constructors[$classname] = $classname;
78 return $constructors[$classname] = NULL;
81 //This function retrieves a method-defined property of a class WITHOUT instantiating an object
82 //It seems that the only way to use the :: operator with variable class names is eval() :(
83 //For caveats with this technique, see the PHP docs on operator ::
84 function block_method_result($blockname, $method) {
85 if(!block_load_class($blockname)) {
86 return NULL;
88 return eval('return block_'.$blockname.'::'.$method.'();');
91 //This function creates a new object of the specified block class
92 function block_instance($blockname, $instance = NULL) {
93 if(!block_load_class($blockname)) {
94 return false;
96 $classname = 'block_'.$blockname;
97 $retval = new $classname;
98 if($instance !== NULL) {
99 $retval->_load_instance($instance);
101 return $retval;
104 //This function loads the necessary class files for a block
105 //Whenever you want to load a block, use this first
106 function block_load_class($blockname) {
107 global $CFG;
109 if (empty($blockname)) {
110 return false;
113 require_once($CFG->dirroot.'/blocks/moodleblock.class.php');
114 $classname = 'block_'.$blockname;
115 include_once($CFG->dirroot.'/blocks/'.$blockname.'/block_'.$blockname.'.php');
117 // After all this, return value indicating success or failure
118 return class_exists($classname);
121 // This function returns an array with the IDs of any blocks that you can add to your page.
122 // Parameters are passed by reference for speed; they are not modified at all.
123 function blocks_get_missing(&$page, &$pageblocks) {
125 $missingblocks = array();
126 $allblocks = blocks_get_record();
127 $pageformat = $page->get_format_name();
129 if(!empty($allblocks)) {
130 foreach($allblocks as $block) {
131 if($block->visible && (!blocks_find_block($block->id, $pageblocks) || $block->multiple)) {
132 // And if it's applicable for display in this format...
133 if(blocks_name_allowed_in_format($block->name, $pageformat)) {
134 // ...add it to the missing blocks
135 $missingblocks[] = $block->id;
140 return $missingblocks;
143 function blocks_remove_inappropriate($page) {
144 $pageblocks = blocks_get_by_page($page);
146 if(empty($pageblocks)) {
147 return;
150 if(($pageformat = $page->get_format_name()) == NULL) {
151 return;
154 foreach($pageblocks as $position) {
155 foreach($position as $instance) {
156 $block = blocks_get_record($instance->blockid);
157 if(!blocks_name_allowed_in_format($block->name, $pageformat)) {
158 blocks_delete_instance($instance);
164 function blocks_name_allowed_in_format($name, $pageformat) {
165 $formats = block_method_result($name, 'applicable_formats');
166 $accept = NULL;
167 $depth = -1;
168 foreach($formats as $format => $allowed) {
169 $thisformat = '^'.str_replace('*', '[^-]*', $format).'.*$';
170 if(ereg($thisformat, $pageformat)) {
171 if(($scount = substr_count($format, '-')) > $depth) {
172 $depth = $scount;
173 $accept = $allowed;
177 if($accept === NULL) {
178 $accept = !empty($formats['all']);
180 return $accept;
183 function blocks_delete_instance($instance) {
184 global $CFG;
186 // Get the block object and call instance_delete() first
187 if(!$record = blocks_get_record($instance->blockid)) {
188 return false;
190 if(!$obj = block_instance($record->name, $instance)) {
191 return false;
194 // Return value ignored
195 $obj->instance_delete();
197 // Now kill the db record;
198 delete_records('block_instance', 'id', $instance->id);
199 // And now, decrement the weight of all blocks after this one
200 execute_sql('UPDATE '.$CFG->prefix.'block_instance SET weight = weight - 1 WHERE pagetype = \''.$instance->pagetype.
201 '\' AND pageid = '.$instance->pageid.' AND position = \''.$instance->position.
202 '\' AND weight > '.$instance->weight, false);
203 return true;
206 // Accepts an array of block instances and checks to see if any of them have content to display
207 // (causing them to calculate their content in the process). Returns true or false. Parameter passed
208 // by reference for speed; the array is actually not modified.
209 function blocks_have_content(&$pageblocks, $position) {
210 foreach($pageblocks[$position] as $instance) {
211 if(!$instance->visible) {
212 continue;
214 if(!$record = blocks_get_record($instance->blockid)) {
215 continue;
217 if(!$obj = block_instance($record->name, $instance)) {
218 continue;
220 if(!$obj->is_empty()) {
221 return true;
225 return false;
228 // This function prints one group of blocks in a page
229 // Parameters passed by reference for speed; they are not modified.
230 function blocks_print_group(&$page, &$pageblocks, $position) {
232 if(empty($pageblocks[$position])) {
233 $pageblocks[$position] = array();
234 $maxweight = 0;
236 else {
237 $maxweight = max(array_keys($pageblocks[$position]));
240 $isediting = $page->user_is_editing();
242 foreach($pageblocks[$position] as $instance) {
243 $block = blocks_get_record($instance->blockid);
244 if(!$block->visible) {
245 // Disabled by the admin
246 continue;
249 if (!$obj = block_instance($block->name, $instance)) {
250 // Invalid block
251 continue;
254 if ($isediting) {
255 $options = 0;
256 // 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:
257 // the first block might still be able to move up if the page says so (i.e., it will change position)
258 $options |= BLOCK_MOVE_UP * ($instance->weight != 0 || ($page->blocks_move_position($instance, BLOCK_MOVE_UP) != $instance->position));
259 // Same thing for downward movement
260 $options |= BLOCK_MOVE_DOWN * ($instance->weight != $maxweight || ($page->blocks_move_position($instance, BLOCK_MOVE_DOWN) != $instance->position));
261 // For left and right movements, it's up to the page to tell us whether they are allowed
262 $options |= BLOCK_MOVE_RIGHT * ($page->blocks_move_position($instance, BLOCK_MOVE_RIGHT) != $instance->position);
263 $options |= BLOCK_MOVE_LEFT * ($page->blocks_move_position($instance, BLOCK_MOVE_LEFT ) != $instance->position);
264 // Finally, the block can be configured if the block class either allows multiple instances, or if it specifically
265 // allows instance configuration (multiple instances override that one). It doesn't have anything to do with what the
266 // administrator has allowed for this block in the site admin options.
267 $options |= BLOCK_CONFIGURE * ( $obj->instance_allow_multiple() || $obj->instance_allow_config() );
268 $obj->_add_edit_controls($options);
271 if(!$instance->visible) {
272 if($isediting) {
273 $obj->_print_shadow();
276 else {
277 $obj->_print_block();
281 if($page->blocks_default_position() == $position && $page->user_is_editing()) {
282 blocks_print_adminblock($page, $pageblocks);
287 // This iterates over an array of blocks and calculates the preferred width
288 // Parameter passed by reference for speed; it's not modified.
289 function blocks_preferred_width(&$instances) {
290 $width = 0;
292 if(empty($instances) || !is_array($instances)) {
293 return 0;
296 $blocks = blocks_get_record();
298 foreach($instances as $instance) {
299 if(!$instance->visible) {
300 continue;
303 if(!$blocks[$instance->blockid]->visible) {
304 continue;
306 $pref = block_method_result($blocks[$instance->blockid]->name, 'preferred_width');
307 if($pref === NULL) {
308 continue;
310 if($pref > $width) {
311 $width = $pref;
314 return $width;
317 function blocks_get_record($blockid = NULL, $invalidate = false) {
318 static $cache = NULL;
320 if($invalidate || empty($cache)) {
321 $cache = get_records('block');
324 if($blockid === NULL) {
325 return $cache;
328 return (isset($cache[$blockid])? $cache[$blockid] : false);
331 function blocks_find_block($blockid, $blocksarray) {
332 foreach($blocksarray as $blockgroup) {
333 foreach($blockgroup as $instance) {
334 if($instance->blockid == $blockid) {
335 return $instance;
339 return false;
342 function blocks_find_instance($instanceid, $blocksarray) {
343 foreach($blocksarray as $subarray) {
344 foreach($subarray as $instance) {
345 if($instance->id == $instanceid) {
346 return $instance;
350 return false;
353 // Simple entry point for anyone that wants to use blocks
354 function blocks_setup(&$PAGE) {
355 $pageblocks = blocks_get_by_page($PAGE);
356 blocks_execute_url_action($PAGE, $pageblocks);
357 return $pageblocks;
360 function blocks_execute_action($page, &$pageblocks, $blockaction, $instanceorid) {
361 global $CFG;
363 if (is_int($instanceorid)) {
364 $blockid = $instanceorid;
365 } else if (is_object($instanceorid)) {
366 $instance = $instanceorid;
369 switch($blockaction) {
370 case 'config':
371 global $USER;
372 $block = blocks_get_record($instance->blockid);
373 // Hacky hacky tricky stuff to get the original human readable block title,
374 // even if the block has configured its title to be something else.
375 // Create the object WITHOUT instance data.
376 $blockobject = block_instance($block->name);
377 if ($blockobject === false) {
378 continue;
380 // Now get the title and AFTER that load up the instance
381 $blocktitle = $blockobject->get_title();
382 $blockobject->_load_instance($instance);
384 optional_param('submitted', 0, PARAM_INT);
386 // Define the data we're going to silently include in the instance config form here,
387 // so we can strip them from the submitted data BEFORE serializing it.
388 $hiddendata = array(
389 'sesskey' => $USER->sesskey,
390 'instanceid' => $instance->id,
391 'blockaction' => 'config'
394 // To this data, add anything the page itself needs to display
395 $hiddendata = array_merge($hiddendata, $page->url_get_parameters());
397 if($data = data_submitted()) {
398 $remove = array_keys($hiddendata);
399 foreach($remove as $item) {
400 unset($data->$item);
402 if(!$blockobject->instance_config_save($data)) {
403 error('Error saving block configuration');
405 // And nothing more, continue with displaying the page
407 else {
408 // We need to show the config screen, so we highjack the display logic and then die
409 $strheading = get_string('blockconfiga', 'moodle', $blocktitle);
410 $page->print_header(get_string('pageheaderconfigablock', 'moodle'), array($strheading => ''));
411 print_heading($strheading);
412 echo '<form method="post" action="'. $page->url_get_path() .'">';
413 echo '<p>';
414 foreach($hiddendata as $name => $val) {
415 echo '<input type="hidden" name="'. $name .'" value="'. $val .'" />';
417 echo '</p>';
418 $blockobject->instance_config_print();
419 echo '</form>';
420 print_footer();
421 die(); // Do not go on with the other page-related stuff
423 break;
424 case 'toggle':
425 if(empty($instance)) {
426 error('Invalid block instance for '.$blockaction);
428 $instance->visible = ($instance->visible) ? 0 : 1;
429 update_record('block_instance', $instance);
430 break;
431 case 'delete':
432 if(empty($instance)) {
433 error('Invalid block instance for '. $blockaction);
435 blocks_delete_instance($instance);
436 break;
437 case 'moveup':
438 if(empty($instance)) {
439 error('Invalid block instance for '. $blockaction);
442 if($instance->weight == 0) {
443 // The block is the first one, so a move "up" probably means it changes position
444 // Where is the instance going to be moved?
445 $newpos = $page->blocks_move_position($instance, BLOCK_MOVE_UP);
446 $newweight = (empty($pageblocks[$newpos]) ? 0 : max(array_keys($pageblocks[$newpos])) + 1);
448 blocks_execute_repositioning($instance, $newpos, $newweight);
450 else {
451 // The block is just moving upwards in the same position.
452 // This configuration will make sure that even if somehow the weights
453 // become not continuous, block move operations will eventually bring
454 // the situation back to normal without printing any warnings.
455 if(!empty($pageblocks[$instance->position][$instance->weight - 1])) {
456 $other = $pageblocks[$instance->position][$instance->weight - 1];
458 if(!empty($other)) {
459 ++$other->weight;
460 update_record('block_instance', $other);
462 --$instance->weight;
463 update_record('block_instance', $instance);
465 break;
466 case 'movedown':
467 if(empty($instance)) {
468 error('Invalid block instance for '. $blockaction);
471 if($instance->weight == max(array_keys($pageblocks[$instance->position]))) {
472 // The block is the last one, so a move "down" probably means it changes position
473 // Where is the instance going to be moved?
474 $newpos = $page->blocks_move_position($instance, BLOCK_MOVE_DOWN);
475 $newweight = (empty($pageblocks[$newpos]) ? 0 : max(array_keys($pageblocks[$newpos])) + 1);
477 blocks_execute_repositioning($instance, $newpos, $newweight);
479 else {
480 // The block is just moving downwards in the same position.
481 // This configuration will make sure that even if somehow the weights
482 // become not continuous, block move operations will eventually bring
483 // the situation back to normal without printing any warnings.
484 if(!empty($pageblocks[$instance->position][$instance->weight + 1])) {
485 $other = $pageblocks[$instance->position][$instance->weight + 1];
487 if(!empty($other)) {
488 --$other->weight;
489 update_record('block_instance', $other);
491 ++$instance->weight;
492 update_record('block_instance', $instance);
494 break;
495 case 'moveleft':
496 if(empty($instance)) {
497 error('Invalid block instance for '. $blockaction);
500 // Where is the instance going to be moved?
501 $newpos = $page->blocks_move_position($instance, BLOCK_MOVE_LEFT);
502 $newweight = (empty($pageblocks[$newpos]) ? 0 : max(array_keys($pageblocks[$newpos])) + 1);
504 blocks_execute_repositioning($instance, $newpos, $newweight);
505 break;
506 case 'moveright':
507 if(empty($instance)) {
508 error('Invalid block instance for '. $blockaction);
511 // Where is the instance going to be moved?
512 $newpos = $page->blocks_move_position($instance, BLOCK_MOVE_RIGHT);
513 $newweight = (empty($pageblocks[$newpos]) ? 0 : max(array_keys($pageblocks[$newpos])) + 1);
515 blocks_execute_repositioning($instance, $newpos, $newweight);
516 break;
517 case 'add':
518 // Add a new instance of this block, if allowed
519 $block = blocks_get_record($blockid);
521 if(empty($block) || !$block->visible) {
522 // Only allow adding if the block exists and is enabled
523 return false;
526 if(!$block->multiple && blocks_find_block($blockid, $pageblocks) !== false) {
527 // If no multiples are allowed and we already have one, return now
528 return false;
531 $newpos = $page->blocks_default_position();
532 $weight = get_record_sql('SELECT 1, max(weight) + 1 AS nextfree FROM '. $CFG->prefix .'block_instance WHERE pageid = '. $page->get_id() .' AND pagetype = \''. $page->get_type() .'\' AND position = \''. $newpos .'\'');
534 $newinstance = new stdClass;
535 $newinstance->blockid = $blockid;
536 $newinstance->pageid = $page->get_id();
537 $newinstance->pagetype = $page->get_type();
538 $newinstance->position = $newpos;
539 $newinstance->weight = empty($weight->nextfree) ? 0 : $weight->nextfree;
540 $newinstance->visible = 1;
541 $newinstance->configdata = '';
542 $newinstance->id = insert_record('block_instance', $newinstance);
544 // If the new instance was created, allow it to do additional setup
545 if($newinstance && ($obj = block_instance($block->name, $newinstance))) {
546 // Return value ignored
547 $obj->instance_create();
550 break;
553 // In order to prevent accidental duplicate actions, redirect to a page with a clean url
554 redirect($page->url_get_full());
557 // You can use this to get the blocks to respond to URL actions without much hassle
558 function blocks_execute_url_action(&$PAGE, &$pageblocks) {
559 $blockaction = optional_param('blockaction');
561 if (empty($blockaction) || !$PAGE->user_allowed_editing() || !confirm_sesskey()) {
562 return;
565 $instanceid = optional_param('instanceid', 0, PARAM_INT);
566 $blockid = optional_param('blockid', 0, PARAM_INT);
568 if (!empty($blockid)) {
569 blocks_execute_action($PAGE, $pageblocks, strtolower($blockaction), $blockid);
572 else if (!empty($instanceid)) {
573 $instance = blocks_find_instance($instanceid, $pageblocks);
574 blocks_execute_action($PAGE, $pageblocks, strtolower($blockaction), $instance);
578 // This shouldn't be used externally at all, it's here for use by blocks_execute_action()
579 // in order to reduce code repetition.
580 function blocks_execute_repositioning(&$instance, $newpos, $newweight) {
581 global $CFG;
583 // If it's staying where it is, don't do anything
584 if($newpos == $instance->position) {
585 return;
588 // Close the weight gap we 'll leave behind
589 execute_sql('UPDATE '. $CFG->prefix .'block_instance SET weight = weight - 1 WHERE pagetype = \''. $instance->pagetype.
590 '\' AND pageid = '. $instance->pageid .' AND position = \'' .$instance->position.
591 '\' AND weight > '. $instance->weight,
592 false);
594 $instance->position = $newpos;
595 $instance->weight = $newweight;
597 update_record('block_instance', $instance);
600 function blocks_get_by_page($page) {
601 $blocks = get_records_select('block_instance', 'pageid = '. $page->get_id() .' AND pagetype = \''. $page->get_type() .'\'', 'position, weight');
603 $positions = $page->blocks_get_positions();
604 $arr = array();
605 foreach($positions as $key => $position) {
606 $arr[$position] = array();
609 if(empty($blocks)) {
610 return $arr;
613 foreach($blocks as $block) {
614 $arr[$block->position][$block->weight] = $block;
617 return $arr;
620 //This function prints the block to admin blocks as necessary
621 function blocks_print_adminblock(&$page, &$pageblocks) {
622 global $USER;
624 $missingblocks = blocks_get_missing($page, $pageblocks);
626 if (!empty($missingblocks)) {
627 $strblocks = get_string('blocks');
628 $stradd = get_string('add');
629 foreach ($missingblocks as $blockid) {
630 $block = blocks_get_record($blockid);
631 $blockobject = block_instance($block->name);
632 if ($blockobject === false) {
633 continue;
635 $menu[$block->id] = $blockobject->get_title();
637 asort($menu);
639 $target = $page->url_get_full(array('sesskey' => $USER->sesskey, 'blockaction' => 'add'));
640 $content = popup_form($target.'&amp;blockid=', $menu, 'add_block', '', $stradd .'...', '', '', true);
641 print_side_block($strblocks, $content, NULL, NULL, NULL, array('class' => 'block_adminblock'));
645 function blocks_repopulate_page($page) {
646 global $CFG;
648 $allblocks = blocks_get_record();
650 if(empty($allblocks)) {
651 error('Could not retrieve blocks from the database');
654 // Assemble the information to correlate block names to ids
655 $idforname = array();
656 foreach($allblocks as $block) {
657 $idforname[$block->name] = $block->id;
660 /// If the site override has been defined, it is the only valid one.
661 if (!empty($CFG->defaultblocks_override)) {
662 $blocknames = $CFG->defaultblocks_override;
664 else {
665 $blocknames = $page->blocks_get_default();
668 $positions = $page->blocks_get_positions();
669 $posblocks = explode(':', $blocknames);
671 // Now one array holds the names of the positions, and the other one holds the blocks
672 // that are going to go in each position. Luckily for us, both arrays are numerically
673 // indexed and the indexes match, so we can work straight away... but CAREFULLY!
675 // Ready to start creating block instances, but first drop any existing ones
676 delete_records('block_instance', 'pageid', $page->get_id(), 'pagetype', $page->get_type());
678 // Here we slyly count $posblocks and NOT $positions. This can actually make a difference
679 // if the textual representation has undefined slots in the end. So we only work with as many
680 // positions were retrieved, not with all the page says it has available.
681 $numpositions = count($posblocks);
682 for($i = 0; $i < $numpositions; ++$i) {
683 $position = $positions[$i];
684 $blocknames = explode(',', $posblocks[$i]);
685 $weight = 0;
686 foreach($blocknames as $blockname) {
687 $newinstance = new stdClass;
688 $newinstance->blockid = $idforname[$blockname];
689 $newinstance->pageid = $page->get_id();
690 $newinstance->pagetype = $page->get_type();
691 $newinstance->position = $position;
692 $newinstance->weight = $weight;
693 $newinstance->visible = 1;
694 $newinstance->configdata = '';
696 if(!empty($newinstance->blockid)) {
697 // Only add block if it was recognized
698 insert_record('block_instance', $newinstance);
699 ++$weight;
704 return true;
707 function upgrade_blocks_db($continueto) {
708 /// This function upgrades the blocks tables, if necessary
709 /// It's called from admin/index.php
711 global $CFG, $db;
713 require_once ($CFG->dirroot .'/blocks/version.php'); // Get code versions
715 if (empty($CFG->blocks_version)) { // Blocks have never been installed.
716 $strdatabaseupgrades = get_string('databaseupgrades');
717 print_header($strdatabaseupgrades, $strdatabaseupgrades, $strdatabaseupgrades,
718 '', '', false, '&nbsp;', '&nbsp;');
720 $db->debug=true;
721 if (modify_database($CFG->dirroot .'/blocks/db/'. $CFG->dbtype .'.sql')) {
722 $db->debug = false;
723 if (set_config('blocks_version', $blocks_version)) {
724 notify(get_string('databasesuccess'), 'notifysuccess');
725 notify(get_string('databaseupgradeblocks', '', $blocks_version));
726 print_continue($continueto);
727 exit;
728 } else {
729 error('Upgrade of blocks system failed! (Could not update version in config table)');
731 } else {
732 error('Blocks tables could NOT be set up successfully!');
737 if ($blocks_version > $CFG->blocks_version) { // Upgrade tables
738 $strdatabaseupgrades = get_string('databaseupgrades');
739 print_header($strdatabaseupgrades, $strdatabaseupgrades, $strdatabaseupgrades);
741 require_once ($CFG->dirroot .'/blocks/db/'. $CFG->dbtype .'.php');
743 $db->debug=true;
744 if (blocks_upgrade($CFG->blocks_version)) {
745 $db->debug=false;
746 if (set_config('blocks_version', $blocks_version)) {
747 notify(get_string('databasesuccess'), 'notifysuccess');
748 notify(get_string('databaseupgradeblocks', '', $blocks_version));
749 print_continue($continueto);
750 exit;
751 } else {
752 error('Upgrade of blocks system failed! (Could not update version in config table)');
754 } else {
755 $db->debug=false;
756 error('Upgrade failed! See blocks/version.php');
759 } else if ($blocks_version < $CFG->blocks_version) {
760 notify('WARNING!!! The Blocks version you are using is OLDER than the version that made these databases!');
764 //This function finds all available blocks and install them
765 //into blocks table or do all the upgrade process if newer
766 function upgrade_blocks_plugins($continueto) {
768 global $CFG;
770 $blocktitles = array();
771 $invalidblocks = array();
772 $validblocks = array();
773 $notices = array();
775 //Count the number of blocks in db
776 $blockcount = count_records('block');
777 //If there isn't records. This is the first install, so I remember it
778 if ($blockcount == 0) {
779 $first_install = true;
780 } else {
781 $first_install = false;
784 $site = get_site();
786 if (!$blocks = get_list_of_plugins('blocks', 'db') ) {
787 error('No blocks installed!');
790 include_once($CFG->dirroot .'/blocks/moodleblock.class.php');
791 if(!class_exists('block_base')) {
792 error('Class block_base is not defined or file not found for /blocks/moodleblock.class.php');
795 foreach ($blocks as $blockname) {
797 if ($blockname == 'NEWBLOCK') { // Someone has unzipped the template, ignore it
798 continue;
801 if(!block_is_compatible($blockname)) {
802 // This is an old-style block
803 //$notices[] = 'Block '. $blockname .' is not compatible with the current version of Mooodle and needs to be updated by a programmer.';
804 $invalidblocks[] = $blockname;
805 continue;
808 $fullblock = $CFG->dirroot .'/blocks/'. $blockname;
810 if ( is_readable($fullblock.'/block_'.$blockname.'.php')) {
811 include_once($fullblock.'/block_'.$blockname.'.php');
812 } else {
813 $notices[] = 'Block '. $blockname .': '. $fullblock .'/block_'. $blockname .'.php was not readable';
814 continue;
817 if ( @is_dir($fullblock .'/db/')) {
818 if ( @is_readable($fullblock .'/db/'. $CFG->dbtype .'.php')) {
819 include_once($fullblock .'/db/'. $CFG->dbtype .'.php'); // defines upgrading function
820 } else {
821 //$notices[] ='Block '. $blockname .': '. $fullblock .'/db/'. $CFG->dbtype .'.php was not readable';
822 continue;
826 $classname = 'block_'.$blockname;
827 if(!class_exists($classname)) {
828 $notices[] = 'Block '. $blockname .': '. $classname .' not implemented';
829 continue;
832 // Here is the place to see if the block implements a constructor (old style),
833 // an init() function (new style) or nothing at all (error time).
835 $constructor = get_class_constructor($classname);
836 if(empty($constructor)) {
837 // No constructor
838 $notices[] = 'Block '. $blockname .': class does not have a constructor';
839 $invalidblocks[] = $blockname;
840 continue;
843 $block = new stdClass; // This may be used to update the db below
844 $blockobj = new $classname; // This is what we 'll be testing
846 // Inherits from block_base?
847 if(!is_subclass_of($blockobj, 'block_base')) {
848 $notices[] = 'Block '. $blockname .': class does not inherit from block_base';
849 continue;
852 // OK, it's as we all hoped. For further tests, the object will do them itself.
853 if(!$blockobj->_self_test()) {
854 $notices[] = 'Block '. $blockname .': self test failed';
855 continue;
857 $block->version = $blockobj->get_version();
859 if (!isset($block->version)) {
860 $notices[] = 'Block '. $blockname .': has no version support. It must be updated by a programmer.';
861 continue;
864 $block->name = $blockname; // The name MUST match the directory
865 $blocktitle = $blockobj->get_title();
867 if ($currblock = get_record('block', 'name', $block->name)) {
868 if ($currblock->version == $block->version) {
869 // do nothing
870 } else if ($currblock->version < $block->version) {
871 if (empty($updated_blocks)) {
872 $strblocksetup = get_string('blocksetup');
873 print_header($strblocksetup, $strblocksetup, $strblocksetup, '', '', false, '&nbsp;', '&nbsp;');
875 print_heading('New version of '.$blocktitle.' ('.$block->name.') exists');
876 $upgrade_function = $block->name.'_upgrade';
877 if (function_exists($upgrade_function)) {
878 $db->debug=true;
879 if ($upgrade_function($currblock->version, $block)) {
881 $upgradesuccess = true;
882 } else {
883 $upgradesuccess = false;
885 $db->debug=false;
887 else {
888 $upgradesuccess = true;
890 if(!$upgradesuccess) {
891 notify('Upgrading block '. $block->name .' from '. $currblock->version .' to '. $block->version .' FAILED!');
893 else {
894 // OK so far, now update the block record
895 $block->id = $currblock->id;
896 if (! update_record('block', $block)) {
897 error('Could not update block '. $block->name .' record in block table!');
899 notify(get_string('blocksuccess', '', $blocktitle), 'notifysuccess');
900 echo '<hr />';
902 $updated_blocks = true;
903 } else {
904 error('Version mismatch: block '. $block->name .' can\'t downgrade '. $currblock->version .' -> '. $block->version .'!');
907 } else { // block not installed yet, so install it
909 // If it allows multiples, start with it enabled
910 $block->multiple = $blockobj->instance_allow_multiple();
912 // [pj] Normally this would be inline in the if, but we need to
913 // check for NULL (necessary for 4.0.5 <= PHP < 4.2.0)
914 $conflictblock = array_search($blocktitle, $blocktitles);
915 if($conflictblock !== false && $conflictblock !== NULL) {
916 // Duplicate block titles are not allowed, they confuse people
917 // AND PHP's associative arrays ;)
918 error('<strong>Naming conflict</strong>: block <strong>'.$block->name.'</strong> has the same title with an existing block, <strong>'.$conflictblock.'</strong>!');
920 if (empty($updated_blocks)) {
921 $strblocksetup = get_string('blocksetup');
922 print_header($strblocksetup, $strblocksetup, $strblocksetup, '', '', false, '&nbsp;', '&nbsp;');
924 print_heading($block->name);
925 $updated_blocks = true;
926 $db->debug = true;
927 @set_time_limit(0); // To allow slow databases to complete the long SQL
928 if (!is_dir($fullblock .'/db/') || modify_database($fullblock .'/db/'. $CFG->dbtype .'.sql')) {
929 $db->debug = false;
930 if ($block->id = insert_record('block', $block)) {
931 notify(get_string('blocksuccess', '', $blocktitle), 'notifysuccess');
932 echo '<hr />';
933 } else {
934 error($block->name .' block could not be added to the block list!');
936 } else {
937 error('Block '. $block->name .' tables could NOT be set up successfully!');
941 $blocktitles[$block->name] = $blocktitle;
944 if(!empty($notices)) {
945 foreach($notices as $notice) {
946 notify($notice);
950 // Finally, if we are in the first_install of BLOCKS (this means that we are
951 // upgrading from Moodle < 1.3), put blocks in all existing courses.
952 if ($first_install) {
953 //Iterate over each course
954 if ($courses = get_records('course')) {
955 foreach ($courses as $course) {
956 $page = page_create_object(PAGE_COURSE_VIEW, $course->id);
957 blocks_repopulate_page($page);
962 if (!empty($CFG->siteblocksadded)) { /// This is a once-off hack to make a proper upgrade
963 $page = page_create_object(PAGE_COURSE_VIEW, SITEID);
964 blocks_repopulate_page($page);
965 delete_records('config', 'name', 'siteblocksadded');
968 if (!empty($updated_blocks)) {
969 print_continue($continueto);
970 die;