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 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);
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)) {
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
)) {
235 if(!$record = blocks_get_record($instance->blockid
)) {
238 if(!$obj = block_instance($record->name
, $instance)) {
241 if(!$obj->is_empty()) {
243 // for blocks_print_group()
244 $instance->rec
= $record;
245 $instance->obj
= $obj;
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;
258 if (empty($pageblocks[$position])) {
259 $groupblocks = array();
262 $groupblocks = $pageblocks[$position];
263 $maxweight = max(array_keys($groupblocks));
267 foreach ($groupblocks as $instance) {
268 if (!empty($instance->pinned
)) {
273 $isediting = $page->user_is_editing();
276 foreach($groupblocks as $instance) {
279 // $instance may have ->rec and ->obj
280 // cached from when we walked $pageblocks
281 // in blocks_have_content()
282 if (empty($instance->rec
)) {
283 if (empty($instance->blockid
)) {
284 continue; // Can't do anything
286 $block = blocks_get_record($instance->blockid
);
288 $block = $instance->rec
;
292 // Block doesn't exist! We should delete this instance!
296 if (empty($block->visible
)) {
297 // Disabled by the admin
301 if (empty($instance->obj
)) {
302 if (!$obj = block_instance($block->name
, $instance)) {
307 $obj = $instance->obj
;
310 $editalways = $page->edit_always();
313 if (($isediting && empty($instance->pinned
)) ||
!empty($editalways)) {
315 // 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:
316 // the first block might still be able to move up if the page says so (i.e., it will change position)
317 $options |
= BLOCK_MOVE_UP
* ($instance->weight
!= 0 ||
($page->blocks_move_position($instance, BLOCK_MOVE_UP
) != $instance->position
));
318 // Same thing for downward movement
319 $options |
= BLOCK_MOVE_DOWN
* ($instance->weight
!= $maxweight ||
($page->blocks_move_position($instance, BLOCK_MOVE_DOWN
) != $instance->position
));
320 // For left and right movements, it's up to the page to tell us whether they are allowed
321 $options |
= BLOCK_MOVE_RIGHT
* ($page->blocks_move_position($instance, BLOCK_MOVE_RIGHT
) != $instance->position
);
322 $options |
= BLOCK_MOVE_LEFT
* ($page->blocks_move_position($instance, BLOCK_MOVE_LEFT
) != $instance->position
);
323 // Finally, the block can be configured if the block class either allows multiple instances, or if it specifically
324 // allows instance configuration (multiple instances override that one). It doesn't have anything to do with what the
325 // administrator has allowed for this block in the site admin options.
326 $options |
= BLOCK_CONFIGURE
* ( $obj->instance_allow_multiple() ||
$obj->instance_allow_config() );
327 $obj->_add_edit_controls($options);
330 if (!$instance->visible
&& empty($COURSE->javascriptportal
)) {
332 $obj->_print_shadow();
336 if(!empty($COURSE->javascriptportal
)) {
337 $COURSE->javascriptportal
->currentblocksection
= $position;
339 $obj->_print_block();
341 if (!empty($COURSE->javascriptportal
)
342 && (empty($instance->pinned
) ||
!$instance->pinned
)) {
343 $COURSE->javascriptportal
->block_add('inst'.$instance->id
, !$instance->visible
);
348 // we are on the default position/side AND
349 // we're editing the page AND
351 // we have the capability to manage blocks OR
352 // we are in myMoodle page AND have the capibility to manage myMoodle blocks
355 // for constant PAGE_MY_MOODLE
356 include_once($CFG->dirroot
.'/my/pagelib.php');
358 $coursecontext = get_context_instance(CONTEXT_COURSE
, $COURSE->id
);
359 $myownblogpage = (isset($page->filtertype
) && isset($page->filterselect
) && $page->type
=='blog-view' && $page->filtertype
=='user' && $page->filterselect
== $USER->id
);
361 $managecourseblocks = has_capability('moodle/site:manageblocks', $coursecontext);
362 $editmymoodle = $page->type
== PAGE_MY_MOODLE
&& has_capability('moodle/my:manageblocks', $coursecontext);
364 if ($page->blocks_default_position() == $position &&
365 $page->user_is_editing() &&
366 ($managecourseblocks ||
$editmymoodle ||
$myownblogpage ||
defined('ADMIN_STICKYBLOCKS'))) {
368 blocks_print_adminblock($page, $pageblocks);
372 // This iterates over an array of blocks and calculates the preferred width
373 // Parameter passed by reference for speed; it's not modified.
374 function blocks_preferred_width(&$instances) {
377 if(empty($instances) ||
!is_array($instances)) {
381 $blocks = blocks_get_record();
383 foreach($instances as $instance) {
384 if(!$instance->visible
) {
388 if (!array_key_exists($instance->blockid
, $blocks)) {
389 // Block doesn't exist! We should delete this instance!
393 if(!$blocks[$instance->blockid
]->visible
) {
396 $pref = block_method_result($blocks[$instance->blockid
]->name
, 'preferred_width');
407 function blocks_get_record($blockid = NULL, $invalidate = false) {
408 static $cache = NULL;
410 if($invalidate ||
empty($cache)) {
411 $cache = get_records('block');
414 if($blockid === NULL) {
418 return (isset($cache[$blockid])?
$cache[$blockid] : false);
421 function blocks_find_block($blockid, $blocksarray) {
422 if (empty($blocksarray)) {
425 foreach($blocksarray as $blockgroup) {
426 if (empty($blockgroup)) {
429 foreach($blockgroup as $instance) {
430 if($instance->blockid
== $blockid) {
438 function blocks_find_instance($instanceid, $blocksarray) {
439 foreach($blocksarray as $subarray) {
440 foreach($subarray as $instance) {
441 if($instance->id
== $instanceid) {
449 // Simple entry point for anyone that wants to use blocks
450 function blocks_setup(&$PAGE,$pinned=BLOCKS_PINNED_FALSE
) {
452 case BLOCKS_PINNED_TRUE
:
453 $pageblocks = blocks_get_pinned($PAGE);
455 case BLOCKS_PINNED_BOTH
:
456 $pageblocks = blocks_get_by_page_pinned($PAGE);
458 case BLOCKS_PINNED_FALSE
:
460 $pageblocks = blocks_get_by_page($PAGE);
463 blocks_execute_url_action($PAGE, $pageblocks,($pinned==BLOCKS_PINNED_TRUE
));
467 function blocks_execute_action($page, &$pageblocks, $blockaction, $instanceorid, $pinned=false, $redirect=true) {
470 if (is_int($instanceorid)) {
471 $blockid = $instanceorid;
472 } else if (is_object($instanceorid)) {
473 $instance = $instanceorid;
476 switch($blockaction) {
479 $block = blocks_get_record($instance->blockid
);
480 // Hacky hacky tricky stuff to get the original human readable block title,
481 // even if the block has configured its title to be something else.
482 // Create the object WITHOUT instance data.
483 $blockobject = block_instance($block->name
);
484 if ($blockobject === false) {
488 // First of all check to see if the block wants to be edited
489 if(!$blockobject->user_can_edit()) {
493 // Now get the title and AFTER that load up the instance
494 $blocktitle = $blockobject->get_title();
495 $blockobject->_load_instance($instance);
497 optional_param('submitted', 0, PARAM_INT
);
499 // Define the data we're going to silently include in the instance config form here,
500 // so we can strip them from the submitted data BEFORE serializing it.
502 'sesskey' => $USER->sesskey
,
503 'instanceid' => $instance->id
,
504 'blockaction' => 'config'
507 // To this data, add anything the page itself needs to display
508 $hiddendata = array_merge($hiddendata, $page->url_get_parameters());
510 if($data = data_submitted()) {
511 $remove = array_keys($hiddendata);
512 foreach($remove as $item) {
515 if(!$blockobject->instance_config_save($data,$pinned)) {
516 error('Error saving block configuration');
518 // And nothing more, continue with displaying the page
521 // We need to show the config screen, so we highjack the display logic and then die
522 $strheading = get_string('blockconfiga', 'moodle', $blocktitle);
523 $page->print_header(get_string('pageheaderconfigablock', 'moodle'), array($strheading => ''));
525 echo '<div class="block-config" id="'.$block->name
.'">'; /// Make CSS easier
527 print_heading($strheading);
528 echo '<form method="post" name="block-config" action="'. $page->url_get_path() .'">';
530 foreach($hiddendata as $name => $val) {
531 echo '<input type="hidden" name="'. $name .'" value="'. $val .'" />';
534 $blockobject->instance_config_print();
538 $CFG->pagepath
= 'blocks/' . $block->name
;
540 die(); // Do not go on with the other page-related stuff
544 if(empty($instance)) {
545 error('Invalid block instance for '.$blockaction);
547 $instance->visible
= ($instance->visible
) ?
0 : 1;
548 if (!empty($pinned)) {
549 update_record('block_pinned', $instance);
551 update_record('block_instance', $instance);
555 if(empty($instance)) {
556 error('Invalid block instance for '. $blockaction);
558 blocks_delete_instance($instance, $pinned);
561 if(empty($instance)) {
562 error('Invalid block instance for '. $blockaction);
565 if($instance->weight
== 0) {
566 // The block is the first one, so a move "up" probably means it changes position
567 // Where is the instance going to be moved?
568 $newpos = $page->blocks_move_position($instance, BLOCK_MOVE_UP
);
569 $newweight = (empty($pageblocks[$newpos]) ?
0 : max(array_keys($pageblocks[$newpos])) +
1);
571 blocks_execute_repositioning($instance, $newpos, $newweight, $pinned);
574 // The block is just moving upwards in the same position.
575 // This configuration will make sure that even if somehow the weights
576 // become not continuous, block move operations will eventually bring
577 // the situation back to normal without printing any warnings.
578 if(!empty($pageblocks[$instance->position
][$instance->weight
- 1])) {
579 $other = $pageblocks[$instance->position
][$instance->weight
- 1];
583 if (!empty($pinned)) {
584 update_record('block_pinned', $other);
586 update_record('block_instance', $other);
590 if (!empty($pinned)) {
591 update_record('block_pinned', $instance);
593 update_record('block_instance', $instance);
598 if(empty($instance)) {
599 error('Invalid block instance for '. $blockaction);
602 if($instance->weight
== max(array_keys($pageblocks[$instance->position
]))) {
603 // The block is the last one, so a move "down" probably means it changes position
604 // Where is the instance going to be moved?
605 $newpos = $page->blocks_move_position($instance, BLOCK_MOVE_DOWN
);
606 $newweight = (empty($pageblocks[$newpos]) ?
0 : max(array_keys($pageblocks[$newpos])) +
1);
608 blocks_execute_repositioning($instance, $newpos, $newweight, $pinned);
611 // The block is just moving downwards in the same position.
612 // This configuration will make sure that even if somehow the weights
613 // become not continuous, block move operations will eventually bring
614 // the situation back to normal without printing any warnings.
615 if(!empty($pageblocks[$instance->position
][$instance->weight +
1])) {
616 $other = $pageblocks[$instance->position
][$instance->weight +
1];
620 if (!empty($pinned)) {
621 update_record('block_pinned', $other);
623 update_record('block_instance', $other);
627 if (!empty($pinned)) {
628 update_record('block_pinned', $instance);
630 update_record('block_instance', $instance);
635 if(empty($instance)) {
636 error('Invalid block instance for '. $blockaction);
639 // Where is the instance going to be moved?
640 $newpos = $page->blocks_move_position($instance, BLOCK_MOVE_LEFT
);
641 $newweight = (empty($pageblocks[$newpos]) ?
0 : max(array_keys($pageblocks[$newpos])) +
1);
643 blocks_execute_repositioning($instance, $newpos, $newweight, $pinned);
646 if(empty($instance)) {
647 error('Invalid block instance for '. $blockaction);
650 // Where is the instance going to be moved?
651 $newpos = $page->blocks_move_position($instance, BLOCK_MOVE_RIGHT
);
652 $newweight = (empty($pageblocks[$newpos]) ?
0 : max(array_keys($pageblocks[$newpos])) +
1);
654 blocks_execute_repositioning($instance, $newpos, $newweight, $pinned);
657 // Add a new instance of this block, if allowed
658 $block = blocks_get_record($blockid);
660 if(empty($block) ||
!$block->visible
) {
661 // Only allow adding if the block exists and is enabled
665 if(!$block->multiple
&& blocks_find_block($blockid, $pageblocks) !== false) {
666 // If no multiples are allowed and we already have one, return now
670 if(!block_method_result($block->name
, 'user_can_addto', $page)) {
671 // If the block doesn't want to be added...
675 $newpos = $page->blocks_default_position();
676 if (!empty($pinned)) {
677 $sql = 'SELECT 1, max(weight) + 1 AS nextfree FROM '. $CFG->prefix
.'block_pinned WHERE '
678 .' pagetype = \''. $page->get_type() .'\' AND position = \''. $newpos .'\'';
680 $sql = 'SELECT 1, max(weight) + 1 AS nextfree FROM '. $CFG->prefix
.'block_instance WHERE pageid = '. $page->get_id()
681 .' AND pagetype = \''. $page->get_type() .'\' AND position = \''. $newpos .'\'';
683 $weight = get_record_sql($sql);
685 $newinstance = new stdClass
;
686 $newinstance->blockid
= $blockid;
687 if (empty($pinned)) {
688 $newinstance->pageid
= $page->get_id();
690 $newinstance->pagetype
= $page->get_type();
691 $newinstance->position
= $newpos;
692 $newinstance->weight
= empty($weight->nextfree
) ?
0 : $weight->nextfree
;
693 $newinstance->visible
= 1;
694 $newinstance->configdata
= '';
695 if (!empty($pinned)) {
696 $newinstance->id
= insert_record('block_pinned', $newinstance);
698 $newinstance->id
= insert_record('block_instance', $newinstance);
701 // If the new instance was created, allow it to do additional setup
702 if($newinstance && ($obj = block_instance($block->name
, $newinstance))) {
703 // Return value ignored
704 $obj->instance_create();
711 // In order to prevent accidental duplicate actions, redirect to a page with a clean url
712 redirect($page->url_get_full());
716 // You can use this to get the blocks to respond to URL actions without much hassle
717 function blocks_execute_url_action(&$PAGE, &$pageblocks,$pinned=false) {
718 $blockaction = optional_param('blockaction', '', PARAM_ALPHA
);
720 if (empty($blockaction) ||
!$PAGE->user_allowed_editing() ||
!confirm_sesskey()) {
724 $instanceid = optional_param('instanceid', 0, PARAM_INT
);
725 $blockid = optional_param('blockid', 0, PARAM_INT
);
727 if (!empty($blockid)) {
728 blocks_execute_action($PAGE, $pageblocks, strtolower($blockaction), $blockid, $pinned);
731 else if (!empty($instanceid)) {
732 $instance = blocks_find_instance($instanceid, $pageblocks);
733 blocks_execute_action($PAGE, $pageblocks, strtolower($blockaction), $instance, $pinned);
737 // This shouldn't be used externally at all, it's here for use by blocks_execute_action()
738 // in order to reduce code repetition.
739 function blocks_execute_repositioning(&$instance, $newpos, $newweight, $pinned=false) {
742 // If it's staying where it is, don't do anything, unless overridden
743 if ($newpos == $instance->position
) {
747 // Close the weight gap we 'll leave behind
748 if (!empty($pinned)) {
749 $sql = 'UPDATE '. $CFG->prefix
.'block_instance SET weight = weight - 1 '.
750 'WHERE pagetype = \''. $instance->pagetype
.
751 '\' AND position = \'' .$instance->position
.
752 '\' AND weight > '. $instance->weight
;
754 $sql = 'UPDATE '. $CFG->prefix
.'block_instance SET weight = weight - 1 '.
755 'WHERE pagetype = \''. $instance->pagetype
.
756 '\' AND pageid = '. $instance->pageid
.
757 ' AND position = \'' .$instance->position
.
758 '\' AND weight > '. $instance->weight
;
760 execute_sql($sql,false);
762 $instance->position
= $newpos;
763 $instance->weight
= $newweight;
765 if (!empty($pinned)) {
766 update_record('block_pinned', $instance);
768 update_record('block_instance', $instance);
774 * Moves a block to the new position (column) and weight (sort order).
775 * @param $instance - The block instance to be moved.
776 * @param $destpos - BLOCK_POS_LEFT or BLOCK_POS_RIGHT. The destination column.
777 * @param $destweight - The destination sort order. If NULL, we add to the end
778 * of the destination column.
779 * @param $pinned - Are we moving pinned blocks? We can only move pinned blocks
780 * to a new position withing the pinned list. Likewise, we
781 * can only moved non-pinned blocks to a new position within
782 * the non-pinned list.
783 * @return boolean (success or failure).
785 function blocks_move_block($page, &$instance, $destpos, $destweight=NULL, $pinned=false) {
789 $blocklist = blocks_get_pinned($page);
791 $blocklist = blocks_get_by_page($page);
794 if ($blocklist[$instance->position
][$instance->weight
]->id
!= $instance->id
) {
795 // The source block instance is not where we think it is.
799 // First we close the gap that will be left behind when we take out the
800 // block from it's current column.
802 $closegapsql = "UPDATE {$CFG->prefix}block_instance
803 SET weight = weight - 1
804 WHERE weight > '$instance->weight'
805 AND position = '$instance->position'
806 AND pagetype = '$instance->pagetype'";
808 $closegapsql = "UPDATE {$CFG->prefix}block_instance
809 SET weight = weight - 1
810 WHERE weight > '$instance->weight'
811 AND position = '$instance->position'
812 AND pagetype = '$instance->pagetype'
813 AND pageid = '$instance->pageid'";
815 if (!execute_sql($closegapsql, false)) {
819 // Now let's make space for the block being moved.
821 $opengapsql = "UPDATE {$CFG->prefix}block_instance
822 SET weight = weight + 1
823 WHERE weight >= '$destweight'
824 AND position = '$destpos'
825 AND pagetype = '$instance->pagetype'";
827 $opengapsql = "UPDATE {$CFG->prefix}block_instance
828 SET weight = weight + 1
829 WHERE weight >= '$destweight'
830 AND position = '$destpos'
831 AND pagetype = '$instance->pagetype'
832 AND pageid = '$instance->pageid'";
834 if (!execute_sql($opengapsql, false)) {
839 $instance->position
= $destpos;
840 $instance->weight
= $destweight;
843 $table = 'block_pinned';
845 $table = 'block_instance';
847 return update_record($table, $instance);
852 * Returns an array consisting of 2 arrays:
853 * 1) Array of pinned blocks for position BLOCK_POS_LEFT
854 * 2) Array of pinned blocks for position BLOCK_POS_RIGHT
856 function blocks_get_pinned($page) {
860 if (method_exists($page,'edit_always')) {
861 if ($page->edit_always()) {
866 $blocks = get_records_select('block_pinned', 'pagetype = \''. $page->get_type() .
867 '\''.(($visible) ?
'AND visible = 1' : ''), 'position, weight');
869 $positions = $page->blocks_get_positions();
872 foreach($positions as $key => $position) {
873 $arr[$position] = array();
880 foreach($blocks as $block) {
881 $block->pinned
= true; // so we know we can't move it.
882 // make up an instanceid if we can..
883 $block->pageid
= $page->get_id();
884 $arr[$block->position
][$block->weight
] = $block;
892 * Similar to blocks_get_by_page(), except that, the array returned includes
893 * pinned blocks as well. Pinned blocks are always appended before normal
896 function blocks_get_by_page_pinned($page) {
897 $pinned = blocks_get_pinned($page);
898 $user = blocks_get_by_page($page);
902 foreach ($pinned as $pos => $arr) {
903 $weights[$pos] = count($arr);
906 foreach ($user as $pos => $blocks) {
907 if (!array_key_exists($pos,$pinned)) {
908 $pinned[$pos] = array();
910 if (!array_key_exists($pos,$weights)) {
913 foreach ($blocks as $block) {
914 $pinned[$pos][$weights[$pos]] = $block;
923 * Returns an array of blocks for the page. Pinned blocks are excluded.
925 function blocks_get_by_page($page) {
926 $blocks = get_records_select('block_instance', "pageid = '". $page->get_id() .
927 "' AND pagetype = '". $page->get_type() ."'", 'position, weight');
929 $positions = $page->blocks_get_positions();
931 foreach($positions as $key => $position) {
932 $arr[$position] = array();
939 foreach($blocks as $block) {
940 $arr[$block->position
][$block->weight
] = $block;
946 //This function prints the block to admin blocks as necessary
947 function blocks_print_adminblock(&$page, &$pageblocks) {
950 $missingblocks = blocks_get_missing($page, $pageblocks);
952 if (!empty($missingblocks)) {
953 $strblocks = '<div class="title"><h2>';
954 $strblocks .= get_string('blocks');
955 $strblocks .= '</h2></div>';
956 $stradd = get_string('add');
957 foreach ($missingblocks as $blockid) {
958 $block = blocks_get_record($blockid);
959 $blockobject = block_instance($block->name
);
960 if ($blockobject === false) {
963 if(!$blockobject->user_can_addto($page)) {
966 $menu[$block->id
] = $blockobject->get_title();
970 $target = $page->url_get_full(array('sesskey' => $USER->sesskey
, 'blockaction' => 'add'));
971 $content = popup_form($target.'&blockid=', $menu, 'add_block', '', $stradd .'...', '', '', true);
972 print_side_block($strblocks, $content, NULL, NULL, NULL, array('class' => 'block_adminblock'));
977 * Delete all the blocks from a particular page.
979 * @param string $pagetype the page type.
980 * @param integer $pageid the page id.
981 * @return success of failure.
983 function blocks_delete_all_on_page($pagetype, $pageid) {
984 if ($instances = get_records_select('block_instance', "pageid = $pageid AND pagetype = '$pagetype'")) {
985 foreach ($instances as $instance) {
986 delete_context(CONTEXT_BLOCK
, $instance->id
); // Ingore any failures here.
989 return delete_records('block_instance', 'pageid', $pageid, 'pagetype', $pagetype);
992 // Dispite what this function is called, it seems to be mostly used to populate
993 // the default blocks when a new course (or whatever) is created.
994 function blocks_repopulate_page($page) {
997 $allblocks = blocks_get_record();
999 if(empty($allblocks)) {
1000 error('Could not retrieve blocks from the database');
1003 // Assemble the information to correlate block names to ids
1004 $idforname = array();
1005 foreach($allblocks as $block) {
1006 $idforname[$block->name
] = $block->id
;
1009 /// If the site override has been defined, it is the only valid one.
1010 if (!empty($CFG->defaultblocks_override
)) {
1011 $blocknames = $CFG->defaultblocks_override
;
1014 $blocknames = $page->blocks_get_default();
1017 $positions = $page->blocks_get_positions();
1018 $posblocks = explode(':', $blocknames);
1020 // Now one array holds the names of the positions, and the other one holds the blocks
1021 // that are going to go in each position. Luckily for us, both arrays are numerically
1022 // indexed and the indexes match, so we can work straight away... but CAREFULLY!
1024 // Ready to start creating block instances, but first drop any existing ones
1025 blocks_delete_all_on_page($page->get_type(), $page->get_id());
1027 // Here we slyly count $posblocks and NOT $positions. This can actually make a difference
1028 // if the textual representation has undefined slots in the end. So we only work with as many
1029 // positions were retrieved, not with all the page says it has available.
1030 $numpositions = count($posblocks);
1031 for($i = 0; $i < $numpositions; ++
$i) {
1032 $position = $positions[$i];
1033 $blocknames = explode(',', $posblocks[$i]);
1035 foreach($blocknames as $blockname) {
1036 $newinstance = new stdClass
;
1037 $newinstance->blockid
= $idforname[$blockname];
1038 $newinstance->pageid
= $page->get_id();
1039 $newinstance->pagetype
= $page->get_type();
1040 $newinstance->position
= $position;
1041 $newinstance->weight
= $weight;
1042 $newinstance->visible
= 1;
1043 $newinstance->configdata
= '';
1045 if(!empty($newinstance->blockid
)) {
1046 // Only add block if it was recognized
1047 insert_record('block_instance', $newinstance);
1056 function upgrade_blocks_db($continueto) {
1057 /// This function upgrades the blocks tables, if necessary
1058 /// It's called from admin/index.php
1062 require_once ($CFG->dirroot
.'/blocks/version.php'); // Get code versions
1064 if (empty($CFG->blocks_version
)) { // Blocks have never been installed.
1065 $strdatabaseupgrades = get_string('databaseupgrades');
1066 print_header($strdatabaseupgrades, $strdatabaseupgrades,
1067 build_navigation(array(array('name' => $strdatabaseupgrades, 'link' => null, 'type' => 'misc'))), '',
1068 upgrade_get_javascript(), false, ' ', ' ');
1070 upgrade_log_start();
1071 print_heading('blocks');
1074 /// Both old .sql files and new install.xml are supported
1075 /// but we priorize install.xml (XMLDB) if present
1077 if (file_exists($CFG->dirroot
. '/blocks/db/install.xml')) {
1078 $status = install_from_xmldb_file($CFG->dirroot
. '/blocks/db/install.xml'); //New method
1079 } else if (file_exists($CFG->dirroot
. '/blocks/db/' . $CFG->dbtype
. '.sql')) {
1080 $status = modify_database($CFG->dirroot
. '/blocks/db/' . $CFG->dbtype
. '.sql'); //Old method
1085 if (set_config('blocks_version', $blocks_version)) {
1086 notify(get_string('databasesuccess'), 'notifysuccess');
1087 notify(get_string('databaseupgradeblocks', '', $blocks_version), 'notifysuccess');
1088 print_continue($continueto);
1089 print_footer('none');
1092 error('Upgrade of blocks system failed! (Could not update version in config table)');
1095 error('Blocks tables could NOT be set up successfully!');
1099 /// Upgrading code starts here
1100 $oldupgrade = false;
1101 $newupgrade = false;
1102 if (is_readable($CFG->dirroot
. '/blocks/db/' . $CFG->dbtype
. '.php')) {
1103 include_once($CFG->dirroot
. '/blocks/db/' . $CFG->dbtype
. '.php'); // defines old upgrading function
1106 if (is_readable($CFG->dirroot
. '/blocks/db/upgrade.php')) {
1107 include_once($CFG->dirroot
. '/blocks/db/upgrade.php'); // defines new upgrading function
1111 if ($blocks_version > $CFG->blocks_version
) { // Upgrade tables
1112 $strdatabaseupgrades = get_string('databaseupgrades');
1113 print_header($strdatabaseupgrades, $strdatabaseupgrades,
1114 build_navigation(array(array('name' => $strdatabaseupgrades, 'link' => null, 'type' => 'misc'))), '', upgrade_get_javascript());
1116 upgrade_log_start();
1117 print_heading('blocks');
1119 /// Run de old and new upgrade functions for the module
1120 $oldupgrade_function = 'blocks_upgrade';
1121 $newupgrade_function = 'xmldb_blocks_upgrade';
1123 /// First, the old function if exists
1124 $oldupgrade_status = true;
1125 if ($oldupgrade && function_exists($oldupgrade_function)) {
1127 $oldupgrade_status = $oldupgrade_function($CFG->blocks_version
);
1128 } else if ($oldupgrade) {
1129 notify ('Upgrade function ' . $oldupgrade_function . ' was not available in ' .
1130 '/blocks/db/' . $CFG->dbtype
. '.php');
1133 /// Then, the new function if exists and the old one was ok
1134 $newupgrade_status = true;
1135 if ($newupgrade && function_exists($newupgrade_function) && $oldupgrade_status) {
1137 $newupgrade_status = $newupgrade_function($CFG->blocks_version
);
1138 } else if ($newupgrade) {
1139 notify ('Upgrade function ' . $newupgrade_function . ' was not available in ' .
1140 '/blocks/db/upgrade.php');
1144 /// Now analyze upgrade results
1145 if ($oldupgrade_status && $newupgrade_status) { // No upgrading failed
1146 if (set_config('blocks_version', $blocks_version)) {
1147 notify(get_string('databasesuccess'), 'notifysuccess');
1148 notify(get_string('databaseupgradeblocks', '', $blocks_version), 'notifysuccess');
1149 print_continue($continueto);
1150 print_footer('none');
1153 error('Upgrade of blocks system failed! (Could not update version in config table)');
1156 error('Upgrade failed! See blocks/version.php');
1159 } else if ($blocks_version < $CFG->blocks_version
) {
1160 upgrade_log_start();
1161 notify('WARNING!!! The Blocks version you are using is OLDER than the version that made these databases!');
1163 upgrade_log_finish();
1166 //This function finds all available blocks and install them
1167 //into blocks table or do all the upgrade process if newer
1168 function upgrade_blocks_plugins($continueto) {
1172 $blocktitles = array();
1173 $invalidblocks = array();
1174 $validblocks = array();
1177 //Count the number of blocks in db
1178 $blockcount = count_records('block');
1179 //If there isn't records. This is the first install, so I remember it
1180 if ($blockcount == 0) {
1181 $first_install = true;
1183 $first_install = false;
1188 if (!$blocks = get_list_of_plugins('blocks', 'db') ) {
1189 error('No blocks installed!');
1192 include_once($CFG->dirroot
.'/blocks/moodleblock.class.php');
1193 if(!class_exists('block_base')) {
1194 error('Class block_base is not defined or file not found for /blocks/moodleblock.class.php');
1197 foreach ($blocks as $blockname) {
1199 if ($blockname == 'NEWBLOCK') { // Someone has unzipped the template, ignore it
1203 if(!block_is_compatible($blockname)) {
1204 // This is an old-style block
1205 //$notices[] = 'Block '. $blockname .' is not compatible with the current version of Mooodle and needs to be updated by a programmer.';
1206 $invalidblocks[] = $blockname;
1210 $fullblock = $CFG->dirroot
.'/blocks/'. $blockname;
1212 if ( is_readable($fullblock.'/block_'.$blockname.'.php')) {
1213 include_once($fullblock.'/block_'.$blockname.'.php');
1215 $notices[] = 'Block '. $blockname .': '. $fullblock .'/block_'. $blockname .'.php was not readable';
1219 $oldupgrade = false;
1220 $newupgrade = false;
1221 if ( @is_dir
($fullblock .'/db/')) {
1222 if ( @is_readable
($fullblock .'/db/'. $CFG->dbtype
.'.php')) {
1223 include_once($fullblock .'/db/'. $CFG->dbtype
.'.php'); // defines old upgrading function
1226 if ( @is_readable
($fullblock .'/db/upgrade.php')) {
1227 include_once($fullblock .'/db/upgrade.php'); // defines new upgrading function
1232 $classname = 'block_'.$blockname;
1233 if(!class_exists($classname)) {
1234 $notices[] = 'Block '. $blockname .': '. $classname .' not implemented';
1238 // Here is the place to see if the block implements a constructor (old style),
1239 // an init() function (new style) or nothing at all (error time).
1241 $constructor = get_class_constructor($classname);
1242 if(empty($constructor)) {
1244 $notices[] = 'Block '. $blockname .': class does not have a constructor';
1245 $invalidblocks[] = $blockname;
1249 $block = new stdClass
; // This may be used to update the db below
1250 $blockobj = new $classname; // This is what we 'll be testing
1252 // Inherits from block_base?
1253 if(!is_subclass_of($blockobj, 'block_base')) {
1254 $notices[] = 'Block '. $blockname .': class does not inherit from block_base';
1258 // OK, it's as we all hoped. For further tests, the object will do them itself.
1259 if(!$blockobj->_self_test()) {
1260 $notices[] = 'Block '. $blockname .': self test failed';
1263 $block->version
= $blockobj->get_version();
1265 if (!isset($block->version
)) {
1266 $notices[] = 'Block '. $blockname .': has no version support. It must be updated by a programmer.';
1270 $block->name
= $blockname; // The name MUST match the directory
1271 $blocktitle = $blockobj->get_title();
1273 if ($currblock = get_record('block', 'name', $block->name
)) {
1274 if ($currblock->version
== $block->version
) {
1276 } else if ($currblock->version
< $block->version
) {
1277 if (empty($updated_blocks)) {
1278 $strblocksetup = get_string('blocksetup');
1279 print_header($strblocksetup, $strblocksetup,
1280 build_navigation(array(array('name' => $strblocksetup, 'link' => null, 'type' => 'misc'))), '',
1281 upgrade_get_javascript(), false, ' ', ' ');
1283 $updated_blocks = true;
1284 upgrade_log_start();
1285 print_heading('New version of '.$blocktitle.' ('.$block->name
.') exists');
1286 @set_time_limit
(0); // To allow slow databases to complete the long SQL
1288 /// Run de old and new upgrade functions for the module
1289 $oldupgrade_function = $block->name
.'_upgrade';
1290 $newupgrade_function = 'xmldb_block_' . $block->name
.'_upgrade';
1292 /// First, the old function if exists
1293 $oldupgrade_status = true;
1294 if ($oldupgrade && function_exists($oldupgrade_function)) {
1296 $oldupgrade_status = $oldupgrade_function($currblock->version
, $block);
1297 } else if ($oldupgrade) {
1298 notify ('Upgrade function ' . $oldupgrade_function . ' was not available in ' .
1299 $fullblock . '/db/' . $CFG->dbtype
. '.php');
1302 /// Then, the new function if exists and the old one was ok
1303 $newupgrade_status = true;
1304 if ($newupgrade && function_exists($newupgrade_function) && $oldupgrade_status) {
1306 $newupgrade_status = $newupgrade_function($currblock->version
, $block);
1307 } else if ($newupgrade) {
1308 notify ('Upgrade function ' . $newupgrade_function . ' was not available in ' .
1309 $fullblock . '/db/upgrade.php');
1313 /// Now analyze upgrade results
1314 if ($oldupgrade_status && $newupgrade_status) { // No upgrading failed
1316 // Set the block cron on upgrade
1317 $block->cron
= !empty($blockobj->cron
) ?
$blockobj->cron
: 0;
1319 // OK so far, now update the block record
1320 $block->id
= $currblock->id
;
1321 if (! update_record('block', $block)) {
1322 error('Could not update block '. $block->name
.' record in block table!');
1324 $component = 'block/'.$block->name
;
1325 if (!update_capabilities($component)) {
1326 error('Could not update '.$block->name
.' capabilities!');
1329 events_update_definition($component);
1330 notify(get_string('blocksuccess', '', $blocktitle), 'notifysuccess');
1332 notify('Upgrading block '. $block->name
.' from '. $currblock->version
.' to '. $block->version
.' FAILED!');
1336 upgrade_log_start();
1337 error('Version mismatch: block '. $block->name
.' can\'t downgrade '. $currblock->version
.' -> '. $block->version
.'!');
1340 } else { // block not installed yet, so install it
1342 // If it allows multiples, start with it enabled
1343 if ($blockobj->instance_allow_multiple()) {
1344 $block->multiple
= 1;
1347 // Set the block cron on install
1348 $block->cron
= !empty($blockobj->cron
) ?
$blockobj->cron
: 0;
1350 // [pj] Normally this would be inline in the if, but we need to
1351 // check for NULL (necessary for 4.0.5 <= PHP < 4.2.0)
1352 $conflictblock = array_search($blocktitle, $blocktitles);
1353 if($conflictblock !== false && $conflictblock !== NULL) {
1354 // Duplicate block titles are not allowed, they confuse people
1355 // AND PHP's associative arrays ;)
1356 error('<strong>Naming conflict</strong>: block <strong>'.$block->name
.'</strong> has the same title with an existing block, <strong>'.$conflictblock.'</strong>!');
1358 if (empty($updated_blocks)) {
1359 $strblocksetup = get_string('blocksetup');
1360 print_header($strblocksetup, $strblocksetup,
1361 build_navigation(array(array('name' => $strblocksetup, 'link' => null, 'type' => 'misc'))), '',
1362 upgrade_get_javascript(), false, ' ', ' ');
1364 $updated_blocks = true;
1365 upgrade_log_start();
1366 print_heading($block->name
);
1368 @set_time_limit
(0); // To allow slow databases to complete the long SQL
1370 /// Both old .sql files and new install.xml are supported
1371 /// but we priorize install.xml (XMLDB) if present
1373 if (file_exists($fullblock . '/db/install.xml')) {
1374 $status = install_from_xmldb_file($fullblock . '/db/install.xml'); //New method
1375 } else if (file_exists($fullblock .'/db/'. $CFG->dbtype
.'.sql')) {
1376 $status = modify_database($fullblock .'/db/'. $CFG->dbtype
.'.sql'); //Old method
1383 if ($block->id
= insert_record('block', $block)) {
1384 $blockobj->after_install();
1385 $component = 'block/'.$block->name
;
1386 if (!update_capabilities($component)) {
1387 notify('Could not set up '.$block->name
.' capabilities!');
1390 events_update_definition($component);
1391 notify(get_string('blocksuccess', '', $blocktitle), 'notifysuccess');
1394 error($block->name
.' block could not be added to the block list!');
1397 error('Block '. $block->name
.' tables could NOT be set up successfully!');
1401 $blocktitles[$block->name
] = $blocktitle;
1404 if(!empty($notices)) {
1405 upgrade_log_start();
1406 foreach($notices as $notice) {
1411 // Finally, if we are in the first_install of BLOCKS (this means that we are
1412 // upgrading from Moodle < 1.3), put blocks in all existing courses.
1413 if ($first_install) {
1414 upgrade_log_start();
1415 //Iterate over each course
1416 if ($courses = get_records('course')) {
1417 foreach ($courses as $course) {
1418 $page = page_create_object(PAGE_COURSE_VIEW
, $course->id
);
1419 blocks_repopulate_page($page);
1424 if (!empty($CFG->siteblocksadded
)) { /// This is a once-off hack to make a proper upgrade
1425 upgrade_log_start();
1426 $page = page_create_object(PAGE_COURSE_VIEW
, SITEID
);
1427 blocks_repopulate_page($page);
1428 delete_records('config', 'name', 'siteblocksadded');
1431 upgrade_log_finish();
1433 if (!empty($updated_blocks)) {
1434 print_continue($continueto);
1435 print_footer('none');