"MDL-16911, separate listing and search in youtube plugin"
[moodle.git] / lib / blocklib.php
CommitLineData
dcb1bd3c 1<?php //$Id$
0f3fe4b6 2
3//This library includes all the necessary stuff to use blocks in course pages
4
0f3fe4b6 5define('BLOCK_MOVE_LEFT', 0x01);
6define('BLOCK_MOVE_RIGHT', 0x02);
7define('BLOCK_MOVE_UP', 0x04);
8define('BLOCK_MOVE_DOWN', 0x08);
9b4b78fd 9define('BLOCK_CONFIGURE', 0x10);
0f3fe4b6 10
9b4b78fd 11define('BLOCK_POS_LEFT', 'l');
12define('BLOCK_POS_RIGHT', 'r');
0e9af917 13
ee6055eb 14define('BLOCKS_PINNED_TRUE',0);
15define('BLOCKS_PINNED_FALSE',1);
16define('BLOCKS_PINNED_BOTH',2);
17
f032aa7a 18require_once($CFG->libdir.'/pagelib.php');
0be6f678 19require_once($CFG->dirroot.'/course/lib.php'); // needed to solve all those: Call to undefined function: print_recent_activity() when adding Recent Activity
61abc65b 20
0f3fe4b6 21//This function retrieves a method-defined property of a class WITHOUT instantiating an object
11306331 22function block_method_result($blockname, $method, $param = NULL) {
0f3fe4b6 23 if(!block_load_class($blockname)) {
24 return NULL;
25 }
11306331 26 return call_user_func(array('block_'.$blockname, $method), $param);
0f3fe4b6 27}
28
29//This function creates a new object of the specified block class
9b4b78fd 30function block_instance($blockname, $instance = NULL) {
0f3fe4b6 31 if(!block_load_class($blockname)) {
32 return false;
33 }
e89d741a 34 $classname = 'block_'.$blockname;
f032aa7a 35 $retval = new $classname;
9b4b78fd 36 if($instance !== NULL) {
1345403a 37 $retval->_load_instance($instance);
9b4b78fd 38 }
39 return $retval;
0f3fe4b6 40}
41
42//This function loads the necessary class files for a block
43//Whenever you want to load a block, use this first
44function block_load_class($blockname) {
45 global $CFG;
46
a9033ad5 47 if(empty($blockname)) {
c7a9e293 48 return false;
49 }
50
e89d741a 51 $classname = 'block_'.$blockname;
a9033ad5 52
53 if(class_exists($classname)) {
54 return true;
55 }
56
57 require_once($CFG->dirroot.'/blocks/moodleblock.class.php');
e9a20759 58 @include_once($CFG->dirroot.'/blocks/'.$blockname.'/block_'.$blockname.'.php'); // do not throw errors if block code not present
0f3fe4b6 59
0f3fe4b6 60 return class_exists($classname);
61}
62
c8e0b579 63// This function returns an array with the IDs of any blocks that you can add to your page.
64// Parameters are passed by reference for speed; they are not modified at all.
65function blocks_get_missing(&$page, &$pageblocks) {
f032aa7a 66
67 $missingblocks = array();
68 $allblocks = blocks_get_record();
69 $pageformat = $page->get_format_name();
70
71 if(!empty($allblocks)) {
72 foreach($allblocks as $block) {
73 if($block->visible && (!blocks_find_block($block->id, $pageblocks) || $block->multiple)) {
74 // And if it's applicable for display in this format...
5bbbe0be 75 if(blocks_name_allowed_in_format($block->name, $pageformat)) {
8a47e075 76 // ...add it to the missing blocks
f032aa7a 77 $missingblocks[] = $block->id;
78 }
79 }
80 }
81 }
82 return $missingblocks;
83}
84
85function blocks_remove_inappropriate($page) {
86 $pageblocks = blocks_get_by_page($page);
87
88 if(empty($pageblocks)) {
89 return;
90 }
91
92 if(($pageformat = $page->get_format_name()) == NULL) {
93 return;
94 }
95
96 foreach($pageblocks as $position) {
97 foreach($position as $instance) {
98 $block = blocks_get_record($instance->blockid);
5bbbe0be 99 if(!blocks_name_allowed_in_format($block->name, $pageformat)) {
8a47e075 100 blocks_delete_instance($instance);
f032aa7a 101 }
102 }
103 }
104}
105
5bbbe0be 106function blocks_name_allowed_in_format($name, $pageformat) {
afd1ec02 107
5bbbe0be 108 $accept = NULL;
109 $depth = -1;
c5d883fc 110 if ($formats = block_method_result($name, 'applicable_formats')) {
1bece917 111 foreach($formats as $format => $allowed) {
112 $thisformat = '^'.str_replace('*', '[^-]*', $format).'.*$';
113 if(ereg($thisformat, $pageformat)) {
114 if(($scount = substr_count($format, '-')) > $depth) {
115 $depth = $scount;
116 $accept = $allowed;
c5d883fc 117 }
118 }
5bbbe0be 119 }
120 }
121 if($accept === NULL) {
122 $accept = !empty($formats['all']);
123 }
124 return $accept;
125}
126
0d6b9d4f 127function blocks_delete_instance($instance,$pinned=false) {
58ff964f 128 global $DB;
f032aa7a 129
e9a20759 130 // Get the block object and call instance_delete() if possible
7fa944ca 131 if($record = blocks_get_record($instance->blockid)) {
132 if($obj = block_instance($record->name, $instance)) {
e9a20759 133 // Return value ignored
134 $obj->instance_delete();
135 }
b33dd23a 136 }
137
0d6b9d4f 138 if (!empty($pinned)) {
58ff964f 139 $DB->delete_records('block_pinned', array('id'=>$instance->id));
0d6b9d4f 140 // And now, decrement the weight of all blocks after this one
58ff964f 141 $sql = "UPDATE {block_pinned}
142 SET weight = weight - 1
143 WHERE pagetype = ? AND position = ? AND weight > ?";
144 $params = array($instance->pagetype, $instance->position, $instance->weight);
145 $DB->execute($sql, $params);
0d6b9d4f 146 } else {
147 // Now kill the db record;
58ff964f 148 $DB->delete_records('block_instance', array('id'=>$instance->id));
19f5b2db 149 delete_context(CONTEXT_BLOCK, $instance->id);
0d6b9d4f 150 // And now, decrement the weight of all blocks after this one
58ff964f 151 $sql = "UPDATE {block_instance}
152 SET weight = weight - 1
153 WHERE pagetype = ? AND pageid = ?
154 AND position = ? AND weight > ?";
155 $params = array($instance->pagetype, $instance->pageid, $instance->position, $instance->weight);
156 $DB->execute($sql, $params);
0d6b9d4f 157 }
2e477369 158 return true;
f032aa7a 159}
160
c8e0b579 161// Accepts an array of block instances and checks to see if any of them have content to display
162// (causing them to calculate their content in the process). Returns true or false. Parameter passed
163// by reference for speed; the array is actually not modified.
dffd4bb9 164function blocks_have_content(&$pageblocks, $position) {
0d6b9d4f 165
166 if (empty($pageblocks) || !is_array($pageblocks) || !array_key_exists($position,$pageblocks)) {
167 return false;
168 }
66c7e47b 169 // use a for() loop to get references to the array elements
170 // foreach() cannot fetch references in PHP v4.x
171 for ($n=0; $n<count($pageblocks[$position]);$n++) {
172 $instance = &$pageblocks[$position][$n];
6b726eb4 173 if (empty($instance->visible)) {
7933cc6b 174 continue;
175 }
3ef642d9 176 if(!$record = blocks_get_record($instance->blockid)) {
7933cc6b 177 continue;
178 }
3ef642d9 179 if(!$obj = block_instance($record->name, $instance)) {
9b4b78fd 180 continue;
181 }
3ef642d9 182 if(!$obj->is_empty()) {
afd1ec02 183 // cache rec and obj
66c7e47b 184 // for blocks_print_group()
b1a308be 185 $instance->rec = $record;
afd1ec02 186 $instance->obj = $obj;
3ef642d9 187 return true;
0f3fe4b6 188 }
189 }
9b4b78fd 190
0f3fe4b6 191 return false;
192}
193
c8e0b579 194// This function prints one group of blocks in a page
195// Parameters passed by reference for speed; they are not modified.
66492322 196function blocks_print_group(&$page, &$pageblocks, $position) {
6ad71d66 197 global $COURSE, $CFG, $USER;
66492322 198
6b726eb4 199 if (empty($pageblocks[$position])) {
200 $groupblocks = array();
b35fc182 201 $maxweight = 0;
6b726eb4 202 } else {
203 $groupblocks = $pageblocks[$position];
204 $maxweight = max(array_keys($groupblocks));
9b4b78fd 205 }
3cdc4597 206
6b726eb4 207
208 foreach ($groupblocks as $instance) {
4374ee2c 209 if (!empty($instance->pinned)) {
210 $maxweight--;
211 }
212 }
0f3fe4b6 213
f032aa7a 214 $isediting = $page->user_is_editing();
6b726eb4 215
216
217 foreach($groupblocks as $instance) {
218
afd1ec02 219
66c7e47b 220 // $instance may have ->rec and ->obj
221 // cached from when we walked $pageblocks
222 // in blocks_have_content()
223 if (empty($instance->rec)) {
6b726eb4 224 if (empty($instance->blockid)) {
225 continue; // Can't do anything
226 }
66c7e47b 227 $block = blocks_get_record($instance->blockid);
228 } else {
229 $block = $instance->rec;
230 }
f809df70 231
232 if (empty($block)) {
233 // Block doesn't exist! We should delete this instance!
234 continue;
235 }
236
6b726eb4 237 if (empty($block->visible)) {
9b4b78fd 238 // Disabled by the admin
239 continue;
240 }
afd1ec02 241
66c7e47b 242 if (empty($instance->obj)) {
243 if (!$obj = block_instance($block->name, $instance)) {
244 // Invalid block
245 continue;
246 }
247 } else {
248 $obj = $instance->obj;
ab0e4dd4 249 }
0f3fe4b6 250
4374ee2c 251 $editalways = $page->edit_always();
0d6b9d4f 252
6b726eb4 253
0d6b9d4f 254 if (($isediting && empty($instance->pinned)) || !empty($editalways)) {
9b4b78fd 255 $options = 0;
f032aa7a 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() );
1345403a 268 $obj->_add_edit_controls($options);
9b4b78fd 269 }
0f3fe4b6 270
0a0bb380 271 if (!$instance->visible && empty($COURSE->javascriptportal)) {
272 if ($isediting) {
1345403a 273 $obj->_print_shadow();
0f3fe4b6 274 }
0a0bb380 275 } else {
4a1a14c9 276 global $COURSE;
d23157d8 277 if(!empty($COURSE->javascriptportal)) {
278 $COURSE->javascriptportal->currentblocksection = $position;
279 }
1345403a 280 $obj->_print_block();
9b4b78fd 281 }
d23157d8 282 if (!empty($COURSE->javascriptportal)
283 && (empty($instance->pinned) || !$instance->pinned)) {
afd1ec02 284 $COURSE->javascriptportal->block_add('inst'.$instance->id, !$instance->visible);
d23157d8 285 }
286 } // End foreach
287
282c1695 288 // Check if
289 // we are on the default position/side AND
290 // we're editing the page AND
291 // (
292 // we have the capability to manage blocks OR
293 // we are in myMoodle page AND have the capibility to manage myMoodle blocks
294 // )
6ad71d66 295
296 // for constant PAGE_MY_MOODLE
297 include_once($CFG->dirroot.'/my/pagelib.php');
afd1ec02 298
6ad71d66 299 $coursecontext = get_context_instance(CONTEXT_COURSE, $COURSE->id);
300 $myownblogpage = (isset($page->filtertype) && isset($page->filterselect) && $page->type=='blog-view' && $page->filtertype=='user' && $page->filterselect == $USER->id);
afd1ec02 301
6ad71d66 302 $managecourseblocks = has_capability('moodle/site:manageblocks', $coursecontext);
303 $editmymoodle = $page->type == PAGE_MY_MOODLE && has_capability('moodle/my:manageblocks', $coursecontext);
afd1ec02 304
0be6f678 305 if ($page->blocks_default_position() == $position &&
306 $page->user_is_editing() &&
ee1efe0b 307 ($managecourseblocks || $editmymoodle || $myownblogpage || defined('ADMIN_STICKYBLOCKS'))) {
6ad71d66 308
66492322 309 blocks_print_adminblock($page, $pageblocks);
310 }
0f3fe4b6 311}
312
c8e0b579 313// This iterates over an array of blocks and calculates the preferred width
314// Parameter passed by reference for speed; it's not modified.
315function blocks_preferred_width(&$instances) {
0f3fe4b6 316 $width = 0;
317
9b4b78fd 318 if(empty($instances) || !is_array($instances)) {
0f3fe4b6 319 return 0;
320 }
ff6191b7 321
322 $blocks = blocks_get_record();
323
9b4b78fd 324 foreach($instances as $instance) {
325 if(!$instance->visible) {
fe78a3dc 326 continue;
0c9c6363 327 }
ff6191b7 328
f809df70 329 if (!array_key_exists($instance->blockid, $blocks)) {
330 // Block doesn't exist! We should delete this instance!
331 continue;
332 }
333
ff6191b7 334 if(!$blocks[$instance->blockid]->visible) {
9b687320 335 continue;
336 }
ff6191b7 337 $pref = block_method_result($blocks[$instance->blockid]->name, 'preferred_width');
9b4b78fd 338 if($pref === NULL) {
339 continue;
340 }
341 if($pref > $width) {
342 $width = $pref;
0f3fe4b6 343 }
344 }
345 return $width;
346}
347
9b4b78fd 348function blocks_get_record($blockid = NULL, $invalidate = false) {
58ff964f 349 global $DB;
350
9b4b78fd 351 static $cache = NULL;
0f3fe4b6 352
9b4b78fd 353 if($invalidate || empty($cache)) {
58ff964f 354 $cache = $DB->get_records('block');
9b4b78fd 355 }
0f3fe4b6 356
9b4b78fd 357 if($blockid === NULL) {
358 return $cache;
359 }
0f3fe4b6 360
9b4b78fd 361 return (isset($cache[$blockid])? $cache[$blockid] : false);
362}
363
364function blocks_find_block($blockid, $blocksarray) {
0d6b9d4f 365 if (empty($blocksarray)) {
366 return false;
367 }
9b4b78fd 368 foreach($blocksarray as $blockgroup) {
0d6b9d4f 369 if (empty($blockgroup)) {
370 continue;
371 }
9b4b78fd 372 foreach($blockgroup as $instance) {
373 if($instance->blockid == $blockid) {
374 return $instance;
375 }
376 }
377 }
378 return false;
379}
380
381function blocks_find_instance($instanceid, $blocksarray) {
382 foreach($blocksarray as $subarray) {
383 foreach($subarray as $instance) {
384 if($instance->id == $instanceid) {
385 return $instance;
386 }
387 }
388 }
389 return false;
390}
391
ec79d3e4 392// Simple entry point for anyone that wants to use blocks
ee6055eb 393function blocks_setup(&$PAGE,$pinned=BLOCKS_PINNED_FALSE) {
394 switch ($pinned) {
395 case BLOCKS_PINNED_TRUE:
396 $pageblocks = blocks_get_pinned($PAGE);
397 break;
398 case BLOCKS_PINNED_BOTH:
399 $pageblocks = blocks_get_by_page_pinned($PAGE);
400 break;
401 case BLOCKS_PINNED_FALSE:
402 default:
403 $pageblocks = blocks_get_by_page($PAGE);
404 break;
405 }
406 blocks_execute_url_action($PAGE, $pageblocks,($pinned==BLOCKS_PINNED_TRUE));
ec79d3e4 407 return $pageblocks;
408}
409
b1631fef 410function blocks_execute_action($page, &$pageblocks, $blockaction, $instanceorid, $pinned=false, $redirect=true) {
58ff964f 411 global $CFG, $USER, $DB;
9b4b78fd 412
a9c75a9c 413 if (is_int($instanceorid)) {
9b4b78fd 414 $blockid = $instanceorid;
a9c75a9c 415 } else if (is_object($instanceorid)) {
9b4b78fd 416 $instance = $instanceorid;
417 }
0f3fe4b6 418
419 switch($blockaction) {
9b4b78fd 420 case 'config':
9b4b78fd 421 $block = blocks_get_record($instance->blockid);
e82d6cac 422 // Hacky hacky tricky stuff to get the original human readable block title,
423 // even if the block has configured its title to be something else.
afd1ec02 424 // Create the object WITHOUT instance data.
e82d6cac 425 $blockobject = block_instance($block->name);
9b4b78fd 426 if ($blockobject === false) {
11306331 427 break;
428 }
afd1ec02 429
11306331 430 // First of all check to see if the block wants to be edited
431 if(!$blockobject->user_can_edit()) {
432 break;
9b4b78fd 433 }
11306331 434
e82d6cac 435 // Now get the title and AFTER that load up the instance
436 $blocktitle = $blockobject->get_title();
437 $blockobject->_load_instance($instance);
afd1ec02 438
27ec21a0 439 // Define the data we're going to silently include in the instance config form here,
9b4b78fd 440 // so we can strip them from the submitted data BEFORE serializing it.
441 $hiddendata = array(
19f5b2db 442 'sesskey' => sesskey(),
9b4b78fd 443 'instanceid' => $instance->id,
444 'blockaction' => 'config'
445 );
f032aa7a 446
447 // To this data, add anything the page itself needs to display
448 $hiddendata = array_merge($hiddendata, $page->url_get_parameters());
9b4b78fd 449
294ce987 450 if ($data = data_submitted()) {
9b4b78fd 451 $remove = array_keys($hiddendata);
452 foreach($remove as $item) {
453 unset($data->$item);
0f3fe4b6 454 }
58ff964f 455 if(!$blockobject->instance_config_save($data, $pinned)) {
e49ef64a 456 print_error('cannotsaveblock');
0f3fe4b6 457 }
9b4b78fd 458 // And nothing more, continue with displaying the page
0f3fe4b6 459 }
9b4b78fd 460 else {
f032aa7a 461 // We need to show the config screen, so we highjack the display logic and then die
e82d6cac 462 $strheading = get_string('blockconfiga', 'moodle', $blocktitle);
edb42f09 463 $page->print_header(get_string('pageheaderconfigablock', 'moodle'), array($strheading => ''));
b9709905 464
465 echo '<div class="block-config" id="'.$block->name.'">'; /// Make CSS easier
0be6f678 466
edb42f09 467 print_heading($strheading);
f359b612 468 echo '<form method="post" name="block-config" action="'. $page->url_get_path() .'">';
9b4b78fd 469 echo '<p>';
470 foreach($hiddendata as $name => $val) {
27ec21a0 471 echo '<input type="hidden" name="'. $name .'" value="'. $val .'" />';
0f3fe4b6 472 }
9b4b78fd 473 echo '</p>';
474 $blockobject->instance_config_print();
475 echo '</form>';
b9709905 476
477 echo '</div>';
a2c28054 478 $CFG->pagepath = 'blocks/' . $block->name;
9b4b78fd 479 print_footer();
f032aa7a 480 die(); // Do not go on with the other page-related stuff
0f3fe4b6 481 }
482 break;
9b4b78fd 483 case 'toggle':
484 if(empty($instance)) {
e49ef64a 485 print_error('invalidblockinstance', '', '', $blockaction);
0f3fe4b6 486 }
9b4b78fd 487 $instance->visible = ($instance->visible) ? 0 : 1;
0d6b9d4f 488 if (!empty($pinned)) {
58ff964f 489 $DB->update_record('block_pinned', $instance);
0d6b9d4f 490 } else {
58ff964f 491 $DB->update_record('block_instance', $instance);
0d6b9d4f 492 }
9b4b78fd 493 break;
494 case 'delete':
495 if(empty($instance)) {
e49ef64a 496 print_error('invalidblockinstance', '', '', $blockaction);
0f3fe4b6 497 }
0d6b9d4f 498 blocks_delete_instance($instance, $pinned);
0f3fe4b6 499 break;
500 case 'moveup':
9b4b78fd 501 if(empty($instance)) {
e49ef64a 502 print_error('invalidblockinstance', '', '', $blockaction);
9b4b78fd 503 }
f032aa7a 504
505 if($instance->weight == 0) {
506 // The block is the first one, so a move "up" probably means it changes position
507 // Where is the instance going to be moved?
508 $newpos = $page->blocks_move_position($instance, BLOCK_MOVE_UP);
6b853ff4 509 $newweight = (empty($pageblocks[$newpos]) ? 0 : max(array_keys($pageblocks[$newpos])) + 1);
f032aa7a 510
0d6b9d4f 511 blocks_execute_repositioning($instance, $newpos, $newweight, $pinned);
89a5baab 512 }
f032aa7a 513 else {
514 // The block is just moving upwards in the same position.
515 // This configuration will make sure that even if somehow the weights
516 // become not continuous, block move operations will eventually bring
517 // the situation back to normal without printing any warnings.
518 if(!empty($pageblocks[$instance->position][$instance->weight - 1])) {
519 $other = $pageblocks[$instance->position][$instance->weight - 1];
520 }
521 if(!empty($other)) {
522 ++$other->weight;
0d6b9d4f 523 if (!empty($pinned)) {
58ff964f 524 $DB->update_record('block_pinned', $other);
0d6b9d4f 525 } else {
58ff964f 526 $DB->update_record('block_instance', $other);
afd1ec02 527 }
f032aa7a 528 }
529 --$instance->weight;
0d6b9d4f 530 if (!empty($pinned)) {
58ff964f 531 $DB->update_record('block_pinned', $instance);
0d6b9d4f 532 } else {
58ff964f 533 $DB->update_record('block_instance', $instance);
0d6b9d4f 534 }
0f3fe4b6 535 }
536 break;
537 case 'movedown':
9b4b78fd 538 if(empty($instance)) {
e49ef64a 539 print_error('invalidblockinstance', '', '', $blockaction);
9b4b78fd 540 }
f032aa7a 541
542 if($instance->weight == max(array_keys($pageblocks[$instance->position]))) {
543 // The block is the last one, so a move "down" probably means it changes position
544 // Where is the instance going to be moved?
545 $newpos = $page->blocks_move_position($instance, BLOCK_MOVE_DOWN);
6b853ff4 546 $newweight = (empty($pageblocks[$newpos]) ? 0 : max(array_keys($pageblocks[$newpos])) + 1);
f032aa7a 547
0d6b9d4f 548 blocks_execute_repositioning($instance, $newpos, $newweight, $pinned);
89a5baab 549 }
f032aa7a 550 else {
551 // The block is just moving downwards in the same position.
552 // This configuration will make sure that even if somehow the weights
553 // become not continuous, block move operations will eventually bring
554 // the situation back to normal without printing any warnings.
555 if(!empty($pageblocks[$instance->position][$instance->weight + 1])) {
556 $other = $pageblocks[$instance->position][$instance->weight + 1];
557 }
558 if(!empty($other)) {
559 --$other->weight;
0d6b9d4f 560 if (!empty($pinned)) {
58ff964f 561 $DB->update_record('block_pinned', $other);
0d6b9d4f 562 } else {
58ff964f 563 $DB->update_record('block_instance', $other);
0d6b9d4f 564 }
f032aa7a 565 }
566 ++$instance->weight;
0d6b9d4f 567 if (!empty($pinned)) {
58ff964f 568 $DB->update_record('block_pinned', $instance);
0d6b9d4f 569 } else {
58ff964f 570 $DB->update_record('block_instance', $instance);
0d6b9d4f 571 }
0f3fe4b6 572 }
573 break;
9b4b78fd 574 case 'moveleft':
575 if(empty($instance)) {
e49ef64a 576 print_error('invalidblockinstance', '', '', $blockaction);
9b4b78fd 577 }
f032aa7a 578
579 // Where is the instance going to be moved?
580 $newpos = $page->blocks_move_position($instance, BLOCK_MOVE_LEFT);
6b853ff4 581 $newweight = (empty($pageblocks[$newpos]) ? 0 : max(array_keys($pageblocks[$newpos])) + 1);
f032aa7a 582
0d6b9d4f 583 blocks_execute_repositioning($instance, $newpos, $newweight, $pinned);
0f3fe4b6 584 break;
9b4b78fd 585 case 'moveright':
586 if(empty($instance)) {
e49ef64a 587 print_error('invalidblockinstance', '', '', $blockaction);
9b4b78fd 588 }
f032aa7a 589
590 // Where is the instance going to be moved?
591 $newpos = $page->blocks_move_position($instance, BLOCK_MOVE_RIGHT);
6b853ff4 592 $newweight = (empty($pageblocks[$newpos]) ? 0 : max(array_keys($pageblocks[$newpos])) + 1);
f032aa7a 593
0d6b9d4f 594 blocks_execute_repositioning($instance, $newpos, $newweight, $pinned);
9b4b78fd 595 break;
596 case 'add':
597 // Add a new instance of this block, if allowed
598 $block = blocks_get_record($blockid);
0f3fe4b6 599
3cacefda 600 if(empty($block) || !$block->visible) {
601 // Only allow adding if the block exists and is enabled
11306331 602 break;
9b4b78fd 603 }
0f3fe4b6 604
89a5baab 605 if(!$block->multiple && blocks_find_block($blockid, $pageblocks) !== false) {
606 // If no multiples are allowed and we already have one, return now
11306331 607 break;
608 }
609
610 if(!block_method_result($block->name, 'user_can_addto', $page)) {
611 // If the block doesn't want to be added...
612 break;
89a5baab 613 }
614
f032aa7a 615 $newpos = $page->blocks_default_position();
0d6b9d4f 616 if (!empty($pinned)) {
58ff964f 617 $sql = "SELECT 1, MAX(weight) + 1 AS nextfree
618 FROM {block_pinned}
619 WHERE pagetype = ? AND position = ?";
620 $params = array($page->get_type(), $newpos);
621
0d6b9d4f 622 } else {
58ff964f 623 $sql = "SELECT 1, MAX(weight) + 1 AS nextfree
624 FROM {block_instance}
625 WHERE pageid = ? AND pagetype = ? AND position = ?";
626 $params = array($page->get_id(), $page->get_type(), $newpos);
0d6b9d4f 627 }
58ff964f 628 $weight = $DB->get_record_sql($sql, $params);
9b4b78fd 629
630 $newinstance = new stdClass;
631 $newinstance->blockid = $blockid;
0d6b9d4f 632 if (empty($pinned)) {
633 $newinstance->pageid = $page->get_id();
634 }
f032aa7a 635 $newinstance->pagetype = $page->get_type();
636 $newinstance->position = $newpos;
ff679897 637 $newinstance->weight = empty($weight->nextfree) ? 0 : $weight->nextfree;
9b4b78fd 638 $newinstance->visible = 1;
639 $newinstance->configdata = '';
0d6b9d4f 640 if (!empty($pinned)) {
58ff964f 641 $newinstance->id = $DB->insert_record('block_pinned', $newinstance);
0d6b9d4f 642 } else {
58ff964f 643 $newinstance->id = $DB->insert_record('block_instance', $newinstance);
0d6b9d4f 644 }
b33dd23a 645
646 // If the new instance was created, allow it to do additional setup
647 if($newinstance && ($obj = block_instance($block->name, $newinstance))) {
648 // Return value ignored
649 $obj->instance_create();
650 }
651
9b4b78fd 652 break;
653 }
f032aa7a 654
b1631fef 655 if ($redirect) {
656 // In order to prevent accidental duplicate actions, redirect to a page with a clean url
657 redirect($page->url_get_full());
658 }
f032aa7a 659}
660
da71112b 661// You can use this to get the blocks to respond to URL actions without much hassle
0d6b9d4f 662function blocks_execute_url_action(&$PAGE, &$pageblocks,$pinned=false) {
02cc05a7 663 $blockaction = optional_param('blockaction', '', PARAM_ALPHA);
da71112b 664
3edc57e1 665 if (empty($blockaction) || !$PAGE->user_allowed_editing() || !confirm_sesskey()) {
da71112b 666 return;
667 }
668
669 $instanceid = optional_param('instanceid', 0, PARAM_INT);
670 $blockid = optional_param('blockid', 0, PARAM_INT);
afd1ec02 671
da71112b 672 if (!empty($blockid)) {
0d6b9d4f 673 blocks_execute_action($PAGE, $pageblocks, strtolower($blockaction), $blockid, $pinned);
da71112b 674
675 }
676 else if (!empty($instanceid)) {
677 $instance = blocks_find_instance($instanceid, $pageblocks);
0d6b9d4f 678 blocks_execute_action($PAGE, $pageblocks, strtolower($blockaction), $instance, $pinned);
da71112b 679 }
680}
681
f032aa7a 682// This shouldn't be used externally at all, it's here for use by blocks_execute_action()
683// in order to reduce code repetition.
29ca8b88 684function blocks_execute_repositioning(&$instance, $newpos, $newweight, $pinned=false) {
58ff964f 685 global $DB;
f032aa7a 686
c4308cfa 687 // If it's staying where it is, don't do anything, unless overridden
29ca8b88 688 if ($newpos == $instance->position) {
f032aa7a 689 return;
690 }
691
692 // Close the weight gap we 'll leave behind
0d6b9d4f 693 if (!empty($pinned)) {
58ff964f 694 $sql = "UPDATE {block_instance}
695 SET weight = weight - 1
696 WHERE pagetype = ? AND position = ? AND weight > ?";
697 $params = array($instance->pagetype, $instance->position, $instance->weight);
698
0d6b9d4f 699 } else {
58ff964f 700 $sql = "UPDATE {block_instance}
701 SET weight = weight - 1
702 WHERE pagetype = ? AND pageid = ?
703 AND position = ? AND weight > ?";
704 $params = array($instance->pagetype, $instance->pageid, $instance->position, $instance->weight);
0d6b9d4f 705 }
58ff964f 706 $DB->execute($sql, $params);
f032aa7a 707
708 $instance->position = $newpos;
709 $instance->weight = $newweight;
710
0d6b9d4f 711 if (!empty($pinned)) {
58ff964f 712 $DB->update_record('block_pinned', $instance);
0d6b9d4f 713 } else {
58ff964f 714 $DB->update_record('block_instance', $instance);
0d6b9d4f 715 }
716}
717
29ca8b88 718
719/**
720 * Moves a block to the new position (column) and weight (sort order).
721 * @param $instance - The block instance to be moved.
722 * @param $destpos - BLOCK_POS_LEFT or BLOCK_POS_RIGHT. The destination column.
723 * @param $destweight - The destination sort order. If NULL, we add to the end
724 * of the destination column.
725 * @param $pinned - Are we moving pinned blocks? We can only move pinned blocks
726 * to a new position withing the pinned list. Likewise, we
727 * can only moved non-pinned blocks to a new position within
728 * the non-pinned list.
729 * @return boolean (success or failure).
730 */
731function blocks_move_block($page, &$instance, $destpos, $destweight=NULL, $pinned=false) {
58ff964f 732 global $CFG, $DB;
afd1ec02 733
29ca8b88 734 if ($pinned) {
735 $blocklist = blocks_get_pinned($page);
736 } else {
737 $blocklist = blocks_get_by_page($page);
738 }
afd1ec02 739
29ca8b88 740 if ($blocklist[$instance->position][$instance->weight]->id != $instance->id) {
741 // The source block instance is not where we think it is.
c4308cfa 742 return false;
d23157d8 743 }
afd1ec02 744
29ca8b88 745 // First we close the gap that will be left behind when we take out the
746 // block from it's current column.
747 if ($pinned) {
58ff964f 748 $closegapsql = "UPDATE {block_instance}
afd1ec02 749 SET weight = weight - 1
58ff964f 750 WHERE weight > ? AND position = ? AND pagetype = ?";
751 $params = array($instance->weight, $instance->position, $instance->pagetype);
e028ed34 752 } else {
58ff964f 753 $closegapsql = "UPDATE {block_instance}
afd1ec02 754 SET weight = weight - 1
58ff964f 755 WHERE weight > ? AND position = ?
756 AND pagetype = ? AND pageid = ?";
757 $params = array($instance->weight, $instance->position, $instance->pagetype, $instance->pageid);
29ca8b88 758 }
58ff964f 759 if (!$DB->execute($closegapsql, $params)) {
29ca8b88 760 return false;
77e65ff7 761 }
afd1ec02 762
29ca8b88 763 // Now let's make space for the block being moved.
764 if ($pinned) {
58ff964f 765 $opengapsql = "UPDATE {block_instance}
afd1ec02 766 SET weight = weight + 1
58ff964f 767 WHERE weight >= ? AND position = ? AND pagetype = ?";
768 $params = array($destweight, $destpos, $instance->pagetype);
d23157d8 769 } else {
58ff964f 770 $opengapsql = "UPDATE {block_instance}
771 SET weight = weight + 1
772 WHERE weight >= ? AND position = ?
773 AND pagetype = ? AND pageid = ?";
774 $params = array($destweight, $destpos, $instance->pagetype, $instance->pageid);
29ca8b88 775 }
655b09ca 776 if (!$DB->execute($opengapsql, $params)) {
29ca8b88 777 return false;
c4308cfa 778 }
afd1ec02 779
29ca8b88 780 // Move the block.
781 $instance->position = $destpos;
782 $instance->weight = $destweight;
e028ed34 783
29ca8b88 784 if ($pinned) {
785 $table = 'block_pinned';
786 } else {
787 $table = 'block_instance';
788 }
58ff964f 789 return $DB->update_record($table, $instance);
e028ed34 790}
791
d23157d8 792
793/**
794 * Returns an array consisting of 2 arrays:
795 * 1) Array of pinned blocks for position BLOCK_POS_LEFT
796 * 2) Array of pinned blocks for position BLOCK_POS_RIGHT
797 */
0d6b9d4f 798function blocks_get_pinned($page) {
58ff964f 799 global $DB;
afd1ec02 800
0d6b9d4f 801 $visible = true;
802
803 if (method_exists($page,'edit_always')) {
804 if ($page->edit_always()) {
805 $visible = false;
806 }
807 }
afd1ec02 808
58ff964f 809 $select = "pagetype = ?";
810 $params = array($page->get_type());
811
812 if ($visible) {
813 $select .= " AND visible = 1";
814 }
815
816 $blocks = $DB->get_records_select('block_pinned', $select, $params, 'position, weight');
0d6b9d4f 817
818 $positions = $page->blocks_get_positions();
819 $arr = array();
820
821 foreach($positions as $key => $position) {
822 $arr[$position] = array();
823 }
824
825 if(empty($blocks)) {
826 return $arr;
827 }
828
829 foreach($blocks as $block) {
830 $block->pinned = true; // so we know we can't move it.
ddf1935f 831 // make up an instanceid if we can..
832 $block->pageid = $page->get_id();
0d6b9d4f 833 $arr[$block->position][$block->weight] = $block;
834 }
835
afd1ec02 836 return $arr;
0d6b9d4f 837}
838
839
d23157d8 840/**
841 * Similar to blocks_get_by_page(), except that, the array returned includes
842 * pinned blocks as well. Pinned blocks are always appended before normal
843 * block instances.
844 */
0d6b9d4f 845function blocks_get_by_page_pinned($page) {
846 $pinned = blocks_get_pinned($page);
847 $user = blocks_get_by_page($page);
afd1ec02 848
0d6b9d4f 849 $weights = array();
850
851 foreach ($pinned as $pos => $arr) {
852 $weights[$pos] = count($arr);
853 }
854
855 foreach ($user as $pos => $blocks) {
856 if (!array_key_exists($pos,$pinned)) {
857 $pinned[$pos] = array();
858 }
859 if (!array_key_exists($pos,$weights)) {
860 $weights[$pos] = 0;
861 }
77e65ff7 862 foreach ($blocks as $block) {
0d6b9d4f 863 $pinned[$pos][$weights[$pos]] = $block;
864 $weights[$pos]++;
865 }
866 }
867 return $pinned;
0f3fe4b6 868}
869
d23157d8 870
871/**
872 * Returns an array of blocks for the page. Pinned blocks are excluded.
873 */
9b4b78fd 874function blocks_get_by_page($page) {
58ff964f 875 global $DB;
876
877 $blocks = $DB->get_records_select('block_instance', "pageid = ? AND pagetype = ?", array($page->get_id(), $page->get_type()),
878 'position, weight');
f032aa7a 879
880 $positions = $page->blocks_get_positions();
881 $arr = array();
882 foreach($positions as $key => $position) {
883 $arr[$position] = array();
884 }
0f3fe4b6 885
9b4b78fd 886 if(empty($blocks)) {
887 return $arr;
888 }
0f3fe4b6 889
77e65ff7 890 foreach($blocks as $block) {
9b4b78fd 891 $arr[$block->position][$block->weight] = $block;
0f3fe4b6 892 }
d23157d8 893 return $arr;
9b4b78fd 894}
0f3fe4b6 895
d23157d8 896
9b4b78fd 897//This function prints the block to admin blocks as necessary
c1d8705f 898function blocks_print_adminblock(&$page, &$pageblocks) {
9b4b78fd 899 global $USER;
0f3fe4b6 900
c1d8705f 901 $missingblocks = blocks_get_missing($page, $pageblocks);
902
9b4b78fd 903 if (!empty($missingblocks)) {
74fd9ff9 904 $strblocks = '<div class="title"><h2>';
303fe9f4 905 $strblocks .= get_string('blocks');
552adc27 906 $strblocks .= '</h2></div>';
c1d8705f 907 $stradd = get_string('add');
9b4b78fd 908 foreach ($missingblocks as $blockid) {
909 $block = blocks_get_record($blockid);
9b4b78fd 910 $blockobject = block_instance($block->name);
911 if ($blockobject === false) {
912 continue;
913 }
11306331 914 if(!$blockobject->user_can_addto($page)) {
915 continue;
916 }
9b4b78fd 917 $menu[$block->id] = $blockobject->get_title();
918 }
4a4c30d2 919 asort($menu);
0f3fe4b6 920
19f5b2db 921 $target = $page->url_get_full(array('sesskey' => sesskey(), 'blockaction' => 'add'));
f032aa7a 922 $content = popup_form($target.'&amp;blockid=', $menu, 'add_block', '', $stradd .'...', '', '', true);
afd8402c 923 print_side_block($strblocks, $content, NULL, NULL, NULL, array('class' => 'block_adminblock'));
0f3fe4b6 924 }
0f3fe4b6 925}
926
19f5b2db 927/**
928 * Delete all the blocks from a particular page.
929 *
930 * @param string $pagetype the page type.
931 * @param integer $pageid the page id.
932 * @return success of failure.
933 */
934function blocks_delete_all_on_page($pagetype, $pageid) {
935 global $DB;
936 if ($instances = $DB->get_records('block_instance', array('pageid' => $pageid, 'pagetype' => $pagetype))) {
937 foreach ($instances as $instance) {
938 delete_context(CONTEXT_BLOCK, $instance->id); // Ingore any failures here.
939 }
940 }
941 return $DB->delete_records('block_instance', array('pageid' => $pageid, 'pagetype' => $pagetype));
942}
943
944// Dispite what this function is called, it seems to be mostly used to populate
945// the default blocks when a new course (or whatever) is created.
9b4b78fd 946function blocks_repopulate_page($page) {
7e0489f4 947 global $CFG, $DB;
5b224948 948
9b4b78fd 949 $allblocks = blocks_get_record();
950
951 if(empty($allblocks)) {
e49ef64a 952 print_error('cannotgetblock');
9b4b78fd 953 }
954
f032aa7a 955 // Assemble the information to correlate block names to ids
9b4b78fd 956 $idforname = array();
957 foreach($allblocks as $block) {
958 $idforname[$block->name] = $block->id;
959 }
960
f032aa7a 961 /// If the site override has been defined, it is the only valid one.
962 if (!empty($CFG->defaultblocks_override)) {
963 $blocknames = $CFG->defaultblocks_override;
964 }
965 else {
966 $blocknames = $page->blocks_get_default();
967 }
afd1ec02 968
f032aa7a 969 $positions = $page->blocks_get_positions();
970 $posblocks = explode(':', $blocknames);
971
972 // Now one array holds the names of the positions, and the other one holds the blocks
973 // that are going to go in each position. Luckily for us, both arrays are numerically
974 // indexed and the indexes match, so we can work straight away... but CAREFULLY!
9b4b78fd 975
f032aa7a 976 // Ready to start creating block instances, but first drop any existing ones
19f5b2db 977 blocks_delete_all_on_page($page->get_type(), $page->get_id());
f032aa7a 978
979 // Here we slyly count $posblocks and NOT $positions. This can actually make a difference
980 // if the textual representation has undefined slots in the end. So we only work with as many
981 // positions were retrieved, not with all the page says it has available.
982 $numpositions = count($posblocks);
983 for($i = 0; $i < $numpositions; ++$i) {
984 $position = $positions[$i];
985 $blocknames = explode(',', $posblocks[$i]);
9b4b78fd 986 $weight = 0;
987 foreach($blocknames as $blockname) {
988 $newinstance = new stdClass;
989 $newinstance->blockid = $idforname[$blockname];
f032aa7a 990 $newinstance->pageid = $page->get_id();
991 $newinstance->pagetype = $page->get_type();
9b4b78fd 992 $newinstance->position = $position;
993 $newinstance->weight = $weight;
994 $newinstance->visible = 1;
995 $newinstance->configdata = '';
3cacefda 996
997 if(!empty($newinstance->blockid)) {
998 // Only add block if it was recognized
58ff964f 999 $DB->insert_record('block_instance', $newinstance);
3cacefda 1000 ++$weight;
1001 }
0f3fe4b6 1002 }
1003 }
9b4b78fd 1004
1005 return true;
0f3fe4b6 1006}
1007
f10306b9 1008?>