forked from moodle/moodle
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathoutputrenderers.php
2417 lines (2122 loc) · 95 KB
/
outputrenderers.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/>.
/**
* Classes for rendering HTML output for Moodle.
*
* Please see http://docs.moodle.org/en/Developement:How_Moodle_outputs_HTML
* for an overview.
*
* @package moodlecore
* @copyright 2009 Tim Hunt
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
/**
* Simple base class for Moodle renderers.
*
* Tracks the xhtml_container_stack to use, which is passed in in the constructor.
*
* Also has methods to facilitate generating HTML output.
*
* @copyright 2009 Tim Hunt
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
* @since Moodle 2.0
*/
class renderer_base {
/** @var xhtml_container_stack the xhtml_container_stack to use. */
protected $opencontainers;
/** @var moodle_page the page we are rendering for. */
protected $page;
/** @var requested rendering target conatnt */
protected $target;
/**
* Constructor
* @param moodle_page $page the page we are doing output for.
* @param string $target one of rendering target constants
*/
public function __construct(moodle_page $page, $target) {
$this->opencontainers = $page->opencontainers;
$this->page = $page;
$this->target = $target;
}
/**
* Returns rendered widget.
* @param renderable $widget intence with renderable interface
* @return string
*/
public function render(renderable $widget) {
$rendermethod = 'render_'.get_class($widget);
if (method_exists($this, $rendermethod)) {
return $this->$rendermethod($widget);
}
throw new coding_exception('Can not render widget, renderer method ('.$rendermethod.') not found.');
}
/**
* Adds JS handlers needed for event execution for one html element id
* @param component_action $actions
* @param string $id
* @return string id of element, either original submitted or random new if not supplied
*/
public function add_action_handler(component_action $action, $id=null) {
if (!$id) {
$id = html_writer::random_id($action->event);
}
$this->page->requires->event_handler("#$id", $action->event, $action->jsfunction, $action->jsfunctionargs);
return $id;
}
/**
* Have we started output yet?
* @return boolean true if the header has been printed.
*/
public function has_started() {
return $this->page->state >= moodle_page::STATE_IN_BODY;
}
/**
* Given an array or space-separated list of classes, prepares and returns the HTML class attribute value
* @param mixed $classes Space-separated string or array of classes
* @return string HTML class attribute value
*/
public static function prepare_classes($classes) {
if (is_array($classes)) {
return implode(' ', array_unique($classes));
}
return $classes;
}
/**
* Return the moodle_url for an image.
* The exact image location and extension is determined
* automatically by searching for gif|png|jpg|jpeg, please
* note there can not be diferent images with the different
* extension. The imagename is for historical reasons
* a relative path name, it may be changed later for core
* images. It is recommended to not use subdirectories
* in plugin and theme pix directories.
*
* There are three types of images:
* 1/ theme images - stored in theme/mytheme/pix/,
* use component 'theme'
* 2/ core images - stored in /pix/,
* overridden via theme/mytheme/pix_core/
* 3/ plugin images - stored in mod/mymodule/pix,
* overridden via theme/mytheme/pix_plugins/mod/mymodule/,
* example: pix_url('comment', 'mod_glossary')
*
* @param string $imagename the pathname of the image
* @param string $component full plugin name (aka component) or 'theme'
* @return moodle_url
*/
public function pix_url($imagename, $component = 'moodle') {
return $this->page->theme->pix_url($imagename, $component);
}
}
/**
* Basis for all plugin renderers.
*
* @author Petr Skoda (skodak)
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
* @since Moodle 2.0
*/
class plugin_renderer_base extends renderer_base {
/**
* A reference to the current general renderer probably {@see core_renderer}
* @var renderer_base
*/
protected $output;
/**
* Contructor method, calls the parent constructor
* @param moodle_page $page
* @param string $target one of rendering target constants
*/
public function __construct(moodle_page $page, $target) {
$this->output = $page->get_renderer('core', null, $target);
parent::__construct($page, $target);
}
/**
* Returns rendered widget.
* @param renderable $widget intence with renderable interface
* @return string
*/
public function render(renderable $widget) {
$rendermethod = 'render_'.get_class($widget);
if (method_exists($this, $rendermethod)) {
return $this->$rendermethod($widget);
}
// pass to core renderer if method not found here
$this->output->render($widget);
}
/**
* Magic method used to pass calls otherwise meant for the standard renderer
* to it to ensure we don't go causing unnessecary greif.
*
* @param string $method
* @param array $arguments
* @return mixed
*/
public function __call($method, $arguments) {
if (method_exists('renderer_base', $method)) {
throw new coding_exception('Protected method called against '.__CLASS__.' :: '.$method);
}
if (method_exists($this->output, $method)) {
return call_user_func_array(array($this->output, $method), $arguments);
} else {
throw new coding_exception('Unknown method called against '.__CLASS__.' :: '.$method);
}
}
}
/**
* The standard implementation of the core_renderer interface.
*
* @copyright 2009 Tim Hunt
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
* @since Moodle 2.0
*/
class core_renderer extends renderer_base {
/** @var string used in {@link header()}. */
const PERFORMANCE_INFO_TOKEN = '%%PERFORMANCEINFO%%';
/** @var string used in {@link header()}. */
const END_HTML_TOKEN = '%%ENDHTML%%';
/** @var string used in {@link header()}. */
const MAIN_CONTENT_TOKEN = '[MAIN CONTENT GOES HERE]';
/** @var string used to pass information from {@link doctype()} to {@link standard_head_html()}. */
protected $contenttype;
/** @var string used by {@link redirect_message()} method to communicate with {@link header()}. */
protected $metarefreshtag = '';
/**
* Get the DOCTYPE declaration that should be used with this page. Designed to
* be called in theme layout.php files.
* @return string the DOCTYPE declaration (and any XML prologue) that should be used.
*/
public function doctype() {
global $CFG;
$doctype = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">' . "\n";
$this->contenttype = 'text/html; charset=utf-8';
if (empty($CFG->xmlstrictheaders)) {
return $doctype;
}
// We want to serve the page with an XML content type, to force well-formedness errors to be reported.
$prolog = '<?xml version="1.0" encoding="utf-8"?>' . "\n";
if (isset($_SERVER['HTTP_ACCEPT']) && strpos($_SERVER['HTTP_ACCEPT'], 'application/xhtml+xml') !== false) {
// Firefox and other browsers that can cope natively with XHTML.
$this->contenttype = 'application/xhtml+xml; charset=utf-8';
} else if (preg_match('/MSIE.*Windows NT/', $_SERVER['HTTP_USER_AGENT'])) {
// IE can't cope with application/xhtml+xml, but it will cope if we send application/xml with an XSL stylesheet.
$this->contenttype = 'application/xml; charset=utf-8';
$prolog .= '<?xml-stylesheet type="text/xsl" href="' . $CFG->httpswwwroot . '/lib/xhtml.xsl"?>' . "\n";
} else {
$prolog = '';
}
return $prolog . $doctype;
}
/**
* The attributes that should be added to the <html> tag. Designed to
* be called in theme layout.php files.
* @return string HTML fragment.
*/
public function htmlattributes() {
return get_html_lang(true) . ' xmlns="http://www.w3.org/1999/xhtml"';
}
/**
* The standard tags (meta tags, links to stylesheets and JavaScript, etc.)
* that should be included in the <head> tag. Designed to be called in theme
* layout.php files.
* @return string HTML fragment.
*/
public function standard_head_html() {
global $CFG, $SESSION;
$output = '';
$output .= '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />' . "\n";
$output .= '<meta name="keywords" content="moodle, ' . $this->page->title . '" />' . "\n";
if (!$this->page->cacheable) {
$output .= '<meta http-equiv="pragma" content="no-cache" />' . "\n";
$output .= '<meta http-equiv="expires" content="0" />' . "\n";
}
// This is only set by the {@link redirect()} method
$output .= $this->metarefreshtag;
// Check if a periodic refresh delay has been set and make sure we arn't
// already meta refreshing
if ($this->metarefreshtag=='' && $this->page->periodicrefreshdelay!==null) {
$output .= '<meta http-equiv="refresh" content="'.$this->page->periodicrefreshdelay.';url='.$this->page->url->out().'" />';
}
$this->page->requires->js_function_call('setTimeout', array('fix_column_widths()', 20));
$focus = $this->page->focuscontrol;
if (!empty($focus)) {
if (preg_match("#forms\['([a-zA-Z0-9]+)'\].elements\['([a-zA-Z0-9]+)'\]#", $focus, $matches)) {
// This is a horrifically bad way to handle focus but it is passed in
// through messy formslib::moodleform
$this->page->requires->js_function_call('old_onload_focus', array($matches[1], $matches[2]));
} else if (strpos($focus, '.')!==false) {
// Old style of focus, bad way to do it
debugging('This code is using the old style focus event, Please update this code to focus on an element id or the moodleform focus method.', DEBUG_DEVELOPER);
$this->page->requires->js_function_call('old_onload_focus', explode('.', $focus, 2));
} else {
// Focus element with given id
$this->page->requires->js_function_call('focuscontrol', array($focus));
}
}
// Get the theme stylesheet - this has to be always first CSS, this loads also styles.css from all plugins;
// any other custom CSS can not be overridden via themes and is highly discouraged
$urls = $this->page->theme->css_urls($this->page);
foreach ($urls as $url) {
$this->page->requires->css_theme($url);
}
// Get the theme javascript head and footer
$jsurl = $this->page->theme->javascript_url(true);
$this->page->requires->js($jsurl, true);
$jsurl = $this->page->theme->javascript_url(false);
$this->page->requires->js($jsurl);
// Perform a browser environment check for the flash version. Should only run once per login session.
if (!NO_MOODLE_COOKIES && isloggedin() && !empty($CFG->excludeoldflashclients) && empty($SESSION->flashversion)) {
$this->page->requires->js('/lib/swfobject/swfobject.js');
$this->page->requires->js_init_call('M.core_flashdetect.init');
}
// Get any HTML from the page_requirements_manager.
$output .= $this->page->requires->get_head_code($this->page, $this);
// List alternate versions.
foreach ($this->page->alternateversions as $type => $alt) {
$output .= html_writer::empty_tag('link', array('rel' => 'alternate',
'type' => $type, 'title' => $alt->title, 'href' => $alt->url));
}
return $output;
}
/**
* The standard tags (typically skip links) that should be output just inside
* the start of the <body> tag. Designed to be called in theme layout.php files.
* @return string HTML fragment.
*/
public function standard_top_of_body_html() {
return $this->page->requires->get_top_of_body_code();
}
/**
* The standard tags (typically performance information and validation links,
* if we are in developer debug mode) that should be output in the footer area
* of the page. Designed to be called in theme layout.php files.
* @return string HTML fragment.
*/
public function standard_footer_html() {
global $CFG;
// This function is normally called from a layout.php file in {@link header()}
// but some of the content won't be known until later, so we return a placeholder
// for now. This will be replaced with the real content in {@link footer()}.
$output = self::PERFORMANCE_INFO_TOKEN;
if ($this->page->legacythemeinuse) {
// The legacy theme is in use print the notification
$output .= html_writer::tag('div', get_string('legacythemeinuse'), array('class'=>'legacythemeinuse'));
}
if (!empty($CFG->debugpageinfo)) {
$output .= '<div class="performanceinfo">This page is: ' . $this->page->debug_summary() . '</div>';
}
if (!empty($CFG->debugvalidators)) {
$output .= '<div class="validators"><ul>
<li><a href="http://validator.w3.org/check?verbose=1&ss=1&uri=' . urlencode(qualified_me()) . '">Validate HTML</a></li>
<li><a href="http://www.contentquality.com/mynewtester/cynthia.exe?rptmode=-1&url1=' . urlencode(qualified_me()) . '">Section 508 Check</a></li>
<li><a href="http://www.contentquality.com/mynewtester/cynthia.exe?rptmode=0&warnp2n3e=1&url1=' . urlencode(qualified_me()) . '">WCAG 1 (2,3) Check</a></li>
</ul></div>';
}
return $output;
}
/**
* The standard tags (typically script tags that are not needed earlier) that
* should be output after everything else, . Designed to be called in theme layout.php files.
* @return string HTML fragment.
*/
public function standard_end_of_body_html() {
// This function is normally called from a layout.php file in {@link header()}
// but some of the content won't be known until later, so we return a placeholder
// for now. This will be replaced with the real content in {@link footer()}.
echo self::END_HTML_TOKEN;
}
/**
* Return the standard string that says whether you are logged in (and switched
* roles/logged in as another user).
* @return string HTML fragment.
*/
public function login_info() {
global $USER, $CFG, $DB;
if (during_initial_install()) {
return '';
}
$course = $this->page->course;
if (session_is_loggedinas()) {
$realuser = session_get_realuser();
$fullname = fullname($realuser, true);
$realuserinfo = " [<a href=\"$CFG->wwwroot/course/loginas.php?id=$course->id&return=1&sesskey=".sesskey()."\">$fullname</a>] ";
} else {
$realuserinfo = '';
}
$loginurl = get_login_url();
if (empty($course->id)) {
// $course->id is not defined during installation
return '';
} else if (isloggedin()) {
$context = get_context_instance(CONTEXT_COURSE, $course->id);
$fullname = fullname($USER, true);
// Since Moodle 2.0 this link always goes to the public profile page (not the course profile page)
$username = "<a href=\"$CFG->wwwroot/user/profile.php?id=$USER->id\">$fullname</a>";
if (is_mnet_remote_user($USER) and $idprovider = $DB->get_record('mnet_host', array('id'=>$USER->mnethostid))) {
$username .= " from <a href=\"{$idprovider->wwwroot}\">{$idprovider->name}</a>";
}
if (isset($USER->username) && $USER->username == 'guest') {
$loggedinas = $realuserinfo.get_string('loggedinasguest').
" (<a href=\"$loginurl\">".get_string('login').'</a>)';
} else if (!empty($USER->access['rsw'][$context->path])) {
$rolename = '';
if ($role = $DB->get_record('role', array('id'=>$USER->access['rsw'][$context->path]))) {
$rolename = ': '.format_string($role->name);
}
$loggedinas = get_string('loggedinas', 'moodle', $username).$rolename.
" (<a href=\"$CFG->wwwroot/course/view.php?id=$course->id&switchrole=0&sesskey=".sesskey()."\">".get_string('switchrolereturn').'</a>)';
} else {
$loggedinas = $realuserinfo.get_string('loggedinas', 'moodle', $username).' '.
" (<a href=\"$CFG->wwwroot/login/logout.php?sesskey=".sesskey()."\">".get_string('logout').'</a>)';
}
} else {
$loggedinas = get_string('loggedinnot', 'moodle').
" (<a href=\"$loginurl\">".get_string('login').'</a>)';
}
$loggedinas = '<div class="logininfo">'.$loggedinas.'</div>';
if (isset($SESSION->justloggedin)) {
unset($SESSION->justloggedin);
if (!empty($CFG->displayloginfailures)) {
if (!empty($USER->username) and $USER->username != 'guest') {
if ($count = count_login_failures($CFG->displayloginfailures, $USER->username, $USER->lastlogin)) {
$loggedinas .= ' <div class="loginfailures">';
if (empty($count->accounts)) {
$loggedinas .= get_string('failedloginattempts', '', $count);
} else {
$loggedinas .= get_string('failedloginattemptsall', '', $count);
}
if (has_capability('coursereport/log:view', get_context_instance(CONTEXT_SYSTEM))) {
$loggedinas .= ' (<a href="'.$CFG->wwwroot.'/course/report/log/index.php'.
'?chooselog=1&id=1&modid=site_errors">'.get_string('logs').'</a>)';
}
$loggedinas .= '</div>';
}
}
}
}
return $loggedinas;
}
/**
* Return the 'back' link that normally appears in the footer.
* @return string HTML fragment.
*/
public function home_link() {
global $CFG, $SITE;
if ($this->page->pagetype == 'site-index') {
// Special case for site home page - please do not remove
return '<div class="sitelink">' .
'<a title="Moodle" href="http://moodle.org/">' .
'<img style="width:100px;height:30px" src="' . $this->pix_url('moodlelogo') . '" alt="moodlelogo" /></a></div>';
} else if (!empty($CFG->target_release) && $CFG->target_release != $CFG->release) {
// Special case for during install/upgrade.
return '<div class="sitelink">'.
'<a title="Moodle" href="http://docs.moodle.org/en/Administrator_documentation" onclick="this.target=\'_blank\'">' .
'<img style="width:100px;height:30px" src="' . $this->pix_url('moodlelogo') . '" alt="moodlelogo" /></a></div>';
} else if ($this->page->course->id == $SITE->id || strpos($this->page->pagetype, 'course-view') === 0) {
return '<div class="homelink"><a href="' . $CFG->wwwroot . '/">' .
get_string('home') . '</a></div>';
} else {
return '<div class="homelink"><a href="' . $CFG->wwwroot . '/course/view.php?id=' . $this->page->course->id . '">' .
format_string($this->page->course->shortname) . '</a></div>';
}
}
/**
* Redirects the user by any means possible given the current state
*
* This function should not be called directly, it should always be called using
* the redirect function in lib/weblib.php
*
* The redirect function should really only be called before page output has started
* however it will allow itself to be called during the state STATE_IN_BODY
*
* @param string $encodedurl The URL to send to encoded if required
* @param string $message The message to display to the user if any
* @param int $delay The delay before redirecting a user, if $message has been
* set this is a requirement and defaults to 3, set to 0 no delay
* @param boolean $debugdisableredirect this redirect has been disabled for
* debugging purposes. Display a message that explains, and don't
* trigger the redirect.
* @return string The HTML to display to the user before dying, may contain
* meta refresh, javascript refresh, and may have set header redirects
*/
public function redirect_message($encodedurl, $message, $delay, $debugdisableredirect) {
global $CFG;
$url = str_replace('&', '&', $encodedurl);
switch ($this->page->state) {
case moodle_page::STATE_BEFORE_HEADER :
// No output yet it is safe to delivery the full arsenal of redirect methods
if (!$debugdisableredirect) {
// Don't use exactly the same time here, it can cause problems when both redirects fire at the same time.
$this->metarefreshtag = '<meta http-equiv="refresh" content="'. $delay .'; url='. $encodedurl .'" />'."\n";
$this->page->requires->js_function_call('document.location.replace', array($url), false, ($delay + 3));
}
$output = $this->header();
break;
case moodle_page::STATE_PRINTING_HEADER :
// We should hopefully never get here
throw new coding_exception('You cannot redirect while printing the page header');
break;
case moodle_page::STATE_IN_BODY :
// We really shouldn't be here but we can deal with this
debugging("You should really redirect before you start page output");
if (!$debugdisableredirect) {
$this->page->requires->js_function_call('document.location.replace', array($url), false, $delay);
}
$output = $this->opencontainers->pop_all_but_last();
break;
case moodle_page::STATE_DONE :
// Too late to be calling redirect now
throw new coding_exception('You cannot redirect after the entire page has been generated');
break;
}
$output .= $this->notification($message, 'redirectmessage');
$output .= '<a href="'. $encodedurl .'">'. get_string('continue') .'</a>';
if ($debugdisableredirect) {
$output .= '<p><strong>Error output, so disabling automatic redirect.</strong></p>';
}
$output .= $this->footer();
return $output;
}
/**
* Start output by sending the HTTP headers, and printing the HTML <head>
* and the start of the <body>.
*
* To control what is printed, you should set properties on $PAGE. If you
* are familiar with the old {@link print_header()} function from Moodle 1.9
* you will find that there are properties on $PAGE that correspond to most
* of the old parameters to could be passed to print_header.
*
* Not that, in due course, the remaining $navigation, $menu parameters here
* will be replaced by more properties of $PAGE, but that is still to do.
*
* @return string HTML that you must output this, preferably immediately.
*/
public function header() {
global $USER, $CFG;
$this->page->set_state(moodle_page::STATE_PRINTING_HEADER);
// Find the appropriate page layout file, based on $this->page->pagelayout.
$layoutfile = $this->page->theme->layout_file($this->page->pagelayout);
// Render the layout using the layout file.
$rendered = $this->render_page_layout($layoutfile);
// Slice the rendered output into header and footer.
$cutpos = strpos($rendered, self::MAIN_CONTENT_TOKEN);
if ($cutpos === false) {
throw new coding_exception('page layout file ' . $layoutfile .
' does not contain the string "' . self::MAIN_CONTENT_TOKEN . '".');
}
$header = substr($rendered, 0, $cutpos);
$footer = substr($rendered, $cutpos + strlen(self::MAIN_CONTENT_TOKEN));
if (empty($this->contenttype)) {
debugging('The page layout file did not call $OUTPUT->doctype()');
$header = $this->doctype() . $header;
}
send_headers($this->contenttype, $this->page->cacheable);
$this->opencontainers->push('header/footer', $footer);
$this->page->set_state(moodle_page::STATE_IN_BODY);
return $header . $this->skip_link_target();
}
/**
* Renders and outputs the page layout file.
* @param string $layoutfile The name of the layout file
* @return string HTML code
*/
protected function render_page_layout($layoutfile) {
global $CFG, $SITE, $USER;
// The next lines are a bit tricky. The point is, here we are in a method
// of a renderer class, and this object may, or may not, be the same as
// the global $OUTPUT object. When rendering the page layout file, we want to use
// this object. However, people writing Moodle code expect the current
// renderer to be called $OUTPUT, not $this, so define a variable called
// $OUTPUT pointing at $this. The same comment applies to $PAGE and $COURSE.
$OUTPUT = $this;
$PAGE = $this->page;
$COURSE = $this->page->course;
ob_start();
include($layoutfile);
$rendered = ob_get_contents();
ob_end_clean();
return $rendered;
}
/**
* Outputs the page's footer
* @return string HTML fragment
*/
public function footer() {
global $CFG, $DB;
$output = $this->container_end_all(true);
$footer = $this->opencontainers->pop('header/footer');
if (debugging() and $DB and $DB->is_transaction_started()) {
// TODO: MDL-20625 print warning - transaction will be rolled back
}
// Provide some performance info if required
$performanceinfo = '';
if (defined('MDL_PERF') || (!empty($CFG->perfdebug) and $CFG->perfdebug > 7)) {
$perf = get_performance_info();
if (defined('MDL_PERFTOLOG') && !function_exists('register_shutdown_function')) {
error_log("PERF: " . $perf['txt']);
}
if (defined('MDL_PERFTOFOOT') || debugging() || $CFG->perfdebug > 7) {
$performanceinfo = $perf['html'];
}
}
$footer = str_replace(self::PERFORMANCE_INFO_TOKEN, $performanceinfo, $footer);
$footer = str_replace(self::END_HTML_TOKEN, $this->page->requires->get_end_code(), $footer);
$this->page->set_state(moodle_page::STATE_DONE);
return $output . $footer;
}
/**
* Close all but the last open container. This is useful in places like error
* handling, where you want to close all the open containers (apart from <body>)
* before outputting the error message.
* @param bool $shouldbenone assert that the stack should be empty now - causes a
* developer debug warning if it isn't.
* @return string the HTML required to close any open containers inside <body>.
*/
public function container_end_all($shouldbenone = false) {
return $this->opencontainers->pop_all_but_last($shouldbenone);
}
/**
* Returns lang menu or '', this method also checks forcing of languages in courses.
* @return string
*/
public function lang_menu() {
global $CFG;
if (empty($CFG->langmenu)) {
return '';
}
if ($this->page->course != SITEID and !empty($this->page->course->lang)) {
// do not show lang menu if language forced
return '';
}
$currlang = current_language();
$langs = get_string_manager()->get_list_of_translations();
if (count($langs) < 2) {
return '';
}
$s = new single_select($this->page->url, 'lang', $langs, $currlang, null);
$s->label = get_accesshide(get_string('language'));
$s->class = 'langmenu';
return $this->render($s);
}
/**
* Output the row of editing icons for a block, as defined by the controls array.
* @param array $controls an array like {@link block_contents::$controls}.
* @return HTML fragment.
*/
public function block_controls($controls) {
if (empty($controls)) {
return '';
}
$controlshtml = array();
foreach ($controls as $control) {
$controlshtml[] = html_writer::tag('a',
html_writer::empty_tag('img', array('src' => $this->pix_url($control['icon'])->out(false), 'alt' => $control['caption'])),
array('class' => 'icon','title' => $control['caption'], 'href' => $control['url']));
}
return html_writer::tag('div', implode('', $controlshtml), array('class' => 'commands'));
}
/**
* Prints a nice side block with an optional header.
*
* The content is described
* by a {@link block_contents} object.
*
* @param block_contents $bc HTML for the content
* @param string $region the region the block is appearing in.
* @return string the HTML to be output.
*/
function block(block_contents $bc, $region) {
$bc = clone($bc); // Avoid messing up the object passed in.
if (empty($bc->blockinstanceid) || !strip_tags($bc->title)) {
$bc->collapsible = block_contents::NOT_HIDEABLE;
}
if ($bc->collapsible == block_contents::HIDDEN) {
$bc->add_class('hidden');
}
if (!empty($bc->controls)) {
$bc->add_class('block_with_controls');
}
$skiptitle = strip_tags($bc->title);
if (empty($skiptitle)) {
$output = '';
$skipdest = '';
} else {
$output = html_writer::tag('a', get_string('skipa', 'access', $skiptitle), array('href' => '#sb-' . $bc->skipid, 'class' => 'skip-block'));
$skipdest = html_writer::tag('span', '', array('id' => 'sb-' . $bc->skipid, 'class' => 'skip-block-to'));
}
$output .= html_writer::start_tag('div', $bc->attributes);
$controlshtml = $this->block_controls($bc->controls);
$title = '';
if ($bc->title) {
$title = html_writer::tag('h2', $bc->title, null);
}
if ($title || $controlshtml) {
$output .= html_writer::tag('div', html_writer::tag('div', html_writer::tag('div', '', array('class'=>'block_action')). $title . $controlshtml, array('class' => 'title')), array('class' => 'header'));
}
$output .= html_writer::start_tag('div', array('class' => 'content'));
if (!$title && !$controlshtml) {
$output .= html_writer::tag('div', '', array('class'=>'block_action notitle'));
}
$output .= $bc->content;
if ($bc->footer) {
$output .= html_writer::tag('div', $bc->footer, array('class' => 'footer'));
}
$output .= html_writer::end_tag('div');
$output .= html_writer::end_tag('div');
if ($bc->annotation) {
$output .= html_writer::tag('div', $bc->annotation, array('class' => 'blockannotation'));
}
$output .= $skipdest;
$this->init_block_hider_js($bc);
return $output;
}
/**
* Calls the JS require function to hide a block.
* @param block_contents $bc A block_contents object
* @return void
*/
protected function init_block_hider_js(block_contents $bc) {
if (!empty($bc->attributes['id']) and $bc->collapsible != block_contents::NOT_HIDEABLE) {
$userpref = 'block' . $bc->blockinstanceid . 'hidden';
user_preference_allow_ajax_update($userpref, PARAM_BOOL);
$this->page->requires->yui2_lib('dom');
$this->page->requires->yui2_lib('event');
$plaintitle = strip_tags($bc->title);
$this->page->requires->js_function_call('new block_hider', array($bc->attributes['id'], $userpref,
get_string('hideblocka', 'access', $plaintitle), get_string('showblocka', 'access', $plaintitle),
$this->pix_url('t/switch_minus')->out(false), $this->pix_url('t/switch_plus')->out(false)));
}
}
/**
* Render the contents of a block_list.
* @param array $icons the icon for each item.
* @param array $items the content of each item.
* @return string HTML
*/
public function list_block_contents($icons, $items) {
$row = 0;
$lis = array();
foreach ($items as $key => $string) {
$item = html_writer::start_tag('li', array('class' => 'r' . $row));
if (!empty($icons[$key])) { //test if the content has an assigned icon
$item .= html_writer::tag('div', $icons[$key], array('class' => 'icon column c0'));
}
$item .= html_writer::tag('div', $string, array('class' => 'column c1'));
$item .= html_writer::end_tag('li');
$lis[] = $item;
$row = 1 - $row; // Flip even/odd.
}
return html_writer::tag('ul', implode("\n", $lis), array('class' => 'list'));
}
/**
* Output all the blocks in a particular region.
* @param string $region the name of a region on this page.
* @return string the HTML to be output.
*/
public function blocks_for_region($region) {
$blockcontents = $this->page->blocks->get_content_for_region($region, $this);
$output = '';
foreach ($blockcontents as $bc) {
if ($bc instanceof block_contents) {
$output .= $this->block($bc, $region);
} else if ($bc instanceof block_move_target) {
$output .= $this->block_move_target($bc);
} else {
throw new coding_exception('Unexpected type of thing (' . get_class($bc) . ') found in list of block contents.');
}
}
return $output;
}
/**
* Output a place where the block that is currently being moved can be dropped.
* @param block_move_target $target with the necessary details.
* @return string the HTML to be output.
*/
public function block_move_target($target) {
return html_writer::tag('a', html_writer::tag('span', $target->text, array('class' => 'accesshide')), array('href' => $target->url, 'class' => 'blockmovetarget'));
}
/**
* Renders a sepcial html link with attached action
*
* @param string|moodle_url $url
* @param string $text HTML fragment
* @param component_action $action
* @param array $attributes associative array of html link attributes + disabled
* @return HTML fragment
*/
public function action_link($url, $text, component_action $action = null, array $attributes=null) {
if (!($url instanceof moodle_url)) {
$url = new moodle_url($url);
}
$link = new action_link($url, $text, $action, $attributes);
return $this->render($link);
}
/**
* Implementation of action_link rendering
* @param action_link $link
* @return string HTML fragment
*/
protected function render_action_link(action_link $link) {
global $CFG;
// A disabled link is rendered as formatted text
if (!empty($link->attributes['disabled'])) {
// do not use div here due to nesting restriction in xhtml strict
return html_writer::tag('span', $link->text, array('class'=>'currentlink'));
}
$attributes = $link->attributes;
unset($link->attributes['disabled']);
$attributes['href'] = $link->url;
if ($link->actions) {
if (empty($attributes['id'])) {
$id = html_writer::random_id('action_link');
$attributes['id'] = $id;
} else {
$id = $attributes['id'];
}
foreach ($link->actions as $action) {
$this->add_action_handler($action, $id);
}
}
return html_writer::tag('a', $link->text, $attributes);
}
/**
* Similar to action_link, image is used instead of the text
*
* @param string|moodle_url $url A string URL or moodel_url
* @param pix_icon $pixicon
* @param component_action $action
* @param array $attributes associative array of html link attributes + disabled
* @param bool $linktext show title next to image in link
* @return string HTML fragment
*/
public function action_icon($url, pix_icon $pixicon, component_action $action = null, array $attributes = null, $linktext=false) {
if (!($url instanceof moodle_url)) {
$url = new moodle_url($url);
}
$attributes = (array)$attributes;
if (empty($attributes['class'])) {
// let ppl override the class via $options
$attributes['class'] = 'action-icon';
}
$icon = $this->render($pixicon);
if ($linktext) {
$text = $pixicon->attributes['alt'];
} else {
$text = '';
}
return $this->action_link($url, $text.$icon, $action, $attributes);
}
/**
* Print a message along with button choices for Continue/Cancel
*
* If a string or moodle_url is given instead of a single_button, method defaults to post.
*
* @param string $message The question to ask the user
* @param single_button|moodle_url|string $continue The single_button component representing the Continue answer. Can also be a moodle_url or string URL
* @param single_button|moodle_url|string $cancel The single_button component representing the Cancel answer. Can also be a moodle_url or string URL
* @return string HTML fragment
*/
public function confirm($message, $continue, $cancel) {
if ($continue instanceof single_button) {
// ok
} else if (is_string($continue)) {
$continue = new single_button(new moodle_url($continue), get_string('continue'), 'post');
} else if ($continue instanceof moodle_url) {
$continue = new single_button($continue, get_string('continue'), 'post');
} else {
throw new coding_exception('The continue param to $OUTPUT->confirm() must be either a URL (string/moodle_url) or a single_button instance.');
}
if ($cancel instanceof single_button) {
// ok
} else if (is_string($cancel)) {
$cancel = new single_button(new moodle_url($cancel), get_string('cancel'), 'get');
} else if ($cancel instanceof moodle_url) {
$cancel = new single_button($cancel, get_string('cancel'), 'get');
} else {
throw new coding_exception('The cancel param to $OUTPUT->confirm() must be either a URL (string/moodle_url) or a single_button instance.');
}
$output = $this->box_start('generalbox', 'notice');
$output .= html_writer::tag('p', $message);
$output .= html_writer::tag('div', $this->render($continue) . $this->render($cancel), array('class' => 'buttons'));
$output .= $this->box_end();
return $output;
}
/**
* Returns a form with a single button.
*
* @param string|moodle_url $url
* @param string $label button text
* @param string $method get or post submit method
* @param array $options associative array {disabled, title, etc.}
* @return string HTML fragment
*/
public function single_button($url, $label, $method='post', array $options=null) {
if (!($url instanceof moodle_url)) {
$url = new moodle_url($url);
}
$button = new single_button($url, $label, $method);
foreach ((array)$options as $key=>$value) {
if (array_key_exists($key, $button)) {
$button->$key = $value;
}
}
return $this->render($button);
}
/**
* Internal implementation of single_button rendering
* @param single_button $button
* @return string HTML fragment
*/
protected function render_single_button(single_button $button) {
$attributes = array('type' => 'submit',