Fixes bug MDL-8234, "New groups code & AS keyword"
[moodle-pu.git] / lib / pagelib.php
blob7924d199e5fe3f8bd9aa1dfbd2e47bafbd79027a
1 <?php //$Id$
3 /**
4 * This file contains the parent class for moodle pages, page_base,
5 * as well as the page_course subclass.
6 * A page is defined by its page type (ie. course, blog, activity) and its page id
7 * (courseid, blogid, activity id, etc).
9 * @author Jon Papaioannou
10 * @version $Id$
11 * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
12 * @package pages
15 function page_import_types($path) {
16 global $CFG;
18 static $types = array();
20 if(substr($path, -1) != '/') {
21 $path .= '/';
24 $path = clean_param($path, PARAM_PATH);
26 if(isset($types[$path])) {
27 return $types[$path];
30 $file = $CFG->dirroot.'/'.$path.'pagelib.php';
32 if(is_file($file)) {
33 require($file);
34 if(!isset($DEFINEDPAGES)) {
35 error('Imported '.$file.' but found no page classes');
37 return $types[$path] = $DEFINEDPAGES;
40 return false;
43 /**
44 * Factory function page_create_object(). Called with a numeric ID for a page, it autodetects
45 * the page type, constructs the correct object and returns it.
48 function page_create_instance($instance) {
49 page_id_and_class($id, $class);
50 return page_create_object($id, $instance);
53 /**
54 * Factory function page_create_object(). Called with a pagetype identifier and possibly with
55 * its numeric ID. Returns a fully constructed page_base subclass you can work with.
58 function page_create_object($type, $id = NULL) {
59 global $CFG;
61 $data = new stdClass;
62 $data->pagetype = $type;
63 $data->pageid = $id;
65 $classname = page_map_class($type);
67 $object = &new $classname;
68 // TODO: subclassing check here
70 if ($object->get_type() !== $type) {
71 // Somehow somewhere someone made a mistake
72 debugging('Page object\'s type ('. $object->get_type() .') does not match requested type ('. $type .')');
75 $object->init_quick($data);
76 return $object;
79 /**
80 * Function page_map_class() is the way for your code to define its own page subclasses and let Moodle recognize them.
81 * Use it to associate the textual identifier of your Page with the actual class name that has to be instantiated.
84 function page_map_class($type, $classname = NULL) {
85 global $CFG;
87 static $mappings = NULL;
89 if ($mappings === NULL) {
90 $mappings = array(
91 PAGE_COURSE_VIEW => 'page_course'
95 if (!empty($type) && !empty($classname)) {
96 $mappings[$type] = $classname;
99 if (!isset($mappings[$type])) {
100 debugging('Page class mapping requested for unknown type: '.$type);
103 if (empty($classname) && !class_exists($mappings[$type])) {
104 debugging('Page class mapping for id "'.$type.'" exists but class "'.$mappings[$type].'" is not defined');
107 return $mappings[$type];
111 * Parent class from which all Moodle page classes derive
113 * @author Jon Papaioannou
114 * @package pages
115 * @todo This parent class is very messy still. Please for the moment ignore it and move on to the derived class page_course to see the comments there.
118 class page_base {
120 * The string identifier for the type of page being described.
121 * @var string $type
123 var $type = NULL;
126 * The numeric identifier of the page being described.
127 * @var int $id
129 var $id = NULL;
132 * Class bool to determine if the instance's full initialization has been completed.
133 * @var boolean $full_init_done
135 var $full_init_done = false;
138 * The class attribute that Moodle has to assign to the BODY tag for this page.
139 * @var string $body_class
141 var $body_class = NULL;
144 * The id attribute that Moodle has to assign to the BODY tag for this page.
145 * @var string $body_id
147 var $body_id = NULL;
149 /// Class Functions
151 // CONSTRUCTION
153 // A whole battery of functions to allow standardized-name constructors in all versions of PHP.
154 // The constructor is actually called construct()
155 function page_base() {
156 $this->construct();
159 function __construct() {
160 $this->construct();
163 function construct() {
164 page_id_and_class($this->body_id, $this->body_class);
167 // USER-RELATED THINGS
169 // By default, no user is editing anything and none CAN edit anything. Developers
170 // will have to override these settings to let Moodle know when it should grant
171 // editing rights to the user viewing the page.
172 function user_allowed_editing() {
173 trigger_error('Page class does not implement method <strong>user_allowed_editing()</strong>', E_USER_WARNING);
174 return false;
176 function user_is_editing() {
177 trigger_error('Page class does not implement method <strong>user_is_editing()</strong>', E_USER_WARNING);
178 return false;
181 // HTML OUTPUT SECTION
183 // We have absolutely no idea what derived pages are all about
184 function print_header($title, $morebreadcrumbs) {
185 trigger_error('Page class does not implement method <strong>print_header()</strong>', E_USER_WARNING);
186 return;
189 // BLOCKS RELATED SECTION
191 // By default, pages don't have any blocks. Override this in your derived class if you need blocks.
192 function blocks_get_positions() {
193 return array();
196 // Thus there is no default block position. If you override the above you should override this one too.
197 // Because this makes sense only if blocks_get_positions() is overridden and because these two should
198 // be overridden as a group or not at all, this one issues a warning. The sneaky part is that this warning
199 // will only be seen if you override blocks_get_positions() but NOT blocks_default_position().
200 function blocks_default_position() {
201 trigger_error('Page class does not implement method <strong>blocks_default_position()</strong>', E_USER_WARNING);
202 return NULL;
205 // If you don't override this, newly constructed pages of this kind won't have any blocks.
206 function blocks_get_default() {
207 return '';
210 // If you don't override this, your blocks will not be able to change positions
211 function blocks_move_position(&$instance, $move) {
212 return $instance->position;
215 // SELF-REPORTING SECTION
217 // Derived classes HAVE to define their "home url"
218 function url_get_path() {
219 trigger_error('Page class does not implement method <strong>url_get_path()</strong>', E_USER_WARNING);
220 return NULL;
223 // It's not always required to pass any arguments to the home url, so this doesn't trigger any errors (sensible default)
224 function url_get_parameters() {
225 return array();
228 // This should actually NEVER be overridden unless you have GOOD reason. Works fine as it is.
229 function url_get_full($extraparams = array()) {
230 $path = $this->url_get_path();
231 if(empty($path)) {
232 return NULL;
235 $params = $this->url_get_parameters();
236 if (!empty($params)) {
237 $params = array_merge($params, $extraparams);
238 } else {
239 $params = $extraparams;
242 if(empty($params)) {
243 return $path;
246 $first = true;
248 foreach($params as $var => $value) {
249 $path .= $first? '?' : '&amp;';
250 $path .= $var .'='. urlencode($value);
251 $first = false;
254 return $path;
257 // This forces implementers to actually hardwire their page identification constant in the class.
258 // Good thing, if you ask me. That way we can later auto-detect "installed" page types by querying
259 // the classes themselves in the future.
260 function get_type() {
261 trigger_error('Page class does not implement method <strong>get_type()</strong>', E_USER_ERROR);
262 return NULL;
265 // Simple stuff, do not override this.
266 function get_id() {
267 return $this->id;
270 // "Sensible default" case here. Take it from the body id.
271 function get_format_name() {
272 return $this->body_id;
275 // Returns $this->body_class
276 function get_body_class() {
277 return $this->body_class;
280 // Returns $this->body_id
281 function get_body_id() {
282 return $this->body_id;
285 // Initialize the data members of the parent class
286 function init_quick($data) {
287 $this->type = $data->pagetype;
288 $this->id = $data->pageid;
291 function init_full() {
292 $this->full_init_done = true;
296 // is this page always editable, regardless of anything else?
297 function edit_always() {
298 return (has_capability('moodle/site:manageblocks', get_context_instance(CONTEXT_SYSTEM, SITEID)) && defined('ADMIN_STICKYBLOCKS'));
304 * Class that models the behavior of a moodle course
306 * @author Jon Papaioannou
307 * @package pages
310 class page_course extends page_base {
312 // Any data we might need to store specifically about ourself should be declared here.
313 // After init_full() is called for the first time, ALL of these variables should be
314 // initialized correctly and ready for use.
315 var $courserecord = NULL;
317 // Do any validation of the officially recognized bits of the data and forward to parent.
318 // Do NOT load up "expensive" resouces (e.g. SQL data) here!
319 function init_quick($data) {
320 if(empty($data->pageid) && !defined('ADMIN_STICKYBLOCKS')) {
321 error('Cannot quickly initialize page: empty course id');
323 parent::init_quick($data);
326 // Here you should load up all heavy-duty data for your page. Basically everything that
327 // does not NEED to be loaded for the class to make basic decisions should NOT be loaded
328 // in init_quick() and instead deferred here. Of course this function had better recognize
329 // $this->full_init_done to prevent wasteful multiple-time data retrieval.
330 function init_full() {
331 if($this->full_init_done) {
332 return;
334 if (empty($this->id)) {
335 $this->id = 0; // avoid db errors
337 $this->courserecord = get_record('course', 'id', $this->id);
338 if(empty($this->courserecord) && !defined('ADMIN_STICKYBLOCKS')) {
339 error('Cannot fully initialize page: invalid course id '. $this->id);
341 $this->full_init_done = true;
344 // USER-RELATED THINGS
346 // Can user edit the course page or "sticky page"?
347 // This is also about editting of blocks BUT mainly activities in course page layout, see
348 // update_course_icon() - it must use the same capability
349 function user_allowed_editing() {
350 if (has_capability('moodle/site:manageblocks', get_context_instance(CONTEXT_SYSTEM, SITEID)) && defined('ADMIN_STICKYBLOCKS')) {
351 return true;
353 return has_capability('moodle/course:manageactivities', get_context_instance(CONTEXT_COURSE, $this->id));
356 // Is the user actually editing this course page or "sticky page" right now?
357 function user_is_editing() {
358 if (has_capability('moodle/site:manageblocks', get_context_instance(CONTEXT_SYSTEM, SITEID)) && defined('ADMIN_STICKYBLOCKS')) {
359 //always in edit mode on sticky page
360 return true;
362 return isediting($this->id);
365 // HTML OUTPUT SECTION
367 // This function prints out the common part of the page's header.
368 // You should NEVER print the header "by hand" in other code.
369 function print_header($title, $morebreadcrumbs=NULL, $meta='', $bodytags='') {
370 global $USER, $CFG;
372 $this->init_full();
373 $replacements = array(
374 '%fullname%' => $this->courserecord->fullname
376 foreach($replacements as $search => $replace) {
377 $title = str_replace($search, $replace, $title);
380 if($this->courserecord->id == SITEID) {
381 $breadcrumbs = array();
383 else {
384 $breadcrumbs = array($this->courserecord->shortname => $CFG->wwwroot.'/course/view.php?id='.$this->courserecord->id);
387 if(!empty($morebreadcrumbs)) {
388 $breadcrumbs = array_merge($breadcrumbs, $morebreadcrumbs);
391 $total = count($breadcrumbs);
392 $current = 1;
393 $crumbtext = '';
394 foreach($breadcrumbs as $text => $href) {
395 if($current++ == $total) {
396 $crumbtext .= ' '.$text;
398 else {
399 $crumbtext .= ' <a href="'.$href.'">'.$text.'</a> ->';
403 // The "Editing On" button will be appearing only in the "main" course screen
404 // (i.e., no breadcrumbs other than the default one added inside this function)
405 $buttons = switchroles_form($this->courserecord->id) . update_course_icon($this->courserecord->id );
406 $buttons = empty($morebreadcrumbs) ? $buttons : '&nbsp;';
408 print_header($title, $this->courserecord->fullname, $crumbtext,
409 '', $meta, true, $buttons, user_login_string($this->courserecord, $USER), false, $bodytags);
411 echo '<div class="accesshide"><a href="#startofcontent">'.get_string('skiptomaincontent').'</a></div>';
414 // SELF-REPORTING SECTION
416 // This is hardwired here so the factory function page_create_object() can be sure there was no mistake.
417 // Also, it doubles as a way to let others inquire about our type.
418 function get_type() {
419 return PAGE_COURSE_VIEW;
422 // This is like the "category" of a page of this "type". For example, if the type is PAGE_COURSE_VIEW
423 // the format_name is the actual name of the course format. If the type were PAGE_ACTIVITY_VIEW, then
424 // the format_name might be that activity's name etc.
425 function get_format_name() {
426 $this->init_full();
427 if (defined('ADMIN_STICKYBLOCKS')) {
428 return PAGE_COURSE_VIEW;
430 if($this->id == SITEID) {
431 return parent::get_format_name();
433 return $this->body_id.'-'.$this->courserecord->format;
436 // This should return a fully qualified path to the URL which is responsible for displaying us.
437 function url_get_path() {
438 global $CFG;
439 if (defined('ADMIN_STICKYBLOCKS')) {
440 return $CFG->wwwroot.'/'.$CFG->admin.'/stickyblocks.php';
442 if($this->id == SITEID) {
443 return $CFG->wwwroot .'/index.php';
445 else {
446 return $CFG->wwwroot .'/course/view.php';
450 // This should return an associative array of any GET/POST parameters that are needed by the URL
451 // which displays us to make it work. If none are needed, return an empty array.
452 function url_get_parameters() {
453 if (defined('ADMIN_STICKYBLOCKS')) {
454 return array('pt' => ADMIN_STICKYBLOCKS);
456 if($this->id == SITEID) {
457 return array();
459 else {
460 return array('id' => $this->id);
464 // BLOCKS RELATED SECTION
466 // Which are the positions in this page which support blocks? Return an array containing their identifiers.
467 // BE CAREFUL, ORDER DOES MATTER! In textual representations, lists of blocks in a page use the ':' character
468 // to delimit different positions in the page. The part before the first ':' in such a representation will map
469 // directly to the first item of the array you return here, the second to the next one and so on. This way,
470 // you can add more positions in the future without interfering with legacy textual representations.
471 function blocks_get_positions() {
472 return array(BLOCK_POS_LEFT, BLOCK_POS_RIGHT);
475 // When a new block is created in this page, which position should it go to?
476 function blocks_default_position() {
477 return BLOCK_POS_RIGHT;
480 // When we are creating a new page, use the data at your disposal to provide a textual representation of the
481 // blocks that are going to get added to this new page. Delimit block names with commas (,) and use double
482 // colons (:) to delimit between block positions in the page. See blocks_get_positions() for additional info.
483 function blocks_get_default() {
484 global $CFG;
486 $this->init_full();
488 if($this->id == SITEID) {
489 // Is it the site?
490 if (!empty($CFG->defaultblocks_site)) {
491 $blocknames = $CFG->defaultblocks_site;
493 /// Failsafe - in case nothing was defined.
494 else {
495 $blocknames = 'site_main_menu,admin_tree:course_summary,calendar_month';
498 // It's a normal course, so do it according to the course format
499 else {
500 $pageformat = $this->courserecord->format;
501 if (!empty($CFG->{'defaultblocks_'. $pageformat})) {
502 $blocknames = $CFG->{'defaultblocks_'. $pageformat};
504 else {
505 $format_config = $CFG->dirroot.'/course/format/'.$pageformat.'/config.php';
506 if (@is_file($format_config) && is_readable($format_config)) {
507 require($format_config);
509 if (!empty($format['defaultblocks'])) {
510 $blocknames = $format['defaultblocks'];
512 else if (!empty($CFG->defaultblocks)){
513 $blocknames = $CFG->defaultblocks;
515 /// Failsafe - in case nothing was defined.
516 else {
517 $blocknames = 'participants,activity_modules,search_forums,admin,course_list:news_items,calendar_upcoming,recent_activity';
522 return $blocknames;
525 // Given an instance of a block in this page and the direction in which we want to move it, where is
526 // it going to go? Return the identifier of the instance's new position. This allows us to tell blocklib
527 // how we want the blocks to move around in this page in an arbitrarily complex way. If the move as given
528 // does not make sense, make sure to return the instance's original position.
530 // Since this is going to get called a LOT, pass the instance by reference purely for speed. Do **NOT**
531 // modify its data in any way, this will actually confuse blocklib!!!
532 function blocks_move_position(&$instance, $move) {
533 if($instance->position == BLOCK_POS_LEFT && $move == BLOCK_MOVE_RIGHT) {
534 return BLOCK_POS_RIGHT;
535 } else if ($instance->position == BLOCK_POS_RIGHT && $move == BLOCK_MOVE_LEFT) {
536 return BLOCK_POS_LEFT;
538 return $instance->position;
543 * Class that models the common parts of all activity modules
545 * @author Jon Papaioannou
546 * @package pages
549 class page_generic_activity extends page_base {
550 var $activityname = NULL;
551 var $courserecord = NULL;
552 var $modulerecord = NULL;
553 var $activityrecord = NULL;
555 function init_full() {
556 if($this->full_init_done) {
557 return;
559 if(empty($this->activityname)) {
560 error('Page object derived from page_generic_activity but did not define $this->activityname');
562 $module = get_record('modules', 'name', $this->activityname);
563 $this->modulerecord = get_record('course_modules', 'module', $module->id, 'instance', $this->id);
564 if(empty($this->modulerecord)) {
565 error('Cannot fully initialize page: invalid '.$this->activityname.' instance id '. $this->id);
567 $this->courserecord = get_record('course', 'id', $this->modulerecord->course);
568 if(empty($this->courserecord)) {
569 error('Cannot fully initialize page: invalid course id '. $this->modulerecord->course);
571 $this->activityrecord = get_record($this->activityname, 'id', $this->id);
572 if(empty($this->courserecord)) {
573 error('Cannot fully initialize page: invalid '.$this->activityname.' id '. $this->id);
575 $this->full_init_done = true;
578 function user_allowed_editing() {
579 $this->init_full();
580 return has_capability('moodle/site:manageblocks', get_context_instance(CONTEXT_COURSE, $this->modulerecord->course));
583 function user_is_editing() {
584 $this->init_full();
585 return isediting($this->modulerecord->course);
588 function url_get_path() {
589 global $CFG;
590 return $CFG->wwwroot .'/mod/'.$this->activityname.'/view.php';
593 function url_get_parameters() {
594 $this->init_full();
595 return array('id' => $this->modulerecord->id);
598 function blocks_get_positions() {
599 return array(BLOCK_POS_LEFT);
602 function blocks_default_position() {
603 return BLOCK_POS_LEFT;