3 //This library includes all the necessary stuff to use blocks in course pages
5 define('BLOCK_MOVE_LEFT', 0x01);
6 define('BLOCK_MOVE_RIGHT', 0x02);
7 define('BLOCK_MOVE_UP', 0x04);
8 define('BLOCK_MOVE_DOWN', 0x08);
9 define('BLOCK_CONFIGURE', 0x10);
11 define('BLOCK_POS_LEFT', 'l');
12 define('BLOCK_POS_RIGHT', 'r');
14 define('BLOCKS_PINNED_TRUE',0);
15 define('BLOCKS_PINNED_FALSE',1);
16 define('BLOCKS_PINNED_BOTH',2);
18 require_once($CFG->libdir
.'/pagelib.php');
19 require_once($CFG->dirroot
.'/course/lib.php'); // needed to solve all those: Call to undefined function: print_recent_activity() when adding Recent Activity
21 // Returns false if this block is incompatible with the current version of Moodle.
22 function block_is_compatible($blockname) {
25 $file = @file
($CFG->dirroot
.'/blocks/'.$blockname.'/block_'.$blockname.'.php'); // ignore errors when file does not exist
30 foreach($file as $line) {
31 // If you find MoodleBlock (appearing in the class declaration) it's not compatible
32 if(strpos($line, 'MoodleBlock')) {
35 // But if we find a { it means the class declaration is over, so it's compatible
36 else if(strpos($line, '{')) {
44 // Returns the case-sensitive name of the class' constructor function. This includes both
45 // PHP5- and PHP4-style constructors. If no appropriate constructor can be found, returns NULL.
46 // If there is no such class, returns boolean false.
47 function get_class_constructor($classname) {
49 static $constructors = array();
51 if(!class_exists($classname)) {
55 // Tests indicate this doesn't hurt even in PHP5.
56 $classname = strtolower($classname);
58 // Return cached value, if exists
59 if(isset($constructors[$classname])) {
60 return $constructors[$classname];
63 // Get a list of methods. After examining several different ways of
64 // doing the check, (is_callable, method_exists, function_exists etc)
65 // it seems that this is the most reliable one.
66 $methods = get_class_methods($classname);
69 if(phpversion() >= '5') {
70 if(in_array('__construct', $methods)) {
71 return $constructors[$classname] = '__construct';
75 // If we have PHP5 but no magic constructor, we have to lowercase the methods
76 $methods = array_map('strtolower', $methods);
78 if(in_array($classname, $methods)) {
79 return $constructors[$classname] = $classname;
82 return $constructors[$classname] = NULL;
85 //This function retrieves a method-defined property of a class WITHOUT instantiating an object
86 function block_method_result($blockname, $method, $param = NULL) {
87 if(!block_load_class($blockname)) {
90 return call_user_func(array('block_'.$blockname, $method), $param);
93 //This function creates a new object of the specified block class
94 function block_instance($blockname, $instance = NULL) {
95 if(!block_load_class($blockname)) {
98 $classname = 'block_'.$blockname;
99 $retval = new $classname;
100 if($instance !== NULL) {
101 $retval->_load_instance($instance);
106 //This function loads the necessary class files for a block
107 //Whenever you want to load a block, use this first
108 function block_load_class($blockname) {
111 if(empty($blockname)) {
115 $classname = 'block_'.$blockname;
117 if(class_exists($classname)) {
121 require_once($CFG->dirroot
.'/blocks/moodleblock.class.php');
122 @include_once
($CFG->dirroot
.'/blocks/'.$blockname.'/block_'.$blockname.'.php'); // do not throw errors if block code not present
124 return class_exists($classname);
127 // This function returns an array with the IDs of any blocks that you can add to your page.
128 // Parameters are passed by reference for speed; they are not modified at all.
129 function blocks_get_missing(&$page, &$pageblocks) {
131 $missingblocks = array();
132 $allblocks = blocks_get_record();
133 $pageformat = $page->get_format_name();
135 if(!empty($allblocks)) {
136 foreach($allblocks as $block) {
137 if($block->visible
&& (!blocks_find_block($block->id
, $pageblocks) ||
$block->multiple
)) {
138 // And if it's applicable for display in this format...
139 if(blocks_name_allowed_in_format($block->name
, $pageformat)) {
140 // ...add it to the missing blocks
141 $missingblocks[] = $block->id
;
146 return $missingblocks;
149 function blocks_remove_inappropriate($page) {
150 $pageblocks = blocks_get_by_page($page);
152 if(empty($pageblocks)) {
156 if(($pageformat = $page->get_format_name()) == NULL) {
160 foreach($pageblocks as $position) {
161 foreach($position as $instance) {
162 $block = blocks_get_record($instance->blockid
);
163 if(!blocks_name_allowed_in_format($block->name
, $pageformat)) {
164 blocks_delete_instance($instance);
170 function blocks_name_allowed_in_format($name, $pageformat) {
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) {
185 if($accept === NULL) {
186 $accept = !empty($formats['all']);
191 function blocks_delete_instance($instance,$pinned=false) {
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);
209 // Now kill the db record;
210 delete_records('block_instance', 'id', $instance->id
);
211 // And now, decrement the weight of all blocks after this one
212 execute_sql('UPDATE '.$CFG->prefix
.'block_instance SET weight = weight - 1 WHERE pagetype = \''.$instance->pagetype
.
213 '\' AND pageid = '.$instance->pageid
.' AND position = \''.$instance->position
.
214 '\' AND weight > '.$instance->weight
, false);
219 // Accepts an array of block instances and checks to see if any of them have content to display
220 // (causing them to calculate their content in the process). Returns true or false. Parameter passed
221 // by reference for speed; the array is actually not modified.
222 function blocks_have_content(&$pageblocks, $position) {
224 if (empty($pageblocks) ||
!is_array($pageblocks) ||
!array_key_exists($position,$pageblocks)) {
227 // use a for() loop to get references to the array elements
228 // foreach() cannot fetch references in PHP v4.x
229 for ($n=0; $n<count($pageblocks[$position]);$n++
) {
230 $instance = &$pageblocks[$position][$n];
231 if(!$instance->visible
) {
234 if(!$record = blocks_get_record($instance->blockid
)) {
237 if(!$obj = block_instance($record->name
, $instance)) {
240 if(!$obj->is_empty()) {
242 // for blocks_print_group()
243 $instance->rec
= $record;
244 $instance->obj
= $obj;
252 // This function prints one group of blocks in a page
253 // Parameters passed by reference for speed; they are not modified.
254 function blocks_print_group(&$page, &$pageblocks, $position) {
255 global $COURSE, $CFG, $USER;
257 if(empty($pageblocks[$position])) {
258 $pageblocks[$position] = array();
262 $maxweight = max(array_keys($pageblocks[$position]));
265 foreach ($pageblocks[$position] as $instance) {
266 if (!empty($instance->pinned
)) {
271 $isediting = $page->user_is_editing();
272 foreach($pageblocks[$position] as $instance) {
274 // $instance may have ->rec and ->obj
275 // cached from when we walked $pageblocks
276 // in blocks_have_content()
277 if (empty($instance->rec
)) {
278 $block = blocks_get_record($instance->blockid
);
280 $block = $instance->rec
;
284 // Block doesn't exist! We should delete this instance!
288 if(!$block->visible
) {
289 // Disabled by the admin
293 if (empty($instance->obj
)) {
294 if (!$obj = block_instance($block->name
, $instance)) {
299 $obj = $instance->obj
;
302 $editalways = $page->edit_always();
304 if (($isediting && empty($instance->pinned
)) ||
!empty($editalways)) {
306 // 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:
307 // the first block might still be able to move up if the page says so (i.e., it will change position)
308 $options |
= BLOCK_MOVE_UP
* ($instance->weight
!= 0 ||
($page->blocks_move_position($instance, BLOCK_MOVE_UP
) != $instance->position
));
309 // Same thing for downward movement
310 $options |
= BLOCK_MOVE_DOWN
* ($instance->weight
!= $maxweight ||
($page->blocks_move_position($instance, BLOCK_MOVE_DOWN
) != $instance->position
));
311 // For left and right movements, it's up to the page to tell us whether they are allowed
312 $options |
= BLOCK_MOVE_RIGHT
* ($page->blocks_move_position($instance, BLOCK_MOVE_RIGHT
) != $instance->position
);
313 $options |
= BLOCK_MOVE_LEFT
* ($page->blocks_move_position($instance, BLOCK_MOVE_LEFT
) != $instance->position
);
314 // Finally, the block can be configured if the block class either allows multiple instances, or if it specifically
315 // allows instance configuration (multiple instances override that one). It doesn't have anything to do with what the
316 // administrator has allowed for this block in the site admin options.
317 $options |
= BLOCK_CONFIGURE
* ( $obj->instance_allow_multiple() ||
$obj->instance_allow_config() );
318 $obj->_add_edit_controls($options);
321 if (!$instance->visible
&& empty($COURSE->javascriptportal
)) {
323 $obj->_print_shadow();
327 if(!empty($COURSE->javascriptportal
)) {
328 $COURSE->javascriptportal
->currentblocksection
= $position;
330 $obj->_print_block();
332 if (!empty($COURSE->javascriptportal
)
333 && (empty($instance->pinned
) ||
!$instance->pinned
)) {
334 $COURSE->javascriptportal
->block_add('inst'.$instance->id
, !$instance->visible
);
339 // we are on the default position/side AND
340 // we're editing the page AND
342 // we have the capability to manage blocks OR
343 // we are in myMoodle page AND have the capibility to manage myMoodle blocks
346 // for constant PAGE_MY_MOODLE
347 include_once($CFG->dirroot
.'/my/pagelib.php');
349 $coursecontext = get_context_instance(CONTEXT_COURSE
, $COURSE->id
);
350 $myownblogpage = (isset($page->filtertype
) && isset($page->filterselect
) && $page->type
=='blog-view' && $page->filtertype
=='user' && $page->filterselect
== $USER->id
);
352 $managecourseblocks = has_capability('moodle/site:manageblocks', $coursecontext);
353 $editmymoodle = $page->type
== PAGE_MY_MOODLE
&& has_capability('moodle/my:manageblocks', $coursecontext);
355 if ($page->blocks_default_position() == $position &&
356 $page->user_is_editing() &&
357 ($managecourseblocks ||
$editmymoodle ||
$myownblogpage)) {
359 blocks_print_adminblock($page, $pageblocks);
363 // This iterates over an array of blocks and calculates the preferred width
364 // Parameter passed by reference for speed; it's not modified.
365 function blocks_preferred_width(&$instances) {
368 if(empty($instances) ||
!is_array($instances)) {
372 $blocks = blocks_get_record();
374 foreach($instances as $instance) {
375 if(!$instance->visible
) {
379 if (!array_key_exists($instance->blockid
, $blocks)) {
380 // Block doesn't exist! We should delete this instance!
384 if(!$blocks[$instance->blockid
]->visible
) {
387 $pref = block_method_result($blocks[$instance->blockid
]->name
, 'preferred_width');
398 function blocks_get_record($blockid = NULL, $invalidate = false) {
399 static $cache = NULL;
401 if($invalidate ||
empty($cache)) {
402 $cache = get_records('block');
405 if($blockid === NULL) {
409 return (isset($cache[$blockid])?
$cache[$blockid] : false);
412 function blocks_find_block($blockid, $blocksarray) {
413 if (empty($blocksarray)) {
416 foreach($blocksarray as $blockgroup) {
417 if (empty($blockgroup)) {
420 foreach($blockgroup as $instance) {
421 if($instance->blockid
== $blockid) {
429 function blocks_find_instance($instanceid, $blocksarray) {
430 foreach($blocksarray as $subarray) {
431 foreach($subarray as $instance) {
432 if($instance->id
== $instanceid) {
440 // Simple entry point for anyone that wants to use blocks
441 function blocks_setup(&$PAGE,$pinned=BLOCKS_PINNED_FALSE
) {
443 case BLOCKS_PINNED_TRUE
:
444 $pageblocks = blocks_get_pinned($PAGE);
446 case BLOCKS_PINNED_BOTH
:
447 $pageblocks = blocks_get_by_page_pinned($PAGE);
449 case BLOCKS_PINNED_FALSE
:
451 $pageblocks = blocks_get_by_page($PAGE);
454 blocks_execute_url_action($PAGE, $pageblocks,($pinned==BLOCKS_PINNED_TRUE
));
458 function blocks_execute_action($page, &$pageblocks, $blockaction, $instanceorid, $pinned=false, $redirect=true) {
461 if (is_int($instanceorid)) {
462 $blockid = $instanceorid;
463 } else if (is_object($instanceorid)) {
464 $instance = $instanceorid;
467 switch($blockaction) {
470 $block = blocks_get_record($instance->blockid
);
471 // Hacky hacky tricky stuff to get the original human readable block title,
472 // even if the block has configured its title to be something else.
473 // Create the object WITHOUT instance data.
474 $blockobject = block_instance($block->name
);
475 if ($blockobject === false) {
479 // First of all check to see if the block wants to be edited
480 if(!$blockobject->user_can_edit()) {
484 // Now get the title and AFTER that load up the instance
485 $blocktitle = $blockobject->get_title();
486 $blockobject->_load_instance($instance);
488 optional_param('submitted', 0, PARAM_INT
);
490 // Define the data we're going to silently include in the instance config form here,
491 // so we can strip them from the submitted data BEFORE serializing it.
493 'sesskey' => $USER->sesskey
,
494 'instanceid' => $instance->id
,
495 'blockaction' => 'config'
498 // To this data, add anything the page itself needs to display
499 $hiddendata = array_merge($hiddendata, $page->url_get_parameters());
501 if($data = data_submitted()) {
502 $remove = array_keys($hiddendata);
503 foreach($remove as $item) {
506 if(!$blockobject->instance_config_save($data,$pinned)) {
507 error('Error saving block configuration');
509 // And nothing more, continue with displaying the page
512 // We need to show the config screen, so we highjack the display logic and then die
513 $strheading = get_string('blockconfiga', 'moodle', $blocktitle);
514 $page->print_header(get_string('pageheaderconfigablock', 'moodle'), array($strheading => ''));
516 echo '<div class="block-config" id="'.$block->name
.'">'; /// Make CSS easier
518 print_heading($strheading);
519 echo '<form method="post" action="'. $page->url_get_path() .'">';
521 foreach($hiddendata as $name => $val) {
522 echo '<input type="hidden" name="'. $name .'" value="'. $val .'" />';
525 $blockobject->instance_config_print();
529 $CFG->pagepath
= 'blocks/' . $block->name
;
531 die(); // Do not go on with the other page-related stuff
535 if(empty($instance)) {
536 error('Invalid block instance for '.$blockaction);
538 $instance->visible
= ($instance->visible
) ?
0 : 1;
539 if (!empty($pinned)) {
540 update_record('block_pinned', $instance);
542 update_record('block_instance', $instance);
546 if(empty($instance)) {
547 error('Invalid block instance for '. $blockaction);
549 blocks_delete_instance($instance, $pinned);
552 if(empty($instance)) {
553 error('Invalid block instance for '. $blockaction);
556 if($instance->weight
== 0) {
557 // The block is the first one, so a move "up" probably means it changes position
558 // Where is the instance going to be moved?
559 $newpos = $page->blocks_move_position($instance, BLOCK_MOVE_UP
);
560 $newweight = (empty($pageblocks[$newpos]) ?
0 : max(array_keys($pageblocks[$newpos])) +
1);
562 blocks_execute_repositioning($instance, $newpos, $newweight, $pinned);
565 // The block is just moving upwards in the same position.
566 // This configuration will make sure that even if somehow the weights
567 // become not continuous, block move operations will eventually bring
568 // the situation back to normal without printing any warnings.
569 if(!empty($pageblocks[$instance->position
][$instance->weight
- 1])) {
570 $other = $pageblocks[$instance->position
][$instance->weight
- 1];
574 if (!empty($pinned)) {
575 update_record('block_pinned', $other);
577 update_record('block_instance', $other);
581 if (!empty($pinned)) {
582 update_record('block_pinned', $instance);
584 update_record('block_instance', $instance);
589 if(empty($instance)) {
590 error('Invalid block instance for '. $blockaction);
593 if($instance->weight
== max(array_keys($pageblocks[$instance->position
]))) {
594 // The block is the last one, so a move "down" probably means it changes position
595 // Where is the instance going to be moved?
596 $newpos = $page->blocks_move_position($instance, BLOCK_MOVE_DOWN
);
597 $newweight = (empty($pageblocks[$newpos]) ?
0 : max(array_keys($pageblocks[$newpos])) +
1);
599 blocks_execute_repositioning($instance, $newpos, $newweight, $pinned);
602 // The block is just moving downwards in the same position.
603 // This configuration will make sure that even if somehow the weights
604 // become not continuous, block move operations will eventually bring
605 // the situation back to normal without printing any warnings.
606 if(!empty($pageblocks[$instance->position
][$instance->weight +
1])) {
607 $other = $pageblocks[$instance->position
][$instance->weight +
1];
611 if (!empty($pinned)) {
612 update_record('block_pinned', $other);
614 update_record('block_instance', $other);
618 if (!empty($pinned)) {
619 update_record('block_pinned', $instance);
621 update_record('block_instance', $instance);
626 if(empty($instance)) {
627 error('Invalid block instance for '. $blockaction);
630 // Where is the instance going to be moved?
631 $newpos = $page->blocks_move_position($instance, BLOCK_MOVE_LEFT
);
632 $newweight = (empty($pageblocks[$newpos]) ?
0 : max(array_keys($pageblocks[$newpos])) +
1);
634 blocks_execute_repositioning($instance, $newpos, $newweight, $pinned);
637 if(empty($instance)) {
638 error('Invalid block instance for '. $blockaction);
641 // Where is the instance going to be moved?
642 $newpos = $page->blocks_move_position($instance, BLOCK_MOVE_RIGHT
);
643 $newweight = (empty($pageblocks[$newpos]) ?
0 : max(array_keys($pageblocks[$newpos])) +
1);
645 blocks_execute_repositioning($instance, $newpos, $newweight, $pinned);
648 // Add a new instance of this block, if allowed
649 $block = blocks_get_record($blockid);
651 if(empty($block) ||
!$block->visible
) {
652 // Only allow adding if the block exists and is enabled
656 if(!$block->multiple
&& blocks_find_block($blockid, $pageblocks) !== false) {
657 // If no multiples are allowed and we already have one, return now
661 if(!block_method_result($block->name
, 'user_can_addto', $page)) {
662 // If the block doesn't want to be added...
666 $newpos = $page->blocks_default_position();
667 if (!empty($pinned)) {
668 $sql = 'SELECT 1, max(weight) + 1 AS nextfree FROM '. $CFG->prefix
.'block_pinned WHERE '
669 .' pagetype = \''. $page->get_type() .'\' AND position = \''. $newpos .'\'';
671 $sql = 'SELECT 1, max(weight) + 1 AS nextfree FROM '. $CFG->prefix
.'block_instance WHERE pageid = '. $page->get_id()
672 .' AND pagetype = \''. $page->get_type() .'\' AND position = \''. $newpos .'\'';
674 $weight = get_record_sql($sql);
676 $newinstance = new stdClass
;
677 $newinstance->blockid
= $blockid;
678 if (empty($pinned)) {
679 $newinstance->pageid
= $page->get_id();
681 $newinstance->pagetype
= $page->get_type();
682 $newinstance->position
= $newpos;
683 $newinstance->weight
= empty($weight->nextfree
) ?
0 : $weight->nextfree
;
684 $newinstance->visible
= 1;
685 $newinstance->configdata
= '';
686 if (!empty($pinned)) {
687 $newinstance->id
= insert_record('block_pinned', $newinstance);
689 $newinstance->id
= insert_record('block_instance', $newinstance);
692 // If the new instance was created, allow it to do additional setup
693 if($newinstance && ($obj = block_instance($block->name
, $newinstance))) {
694 // Return value ignored
695 $obj->instance_create();
702 // In order to prevent accidental duplicate actions, redirect to a page with a clean url
703 redirect($page->url_get_full());
707 // You can use this to get the blocks to respond to URL actions without much hassle
708 function blocks_execute_url_action(&$PAGE, &$pageblocks,$pinned=false) {
709 $blockaction = optional_param('blockaction', '', PARAM_ALPHA
);
711 if (empty($blockaction) ||
!$PAGE->user_allowed_editing() ||
!confirm_sesskey()) {
715 $instanceid = optional_param('instanceid', 0, PARAM_INT
);
716 $blockid = optional_param('blockid', 0, PARAM_INT
);
718 if (!empty($blockid)) {
719 blocks_execute_action($PAGE, $pageblocks, strtolower($blockaction), $blockid, $pinned);
722 else if (!empty($instanceid)) {
723 $instance = blocks_find_instance($instanceid, $pageblocks);
724 blocks_execute_action($PAGE, $pageblocks, strtolower($blockaction), $instance, $pinned);
728 // This shouldn't be used externally at all, it's here for use by blocks_execute_action()
729 // in order to reduce code repetition.
730 function blocks_execute_repositioning(&$instance, $newpos, $newweight, $pinned=false) {
733 // If it's staying where it is, don't do anything, unless overridden
734 if ($newpos == $instance->position
) {
738 // Close the weight gap we 'll leave behind
739 if (!empty($pinned)) {
740 $sql = 'UPDATE '. $CFG->prefix
.'block_instance SET weight = weight - 1 '.
741 'WHERE pagetype = \''. $instance->pagetype
.
742 '\' AND position = \'' .$instance->position
.
743 '\' AND weight > '. $instance->weight
;
745 $sql = 'UPDATE '. $CFG->prefix
.'block_instance SET weight = weight - 1 '.
746 'WHERE pagetype = \''. $instance->pagetype
.
747 '\' AND pageid = '. $instance->pageid
.
748 ' AND position = \'' .$instance->position
.
749 '\' AND weight > '. $instance->weight
;
751 execute_sql($sql,false);
753 $instance->position
= $newpos;
754 $instance->weight
= $newweight;
756 if (!empty($pinned)) {
757 update_record('block_pinned', $instance);
759 update_record('block_instance', $instance);
765 * Moves a block to the new position (column) and weight (sort order).
766 * @param $instance - The block instance to be moved.
767 * @param $destpos - BLOCK_POS_LEFT or BLOCK_POS_RIGHT. The destination column.
768 * @param $destweight - The destination sort order. If NULL, we add to the end
769 * of the destination column.
770 * @param $pinned - Are we moving pinned blocks? We can only move pinned blocks
771 * to a new position withing the pinned list. Likewise, we
772 * can only moved non-pinned blocks to a new position within
773 * the non-pinned list.
774 * @return boolean (success or failure).
776 function blocks_move_block($page, &$instance, $destpos, $destweight=NULL, $pinned=false) {
780 $blocklist = blocks_get_pinned($page);
782 $blocklist = blocks_get_by_page($page);
785 if ($blocklist[$instance->position
][$instance->weight
]->id
!= $instance->id
) {
786 // The source block instance is not where we think it is.
790 // First we close the gap that will be left behind when we take out the
791 // block from it's current column.
793 $closegapsql = "UPDATE {$CFG->prefix}block_instance
794 SET weight = weight - 1
795 WHERE weight > '$instance->weight'
796 AND position = '$instance->position'
797 AND pagetype = '$instance->pagetype'";
799 $closegapsql = "UPDATE {$CFG->prefix}block_instance
800 SET weight = weight - 1
801 WHERE weight > '$instance->weight'
802 AND position = '$instance->position'
803 AND pagetype = '$instance->pagetype'
804 AND pageid = '$instance->pageid'";
806 if (!execute_sql($closegapsql, false)) {
810 // Now let's make space for the block being moved.
812 $opengapsql = "UPDATE {$CFG->prefix}block_instance
813 SET weight = weight + 1
814 WHERE weight >= '$destweight'
815 AND position = '$destpos'
816 AND pagetype = '$instance->pagetype'";
818 $opengapsql = "UPDATE {$CFG->prefix}block_instance
819 SET weight = weight + 1
820 WHERE weight >= '$destweight'
821 AND position = '$destpos'
822 AND pagetype = '$instance->pagetype'
823 AND pageid = '$instance->pageid'";
825 if (!execute_sql($opengapsql, false)) {
830 $instance->position
= $destpos;
831 $instance->weight
= $destweight;
834 $table = 'block_pinned';
836 $table = 'block_instance';
838 return update_record($table, $instance);
843 * Returns an array consisting of 2 arrays:
844 * 1) Array of pinned blocks for position BLOCK_POS_LEFT
845 * 2) Array of pinned blocks for position BLOCK_POS_RIGHT
847 function blocks_get_pinned($page) {
851 if (method_exists($page,'edit_always')) {
852 if ($page->edit_always()) {
857 $blocks = get_records_select('block_pinned', 'pagetype = \''. $page->get_type() .
858 '\''.(($visible) ?
'AND visible = 1' : ''), 'position, weight');
860 $positions = $page->blocks_get_positions();
863 foreach($positions as $key => $position) {
864 $arr[$position] = array();
871 foreach($blocks as $block) {
872 $block->pinned
= true; // so we know we can't move it.
873 // make up an instanceid if we can..
874 $block->pageid
= $page->get_id();
875 $arr[$block->position
][$block->weight
] = $block;
883 * Similar to blocks_get_by_page(), except that, the array returned includes
884 * pinned blocks as well. Pinned blocks are always appended before normal
887 function blocks_get_by_page_pinned($page) {
888 $pinned = blocks_get_pinned($page);
889 $user = blocks_get_by_page($page);
893 foreach ($pinned as $pos => $arr) {
894 $weights[$pos] = count($arr);
897 foreach ($user as $pos => $blocks) {
898 if (!array_key_exists($pos,$pinned)) {
899 $pinned[$pos] = array();
901 if (!array_key_exists($pos,$weights)) {
904 foreach ($blocks as $block) {
905 $pinned[$pos][$weights[$pos]] = $block;
914 * Returns an array of blocks for the page. Pinned blocks are excluded.
916 function blocks_get_by_page($page) {
917 $blocks = get_records_select('block_instance', "pageid = '". $page->get_id() .
918 "' AND pagetype = '". $page->get_type() ."'", 'position, weight');
920 $positions = $page->blocks_get_positions();
922 foreach($positions as $key => $position) {
923 $arr[$position] = array();
930 foreach($blocks as $block) {
931 $arr[$block->position
][$block->weight
] = $block;
937 //This function prints the block to admin blocks as necessary
938 function blocks_print_adminblock(&$page, &$pageblocks) {
941 $missingblocks = blocks_get_missing($page, $pageblocks);
943 if (!empty($missingblocks)) {
944 $strblocks = get_string('blocks');
945 $stradd = get_string('add');
946 foreach ($missingblocks as $blockid) {
947 $block = blocks_get_record($blockid);
948 $blockobject = block_instance($block->name
);
949 if ($blockobject === false) {
952 if(!$blockobject->user_can_addto($page)) {
955 $menu[$block->id
] = $blockobject->get_title();
959 $target = $page->url_get_full(array('sesskey' => $USER->sesskey
, 'blockaction' => 'add'));
960 $content = popup_form($target.'&blockid=', $menu, 'add_block', '', $stradd .'...', '', '', true);
961 print_side_block($strblocks, $content, NULL, NULL, NULL, array('class' => 'block_adminblock'));
965 function blocks_repopulate_page($page) {
968 $allblocks = blocks_get_record();
970 if(empty($allblocks)) {
971 error('Could not retrieve blocks from the database');
974 // Assemble the information to correlate block names to ids
975 $idforname = array();
976 foreach($allblocks as $block) {
977 $idforname[$block->name
] = $block->id
;
980 /// If the site override has been defined, it is the only valid one.
981 if (!empty($CFG->defaultblocks_override
)) {
982 $blocknames = $CFG->defaultblocks_override
;
985 $blocknames = $page->blocks_get_default();
988 $positions = $page->blocks_get_positions();
989 $posblocks = explode(':', $blocknames);
991 // Now one array holds the names of the positions, and the other one holds the blocks
992 // that are going to go in each position. Luckily for us, both arrays are numerically
993 // indexed and the indexes match, so we can work straight away... but CAREFULLY!
995 // Ready to start creating block instances, but first drop any existing ones
996 delete_records('block_instance', 'pageid', $page->get_id(), 'pagetype', $page->get_type());
998 // Here we slyly count $posblocks and NOT $positions. This can actually make a difference
999 // if the textual representation has undefined slots in the end. So we only work with as many
1000 // positions were retrieved, not with all the page says it has available.
1001 $numpositions = count($posblocks);
1002 for($i = 0; $i < $numpositions; ++
$i) {
1003 $position = $positions[$i];
1004 $blocknames = explode(',', $posblocks[$i]);
1006 foreach($blocknames as $blockname) {
1007 $newinstance = new stdClass
;
1008 $newinstance->blockid
= $idforname[$blockname];
1009 $newinstance->pageid
= $page->get_id();
1010 $newinstance->pagetype
= $page->get_type();
1011 $newinstance->position
= $position;
1012 $newinstance->weight
= $weight;
1013 $newinstance->visible
= 1;
1014 $newinstance->configdata
= '';
1016 if(!empty($newinstance->blockid
)) {
1017 // Only add block if it was recognized
1018 insert_record('block_instance', $newinstance);
1027 function upgrade_blocks_db($continueto) {
1028 /// This function upgrades the blocks tables, if necessary
1029 /// It's called from admin/index.php
1033 require_once ($CFG->dirroot
.'/blocks/version.php'); // Get code versions
1035 if (empty($CFG->blocks_version
)) { // Blocks have never been installed.
1036 $strdatabaseupgrades = get_string('databaseupgrades');
1037 print_header($strdatabaseupgrades, $strdatabaseupgrades, $strdatabaseupgrades, '',
1038 upgrade_get_javascript(), false, ' ', ' ');
1040 upgrade_log_start();
1041 print_heading('blocks');
1044 /// Both old .sql files and new install.xml are supported
1045 /// but we priorize install.xml (XMLDB) if present
1047 if (file_exists($CFG->dirroot
. '/blocks/db/install.xml')) {
1048 $status = install_from_xmldb_file($CFG->dirroot
. '/blocks/db/install.xml'); //New method
1049 } else if (file_exists($CFG->dirroot
. '/blocks/db/' . $CFG->dbtype
. '.sql')) {
1050 $status = modify_database($CFG->dirroot
. '/blocks/db/' . $CFG->dbtype
. '.sql'); //Old method
1055 if (set_config('blocks_version', $blocks_version)) {
1056 notify(get_string('databasesuccess'), 'notifysuccess');
1057 notify(get_string('databaseupgradeblocks', '', $blocks_version), 'notifysuccess');
1058 print_continue($continueto);
1059 print_footer('none');
1062 error('Upgrade of blocks system failed! (Could not update version in config table)');
1065 error('Blocks tables could NOT be set up successfully!');
1069 /// Upgrading code starts here
1070 $oldupgrade = false;
1071 $newupgrade = false;
1072 if (is_readable($CFG->dirroot
. '/blocks/db/' . $CFG->dbtype
. '.php')) {
1073 include_once($CFG->dirroot
. '/blocks/db/' . $CFG->dbtype
. '.php'); // defines old upgrading function
1076 if (is_readable($CFG->dirroot
. '/blocks/db/upgrade.php')) {
1077 include_once($CFG->dirroot
. '/blocks/db/upgrade.php'); // defines new upgrading function
1081 if ($blocks_version > $CFG->blocks_version
) { // Upgrade tables
1082 $strdatabaseupgrades = get_string('databaseupgrades');
1083 print_header($strdatabaseupgrades, $strdatabaseupgrades, $strdatabaseupgrades, '', upgrade_get_javascript());
1085 upgrade_log_start();
1086 print_heading('blocks');
1088 /// Run de old and new upgrade functions for the module
1089 $oldupgrade_function = 'blocks_upgrade';
1090 $newupgrade_function = 'xmldb_blocks_upgrade';
1092 /// First, the old function if exists
1093 $oldupgrade_status = true;
1094 if ($oldupgrade && function_exists($oldupgrade_function)) {
1096 $oldupgrade_status = $oldupgrade_function($CFG->blocks_version
);
1097 } else if ($oldupgrade) {
1098 notify ('Upgrade function ' . $oldupgrade_function . ' was not available in ' .
1099 '/blocks/db/' . $CFG->dbtype
. '.php');
1102 /// Then, the new function if exists and the old one was ok
1103 $newupgrade_status = true;
1104 if ($newupgrade && function_exists($newupgrade_function) && $oldupgrade_status) {
1106 $newupgrade_status = $newupgrade_function($CFG->blocks_version
);
1107 } else if ($newupgrade) {
1108 notify ('Upgrade function ' . $newupgrade_function . ' was not available in ' .
1109 '/blocks/db/upgrade.php');
1113 /// Now analyze upgrade results
1114 if ($oldupgrade_status && $newupgrade_status) { // No upgrading failed
1115 if (set_config('blocks_version', $blocks_version)) {
1116 notify(get_string('databasesuccess'), 'notifysuccess');
1117 notify(get_string('databaseupgradeblocks', '', $blocks_version), 'notifysuccess');
1118 print_continue($continueto);
1119 print_footer('none');
1122 error('Upgrade of blocks system failed! (Could not update version in config table)');
1125 error('Upgrade failed! See blocks/version.php');
1128 } else if ($blocks_version < $CFG->blocks_version
) {
1129 upgrade_log_start();
1130 notify('WARNING!!! The Blocks version you are using is OLDER than the version that made these databases!');
1132 upgrade_log_finish();
1135 //This function finds all available blocks and install them
1136 //into blocks table or do all the upgrade process if newer
1137 function upgrade_blocks_plugins($continueto) {
1141 $blocktitles = array();
1142 $invalidblocks = array();
1143 $validblocks = array();
1146 //Count the number of blocks in db
1147 $blockcount = count_records('block');
1148 //If there isn't records. This is the first install, so I remember it
1149 if ($blockcount == 0) {
1150 $first_install = true;
1152 $first_install = false;
1157 if (!$blocks = get_list_of_plugins('blocks', 'db') ) {
1158 error('No blocks installed!');
1161 include_once($CFG->dirroot
.'/blocks/moodleblock.class.php');
1162 if(!class_exists('block_base')) {
1163 error('Class block_base is not defined or file not found for /blocks/moodleblock.class.php');
1166 foreach ($blocks as $blockname) {
1168 if ($blockname == 'NEWBLOCK') { // Someone has unzipped the template, ignore it
1172 if(!block_is_compatible($blockname)) {
1173 // This is an old-style block
1174 //$notices[] = 'Block '. $blockname .' is not compatible with the current version of Mooodle and needs to be updated by a programmer.';
1175 $invalidblocks[] = $blockname;
1179 $fullblock = $CFG->dirroot
.'/blocks/'. $blockname;
1181 if ( is_readable($fullblock.'/block_'.$blockname.'.php')) {
1182 include_once($fullblock.'/block_'.$blockname.'.php');
1184 $notices[] = 'Block '. $blockname .': '. $fullblock .'/block_'. $blockname .'.php was not readable';
1188 $oldupgrade = false;
1189 $newupgrade = false;
1190 if ( @is_dir
($fullblock .'/db/')) {
1191 if ( @is_readable
($fullblock .'/db/'. $CFG->dbtype
.'.php')) {
1192 include_once($fullblock .'/db/'. $CFG->dbtype
.'.php'); // defines old upgrading function
1195 if ( @is_readable
($fullblock .'/db/upgrade.php')) {
1196 include_once($fullblock .'/db/upgrade.php'); // defines new upgrading function
1201 $classname = 'block_'.$blockname;
1202 if(!class_exists($classname)) {
1203 $notices[] = 'Block '. $blockname .': '. $classname .' not implemented';
1207 // Here is the place to see if the block implements a constructor (old style),
1208 // an init() function (new style) or nothing at all (error time).
1210 $constructor = get_class_constructor($classname);
1211 if(empty($constructor)) {
1213 $notices[] = 'Block '. $blockname .': class does not have a constructor';
1214 $invalidblocks[] = $blockname;
1218 $block = new stdClass
; // This may be used to update the db below
1219 $blockobj = new $classname; // This is what we 'll be testing
1221 // Inherits from block_base?
1222 if(!is_subclass_of($blockobj, 'block_base')) {
1223 $notices[] = 'Block '. $blockname .': class does not inherit from block_base';
1227 // OK, it's as we all hoped. For further tests, the object will do them itself.
1228 if(!$blockobj->_self_test()) {
1229 $notices[] = 'Block '. $blockname .': self test failed';
1232 $block->version
= $blockobj->get_version();
1234 if (!isset($block->version
)) {
1235 $notices[] = 'Block '. $blockname .': has no version support. It must be updated by a programmer.';
1239 $block->name
= $blockname; // The name MUST match the directory
1240 $blocktitle = $blockobj->get_title();
1242 if ($currblock = get_record('block', 'name', $block->name
)) {
1243 if ($currblock->version
== $block->version
) {
1245 } else if ($currblock->version
< $block->version
) {
1246 if (empty($updated_blocks)) {
1247 $strblocksetup = get_string('blocksetup');
1248 print_header($strblocksetup, $strblocksetup, $strblocksetup, '',
1249 upgrade_get_javascript(), false, ' ', ' ');
1251 $updated_blocks = true;
1252 upgrade_log_start();
1253 print_heading('New version of '.$blocktitle.' ('.$block->name
.') exists');
1254 @set_time_limit
(0); // To allow slow databases to complete the long SQL
1256 /// Run de old and new upgrade functions for the module
1257 $oldupgrade_function = $block->name
.'_upgrade';
1258 $newupgrade_function = 'xmldb_block_' . $block->name
.'_upgrade';
1260 /// First, the old function if exists
1261 $oldupgrade_status = true;
1262 if ($oldupgrade && function_exists($oldupgrade_function)) {
1264 $oldupgrade_status = $oldupgrade_function($currblock->version
, $block);
1265 } else if ($oldupgrade) {
1266 notify ('Upgrade function ' . $oldupgrade_function . ' was not available in ' .
1267 $fullblock . '/db/' . $CFG->dbtype
. '.php');
1270 /// Then, the new function if exists and the old one was ok
1271 $newupgrade_status = true;
1272 if ($newupgrade && function_exists($newupgrade_function) && $oldupgrade_status) {
1274 $newupgrade_status = $newupgrade_function($currblock->version
, $block);
1275 } else if ($newupgrade) {
1276 notify ('Upgrade function ' . $newupgrade_function . ' was not available in ' .
1277 $fullblock . '/db/upgrade.php');
1281 /// Now analyze upgrade results
1282 if ($oldupgrade_status && $newupgrade_status) { // No upgrading failed
1283 // OK so far, now update the block record
1284 $block->id
= $currblock->id
;
1285 if (! update_record('block', $block)) {
1286 error('Could not update block '. $block->name
.' record in block table!');
1288 $component = 'block/'.$block->name
;
1289 if (!update_capabilities($component)) {
1290 error('Could not update '.$block->name
.' capabilities!');
1293 events_update_definition($component);
1294 notify(get_string('blocksuccess', '', $blocktitle), 'notifysuccess');
1296 notify('Upgrading block '. $block->name
.' from '. $currblock->version
.' to '. $block->version
.' FAILED!');
1300 upgrade_log_start();
1301 error('Version mismatch: block '. $block->name
.' can\'t downgrade '. $currblock->version
.' -> '. $block->version
.'!');
1304 } else { // block not installed yet, so install it
1306 // If it allows multiples, start with it enabled
1307 $block->multiple
= $blockobj->instance_allow_multiple();
1308 if (!empty($blockobj->cron
)) {
1309 $block->cron
= $blockobj->cron
;
1312 // [pj] Normally this would be inline in the if, but we need to
1313 // check for NULL (necessary for 4.0.5 <= PHP < 4.2.0)
1314 $conflictblock = array_search($blocktitle, $blocktitles);
1315 if($conflictblock !== false && $conflictblock !== NULL) {
1316 // Duplicate block titles are not allowed, they confuse people
1317 // AND PHP's associative arrays ;)
1318 error('<strong>Naming conflict</strong>: block <strong>'.$block->name
.'</strong> has the same title with an existing block, <strong>'.$conflictblock.'</strong>!');
1320 if (empty($updated_blocks)) {
1321 $strblocksetup = get_string('blocksetup');
1322 print_header($strblocksetup, $strblocksetup, $strblocksetup, '',
1323 upgrade_get_javascript(), false, ' ', ' ');
1325 $updated_blocks = true;
1326 upgrade_log_start();
1327 print_heading($block->name
);
1329 @set_time_limit
(0); // To allow slow databases to complete the long SQL
1331 /// Both old .sql files and new install.xml are supported
1332 /// but we priorize install.xml (XMLDB) if present
1334 if (file_exists($fullblock . '/db/install.xml')) {
1335 $status = install_from_xmldb_file($fullblock . '/db/install.xml'); //New method
1336 } else if (file_exists($fullblock .'/db/'. $CFG->dbtype
.'.sql')) {
1337 $status = modify_database($fullblock .'/db/'. $CFG->dbtype
.'.sql'); //Old method
1344 if ($block->id
= insert_record('block', $block)) {
1345 $blockobj->after_install();
1346 $component = 'block/'.$block->name
;
1347 if (!update_capabilities($component)) {
1348 notify('Could not set up '.$block->name
.' capabilities!');
1351 events_update_definition($component);
1352 notify(get_string('blocksuccess', '', $blocktitle), 'notifysuccess');
1355 error($block->name
.' block could not be added to the block list!');
1358 error('Block '. $block->name
.' tables could NOT be set up successfully!');
1362 $blocktitles[$block->name
] = $blocktitle;
1365 if(!empty($notices)) {
1366 upgrade_log_start();
1367 foreach($notices as $notice) {
1372 // Finally, if we are in the first_install of BLOCKS (this means that we are
1373 // upgrading from Moodle < 1.3), put blocks in all existing courses.
1374 if ($first_install) {
1375 upgrade_log_start();
1376 //Iterate over each course
1377 if ($courses = get_records('course')) {
1378 foreach ($courses as $course) {
1379 $page = page_create_object(PAGE_COURSE_VIEW
, $course->id
);
1380 blocks_repopulate_page($page);
1385 if (!empty($CFG->siteblocksadded
)) { /// This is a once-off hack to make a proper upgrade
1386 upgrade_log_start();
1387 $page = page_create_object(PAGE_COURSE_VIEW
, SITEID
);
1388 blocks_repopulate_page($page);
1389 delete_records('config', 'name', 'siteblocksadded');
1392 upgrade_log_finish();
1394 if (!empty($updated_blocks)) {
1395 print_continue($continueto);
1396 print_footer('none');