forked from moodle/moodle
-
Notifications
You must be signed in to change notification settings - Fork 1
/
blocklib.php
2759 lines (2443 loc) · 106 KB
/
blocklib.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Block Class and Functions
*
* This file defines the {@link block_manager} class,
*
* @package core
* @subpackage block
* @copyright 1999 onwards Martin Dougiamas http://dougiamas.com
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die();
/**#@+
* Default names for the block regions in the standard theme.
*/
define('BLOCK_POS_LEFT', 'side-pre');
define('BLOCK_POS_RIGHT', 'side-post');
/**#@-*/
define('BUI_CONTEXTS_FRONTPAGE_ONLY', 0);
define('BUI_CONTEXTS_FRONTPAGE_SUBS', 1);
define('BUI_CONTEXTS_ENTIRE_SITE', 2);
define('BUI_CONTEXTS_CURRENT', 0);
define('BUI_CONTEXTS_CURRENT_SUBS', 1);
// Position of "Add block" control, to be used in theme config as a value for $THEME->addblockposition:
// - default: as a fake block that is displayed in editing mode
// - flatnav: "Add block" item in the flat navigation drawer in editing mode
// - custom: none of the above, theme will take care of displaying the control.
define('BLOCK_ADDBLOCK_POSITION_DEFAULT', 0);
define('BLOCK_ADDBLOCK_POSITION_FLATNAV', 1);
define('BLOCK_ADDBLOCK_POSITION_CUSTOM', -1);
/**
* Exception thrown when someone tried to do something with a block that does
* not exist on a page.
*
* @copyright 2009 Tim Hunt
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
* @since Moodle 2.0
*/
class block_not_on_page_exception extends moodle_exception {
/**
* Constructor
* @param int $instanceid the block instance id of the block that was looked for.
* @param object $page the current page.
*/
public function __construct($instanceid, $page) {
$a = new stdClass;
$a->instanceid = $instanceid;
$a->url = $page->url->out();
parent::__construct('blockdoesnotexistonpage', '', $page->url->out(), $a);
}
}
/**
* This class keeps track of the block that should appear on a moodle_page.
*
* The page to work with as passed to the constructor.
*
* @copyright 2009 Tim Hunt
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
* @since Moodle 2.0
*/
class block_manager {
/**
* The UI normally only shows block weights between -MAX_WEIGHT and MAX_WEIGHT,
* although other weights are valid.
*/
const MAX_WEIGHT = 10;
/// Field declarations =========================================================
/**
* the moodle_page we are managing blocks for.
* @var moodle_page
*/
protected $page;
/** @var array region name => 1.*/
protected $regions = array();
/** @var string the region where new blocks are added.*/
protected $defaultregion = null;
/** @var array will be $DB->get_records('blocks') */
protected $allblocks = null;
/**
* @var array blocks that this user can add to this page. Will be a subset
* of $allblocks, but with array keys block->name. Access this via the
* {@link get_addable_blocks()} method to ensure it is lazy-loaded.
*/
protected $addableblocks = null;
/**
* Will be an array region-name => array(db rows loaded in load_blocks);
* @var array
*/
protected $birecordsbyregion = null;
/**
* array region-name => array(block objects); populated as necessary by
* the ensure_instances_exist method.
* @var array
*/
protected $blockinstances = array();
/**
* array region-name => array(block_contents objects) what actually needs to
* be displayed in each region.
* @var array
*/
protected $visibleblockcontent = array();
/**
* array region-name => array(block_contents objects) extra block-like things
* to be displayed in each region, before the real blocks.
* @var array
*/
protected $extracontent = array();
/**
* Used by the block move id, to track whether a block is currently being moved.
*
* When you click on the move icon of a block, first the page needs to reload with
* extra UI for choosing a new position for a particular block. In that situation
* this field holds the id of the block being moved.
*
* @var integer|null
*/
protected $movingblock = null;
/**
* Show only fake blocks
*/
protected $fakeblocksonly = false;
/// Constructor ================================================================
/**
* Constructor.
* @param object $page the moodle_page object object we are managing the blocks for,
* or a reasonable faxilimily. (See the comment at the top of this class
* and {@link http://en.wikipedia.org/wiki/Duck_typing})
*/
public function __construct($page) {
$this->page = $page;
}
/// Getter methods =============================================================
/**
* Get an array of all region names on this page where a block may appear
*
* @return array the internal names of the regions on this page where block may appear.
*/
public function get_regions() {
if (is_null($this->defaultregion)) {
$this->page->initialise_theme_and_output();
}
return array_keys($this->regions);
}
/**
* Get the region name of the region blocks are added to by default
*
* @return string the internal names of the region where new blocks are added
* by default, and where any blocks from an unrecognised region are shown.
* (Imagine that blocks were added with one theme selected, then you switched
* to a theme with different block positions.)
*/
public function get_default_region() {
$this->page->initialise_theme_and_output();
return $this->defaultregion;
}
/**
* The list of block types that may be added to this page.
*
* @return array block name => record from block table.
*/
public function get_addable_blocks() {
$this->check_is_loaded();
if (!is_null($this->addableblocks)) {
return $this->addableblocks;
}
// Lazy load.
$this->addableblocks = array();
$allblocks = blocks_get_record();
if (empty($allblocks)) {
return $this->addableblocks;
}
$undeletableblocks = self::get_undeletable_block_types();
$unaddablebythemeblocks = $this->get_unaddable_by_theme_block_types();
$requiredbythemeblocks = $this->get_required_by_theme_block_types();
$pageformat = $this->page->pagetype;
foreach($allblocks as $block) {
if (!$bi = block_instance($block->name)) {
continue;
}
if ($block->visible && !in_array($block->name, $undeletableblocks) &&
!in_array($block->name, $requiredbythemeblocks) &&
!in_array($block->name, $unaddablebythemeblocks) &&
$bi->can_block_be_added($this->page) &&
($bi->instance_allow_multiple() || !$this->is_block_present($block->name)) &&
blocks_name_allowed_in_format($block->name, $pageformat) &&
$bi->user_can_addto($this->page)) {
$block->title = $bi->get_title();
$this->addableblocks[$block->name] = $block;
}
}
core_collator::asort_objects_by_property($this->addableblocks, 'title');
return $this->addableblocks;
}
/**
* Given a block name, find out of any of them are currently present in the page
* @param string $blockname - the basic name of a block (eg "navigation")
* @return boolean - is there one of these blocks in the current page?
*/
public function is_block_present($blockname) {
if (empty($this->blockinstances)) {
return false;
}
$requiredbythemeblocks = $this->get_required_by_theme_block_types();
foreach ($this->blockinstances as $region) {
foreach ($region as $instance) {
if (empty($instance->instance->blockname)) {
continue;
}
if ($instance->instance->blockname == $blockname) {
if ($instance->instance->requiredbytheme) {
if (!in_array($blockname, $requiredbythemeblocks)) {
continue;
}
}
return true;
}
}
}
return false;
}
/**
* Find out if a block type is known by the system
*
* @param string $blockname the name of the type of block.
* @param boolean $includeinvisible if false (default) only check 'visible' blocks, that is, blocks enabled by the admin.
* @return boolean true if this block in installed.
*/
public function is_known_block_type($blockname, $includeinvisible = false) {
$blocks = $this->get_installed_blocks();
foreach ($blocks as $block) {
if ($block->name == $blockname && ($includeinvisible || $block->visible)) {
return true;
}
}
return false;
}
/**
* Find out if a region exists on a page
*
* @param string $region a region name
* @return boolean true if this region exists on this page.
*/
public function is_known_region($region) {
if (empty($region)) {
return false;
}
return array_key_exists($region, $this->regions);
}
/**
* Get an array of all blocks within a given region
*
* @param string $region a block region that exists on this page.
* @return array of block instances.
*/
public function get_blocks_for_region($region) {
$this->check_is_loaded();
$this->ensure_instances_exist($region);
return $this->blockinstances[$region];
}
/**
* Returns an array of block content objects that exist in a region
*
* @param string $region a block region that exists on this page.
* @return array of block block_contents objects for all the blocks in a region.
*/
public function get_content_for_region($region, $output) {
$this->check_is_loaded();
$this->ensure_content_created($region, $output);
return $this->visibleblockcontent[$region];
}
/**
* Returns an array of block content objects for all the existings regions
*
* @param renderer_base $output the rendered to use
* @return array of block block_contents objects for all the blocks in all regions.
* @since Moodle 3.3
*/
public function get_content_for_all_regions($output) {
$contents = array();
$this->check_is_loaded();
foreach ($this->regions as $region => $val) {
$this->ensure_content_created($region, $output);
$contents[$region] = $this->visibleblockcontent[$region];
}
return $contents;
}
/**
* Helper method used by get_content_for_region.
* @param string $region region name
* @param float $weight weight. May be fractional, since you may want to move a block
* between ones with weight 2 and 3, say ($weight would be 2.5).
* @return moodle_url URL for moving block $this->movingblock to this position.
*/
protected function get_move_target_url($region, $weight) {
return new moodle_url($this->page->url, array('bui_moveid' => $this->movingblock,
'bui_newregion' => $region, 'bui_newweight' => $weight, 'sesskey' => sesskey()));
}
/**
* Determine whether a region contains anything. (Either any real blocks, or
* the add new block UI.)
*
* (You may wonder why the $output parameter is required. Unfortunately,
* because of the way that blocks work, the only reliable way to find out
* if a block will be visible is to get the content for output, and to
* get the content, you need a renderer. Fortunately, this is not a
* performance problem, because we cache the output that is generated, and
* in almost every case where we call region_has_content, we are about to
* output the blocks anyway, so we are not doing wasted effort.)
*
* @param string $region a block region that exists on this page.
* @param core_renderer $output a core_renderer. normally the global $OUTPUT.
* @return boolean Whether there is anything in this region.
*/
public function region_has_content($region, $output) {
if (!$this->is_known_region($region)) {
return false;
}
$this->check_is_loaded();
$this->ensure_content_created($region, $output);
// if ($this->page->user_is_editing() && $this->page->user_can_edit_blocks()) {
// Mark Nielsen's patch - part 1
if ($this->page->user_is_editing() && $this->page->user_can_edit_blocks() && $this->movingblock) {
// If editing is on, we need all the block regions visible, for the
// move blocks UI.
return true;
}
return !empty($this->visibleblockcontent[$region]) || !empty($this->extracontent[$region]);
}
/**
* Determine whether a region contains any fake blocks.
*
* (Fake blocks are typically added to the extracontent array per region)
*
* @param string $region a block region that exists on this page.
* @return boolean Whether there are fake blocks in this region.
*/
public function region_has_fakeblocks($region): bool {
return !empty($this->extracontent[$region]);
}
/**
* Get an array of all of the installed blocks.
*
* @return array contents of the block table.
*/
public function get_installed_blocks() {
global $DB;
if (is_null($this->allblocks)) {
$this->allblocks = $DB->get_records('block');
}
return $this->allblocks;
}
/**
* @return array names of block types that must exist on every page with this theme.
*/
public function get_required_by_theme_block_types() {
$requiredbythemeblocks = false;
if (isset($this->page->theme->requiredblocks)) {
$requiredbythemeblocks = $this->page->theme->requiredblocks;
}
if ($requiredbythemeblocks === false) {
return array('navigation', 'settings');
} else if ($requiredbythemeblocks === '') {
return array();
} else if (is_string($requiredbythemeblocks)) {
return explode(',', $requiredbythemeblocks);
} else {
return $requiredbythemeblocks;
}
}
/**
* It returns the list of blocks that can't be displayed in the "Add a block" list.
* This information is taken from the unaddableblocks theme setting.
*
* @return array A list with the blocks that won't be displayed in the "Add a block" list.
*/
public function get_unaddable_by_theme_block_types(): array {
$unaddablebythemeblocks = [];
if (isset($this->page->theme->settings->unaddableblocks) && !empty($this->page->theme->settings->unaddableblocks)) {
$unaddablebythemeblocks = array_map('trim', explode(',', $this->page->theme->settings->unaddableblocks));
}
return $unaddablebythemeblocks;
}
/**
* Make this block type undeletable and unaddable.
*
* @param mixed $blockidorname string or int
*/
public static function protect_block($blockidorname) {
global $DB;
$syscontext = context_system::instance();
require_capability('moodle/site:config', $syscontext);
$block = false;
if (is_int($blockidorname)) {
$block = $DB->get_record('block', array('id' => $blockidorname), 'id, name', MUST_EXIST);
} else {
$block = $DB->get_record('block', array('name' => $blockidorname), 'id, name', MUST_EXIST);
}
$undeletableblocktypes = self::get_undeletable_block_types();
if (!in_array($block->name, $undeletableblocktypes)) {
$undeletableblocktypes[] = $block->name;
set_config('undeletableblocktypes', implode(',', $undeletableblocktypes));
add_to_config_log('block_protect', "0", "1", $block->name);
}
}
/**
* Make this block type deletable and addable.
*
* @param mixed $blockidorname string or int
*/
public static function unprotect_block($blockidorname) {
global $DB;
$syscontext = context_system::instance();
require_capability('moodle/site:config', $syscontext);
$block = false;
if (is_int($blockidorname)) {
$block = $DB->get_record('block', array('id' => $blockidorname), 'id, name', MUST_EXIST);
} else {
$block = $DB->get_record('block', array('name' => $blockidorname), 'id, name', MUST_EXIST);
}
$undeletableblocktypes = self::get_undeletable_block_types();
if (in_array($block->name, $undeletableblocktypes)) {
$undeletableblocktypes = array_diff($undeletableblocktypes, array($block->name));
set_config('undeletableblocktypes', implode(',', $undeletableblocktypes));
add_to_config_log('block_protect', "1", "0", $block->name);
}
}
/**
* Get the list of "protected" blocks via admin block manager ui.
*
* @return array names of block types that cannot be added or deleted. E.g. array('navigation','settings').
*/
public static function get_undeletable_block_types() {
global $CFG;
$undeletableblocks = false;
if (isset($CFG->undeletableblocktypes)) {
$undeletableblocks = $CFG->undeletableblocktypes;
}
if (empty($undeletableblocks)) {
return array();
} else if (is_string($undeletableblocks)) {
return explode(',', $undeletableblocks);
} else {
return $undeletableblocks;
}
}
/// Setter methods =============================================================
/**
* Add a region to a page
*
* @param string $region add a named region where blocks may appear on the current page.
* This is an internal name, like 'side-pre', not a string to display in the UI.
* @param bool $custom True if this is a custom block region, being added by the page rather than the theme layout.
*/
public function add_region($region, $custom = true) {
global $SESSION;
$this->check_not_yet_loaded();
if ($custom) {
if (array_key_exists($region, $this->regions)) {
// This here is EXACTLY why we should not be adding block regions into a page. It should
// ALWAYS be done in a theme layout.
debugging('A custom region conflicts with a block region in the theme.', DEBUG_DEVELOPER);
}
// We need to register this custom region against the page type being used.
// This allows us to check, when performing block actions, that unrecognised regions can be worked with.
$type = $this->page->pagetype;
if (!isset($SESSION->custom_block_regions)) {
$SESSION->custom_block_regions = array($type => array($region));
} else if (!isset($SESSION->custom_block_regions[$type])) {
$SESSION->custom_block_regions[$type] = array($region);
} else if (!in_array($region, $SESSION->custom_block_regions[$type])) {
$SESSION->custom_block_regions[$type][] = $region;
}
}
$this->regions[$region] = 1;
// Checking the actual property instead of calling get_default_region as it ends up in a recursive call.
if (empty($this->defaultregion)) {
$this->set_default_region($region);
}
}
/**
* Add an array of regions
* @see add_region()
*
* @param array $regions this utility method calls add_region for each array element.
*/
public function add_regions($regions, $custom = true) {
foreach ($regions as $region) {
$this->add_region($region, $custom);
}
}
/**
* Finds custom block regions associated with a page type and registers them with this block manager.
*
* @param string $pagetype
*/
public function add_custom_regions_for_pagetype($pagetype) {
global $SESSION;
if (isset($SESSION->custom_block_regions[$pagetype])) {
foreach ($SESSION->custom_block_regions[$pagetype] as $customregion) {
$this->add_region($customregion, false);
}
}
}
/**
* Set the default region for new blocks on the page
*
* @param string $defaultregion the internal names of the region where new
* blocks should be added by default, and where any blocks from an
* unrecognised region are shown.
*/
public function set_default_region($defaultregion) {
$this->check_not_yet_loaded();
if ($defaultregion) {
$this->check_region_is_known($defaultregion);
}
$this->defaultregion = $defaultregion;
}
/**
* Add something that looks like a block, but which isn't an actual block_instance,
* to this page.
*
* @param block_contents $bc the content of the block-like thing.
* @param string $region a block region that exists on this page.
*/
public function add_fake_block($bc, $region) {
$this->page->initialise_theme_and_output();
if (!$this->is_known_region($region)) {
$region = $this->get_default_region();
}
if (array_key_exists($region, $this->visibleblockcontent)) {
throw new coding_exception('block_manager has already prepared the blocks in region ' .
$region . 'for output. It is too late to add a fake block.');
}
if (!isset($bc->attributes['data-block'])) {
$bc->attributes['data-block'] = '_fake';
}
$bc->attributes['class'] .= ' block_fake';
$this->extracontent[$region][] = $bc;
}
/**
* Checks to see whether all of the blocks within the given region are docked
*
* @see region_uses_dock
* @param string $region
* @return bool True if all of the blocks within that region are docked
*
* Return false as from MDL-64506
*/
public function region_completely_docked($region, $output) {
return false;
}
/**
* Checks to see whether any of the blocks within the given regions are docked
*
* @see region_completely_docked
* @param array|string $regions array of regions (or single region)
* @return bool True if any of the blocks within that region are docked
*
* Return false as from MDL-64506
*/
public function region_uses_dock($regions, $output) {
return false;
}
/// Actions ====================================================================
/**
* This method actually loads the blocks for our page from the database.
*
* @param boolean|null $includeinvisible
* null (default) - load hidden blocks if $this->page->user_is_editing();
* true - load hidden blocks.
* false - don't load hidden blocks.
*/
public function load_blocks($includeinvisible = null) {
global $DB, $CFG;
if (!is_null($this->birecordsbyregion)) {
// Already done.
return;
}
if ($CFG->version < 2009050619) {
// Upgrade/install not complete. Don't try too show any blocks.
$this->birecordsbyregion = array();
return;
}
// Ensure we have been initialised.
if (is_null($this->defaultregion)) {
$this->page->initialise_theme_and_output();
// If there are still no block regions, then there are no blocks on this page.
if (empty($this->regions)) {
$this->birecordsbyregion = array();
return;
}
}
// Check if we need to load normal blocks
if ($this->fakeblocksonly) {
$this->birecordsbyregion = $this->prepare_per_region_arrays();
return;
}
// Exclude auto created blocks if they are not undeletable in this theme.
$requiredbytheme = $this->get_required_by_theme_block_types();
$requiredbythemecheck = '';
$requiredbythemeparams = array();
$requiredbythemenotparams = array();
if (!empty($requiredbytheme)) {
list($testsql, $requiredbythemeparams) = $DB->get_in_or_equal($requiredbytheme, SQL_PARAMS_NAMED, 'requiredbytheme');
list($testnotsql, $requiredbythemenotparams) = $DB->get_in_or_equal($requiredbytheme, SQL_PARAMS_NAMED,
'notrequiredbytheme', false);
$requiredbythemecheck = 'AND ((bi.blockname ' . $testsql . ' AND bi.requiredbytheme = 1) OR ' .
' (bi.blockname ' . $testnotsql . ' AND bi.requiredbytheme = 0))';
} else {
$requiredbythemecheck = 'AND (bi.requiredbytheme = 0)';
}
if (is_null($includeinvisible)) {
$includeinvisible = $this->page->user_is_editing();
}
if ($includeinvisible) {
$visiblecheck = '';
} else {
$visiblecheck = 'AND (bp.visible = 1 OR bp.visible IS NULL) AND (bs.visible = 1 OR bs.visible IS NULL)';
}
$context = $this->page->context;
$contexttest = 'bi.parentcontextid IN (:contextid2, :contextid3)';
$parentcontextparams = array();
$parentcontextids = $context->get_parent_context_ids();
if ($parentcontextids) {
list($parentcontexttest, $parentcontextparams) =
$DB->get_in_or_equal($parentcontextids, SQL_PARAMS_NAMED, 'parentcontext');
$contexttest = "($contexttest OR (bi.showinsubcontexts = 1 AND bi.parentcontextid $parentcontexttest))";
}
$pagetypepatterns = matching_page_type_patterns($this->page->pagetype);
list($pagetypepatterntest, $pagetypepatternparams) =
$DB->get_in_or_equal($pagetypepatterns, SQL_PARAMS_NAMED, 'pagetypepatterntest');
$ccselect = ', ' . context_helper::get_preload_record_columns_sql('ctx');
$ccjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = bi.id AND ctx.contextlevel = :contextlevel)";
$systemcontext = context_system::instance();
$params = array(
'contextlevel' => CONTEXT_BLOCK,
'subpage1' => $this->page->subpage,
'subpage2' => $this->page->subpage,
'subpage3' => $this->page->subpage,
'contextid1' => $context->id,
'contextid2' => $context->id,
'contextid3' => $systemcontext->id,
'contextid4' => $systemcontext->id,
'pagetype' => $this->page->pagetype,
'pagetype2' => $this->page->pagetype,
);
if ($this->page->subpage === '') {
$params['subpage1'] = '';
$params['subpage2'] = '';
$params['subpage3'] = '';
}
$sql = "SELECT
bi.id,
COALESCE(bp.id, bs.id) AS blockpositionid,
bi.blockname,
bi.parentcontextid,
bi.showinsubcontexts,
bi.pagetypepattern,
bi.requiredbytheme,
bi.subpagepattern,
bi.defaultregion,
bi.defaultweight,
COALESCE(bp.visible, bs.visible, 1) AS visible,
COALESCE(bp.region, bs.region, bi.defaultregion) AS region,
COALESCE(bp.weight, bs.weight, bi.defaultweight) AS weight,
bi.configdata
$ccselect
FROM {block_instances} bi
JOIN {block} b ON bi.blockname = b.name
LEFT JOIN {block_positions} bp ON bp.blockinstanceid = bi.id
AND bp.contextid = :contextid1
AND bp.pagetype = :pagetype
AND bp.subpage = :subpage1
LEFT JOIN {block_positions} bs ON bs.blockinstanceid = bi.id
AND bs.contextid = :contextid4
AND bs.pagetype = :pagetype2
AND bs.subpage = :subpage3
$ccjoin
WHERE
$contexttest
AND bi.pagetypepattern $pagetypepatterntest
AND (bi.subpagepattern IS NULL OR bi.subpagepattern = :subpage2)
$visiblecheck
AND b.visible = 1
$requiredbythemecheck
ORDER BY
COALESCE(bp.region, bs.region, bi.defaultregion),
COALESCE(bp.weight, bs.weight, bi.defaultweight),
bi.id";
$allparams = $params + $parentcontextparams + $pagetypepatternparams + $requiredbythemeparams + $requiredbythemenotparams;
$blockinstances = $DB->get_recordset_sql($sql, $allparams);
$this->birecordsbyregion = $this->prepare_per_region_arrays();
$unknown = array();
foreach ($blockinstances as $bi) {
context_helper::preload_from_record($bi);
if ($this->is_known_region($bi->region)) {
$this->birecordsbyregion[$bi->region][] = $bi;
} else {
$unknown[] = $bi;
}
}
$blockinstances->close();
// Pages don't necessarily have a defaultregion. The one time this can
// happen is when there are no theme block regions, but the script itself
// has a block region in the main content area.
if (!empty($this->defaultregion)) {
$this->birecordsbyregion[$this->defaultregion] =
array_merge($this->birecordsbyregion[$this->defaultregion], $unknown);
}
}
/**
* Add a block to the current page, or related pages. The block is added to
* context $this->page->contextid. If $pagetypepattern $subpagepattern
*
* @param string $blockname The type of block to add.
* @param string $region the block region on this page to add the block to.
* @param integer $weight determines the order where this block appears in the region.
* @param boolean $showinsubcontexts whether this block appears in subcontexts, or just the current context.
* @param string|null $pagetypepattern which page types this block should appear on. Defaults to just the current page type.
* @param string|null $subpagepattern which subpage this block should appear on. NULL = any (the default), otherwise only the specified subpage.
* @return block_base
*/
public function add_block($blockname, $region, $weight, $showinsubcontexts, $pagetypepattern = NULL, $subpagepattern = NULL) {
global $DB;
// Allow invisible blocks because this is used when adding default page blocks, which
// might include invisible ones if the user makes some default blocks invisible
$this->check_known_block_type($blockname, true);
$this->check_region_is_known($region);
if (empty($pagetypepattern)) {
$pagetypepattern = $this->page->pagetype;
}
$blockinstance = new stdClass;
$blockinstance->blockname = $blockname;
$blockinstance->parentcontextid = $this->page->context->id;
$blockinstance->showinsubcontexts = !empty($showinsubcontexts);
$blockinstance->pagetypepattern = $pagetypepattern;
$blockinstance->subpagepattern = $subpagepattern;
$blockinstance->defaultregion = $region;
$blockinstance->defaultweight = $weight;
$blockinstance->configdata = '';
$blockinstance->timecreated = time();
$blockinstance->timemodified = $blockinstance->timecreated;
$blockinstance->id = $DB->insert_record('block_instances', $blockinstance);
// Ensure the block context is created.
context_block::instance($blockinstance->id);
// If the new instance was created, allow it to do additional setup
if ($block = block_instance($blockname, $blockinstance)) {
$block->instance_create();
}
if (!is_null($this->birecordsbyregion)) {
// If blocks were already loaded on this page, reload them.
$this->birecordsbyregion = null;
$this->load_blocks();
}
return $block;
}
/**
* When passed a block name create a new instance of the block in the specified region.
*
* @param string $blockname Name of the block to add.
* @param null|string $blockregion If defined add the new block to the specified region.
* @return ?block_base
*/
public function add_block_at_end_of_default_region($blockname, $blockregion = null) {
if (empty($this->birecordsbyregion)) {
// No blocks or block regions exist yet.
return null;
}
if ($blockregion === null) {
$defaulregion = $this->get_default_region();
} else {
$defaulregion = $blockregion;
}
$lastcurrentblock = end($this->birecordsbyregion[$defaulregion]);
if ($lastcurrentblock) {
$weight = $lastcurrentblock->weight + 1;
} else {
$weight = 0;
}
if ($this->page->subpage) {
$subpage = $this->page->subpage;
} else {
$subpage = null;
}
// Special case. Course view page type include the course format, but we
// want to add the block non-format-specifically.
$pagetypepattern = $this->page->pagetype;
if (strpos($pagetypepattern, 'course-view') === 0) {
$pagetypepattern = 'course-view-*';
}
// We should end using this for ALL the blocks, making always the 1st option
// the default one to be used. Until then, this is one hack to avoid the
// 'pagetypewarning' message on blocks initial edition (MDL-27829) caused by
// non-existing $pagetypepattern set. This way at least we guarantee one "valid"
// (the FIRST $pagetypepattern will be set)
// We are applying it to all blocks created in mod pages for now and only if the
// default pagetype is not one of the available options
if (preg_match('/^mod-.*-/', $pagetypepattern)) {
$pagetypelist = generate_page_type_patterns($this->page->pagetype, null, $this->page->context);
// Only go for the first if the pagetype is not a valid option
if (is_array($pagetypelist) && !array_key_exists($pagetypepattern, $pagetypelist)) {
$pagetypepattern = key($pagetypelist);
}
}
// Surely other pages like course-report will need this too, they just are not important
// enough now. This will be decided in the coming days. (MDL-27829, MDL-28150)
return $this->add_block($blockname, $defaulregion, $weight, false, $pagetypepattern, $subpage);
}
/**
* Convenience method, calls add_block repeatedly for all the blocks in $blocks. Optionally, a starting weight
* can be used to decide the starting point that blocks are added in the region, the weight is passed to {@link add_block}
* and incremented by the position of the block in the $blocks array
*
* @param array $blocks array with array keys the region names, and values an array of block names.
* @param string|null $pagetypepattern optional. Passed to {@see self::add_block()}
* @param string|null $subpagepattern optional. Passed to {@see self::add_block()}
* @param bool $showinsubcontexts optional. Passed to {@see self::add_block()}
* @param int $weight optional. Determines the starting point that the blocks are added in the region.
*/
public function add_blocks($blocks, $pagetypepattern = NULL, $subpagepattern = NULL, $showinsubcontexts=false, $weight=0) {
$initialweight = $weight;
$this->add_regions(array_keys($blocks), false);
foreach ($blocks as $region => $regionblocks) {
foreach ($regionblocks as $offset => $blockname) {
$weight = $initialweight + $offset;
$this->add_block($blockname, $region, $weight, $showinsubcontexts, $pagetypepattern, $subpagepattern);
}
}
}
/**
* Move a block to a new position on this page.
*
* If this block cannot appear on any other pages, then we change defaultposition/weight
* in the block_instances table. Otherwise we just set the position on this page.
*
* @param $blockinstanceid the block instance id.
* @param $newregion the new region name.
* @param $newweight the new weight.
*/
public function reposition_block($blockinstanceid, $newregion, $newweight) {
global $DB;
$this->check_region_is_known($newregion);
$inst = $this->find_instance($blockinstanceid);
$bi = $inst->instance;
if ($bi->weight == $bi->defaultweight && $bi->region == $bi->defaultregion &&
!$bi->showinsubcontexts && strpos($bi->pagetypepattern, '*') === false &&
(!$this->page->subpage || $bi->subpagepattern)) {
// Set default position
$newbi = new stdClass;
$newbi->id = $bi->id;
$newbi->defaultregion = $newregion;
$newbi->defaultweight = $newweight;
$newbi->timemodified = time();
$DB->update_record('block_instances', $newbi);
if ($bi->blockpositionid) {
$bp = new stdClass;
$bp->id = $bi->blockpositionid;
$bp->region = $newregion;
$bp->weight = $newweight;
$DB->update_record('block_positions', $bp);
}
} else {
// Just set position on this page.
$bp = new stdClass;
$bp->region = $newregion;
$bp->weight = $newweight;
if ($bi->blockpositionid) {
$bp->id = $bi->blockpositionid;
$DB->update_record('block_positions', $bp);
} else {
$bp->blockinstanceid = $bi->id;
$bp->contextid = $this->page->context->id;
$bp->pagetype = $this->page->pagetype;
if ($this->page->subpage) {
$bp->subpage = $this->page->subpage;