From b7380c4be940e7a8ecaf2bed85d830c63f4c76c8 Mon Sep 17 00:00:00 2001 From: Tim Hunt Date: Wed, 15 Apr 2009 15:46:04 +0800 Subject: moodle_page: MDL-12212 remove useless code as a preparitory step --- admin/pagelib.php | 5 ----- blocks/tag_flickr/block_tag_flickr.php | 2 +- 2 files changed, 1 insertions(+), 6 deletions(-) diff --git a/admin/pagelib.php b/admin/pagelib.php index 7bcff27..ac4e3a8 100644 --- a/admin/pagelib.php +++ b/admin/pagelib.php @@ -121,11 +121,6 @@ class page_admin extends page_base { return $instance->position; } - // does anything need to be done here? - function init_quick($data) { - parent::init_quick($data); - } - function print_header($section = '', $focus='') { global $USER, $CFG, $SITE; diff --git a/blocks/tag_flickr/block_tag_flickr.php b/blocks/tag_flickr/block_tag_flickr.php index eb12112..99a0f5b 100644 --- a/blocks/tag_flickr/block_tag_flickr.php +++ b/blocks/tag_flickr/block_tag_flickr.php @@ -31,7 +31,7 @@ class block_tag_flickr extends block_base { function get_content() { - global $CFG, $USER, $PAGE; + global $CFG, $USER; if ($this->content !== NULL) { return $this->content; -- 1.5.6.3 From bb5b1ff79c46d2dedf969571883ac99f80d01efe Mon Sep 17 00:00:00 2001 From: Tim Hunt Date: Wed, 15 Apr 2009 17:13:00 +0800 Subject: moodle_page: MDL-12212 deprecate page_import_types and clean up file --- lib/pagelib.php | 66 +++++++++++++++++------------------------------------- 1 files changed, 21 insertions(+), 45 deletions(-) diff --git a/lib/pagelib.php b/lib/pagelib.php index 9faff06..224c047 100644 --- a/lib/pagelib.php +++ b/lib/pagelib.php @@ -24,48 +24,30 @@ /////////////////////////////////////////////////////////////////////////// /** - * This file contains the moodle_page class. s, page_base, - * as well as the page_course subclass. - * A page is defined by its page type (ie. course, blog, activity) and its page id - * (courseid, blogid, activity id, etc). + * This file contains the moodle_page class. There is normally a single instance + * of this class in the $PAGE global variable. This class is a central reporitory + * of information about the page we are building up to send back to the user. * * @license http://www.gnu.org/copyleft/gpl.html GNU Public License * @package pages */ +/** + * @deprecated since Moodle 2.0 + * Load any page_base subclasses from the pagelib.php library in a particular folder. + * @param $path the folder path + * @return array an array of page types. + */ function page_import_types($path) { global $CFG; - static $types = array(); - - if(substr($path, -1) != '/') { - $path .= '/'; - } - - $path = clean_param($path, PARAM_PATH); - - if(isset($types[$path])) { - return $types[$path]; - } - - $file = $CFG->dirroot.'/'.$path.'pagelib.php'; - - if(is_file($file)) { - require($file); - if(!isset($DEFINEDPAGES)) { - print_error('nopageclass', 'debug', '', $page); - } - return $types[$path] = $DEFINEDPAGES; - } - - return false; + debugging('Call to deprecated function page_import_types.', DEBUG_DEVELOPER); } /** * Factory function page_create_object(). Called with a numeric ID for a page, it autodetects * the page type, constructs the correct object and returns it. */ - function page_create_instance($instance) { page_id_and_class($id, $class); return page_create_object($id, $instance); @@ -75,7 +57,6 @@ function page_create_instance($instance) { * Factory function page_create_object(). Called with a pagetype identifier and possibly with * its numeric ID. Returns a fully constructed page_base subclass you can work with. */ - function page_create_object($type, $id = NULL) { global $CFG; @@ -101,12 +82,11 @@ function page_create_object($type, $id = NULL) { * Function page_map_class() is the way for your code to define its own page subclasses and let Moodle recognize them. * Use it to associate the textual identifier of your Page with the actual class name that has to be instantiated. */ - function page_map_class($type, $classname = NULL) { global $CFG; static $mappings = NULL; - + if ($mappings === NULL) { $mappings = array( PAGE_COURSE_VIEW => 'page_course' @@ -135,7 +115,6 @@ function page_map_class($type, $classname = NULL) { * @package pages * @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. */ - class page_base { /** * The string identifier for the type of page being described. @@ -259,7 +238,7 @@ class page_base { if(empty($params)) { return $path; } - + $first = true; foreach($params as $var => $value) { @@ -323,7 +302,6 @@ class page_base { * @author Jon Papaioannou * @package pages */ - class page_course extends page_base { // Any data we might need to store specifically about ourself should be declared here. @@ -437,9 +415,9 @@ class page_course extends page_base { foreach($replacements as $search => $replace) { $title = str_replace($search, $replace, $title); } - + $navlinks = array(); - + if(!empty($morenavlinks)) { $navlinks = array_merge($navlinks, $morenavlinks); } @@ -535,7 +513,7 @@ class page_course extends page_base { // colons (:) to delimit between block positions in the page. See blocks_get_positions() for additional info. function blocks_get_default() { global $CFG; - + $this->init_full(); if($this->id == SITEID) { @@ -571,7 +549,7 @@ class page_course extends page_base { } } } - + return $blocknames; } @@ -598,7 +576,6 @@ class page_course extends page_base { * @author Jon Papaioannou * @package pages */ - class page_generic_activity extends page_base { var $activityname = NULL; var $courserecord = NULL; @@ -632,7 +609,7 @@ class page_generic_activity extends page_base { $this->init_full(); // Yu: I think this is wrong, should be checking manageactivities instead //return has_capability('moodle/site:manageblocks', get_context_instance(CONTEXT_COURSE, $this->modulerecord->course)); - return has_capability('moodle/course:manageactivities', get_context_instance(CONTEXT_MODULE, $this->modulerecord->id)); + return has_capability('moodle/course:manageactivities', get_context_instance(CONTEXT_MODULE, $this->modulerecord->id)); } function user_is_editing() { @@ -657,10 +634,10 @@ class page_generic_activity extends page_base { function blocks_default_position() { return BLOCK_POS_LEFT; } - + function print_header($title, $morenavlinks = NULL, $bodytags = '', $meta = '') { global $USER, $CFG; - + $this->init_full(); $replacements = array( '%fullname%' => format_string($this->activityrecord->name) @@ -668,7 +645,7 @@ class page_generic_activity extends page_base { foreach ($replacements as $search => $replace) { $title = str_replace($search, $replace, $title); } - + if (empty($morenavlinks) && $this->user_allowed_editing()) { $buttons = ''; if (!empty($CFG->showblocksonmodpages)) { @@ -681,14 +658,13 @@ class page_generic_activity extends page_base { } else { $buttons = ' '; } - + if (empty($morenavlinks)) { $morenavlinks = array(); } $navigation = build_navigation($morenavlinks, $this->modulerecord); print_header($title, $this->courserecord->fullname, $navigation, '', $meta, true, $buttons, navmenu($this->courserecord, $this->modulerecord), false, $bodytags); } - } ?> -- 1.5.6.3 From 1cdbac344d4d9753c4f498c44a55fef84f882bfd Mon Sep 17 00:00:00 2001 From: Tim Hunt Date: Thu, 16 Apr 2009 16:54:11 +0800 Subject: moodle_page: MDL-12212 start of new moodle_page class * has course and status fields * $PAGE->status updated by print_header and footer * $PAGE->set_course now replace course_setup function * global $PAGE created in setup.php * unit tests for functionality so far * Moodle still seems to work after this commit! --- course/user.php | 2 +- lib/adminlib.php | 4 +- lib/moodlelib.php | 47 ++++---------- lib/pagelib.php | 117 +++++++++++++++++++++++++++++++++- lib/sessionlib.php | 6 +- lib/setup.php | 18 +++++- lib/upgradelib.php | 4 +- lib/weblib.php | 59 ++++++++--------- mod/chat/chatd.php | 9 ++- mod/chat/gui_header_js/chatinput.php | 2 +- mod/chat/gui_header_js/jsupdate.php | 4 +- mod/chat/gui_header_js/jsupdated.php | 4 +- mod/chat/gui_header_js/users.php | 4 +- mod/chat/gui_sockets/chatinput.php | 2 +- mod/forum/post.php | 9 +-- theme/chameleon/ui/css.php | 2 +- 16 files changed, 198 insertions(+), 95 deletions(-) diff --git a/course/user.php b/course/user.php index d090d99..f4efe00 100644 --- a/course/user.php +++ b/course/user.php @@ -26,7 +26,7 @@ require_login(); if (has_capability('moodle/user:viewuseractivitiesreport', $personalcontext) and !has_capability('moodle/course:view', $coursecontext)) { // do not require parents to be enrolled in courses ;-) - course_setup($course); + $PAGE->set_course($course); } else { require_login($course); } diff --git a/lib/adminlib.php b/lib/adminlib.php index 28ab9c3..64b19b3 100644 --- a/lib/adminlib.php +++ b/lib/adminlib.php @@ -4144,7 +4144,7 @@ function admin_apply_default_settings($node=NULL, $unconditional=true) { * @return int number of changed settings */ function admin_write_settings($formdata) { - global $CFG, $SITE, $COURSE, $DB; + global $CFG, $SITE, $PAGE, $DB; $olddbsessions = !empty($CFG->dbsessions); $formdata = (array)$formdata; @@ -4185,7 +4185,7 @@ function admin_write_settings($formdata) { // now update $SITE - it might have been changed $SITE = $DB->get_record('course', array('id'=>$SITE->id)); - course_setup($SITE); + $PAGE->set_course($SITE); // now reload all settings - some of them might depend on the changed admin_get_root(true); diff --git a/lib/moodlelib.php b/lib/moodlelib.php index eeacb62..7b79909 100644 --- a/lib/moodlelib.php +++ b/lib/moodlelib.php @@ -1865,37 +1865,6 @@ function dayofweek($day, $month, $year) { /// USER AUTHENTICATION AND LOGIN //////////////////////////////////////// /** - * Setup all global $CFG course variables, set locale and also themes - * This function can be used on pages that do not require login instead of require_login() - * - * @param mixed $courseorid id of the course or course object - */ -function course_setup($courseorid=0) { - global $COURSE, $SITE, $DB; - -/// Redefine global $COURSE if needed - if (empty($courseorid)) { - // no change in global $COURSE - for backwards compatibiltiy - // if require_rogin() used after require_login($courseid); - } else if (is_object($courseorid)) { - $COURSE = clone($courseorid); - } else { - if ($courseorid == SITEID) { - $COURSE = clone($SITE); - } else { - if (!$COURSE = $DB->get_record('course', array('id'=>$courseorid))) { - print_error('invalidcourseid'); - } - } - } - -/// set locale and themes - moodle_setlocale(); - theme_setup(); - -} - -/** * Returns full login url. * * @param bool $loginguest add login guest param @@ -1945,10 +1914,22 @@ function get_login_url($loginguest=false) { * in order to keep redirects working properly. MDL-14495 */ function require_login($courseorid=0, $autologinguest=true, $cm=null, $setwantsurltome=true) { - global $CFG, $SESSION, $USER, $COURSE, $FULLME; + global $CFG, $SESSION, $USER, $COURSE, $FULLME, $PAGE, $DB; /// setup global $COURSE, themes, language and locale - course_setup($courseorid); + if (!empty($courseorid)) { + if (is_object($courseorid)) { + $course = $courseorid; + } else if ($courseorid == SITEID) { + $course = clone($SITE); + } else { + $course = $DB->get_record('course', array('id' => $courseorid)); + if (!$course) { + throw new moodle_exception('invalidcourseid'); + } + } + $PAGE->set_course($course); + } /// If the user is not even logged in yet then make sure they are if (!isloggedin()) { diff --git a/lib/pagelib.php b/lib/pagelib.php index 224c047..6e4ef01 100644 --- a/lib/pagelib.php +++ b/lib/pagelib.php @@ -33,6 +33,118 @@ */ /** + * $PAGE is a central store of information about the current page we are + * generating in response to the user's request. It does not do very much itself + * except keep track of information, however, it serves as the access point to + * some more significant components like $PAGE->theme, $PAGE->requires, + * $PAGE->blocks, etc. + */ +class moodle_page { + /**#@+ Tracks the where we are in the generation of the page. */ + const STATE_BEFORE_HEADER = 0; + const STATE_PRINTING_HEADER = 1; + const STATE_IN_BODY = 2; + const STATE_PRINTING_FOOTER = 3; + const STATE_DONE = 4; + /**#@-*/ + + protected $_state = self::STATE_BEFORE_HEADER; + + protected $_course = null; + + /** + * @return integer one of the STATE_... constants. You should not normally need + * to use this in your code. It is indended for internal use by this class + * and its friends like print_header, to check that everything is working as + * expected. Also accessible as $PAGE->state. + */ + public function get_state() { + return $this->_state; + } + + /** + * @return boolean has the header already been printed? Also accessible as + * $PAGE->headerprinted. + */ + public function get_headerprinted() { + return $this->_state >= self::STATE_IN_BODY; + } + + /** + * @return object the current course that we are inside - a row from the + * course table. (Also available as $COURSE global.) If we are not inside + * an actual course, this will be the site course. You can also access this + * as $PAGE->course. + */ + public function get_course() { + global $SITE; + if (is_null($this->_course)) { + return $SITE; + } + return $this->_course; + } + + /** + * Set the state. The state must be one of that STATE_... constants, and + * the state is only allowed to advance one step at a time. + * @param integer $state the new state. + */ + public function set_state($state) { + if ($state != $this->_state + 1 || $state > self::STATE_DONE) { + throw new coding_exception('Invalid state passed to moodle_page::set_state. We are in state ' . + $this->_state . ' and state ' . $state . ' was requestsed.'); + } + + if ($state == self::STATE_PRINTING_HEADER && !$this->_course) { + global $SITE; + $this->set_course($SITE); + } + + $this->_state = $state; + } + + /** + * Set the current course. This sets both $PAGE->course and $COURSE. It also + * sets the right theme and locale. + * + * Normally you don't need to call this function yourself, require_login will + * call it for you if you pass a $course to it. You can use this function + * on pages that do need to call require_login(). + * + * @param object the course to set as the global course. + */ + public function set_course($course) { + global $COURSE, $SITE; + + if (empty($course->id)) { + throw new coding_exception('$course passed to moodle_page::set_course does not look like a proper course object.'); + } + + if ($this->_state > self::STATE_BEFORE_HEADER) { + throw new coding_exception('Cannot call moodle_page::set_course after output has been started.'); + } + + $this->_course = clone($course); + $COURSE = $this->_course; + + moodle_setlocale(); + theme_setup(); + } + + /** + * PHP overloading magic to make the $PAGE->course syntax work. + */ + public function __get($field) { + $getmethod = 'get_' . $field; + if (method_exists($this, $getmethod)) { + return $this->$getmethod(); + } else { + throw new coding_exception('Unknown field ' . $field . ' of $PAGE.'); + } + } +} + +/** * @deprecated since Moodle 2.0 * Load any page_base subclasses from the pagelib.php library in a particular folder. * @param $path the folder path @@ -58,7 +170,7 @@ function page_create_instance($instance) { * its numeric ID. Returns a fully constructed page_base subclass you can work with. */ function page_create_object($type, $id = NULL) { - global $CFG; + global $CFG, $PAGE; $data = new stdClass; $data->pagetype = $type; @@ -75,6 +187,7 @@ function page_create_object($type, $id = NULL) { } $object->init_quick($data); + $object->set_course($PAGE->course); return $object; } @@ -115,7 +228,7 @@ function page_map_class($type, $classname = NULL) { * @package pages * @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. */ -class page_base { +class page_base extends moodle_page { /** * The string identifier for the type of page being described. * @var string $type diff --git a/lib/sessionlib.php b/lib/sessionlib.php index d7bb00b..9eadb84 100644 --- a/lib/sessionlib.php +++ b/lib/sessionlib.php @@ -852,7 +852,7 @@ function session_unloginas() { * @return void */ function cron_setup_user($user=null, $course=null) { - global $CFG, $SITE; + global $CFG, $SITE, $PAGE; static $cronuser = null; static $cronsession = null; @@ -882,9 +882,9 @@ function cron_setup_user($user=null, $course=null) { } if ($course) { - course_setup($course); + $PAGE->set_course($course); } else { - course_setup($SITE); + $PAGE->set_course($SITE); } // TODO: it should be possible to improve perf by caching some limited number of users here ;-) diff --git a/lib/setup.php b/lib/setup.php index 8145664..5f0c5a4 100644 --- a/lib/setup.php +++ b/lib/setup.php @@ -58,6 +58,14 @@ global $SESSION; global $USER; /** + * A central store of information about the current page we are + * generating in response to the user's request. + * + * @global moodle_page $PAGE + */ +global $PAGE; + +/** * The current course. An alias for $PAGE->course. * @global object $COURSE */ @@ -263,6 +271,9 @@ global $SCRIPT; get_system_context(); } +/// Create the $PAGE global. + $PAGE = new moodle_page(); + /// Set error reporting back to normal if ($originaldatabasedebug == -1) { $CFG->debug = DEBUG_MINIMAL; @@ -491,8 +502,11 @@ global $SCRIPT; } } - // set default locale and themes - might be changed again later from require_login() - course_setup(); + // We used to call moodle_setlocale() and theme_setup() here, even though they + // would be called again from require_login or $PAGE->set_course. As an experiment + // I am going to try removing those calls. With luck it will help us find and + // fix a few bugs where scripts do not initialise thigns properly, wihtout causing + // too much grief. if (!empty($CFG->guestloginbutton)) { if ($CFG->theme == 'standard' or $CFG->theme == 'standardwhite') { // Temporary measure to help with XHTML validation diff --git a/lib/upgradelib.php b/lib/upgradelib.php index 04b3413..47df59a 100644 --- a/lib/upgradelib.php +++ b/lib/upgradelib.php @@ -745,7 +745,7 @@ function upgrade_log($type, $plugin, $info, $details=null, $backtrace=null) { * The upgrade is finished at the end of script or after timeout. */ function upgrade_started($preinstall=false) { - global $CFG, $DB; + global $CFG, $DB, $PAGE; static $started = false; @@ -757,7 +757,7 @@ function upgrade_started($preinstall=false) { upgrade_set_timeout(120); } else { - if (!CLI_SCRIPT and !defined('HEADER_PRINTED')) { + if (!CLI_SCRIPT and !$PAGE->headerprinted) { $strupgrade = get_string('upgradingversion', 'admin'); print_header($strupgrade.' - Moodle '.$CFG->target_release, $strupgrade, diff --git a/lib/weblib.php b/lib/weblib.php index 823444a..f974041 100644 --- a/lib/weblib.php +++ b/lib/weblib.php @@ -609,9 +609,9 @@ function close_window_button($name='closewindow', $return=false, $reloadopener = * to reload the parent window before this one closes. */ function close_window($delay = 0, $reloadopener = false) { - global $THEME; + global $THEME, $PAGE; - if (!defined('HEADER_PRINTED')) { + if (!$PAGE->headerprinted) { print_header(get_string('closewindow')); } else { print_container_end_all(false, $THEME->open_header_containers); @@ -2134,13 +2134,15 @@ function print_header ($title='', $heading='', $navigation='', $focus='', $meta='', $cache=true, $button=' ', $menu='', $usexml=false, $bodytags='', $return=false) { - global $USER, $CFG, $THEME, $SESSION, $ME, $SITE, $COURSE; + global $USER, $CFG, $THEME, $SESSION, $ME, $SITE, $COURSE, $PAGE; if (gettype($navigation) == 'string' && strlen($navigation) != 0 && $navigation != 'home') { debugging("print_header() was sent a string as 3rd ($navigation) parameter. " . "This is deprecated in favour of an array built by build_navigation(). Please upgrade your code.", DEBUG_DEVELOPER); } + $PAGE->set_state(moodle_page::STATE_PRINTING_HEADER); + $heading = format_string($heading); // Fix for MDL-8582 if (CLI_SCRIPT) { @@ -2153,14 +2155,6 @@ function print_header ($title='', $heading='', $navigation='', $focus='', } } -/// This makes sure that the header is never repeated twice on a page - if (defined('HEADER_PRINTED')) { - debugging('print_header() was called more than once - this should not happen. Please check the code for this page closely. Note: print_error() and redirect() are now safe to call after print_header().'); - return; - } - define('HEADER_PRINTED', 'true'); - - /// Add the required stylesheets $stylesheetshtml = ''; foreach ($CFG->stylesheets as $stylesheet) { @@ -2390,6 +2384,8 @@ function print_header ($title='', $heading='', $navigation='', $focus='', $output .= require_js('', 2); $output .= print_js_call('moodle_initialise_body', array(), true); + $PAGE->set_state(moodle_page::STATE_IN_BODY); + if ($return) { return $output; } else { @@ -2741,13 +2737,15 @@ function print_header_simple($title='', $heading='', $navigation='', $focus='', * @return mixed string or void */ function print_footer($course=NULL, $usercourse=NULL, $return=false) { - global $USER, $CFG, $THEME, $COURSE, $SITE; + global $USER, $CFG, $THEME, $COURSE, $SITE, $PAGE; if (defined('ADMIN_EXT_HEADER_PRINTED') and !defined('ADMIN_EXT_FOOTER_PRINTED')) { admin_externalpage_print_footer(); return; } + $PAGE->set_state(moodle_page::STATE_PRINTING_FOOTER); + /// Course links or special footer if ($course) { if ($course === 'empty') { @@ -2846,6 +2844,8 @@ function print_footer($course=NULL, $usercourse=NULL, $return=false) { $output = ob_get_contents(); ob_end_clean(); + $PAGE->set_state(moodle_page::STATE_DONE); + if ($return) { return $output; } else { @@ -3000,35 +3000,35 @@ function style_sheet_setup($lastmodified=0, $lifetime=300, $themename='', $force header('Expires: ' . gmdate("D, d M Y H:i:s", time() + $lifetime) . ' GMT'); header('Cache-Control: max-age='. $lifetime); header('Pragma: '); - header('Content-type: text/css'); // Correct MIME type + header('Content-type: text/css'); // Correct MIME type $DEFAULT_SHEET_LIST = array('styles_layout', 'styles_fonts', 'styles_color'); if (empty($themename)) { - $themename = current_theme(); // So we have something. Normally not needed. + $themename = current_theme(); // So we have something. Normally not needed. } else { $themename = clean_param($themename, PARAM_SAFEDIR); } - if (!empty($forceconfig)) { // Page wants to use the config from this theme instead + theme_setup($themename); + + if (!empty($forceconfig)) { // Page wants to use the config from this theme instead unset($THEME); include($CFG->themedir.'/'.$forceconfig.'/'.'config.php'); } /// If this is the standard theme calling us, then find out what sheets we need - if ($themename == 'standard') { if (!isset($THEME->standardsheets) or $THEME->standardsheets === true) { // Use all the sheets we have $THEME->sheets = $DEFAULT_SHEET_LIST; - } else if (empty($THEME->standardsheets)) { // We can stop right now! + } else if (empty($THEME->standardsheets)) { // We can stop right now! echo "/***** Nothing required from this stylesheet by main theme *****/\n\n"; exit; - } else { // Use the provided subset only + } else { // Use the provided subset only $THEME->sheets = $THEME->standardsheets; } /// If we are a parent theme, then check for parent definitions - } else if (!empty($THEME->parent) && $themename == $THEME->parent) { if (!isset($THEME->parentsheets) or $THEME->parentsheets === true) { // Use all the sheets we have $THEME->sheets = $DEFAULT_SHEET_LIST; @@ -3041,7 +3041,6 @@ function style_sheet_setup($lastmodified=0, $lifetime=300, $themename='', $force } /// Work out the last modified date for this theme - foreach ($THEME->sheets as $sheet) { if (file_exists($CFG->themedir.'/'.$themename.'/'.$sheet.'.css')) { $sheetmodified = filemtime($CFG->themedir.'/'.$themename.'/'.$sheet.'.css'); @@ -3051,7 +3050,6 @@ function style_sheet_setup($lastmodified=0, $lifetime=300, $themename='', $force } } - /// Get a list of all the files we want to include $files = array(); @@ -3159,10 +3157,10 @@ function style_sheet_setup($lastmodified=0, $lifetime=300, $themename='', $force function theme_setup($theme = '', $params=NULL) { /// Sets up global variables related to themes - global $CFG, $THEME, $SESSION, $USER, $HTTPSPAGEREQUIRED; + global $CFG, $THEME, $SESSION, $USER, $HTTPSPAGEREQUIRED, $PAGE; /// Do not mess with THEME if header already printed - this would break all the extra stuff in global $THEME from print_header()!! - if (defined('HEADER_PRINTED')) { + if ($PAGE->headerprinted) { return; } @@ -3193,7 +3191,6 @@ function theme_setup($theme = '', $params=NULL) { $params[] = 'lang='.current_language(); } - /// Convert params to string if ($params) { $paramstring = '?'.implode('&', $params); @@ -5597,7 +5594,7 @@ function print_error($errorcode, $module='error', $link='', $a=NULL) { * Internal function - do not use directly!! */ function _print_normal_error($errorcode, $module, $a, $link, $backtrace, $debuginfo=null, $showerrordebugwarning=false) { - global $CFG, $SESSION, $THEME, $DB; + global $CFG, $SESSION, $THEME, $DB, $PAGE; if ($DB) { //if you enable db debugging and exception is thrown, the print footer prints a lot of rubbish @@ -5639,7 +5636,7 @@ function _print_normal_error($errorcode, $module, $a, $link, $backtrace, $debugi $errordocroot = 'http://docs.moodle.org'; } - if (! defined('HEADER_PRINTED')) { + if (!$PAGE->headerprinted) { //header not yet printed @header('HTTP/1.0 404 Not Found'); print_header(get_string('error')); @@ -5949,7 +5946,7 @@ function editorshortcutshelpbutton() { * @todo Finish documenting this function */ function notice ($message, $link='', $course=NULL) { - global $CFG, $SITE, $THEME, $COURSE; + global $CFG, $SITE, $THEME, $COURSE, $PAGE; $message = clean_text($message); // In case nasties are in here @@ -5959,7 +5956,7 @@ function notice ($message, $link='', $course=NULL) { die; } - if (! defined('HEADER_PRINTED')) { + if (!$PAGE->headerprinted) { //header not yet printed print_header(get_string('notice')); } else { @@ -6015,7 +6012,7 @@ function notice_yesno ($message, $linkyes, $linkno, $optionsyes=NULL, $optionsno * echo ""; */ function redirect($url, $message='', $delay=-1) { - global $CFG, $THEME, $SESSION; + global $CFG, $THEME, $SESSION, $PAGE; if (!empty($CFG->usesid) && !isset($_COOKIE[session_name()])) { $url = $SESSION->sid_process_url($url); @@ -6045,7 +6042,7 @@ function redirect($url, $message='', $delay=-1) { } /// when no message and header printed yet, try to redirect - if (empty($message) and !defined('HEADER_PRINTED')) { + if (empty($message) and !$PAGE->headerprinted) { // Technically, HTTP/1.1 requires Location: header to contain // the absolute path. (In practice browsers accept relative @@ -6084,7 +6081,7 @@ function redirect($url, $message='', $delay=-1) { if ($delay == -1) { $delay = 3; // if no delay specified wait 3 seconds } - if (! defined('HEADER_PRINTED')) { + if (!$PAGE->headerprinted) { // this type of redirect might not be working in some browsers - such as lynx :-( print_header('', '', '', '', $errorprinted ? '' : ('')); $delay += 3; // double redirect prevention, it was sometimes breaking upgrades before 1.7 diff --git a/mod/chat/chatd.php b/mod/chat/chatd.php index 41d530e..cd99081 100755 --- a/mod/chat/chatd.php +++ b/mod/chat/chatd.php @@ -225,13 +225,12 @@ class ChatDaemon { } function get_user_window($sessionid) { - - global $CFG; + global $CFG, $PAGE; static $str; $info = &$this->sets_info[$sessionid]; - course_setup($info['course'], $info['user']); + $PAGE->set_course($info['course']); $timenow = time(); @@ -702,6 +701,8 @@ EOD; } function message_broadcast($message, $sender) { + global $PAGE; + if(empty($this->conn_sets)) { return true; } @@ -718,7 +719,7 @@ EOD; { // Simply give them the message - course_setup($info['course'], $info['user']); + $PAGE->set_course($info['course']); $output = chat_format_message_manually($message, $info['courseid'], $sender, $info['user']); $this->trace('Delivering message "'.$output->text.'" to '.$this->conn_sets[$sessionid][CHAT_CONNECTION_CHANNEL]); diff --git a/mod/chat/gui_header_js/chatinput.php b/mod/chat/gui_header_js/chatinput.php index cf6e2dc..027ee59 100644 --- a/mod/chat/gui_header_js/chatinput.php +++ b/mod/chat/gui_header_js/chatinput.php @@ -30,7 +30,7 @@ $USER = $DB->get_record('user', array('id'=>$chatuser->userid)); //Setup course, lang and theme - course_setup($chatuser->course); + $PAGE->set_course($course); ob_start(); ?> diff --git a/mod/chat/gui_header_js/jsupdate.php b/mod/chat/gui_header_js/jsupdate.php index a480ccd..e26bb12 100644 --- a/mod/chat/gui_header_js/jsupdate.php +++ b/mod/chat/gui_header_js/jsupdate.php @@ -14,7 +14,7 @@ } //Get the minimal course - if (!$course = $DB->get_record('course', array('id'=>$chatuser->course), 'id,theme,lang')) { + if (!$course = $DB->get_record('course', array('id'=>$chatuser->course))) { print_error('invalidcourseid'); } @@ -25,7 +25,7 @@ $USER->description = ''; //Setup course, lang and theme - course_setup($course); + $PAGE->set_course($course); // force deleting of timed out users if there is a silence in room or just entering if ((time() - $chat_lasttime) > $CFG->chat_old_ping) { diff --git a/mod/chat/gui_header_js/jsupdated.php b/mod/chat/gui_header_js/jsupdated.php index 57421e0..6e198cf 100644 --- a/mod/chat/gui_header_js/jsupdated.php +++ b/mod/chat/gui_header_js/jsupdated.php @@ -36,7 +36,7 @@ } //Get the minimal course - if (!$course = $DB->get_record('course', array('id'=>$chatuser->course), 'id,theme,lang')) { + if (!$course = $DB->get_record('course', array('id'=>$chatuser->course))) { print_error('invalidcourseid'); } @@ -48,7 +48,7 @@ $USER->description = ''; //Setup course, lang and theme - course_setup($course); + $PAGE->set_course($course); // force deleting of timed out users if there is a silence in room or just entering if ((time() - $chat_lasttime) > $CFG->chat_old_ping) { diff --git a/mod/chat/gui_header_js/users.php b/mod/chat/gui_header_js/users.php index e623a2f..aaac235 100644 --- a/mod/chat/gui_header_js/users.php +++ b/mod/chat/gui_header_js/users.php @@ -13,7 +13,7 @@ } //Get the minimal course - if (!$course = $DB->get_record('course', array('id'=>$chatuser->course), 'id,theme,lang')) { + if (!$course = $DB->get_record('course', array('id'=>$chatuser->course))) { print_error('invalidcourseid'); } @@ -24,7 +24,7 @@ $USER->description = ''; //Setup course, lang and theme - course_setup($course); + $PAGE->set_course($course); $courseid = $chatuser->course; diff --git a/mod/chat/gui_sockets/chatinput.php b/mod/chat/gui_sockets/chatinput.php index 8b24a0b..53dbc5c 100644 --- a/mod/chat/gui_sockets/chatinput.php +++ b/mod/chat/gui_sockets/chatinput.php @@ -15,7 +15,7 @@ $USER = $DB->get_record('user', array('id'=>$chatuser->userid)); //Setup course, lang and theme - course_setup($chatuser->course); + $PAGE->set_course($DB->get_record('course', array('id' => $chatuser->course))); ob_start(); ?> diff --git a/mod/forum/post.php b/mod/forum/post.php index 26eab58..8064b00 100644 --- a/mod/forum/post.php +++ b/mod/forum/post.php @@ -134,8 +134,8 @@ print_error('invalidcoursemodule'); } - // call course_setup to use forced language, MDL-6926 - course_setup($course->id); + // Ensure lang, theme, etc. is set up properly. MDL-6926 + $PAGE->set_course($course); $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id); $modcontext = get_context_instance(CONTEXT_MODULE, $cm->id); @@ -441,7 +441,7 @@ print_error('invalidcoursemodule'); } $modcontext = get_context_instance(CONTEXT_MODULE, $cm->id); - require_login($course->id, false, $cm); + require_login($course, false, $cm); if (isguestuser()) { // just in case @@ -452,9 +452,6 @@ $forum->maxattachments = 3; } - // setup course variable to force form language - // fix for MDL-6926 - course_setup($course->id); require_once('post_form.php'); $mform_post = new mod_forum_post_form('post.php', array('course'=>$course, 'cm'=>$cm, 'coursecontext'=>$coursecontext, 'modcontext'=>$modcontext, 'forum'=>$forum, 'post'=>$post)); diff --git a/theme/chameleon/ui/css.php b/theme/chameleon/ui/css.php index 2cfbcd3..57ef7a4 100644 --- a/theme/chameleon/ui/css.php +++ b/theme/chameleon/ui/css.php @@ -13,7 +13,7 @@ if (!$course = $DB->get_record('course', array('id'=>$id))) { print_error('invalidcourseid'); } -course_setup($course); // we should not require login here +$PAGE->set_course($course); // we should not require login here if ($id != SITEID and !empty($CFG->allowcoursethemes) and !empty($course->theme) and !empty($THEME->chameleonteachereditenabled)) { if (!has_capability('moodle/course:update', get_context_instance(CONTEXT_COURSE, $id))) { -- 1.5.6.3 From 96270dc08ff4ae746faf5e0f565cc97fb62c8ade Mon Sep 17 00:00:00 2001 From: Tim Hunt Date: Thu, 16 Apr 2009 17:58:14 +0800 Subject: moodle_page: MDL-12212 implement ->context --- lib/pagelib.php | 26 ++++ lib/simpletest/testpagelib_moodlepage.php | 223 +++++++++++++++++++++++++++++ 2 files changed, 249 insertions(+), 0 deletions(-) create mode 100644 lib/simpletest/testpagelib_moodlepage.php diff --git a/lib/pagelib.php b/lib/pagelib.php index 6e4ef01..eafd37a 100644 --- a/lib/pagelib.php +++ b/lib/pagelib.php @@ -52,6 +52,8 @@ class moodle_page { protected $_course = null; + protected $_context = null; + /** * @return integer one of the STATE_... constants. You should not normally need * to use this in your code. It is indended for internal use by this class @@ -85,6 +87,16 @@ class moodle_page { } /** + * @return object the main context to which this page belongs. + */ + public function get_context() { + if (is_null($this->_context)) { + throw new coding_exception('$PAGE->context accessed before it was known.'); + } + return $this->_context; + } + + /** * Set the state. The state must be one of that STATE_... constants, and * the state is only allowed to advance one step at a time. * @param integer $state the new state. @@ -111,6 +123,8 @@ class moodle_page { * call it for you if you pass a $course to it. You can use this function * on pages that do need to call require_login(). * + * Sets $PAGE->context to the course context, if it is not already set. + * * @param object the course to set as the global course. */ public function set_course($course) { @@ -127,11 +141,23 @@ class moodle_page { $this->_course = clone($course); $COURSE = $this->_course; + if (!$this->_context) { + $this->set_context(get_context_instance(CONTEXT_COURSE, $this->_course->id)); + } + moodle_setlocale(); theme_setup(); } /** + * Set the main context to which this page belongs. + * @param object $context a context object, normally obtained with get_context_instance. + */ + public function set_context($context) { + $this->_context = $context; + } + + /** * PHP overloading magic to make the $PAGE->course syntax work. */ public function __get($field) { diff --git a/lib/simpletest/testpagelib_moodlepage.php b/lib/simpletest/testpagelib_moodlepage.php new file mode 100644 index 0000000..f7de990 --- /dev/null +++ b/lib/simpletest/testpagelib_moodlepage.php @@ -0,0 +1,223 @@ +libdir . '/pagelib.php'); + +/** + * Test functions that affect filter_active table with contextid = $syscontextid. + */ +class moodle_page_test extends UnitTestCase { + protected $testpage; + protected $originalcourse; + + public function setUp() { + global $COURSE; + $this->originalcourse = $COURSE; + $this->testpage = new moodle_page(); + } + + public function tearDown() { + global $COURSE; + $this->testpage = NULL; + $COURSE = $this->originalcourse; + } + + /** Creates an object with all the fields you would expect a $course object to have. */ + protected function create_a_course() { + $course = new stdClass; + $course->id = -1; + $course->category = 2; + $course->fullname = 'Anonymous test course'; + $course->shortname = 'ANON'; + $course->summary = ''; + return $course; + } + + /** Creates an object with all the fields you would expect a $course object to have. */ + protected function create_a_context() { + $context = new stdClass; + $context->id = 2; + $context->contextlevel = CONTEXT_COURSECAT; + $context->instanceid = 1; + $context->path = '/1/2'; + $context->depth = '2'; + return $context; + } + + public function test_course_returns_site_before_set() { + global $SITE; + // Validate + $this->assertIdentical($SITE, $this->testpage->course); + } + + public function test_setting_course_works() { + // Setup fixture + $course = $this->create_a_course(); + $this->testpage->set_context(new stdClass); // Avoid trying to set the context. + // Exercise SUT + $this->testpage->set_course($course); + // Validate + $this->assert(new CheckSpecifiedFieldsExpectation($course), $this->testpage->course); + } + + public function test_global_course_and_page_course_are_same() { + global $COURSE; + // Setup fixture + $course = $this->create_a_course(); + $this->testpage->set_context(new stdClass); // Avoid trying to set the context. + // Exercise SUT + $this->testpage->set_course($course); + // Validate + $this->assertIdentical($this->testpage->course, $COURSE); + } + + public function test_cannot_set_course_once_output_started() { + // Setup fixture + $this->testpage->set_state(moodle_page::STATE_PRINTING_HEADER); + $course = $this->create_a_course(); + // Set expectation. + $this->expectException(); + // Exercise SUT + $this->testpage->set_course($course); + } + + public function test_set_state_normal_path() { + $this->assertEqual(moodle_page::STATE_BEFORE_HEADER, $this->testpage->state); + + $this->testpage->set_state(moodle_page::STATE_PRINTING_HEADER); + $this->assertEqual(moodle_page::STATE_PRINTING_HEADER, $this->testpage->state); + + $this->testpage->set_state(moodle_page::STATE_IN_BODY); + $this->assertEqual(moodle_page::STATE_IN_BODY, $this->testpage->state); + + $this->testpage->set_state(moodle_page::STATE_PRINTING_FOOTER); + $this->assertEqual(moodle_page::STATE_PRINTING_FOOTER, $this->testpage->state); + + $this->testpage->set_state(moodle_page::STATE_DONE); + $this->assertEqual(moodle_page::STATE_DONE, $this->testpage->state); + } + + public function test_set_state_cannot_skip_one() { + // Set expectation. + $this->expectException(); + // Exercise SUT + $this->testpage->set_state(moodle_page::STATE_IN_BODY); + } + + public function test_header_printed_false_initially() { + // Validate + $this->assertFalse($this->testpage->headerprinted); + } + + public function test_header_printed_becomes_true() { + // Exercise SUT + $this->testpage->set_state(moodle_page::STATE_PRINTING_HEADER); + $this->testpage->set_state(moodle_page::STATE_IN_BODY); + // Validate + $this->assertTrue($this->testpage->headerprinted); + } + + public function test_cant_get_context_before_set() { + // Set expectation. + $this->expectException(); + // Exercise SUT + $this->testpage->context; + } + + public function test_set_context() { + // Setup fixture + $context = $this->create_a_context(); + // Exercise SUT + $this->testpage->set_context($context); + // Validate + $this->assert(new CheckSpecifiedFieldsExpectation($context), $this->testpage->context); + } +} + +/** + * Test functions that affect filter_active table with contextid = $syscontextid. + */ +class moodle_page_with_db_test extends UnitTestCaseUsingDatabase { + protected $testpage; + protected $originalcourse; + + public function setUp() { + global $COURSE; + $this->originalcourse = $COURSE; + $this->testpage = new moodle_page(); + $this->create_test_table('context', 'lib'); + $this->switch_to_test_db(); + } + + public function tearDown() { + global $COURSE; + $this->testpage = NULL; + $COURSE = $this->originalcourse; + } + + /** Creates an object with all the fields you would expect a $course object to have. */ + protected function create_a_course_with_context() { + $course = new stdClass; + $course->id = -1; + $course->category = 2; + $course->fullname = 'Anonymous test course'; + $course->shortname = 'ANON'; + $course->summary = ''; + + $context = new stdClass; + $context->contextlevel = CONTEXT_COURSE; + $context->instanceid = $course->id; + $context->path = 'not initialised'; + $context->depth = '-1'; + $this->testdb->insert_record('context', $context); + + return $course; + } + + public function test_setting_course_sets_context() { + // Setup fixture + $course = $this->create_a_course_with_context(); + // Exercise SUT + $this->testpage->set_course($course); + // Validate + $expectedcontext = new stdClass; + $expectedcontext->contextlevel = CONTEXT_COURSE; + $expectedcontext->instanceid = $course->id; + $this->assert(new CheckSpecifiedFieldsExpectation($expectedcontext), $this->testpage->context); + } +} +?> -- 1.5.6.3 From 8ea454bc225726384ec07e9c9fa8166484f35580 Mon Sep 17 00:00:00 2001 From: Tim Hunt Date: Thu, 16 Apr 2009 17:58:56 +0800 Subject: filters: MDL-7336 use $PAGE->context now that it exists --- lib/weblib.php | 14 ++++++-------- 1 files changed, 6 insertions(+), 8 deletions(-) diff --git a/lib/weblib.php b/lib/weblib.php index f974041..284db8b 100644 --- a/lib/weblib.php +++ b/lib/weblib.php @@ -1216,8 +1216,7 @@ function format_text_menu() { * @todo Finish documenting this function */ function format_text($text, $format=FORMAT_MOODLE, $options=NULL, $courseid=NULL) { - - global $CFG, $COURSE, $DB; + global $CFG, $COURSE, $DB, $PAGE; static $croncache = array(); @@ -1262,7 +1261,7 @@ function format_text($text, $format=FORMAT_MOODLE, $options=NULL, $courseid=NULL } else { $filtermanager = new null_filter_manager(); } - $context = get_context_instance(CONTEXT_SYSTEM); // TODO change, once we have $PAGE->context. + $context = $PAGE->context; if (!empty($CFG->cachetext) and empty($options->nocache)) { $hashstr .= $text.'-'.$filtermanager->text_filtering_hash($context, $courseid).'-'.(int)$courseid.'-'.current_language().'-'. @@ -1439,8 +1438,7 @@ function reset_text_filters_cache() { * @return string */ function format_string($string, $striplinks=true, $courseid=NULL ) { - - global $CFG, $COURSE; + global $CFG, $COURSE, $PAGE; //We'll use a in-memory cache here to speed up repeated strings static $strcache = false; @@ -1466,7 +1464,7 @@ function format_string($string, $striplinks=true, $courseid=NULL ) { $string = preg_replace("/\&(?![a-zA-Z0-9#]{1,8};)/", "&", $string); if (!empty($CFG->filterall) && $CFG->version >= 2009040600) { // Avoid errors during the upgrade to the new system. - $context = get_context_instance(CONTEXT_SYSTEM); // TODO change, once we have $PAGE->context. + $context = $PAGE->context; $string = filter_manager::instance()->filter_string($string, $context, $courseid); } @@ -1540,13 +1538,13 @@ function format_text_email($text, $format) { * @return string the filtered string. */ function filter_text($text, $courseid=NULL) { - global $CFG, $COURSE; + global $CFG, $COURSE, $PAGE; if (empty($courseid)) { $courseid = $COURSE->id; // (copied from format_text) } - $context = get_context_instance(CONTEXT_SYSTEM); // TODO change, once we have $PAGE->context. + $context = $PAGE->context; return filter_manager::instance()->filter_text($text, $context, $courseid); } -- 1.5.6.3 From ccd0680939f87e88f1fc8cedd7027c3fe671885a Mon Sep 17 00:00:00 2001 From: Tim Hunt Date: Fri, 17 Apr 2009 11:43:49 +0800 Subject: moodle_page: MDL-12212 implement ->pagetype --- admin/pagelib.php | 4 -- admin/settings.php | 1 + blog/blogpage.php | 11 +----- lib/adminlib.php | 13 ++++--- lib/blocklib.php | 16 ++++---- lib/pagelib.php | 56 ++++++++++++++++++----------- lib/simpletest/testpagelib_moodlepage.php | 14 +++++++ mod/chat/pagelib.php | 4 -- mod/data/pagelib.php | 4 -- mod/lesson/pagelib.php | 4 -- mod/quiz/pagelib.php | 4 -- my/pagelib.php | 4 -- tag/pagelib.php | 4 -- 13 files changed, 67 insertions(+), 72 deletions(-) diff --git a/admin/pagelib.php b/admin/pagelib.php index ac4e3a8..4b99ab8 100644 --- a/admin/pagelib.php +++ b/admin/pagelib.php @@ -151,10 +151,6 @@ class page_admin extends page_base { print_header("$SITE->shortname: " . implode(": ",$this->visiblepathtosection), $SITE->fullname, $navigation, $focus, '', true, $buttons, ''); } - - function get_type() { - return PAGE_ADMIN; - } } ?> diff --git a/admin/settings.php b/admin/settings.php index cc39b20..1521770 100644 --- a/admin/settings.php +++ b/admin/settings.php @@ -11,6 +11,7 @@ $adminediting = optional_param('adminedit', -1, PARAM_BOOL); /// no guest autologin require_login(0, false); +$PAGE->set_context(get_context_instance(CONTEXT_SYSTEM)); $adminroot = admin_get_root(); // need all settings $page = $adminroot->locate($section); diff --git a/blog/blogpage.php b/blog/blogpage.php index baff9b6..f246bf1 100644 --- a/blog/blogpage.php +++ b/blog/blogpage.php @@ -19,13 +19,6 @@ class page_blog extends page_base { var $filterselect = NULL; var $tagid = NULL; - // Mandatory; should return our identifier. - function get_type() { - global $CFG; - require_once($CFG->dirroot .'/blog/lib.php'); - return PAGE_BLOG_VIEW; - } - // we have no format type, use 'blog' //I think it's a bug, but if this is left the default NULL value then pages can //fail to load completely @@ -154,8 +147,8 @@ class page_blog extends page_base { $this->init_full(); // It's a normal blog page - if (!empty($CFG->{'defaultblocks_'. $this->get_type()})) { - $blocknames = $CFG->{'defaultblocks_'. $this->get_type()}; + if (!empty($CFG->{'defaultblocks_'. $this->pagetype})) { + $blocknames = $CFG->{'defaultblocks_'. $this->pagetype}; } else { /// Failsafe - in case nothing was defined. $blocknames = 'admin,calendar_month,online_users,blog_menu'; diff --git a/lib/adminlib.php b/lib/adminlib.php index 64b19b3..da74f47 100644 --- a/lib/adminlib.php +++ b/lib/adminlib.php @@ -3896,6 +3896,13 @@ function admin_externalpage_setup($section, $extrabutton='', $extraurlparams=arr die; } + page_map_class(PAGE_ADMIN, 'page_admin'); + $PAGE = page_create_object(PAGE_ADMIN, 0); // there must be any constant id number + $PAGE->init_extra($section); // hack alert! + $PAGE->set_extra_button($extrabutton); + $PAGE->set_extra_url_params($extraurlparams, $actualurl); + $PAGE->set_context(get_context_instance(CONTEXT_SYSTEM)); + $adminroot = admin_get_root(false, false); // settings not required for external pages $extpage = $adminroot->locate($section); @@ -3910,12 +3917,6 @@ function admin_externalpage_setup($section, $extrabutton='', $extraurlparams=arr die; } - page_map_class(PAGE_ADMIN, 'page_admin'); - $PAGE = page_create_object(PAGE_ADMIN, 0); // there must be any constant id number - $PAGE->init_extra($section); // hack alert! - $PAGE->set_extra_button($extrabutton); - $PAGE->set_extra_url_params($extraurlparams, $actualurl); - $adminediting = optional_param('adminedit', -1, PARAM_BOOL); if (!isset($USER->adminediting)) { diff --git a/lib/blocklib.php b/lib/blocklib.php index c863808..8035049 100644 --- a/lib/blocklib.php +++ b/lib/blocklib.php @@ -645,13 +645,13 @@ function blocks_execute_action($page, &$pageblocks, $blockaction, $instanceorid, $sql = "SELECT 1, MAX(weight) + 1 AS nextfree FROM {block_pinned} WHERE pagetype = ? AND position = ?"; - $params = array($page->get_type(), $newpos); + $params = array($page->pagetype, $newpos); } else { $sql = "SELECT 1, MAX(weight) + 1 AS nextfree FROM {block_instance} WHERE pageid = ? AND pagetype = ? AND position = ?"; - $params = array($page->get_id(), $page->get_type(), $newpos); + $params = array($page->get_id(), $page->pagetype, $newpos); } $weight = $DB->get_record_sql($sql, $params); @@ -660,7 +660,7 @@ function blocks_execute_action($page, &$pageblocks, $blockaction, $instanceorid, if (empty($pinned)) { $newinstance->pageid = $page->get_id(); } - $newinstance->pagetype = $page->get_type(); + $newinstance->pagetype = $page->pagetype; $newinstance->position = $newpos; $newinstance->weight = empty($weight->nextfree) ? 0 : $weight->nextfree; $newinstance->visible = 1; @@ -835,7 +835,7 @@ function blocks_get_pinned($page) { } $select = "pagetype = ?"; - $params = array($page->get_type()); + $params = array($page->pagetype); if ($visible) { $select .= " AND visible = 1"; @@ -902,8 +902,8 @@ function blocks_get_by_page_pinned($page) { function blocks_get_by_page($page) { global $DB; - $blocks = $DB->get_records_select('block_instance', "pageid = ? AND pagetype = ?", array($page->get_id(), $page->get_type()), - 'position, weight'); + $blocks = $DB->get_records_select('block_instance', "pageid = ? AND pagetype = ?", + array($page->get_id(), $page->pagetype), 'position, weight'); $positions = $page->blocks_get_positions(); $arr = array(); @@ -1002,7 +1002,7 @@ function blocks_repopulate_page($page) { // indexed and the indexes match, so we can work straight away... but CAREFULLY! // Ready to start creating block instances, but first drop any existing ones - blocks_delete_all_on_page($page->get_type(), $page->get_id()); + blocks_delete_all_on_page($page->pagetype, $page->get_id()); // Here we slyly count $posblocks and NOT $positions. This can actually make a difference // if the textual representation has undefined slots in the end. So we only work with as many @@ -1016,7 +1016,7 @@ function blocks_repopulate_page($page) { $newinstance = new stdClass; $newinstance->blockid = $idforname[$blockname]; $newinstance->pageid = $page->get_id(); - $newinstance->pagetype = $page->get_type(); + $newinstance->pagetype = $page->pagetype; $newinstance->position = $position; $newinstance->weight = $weight; $newinstance->visible = 1; diff --git a/lib/pagelib.php b/lib/pagelib.php index eafd37a..697bccb 100644 --- a/lib/pagelib.php +++ b/lib/pagelib.php @@ -54,6 +54,8 @@ class moodle_page { protected $_context = null; + protected $_pagetype = null; + /** * @return integer one of the STATE_... constants. You should not normally need * to use this in your code. It is indended for internal use by this class @@ -97,6 +99,16 @@ class moodle_page { } /** + * @return string e.g. 'my-index' or 'mod-quiz-attempt'. Same as the id attribute on . + */ + public function get_pagetype() { + if (is_null($this->_pagetype)) { + throw new coding_exception('$PAGE->pagetype accessed before it was known.'); + } + return $this->_pagetype; + } + + /** * Set the state. The state must be one of that STATE_... constants, and * the state is only allowed to advance one step at a time. * @param integer $state the new state. @@ -158,6 +170,18 @@ class moodle_page { } /** + * @param string $pagetype e.g. 'my-index' or 'mod-quiz-attempt'. Normally + * you do not need to set this manually, it is automatically created from the + * script name. However, on some pages this is overridden. For example, the + * page type for coures/view.php includes the course format, for example + * 'coures-view-weeks'. This gets used as the id attribute on and + * also for determining which blocks are displayed. + */ + public function set_pagetype($pagetype) { + $this->_pagetype = $pagetype; + } + + /** * PHP overloading magic to make the $PAGE->course syntax work. */ public function __get($field) { @@ -168,6 +192,16 @@ class moodle_page { throw new coding_exception('Unknown field ' . $field . ' of $PAGE.'); } } + +/// Deperecated fields and methods for backwards compatibility ================= + /** + * @deprecated since Moodle 2.0 - use $PAGE->pagetype instaed. + * @return string page type. + */ + public function get_type() { + debugging('Call to deprecated method moodle_page::get_type. Please use $PAGE->pagetype instead.'); + return $this->get_pagetype(); + } } /** @@ -203,17 +237,11 @@ function page_create_object($type, $id = NULL) { $data->pageid = $id; $classname = page_map_class($type); - $object = new $classname; - // TODO: subclassing check here - - if ($object->get_type() !== $type) { - // Somehow somewhere someone made a mistake - debugging('Page object\'s type ('. $object->get_type() .') does not match requested type ('. $type .')'); - } $object->init_quick($data); $object->set_course($PAGE->course); + $object->set_pagetype($type); return $object; } @@ -389,14 +417,6 @@ class page_base extends moodle_page { return $path; } - // This forces implementers to actually hardwire their page identification constant in the class. - // Good thing, if you ask me. That way we can later auto-detect "installed" page types by querying - // the classes themselves in the future. - function get_type() { - trigger_error('Page class does not implement method get_type()', E_USER_ERROR); - return NULL; - } - // Simple stuff, do not override this. function get_id() { return $this->id; @@ -582,12 +602,6 @@ class page_course extends page_base { // SELF-REPORTING SECTION - // This is hardwired here so the factory function page_create_object() can be sure there was no mistake. - // Also, it doubles as a way to let others inquire about our type. - function get_type() { - return PAGE_COURSE_VIEW; - } - // This is like the "category" of a page of this "type". For example, if the type is PAGE_COURSE_VIEW // the format_name is the actual name of the course format. If the type were PAGE_ACTIVITY_VIEW, then // the format_name might be that activity's name etc. diff --git a/lib/simpletest/testpagelib_moodlepage.php b/lib/simpletest/testpagelib_moodlepage.php index f7de990..84c5ddf 100644 --- a/lib/simpletest/testpagelib_moodlepage.php +++ b/lib/simpletest/testpagelib_moodlepage.php @@ -166,6 +166,20 @@ class moodle_page_test extends UnitTestCase { // Validate $this->assert(new CheckSpecifiedFieldsExpectation($context), $this->testpage->context); } + + public function test_cant_get_pagetype_before_set() { + // Set expectation. + $this->expectException(); + // Exercise SUT + $this->testpage->pagetype; + } + + public function test_set_pagetype() { + // Exercise SUT + $this->testpage->set_pagetype('a-page-type'); + // Validate + $this->assertEqual('a-page-type', $this->testpage->pagetype); + } } /** diff --git a/mod/chat/pagelib.php b/mod/chat/pagelib.php index 3c5ca7a..23b438a 100644 --- a/mod/chat/pagelib.php +++ b/mod/chat/pagelib.php @@ -24,10 +24,6 @@ class page_chat extends page_generic_activity { $this->activityname = 'chat'; parent::init_quick($data); } - - function get_type() { - return PAGE_CHAT_VIEW; - } } ?> diff --git a/mod/data/pagelib.php b/mod/data/pagelib.php index b0b80ea..8b99f8c 100755 --- a/mod/data/pagelib.php +++ b/mod/data/pagelib.php @@ -31,10 +31,6 @@ class page_data extends page_generic_activity { function print_header($title, $morenavlinks = NULL, $meta) { parent::print_header($title, $morenavlinks, '', $meta); } - - function get_type() { - return PAGE_DATA_VIEW; - } } ?> diff --git a/mod/lesson/pagelib.php b/mod/lesson/pagelib.php index c309433..0d25e9b 100644 --- a/mod/lesson/pagelib.php +++ b/mod/lesson/pagelib.php @@ -140,10 +140,6 @@ class page_lesson extends page_generic_activity { lesson_print_messages(); } - function get_type() { - return PAGE_LESSON_VIEW; - } - function blocks_get_positions() { return array(BLOCK_POS_LEFT, BLOCK_POS_RIGHT); } diff --git a/mod/quiz/pagelib.php b/mod/quiz/pagelib.php index 884a227..c8b9aaa 100644 --- a/mod/quiz/pagelib.php +++ b/mod/quiz/pagelib.php @@ -25,10 +25,6 @@ class page_quiz extends page_generic_activity { $this->activityname = 'quiz'; parent::init_quick($data); } - - function get_type() { - return PAGE_QUIZ_VIEW; - } } ?> diff --git a/my/pagelib.php b/my/pagelib.php index 3ed3f6a..ce7cdd4 100644 --- a/my/pagelib.php +++ b/my/pagelib.php @@ -4,10 +4,6 @@ require_once($CFG->libdir.'/pagelib.php'); class page_my_moodle extends page_base { - function get_type() { - return PAGE_MY_MOODLE; - } - function user_allowed_editing() { page_id_and_class($id,$class); if ($id == PAGE_MY_MOODLE) { diff --git a/tag/pagelib.php b/tag/pagelib.php index d18908f..c1611d2 100644 --- a/tag/pagelib.php +++ b/tag/pagelib.php @@ -9,10 +9,6 @@ define('TAG_FORMAT', 'tag'); class page_tag extends page_base { var $tag_object = NULL; - - function get_type() { - return PAGE_TAG_INDEX; - } function user_allowed_editing() { $systemcontext = get_context_instance(CONTEXT_SYSTEM); -- 1.5.6.3 From ced21e0446e45fb4706df2c53b772b76ef78ee67 Mon Sep 17 00:00:00 2001 From: Tim Hunt Date: Fri, 17 Apr 2009 12:03:18 +0800 Subject: moodle_page: MDL-12212 remove code in legacy page types that stores a course record --- blog/blogpage.php | 11 ++--------- blog/header.php | 2 +- lib/pagelib.php | 47 ++++++++++++++++++----------------------------- mod/lesson/pagelib.php | 8 ++++---- 4 files changed, 25 insertions(+), 43 deletions(-) diff --git a/blog/blogpage.php b/blog/blogpage.php index f246bf1..43839a9 100644 --- a/blog/blogpage.php +++ b/blog/blogpage.php @@ -13,8 +13,6 @@ define('PAGE_BLOG_VIEW', 'blog-view'); class page_blog extends page_base { var $editing = false; - var $courserecord = NULL; - var $courseid = NULL; var $filtertype = NULL; var $filterselect = NULL; var $tagid = NULL; @@ -55,11 +53,6 @@ class page_blog extends page_base { if ($this->courseid == 0 || $this->courseid == 1 || !is_numeric($this->courseid) ) { $this->courseid = ''; - $courserecord = NULL; - } else { - if (! ($courserecord = $DB->get_record('course', array('id'=>$this->courseid))) ) { - print_error('invalidcourseid', 'error', '', $this->courseid); - } } $this->full_init_done = true; } @@ -111,8 +104,8 @@ class page_blog extends page_base { return $array; } - if (!empty($this->courseid)) { - $array['courseid'] = $this->courseid; + if (!empty($this->course->id)) { + $array['courseid'] = $this->course->id; } if (!empty($this->filtertype)) { $array['filtertype'] = $this->filtertype; diff --git a/blog/header.php b/blog/header.php index 58b0d23..e6474bf 100755 --- a/blog/header.php +++ b/blog/header.php @@ -46,7 +46,7 @@ if (empty($USER->id)) { } else { $PAGE = page_create_object($pagetype, $USER->id); } -$PAGE->courseid = $courseid; +$PAGE->set_course($course); $PAGE->filtertype = $filtertype; $PAGE->filterselect = $filterselect; $PAGE->tagid = $tagid; diff --git a/lib/pagelib.php b/lib/pagelib.php index 697bccb..8874eeb 100644 --- a/lib/pagelib.php +++ b/lib/pagelib.php @@ -195,13 +195,21 @@ class moodle_page { /// Deperecated fields and methods for backwards compatibility ================= /** - * @deprecated since Moodle 2.0 - use $PAGE->pagetype instaed. + * @deprecated since Moodle 2.0 - use $PAGE->pagetype instead. * @return string page type. */ public function get_type() { debugging('Call to deprecated method moodle_page::get_type. Please use $PAGE->pagetype instead.'); return $this->get_pagetype(); } + /** + * @deprecated since Moodle 2.0 - use $PAGE->course instead. + * @return object course. + */ + public function get_courserecord() { + debugging('Call to deprecated method moodle_page::get_courserecord. Please use $PAGE->course instead.'); + return $this->get_course(); + } } /** @@ -463,11 +471,6 @@ class page_base extends moodle_page { */ class page_course extends page_base { - // Any data we might need to store specifically about ourself should be declared here. - // After init_full() is called for the first time, ALL of these variables should be - // initialized correctly and ready for use. - var $courserecord = NULL; - // Do any validation of the officially recognized bits of the data and forward to parent. // Do NOT load up "expensive" resouces (e.g. SQL data) here! function init_quick($data) { @@ -490,15 +493,6 @@ class page_course extends page_base { if (empty($this->id)) { $this->id = 0; // avoid db errors } - if ($this->id == $COURSE->id) { - $this->courserecord = $COURSE; - } else { - $this->courserecord = $DB->get_record('course', array('id'=>$this->id)); - } - - if(empty($this->courserecord) && !defined('ADMIN_STICKYBLOCKS')) { - print_error('cannotinitpage', 'debug', '', (object)array('name'=>'course', 'id'=>$this->id)); - } $this->context = get_context_instance(CONTEXT_COURSE, $this->id); @@ -569,7 +563,7 @@ class page_course extends page_base { $this->init_full(); $replacements = array( - '%fullname%' => $this->courserecord->fullname + '%fullname%' => $this->course->fullname ); foreach($replacements as $search => $replace) { $title = str_replace($search, $replace, $title); @@ -585,9 +579,9 @@ class page_course extends page_base { // The "Editing On" button will be appearing only in the "main" course screen // (i.e., no breadcrumbs other than the default one added inside this function) - $buttons = switchroles_form($this->courserecord->id); + $buttons = switchroles_form($this->course->id); if ($this->user_allowed_editing()) { - $buttons .= update_course_icon($this->courserecord->id ); + $buttons .= update_course_icon($this->course->id ); } $buttons = empty($morenavlinks) ? $buttons : ' '; @@ -596,8 +590,8 @@ class page_course extends page_base { $buttons = ($buttons == ' ') ? $extrabuttons : $buttons.$extrabuttons; } - print_header($title, $this->courserecord->fullname, $navigation, - '', $meta, true, $buttons, user_login_string($this->courserecord, $USER), false, $bodytags); + print_header($title, $this->course->fullname, $navigation, + '', $meta, true, $buttons, user_login_string($this->course, $USER), false, $bodytags); } // SELF-REPORTING SECTION @@ -614,7 +608,7 @@ class page_course extends page_base { return parent::get_format_name(); } // This needs to reflect the path hierarchy under Moodle root. - return 'course-view-'.$this->courserecord->format; + return 'course-view-'.$this->course->format; } // This should return a fully qualified path to the URL which is responsible for displaying us. @@ -681,7 +675,7 @@ class page_course extends page_base { } // It's a normal course, so do it according to the course format else { - $pageformat = $this->courserecord->format; + $pageformat = $this->course->format; if (!empty($CFG->{'defaultblocks_'. $pageformat})) { $blocknames = $CFG->{'defaultblocks_'. $pageformat}; } @@ -731,7 +725,6 @@ class page_course extends page_base { */ class page_generic_activity extends page_base { var $activityname = NULL; - var $courserecord = NULL; var $modulerecord = NULL; var $activityrecord = NULL; @@ -747,10 +740,6 @@ class page_generic_activity extends page_base { if (!$this->modulerecord = get_coursemodule_from_instance($this->activityname, $this->id)) { print_error('cannotinitpager', 'debug', '', (object)array('name'=>$this->activityname, 'id'=>$this->id)); } - $this->courserecord = $DB->get_record('course', array('id'=>$this->modulerecord->course)); - if(empty($this->courserecord)) { - print_error('invalidcourseid'); - } $this->activityrecord = $DB->get_record($this->activityname, array('id'=>$this->id)); if(empty($this->activityrecord)) { print_error('cannotinitpager', 'debug', '', (object)array('name'=>$this->activityname, 'id'=>$this->id)); @@ -800,7 +789,7 @@ class page_generic_activity extends page_base { } if (empty($morenavlinks) && $this->user_allowed_editing()) { - $buttons = '
'.update_module_button($this->modulerecord->id, $this->courserecord->id, get_string('modulename', $this->activityname)).'
'; + $buttons = '
'.update_module_button($this->modulerecord->id, $this->courserecord->id, get_string('modulename', $this->activityname)).'
'; if (!empty($CFG->showblocksonmodpages)) { $buttons .= '
'.update_module_button($this->modulerecord->id, $this->course->id, get_string('modulename', $this->activityname)).'
frametarget.' method="get" action="view.php">
'. ''. @@ -816,7 +805,7 @@ class page_generic_activity extends page_base { $morenavlinks = array(); } $navigation = build_navigation($morenavlinks, $this->modulerecord); - print_header($title, $this->courserecord->fullname, $navigation, '', $meta, true, $buttons, navmenu($this->courserecord, $this->modulerecord), false, $bodytags); + print_header($title, $this->course->fullname, $navigation, '', $meta, true, $buttons, navmenu($this->course, $this->modulerecord), false, $bodytags); } } diff --git a/mod/lesson/pagelib.php b/mod/lesson/pagelib.php index 0d25e9b..afd5ad0 100644 --- a/mod/lesson/pagelib.php +++ b/mod/lesson/pagelib.php @@ -73,12 +73,12 @@ class page_lesson extends page_generic_activity { print_error('invalidpageid', 'lesson'); } if (empty($title)) { - $title = "{$this->courserecord->shortname}: $activityname"; + $title = "{$this->course->shortname}: $activityname"; } /// Build the buttons if (has_capability('mod/lesson:edit', $context)) { - $buttons = ''.update_module_button($this->modulerecord->id, $this->courserecord->id, get_string('modulename', 'lesson')); + $buttons = ''.update_module_button($this->modulerecord->id, $this->course->id, get_string('modulename', 'lesson')); if (!empty($this->lessonpageid) and $this->lessonpageid != LESSON_EOL) { $buttons .= 'frametarget.' method="get" action="'.$CFG->wwwroot.'/mod/lesson/lesson.php">'. @@ -125,13 +125,13 @@ class page_lesson extends page_generic_activity { // } $navigation = build_navigation($morenavlinks, $this->modulerecord); - print_header($title, $this->courserecord->fullname, $navigation, '', $meta, true, $buttons, navmenu($this->courserecord, $this->modulerecord)); + print_header($title, $this->course->fullname, $navigation, '', $meta, true, $buttons, navmenu($this->course, $this->modulerecord)); if (has_capability('mod/lesson:manage', $context)) { print_heading_with_help($activityname, 'overview', 'lesson'); // Rename our objects for the sake of the tab code - list($cm, $course, $lesson, $currenttab) = array(&$this->modulerecord, &$this->courserecord, &$this->activityrecord, 'view'); + list($cm, $course, $lesson, $currenttab) = array(&$this->modulerecord, &$this->course, &$this->activityrecord, 'view'); include($CFG->dirroot.'/mod/lesson/tabs.php'); } else { print_heading($activityname); -- 1.5.6.3 From 22d08f9a60f5a0cf8a0cbf4f2bd44b75005c904b Mon Sep 17 00:00:00 2001 From: Tim Hunt Date: Fri, 17 Apr 2009 12:05:45 +0800 Subject: moodle_page: MDL-12212 eliminate two old methods that were never used --- lib/pagelib.php | 10 ---------- 1 files changed, 0 insertions(+), 10 deletions(-) diff --git a/lib/pagelib.php b/lib/pagelib.php index 8874eeb..99ea613 100644 --- a/lib/pagelib.php +++ b/lib/pagelib.php @@ -435,16 +435,6 @@ class page_base extends moodle_page { return $this->body_id; } - // Returns $this->body_class - function get_body_class() { - return $this->body_class; - } - - // Returns $this->body_id - function get_body_id() { - return $this->body_id; - } - // Initialize the data members of the parent class function init_quick($data) { $this->type = $data->pagetype; -- 1.5.6.3 From 52c86b86aa7cd199a3d7e976097305c6040adcf0 Mon Sep 17 00:00:00 2001 From: Tim Hunt Date: Fri, 17 Apr 2009 12:19:46 +0800 Subject: moodle_page: MDL-12212 rewrite blocks_name_allowed_in_format to improve readability --- lib/blocklib.php | 26 +++++++++++++------------- 1 files changed, 13 insertions(+), 13 deletions(-) diff --git a/lib/blocklib.php b/lib/blocklib.php index 8035049..9f72731 100644 --- a/lib/blocklib.php +++ b/lib/blocklib.php @@ -132,21 +132,21 @@ function blocks_remove_inappropriate($page) { } function blocks_name_allowed_in_format($name, $pageformat) { - - $accept = NULL; - $depth = -1; - if ($formats = block_method_result($name, 'applicable_formats')) { - foreach($formats as $format => $allowed) { - $thisformat = '^'.str_replace('*', '[^-]*', $format).'.*$'; - if(ereg($thisformat, $pageformat)) { - if(($scount = substr_count($format, '-')) > $depth) { - $depth = $scount; - $accept = $allowed; - } - } + $accept = NULL; + $maxdepth = -1; + $formats = block_method_result($name, 'applicable_formats'); + if (!$formats) { + $formats = array(); + } + foreach ($formats as $format => $allowed) { + $formatregex = '/^'.str_replace('*', '[^-]*', $format).'.*$/'; + $depth = substr_count($format, '-'); + if (preg_match($formatregex, $pageformat) && $depth > $maxdepth) { + $maxdepth = $depth; + $accept = $allowed; } } - if($accept === NULL) { + if ($accept === NULL) { $accept = !empty($formats['all']); } return $accept; -- 1.5.6.3 From 181fdef5a4451fb42c9035d33e38cd0a1e3179d2 Mon Sep 17 00:00:00 2001 From: Tim Hunt Date: Fri, 17 Apr 2009 15:26:48 +0800 Subject: moodle_page: MDL-12212 kill $CFG->pagepath (use $PAGE->set_pagetype) deprecate $PAGE->get_format_name (use $PAGE->pagetype) deprecate page_id_and_class (use $PAGE->pagetype) --- admin/auth_config.php | 2 +- admin/mnet/enr_course_enrol.php | 2 +- admin/mnet/enr_courses.php | 2 +- admin/mnet/enr_hosts.php | 3 +- admin/stickyblocks.php | 2 +- blog/blogpage.php | 9 --- course/mod.php | 2 +- course/modedit.php | 7 +- lib/blocklib.php | 8 +- lib/pagelib.php | 129 ++++++++++++++++++++-------------- lib/weblib.php | 44 +++--------- login/index.php | 5 +- mod/data/field.php | 13 +--- mod/hotpot/view.php | 7 +-- mod/lesson/action/addbranchtable.php | 2 - mod/lesson/action/addpage.php | 2 - my/pagelib.php | 10 +-- question/question.php | 2 +- tag/pagelib.php | 6 +-- 19 files changed, 115 insertions(+), 142 deletions(-) diff --git a/admin/auth_config.php b/admin/auth_config.php index 0ceca51..542a564 100644 --- a/admin/auth_config.php +++ b/admin/auth_config.php @@ -8,7 +8,7 @@ require_once $CFG->libdir.'/adminlib.php'; $auth = required_param('auth', PARAM_SAFEDIR); -$CFG->pagepath = 'auth/' . $auth; +$PAGE->set_pagetype('auth-' . $auth); admin_externalpage_setup('authsetting'.$auth); diff --git a/admin/mnet/enr_course_enrol.php b/admin/mnet/enr_course_enrol.php index 52dbae7..7cfb03e 100644 --- a/admin/mnet/enr_course_enrol.php +++ b/admin/mnet/enr_course_enrol.php @@ -11,7 +11,7 @@ } admin_externalpage_setup('mnetenrol'); - $CFG->pagepath = 'admin/mnet'; + $PAGE->set_pagetype('admin-mnet'); require_once("$CFG->dirroot/enrol/enrol.class.php"); /// Open the factory class $enrolment = enrolment_factory::factory('mnet'); diff --git a/admin/mnet/enr_courses.php b/admin/mnet/enr_courses.php index cd16a7d..0d9fd8d 100644 --- a/admin/mnet/enr_courses.php +++ b/admin/mnet/enr_courses.php @@ -11,7 +11,7 @@ admin_externalpage_setup('mnetenrol'); - $CFG->pagepath = 'admin/mnet'; + $PAGE->set_pagetype('admin-mnet'); require_once("$CFG->dirroot/enrol/enrol.class.php"); /// Open the factory class $enrolment = enrolment_factory::factory('mnet'); diff --git a/admin/mnet/enr_hosts.php b/admin/mnet/enr_hosts.php index 23f47d0..3a7cdfb 100644 --- a/admin/mnet/enr_hosts.php +++ b/admin/mnet/enr_hosts.php @@ -6,8 +6,7 @@ require_once($CFG->libdir.'/adminlib.php'); admin_externalpage_setup('mnetenrol'); - $CFG->pagepath = 'admin/mnet'; - + $PAGE->set_pagetype('admin-mnet'); require_once("$CFG->dirroot/enrol/enrol.class.php"); /// Open the factory class diff --git a/admin/stickyblocks.php b/admin/stickyblocks.php index c2aefae..8b9eaf0 100644 --- a/admin/stickyblocks.php +++ b/admin/stickyblocks.php @@ -40,7 +40,7 @@ define('ADMIN_STICKYBLOCKS',$pt); $PAGE = page_create_object($pt, SITEID); - $blocks = blocks_setup($PAGE,BLOCKS_PINNED_TRUE); + $blocks = blocks_setup($PAGE, BLOCKS_PINNED_TRUE); $blocks_preferred_width = bounded_number(180, blocks_preferred_width($blocks[BLOCK_POS_LEFT]), 210); $navlinks = array(array('name' => get_string('administration'), diff --git a/blog/blogpage.php b/blog/blogpage.php index 43839a9..67c0111 100644 --- a/blog/blogpage.php +++ b/blog/blogpage.php @@ -17,15 +17,6 @@ class page_blog extends page_base { var $filterselect = NULL; var $tagid = NULL; - // we have no format type, use 'blog' - //I think it's a bug, but if this is left the default NULL value then pages can - //fail to load completely - function get_format_name() { - global $CFG; - require_once($CFG->dirroot .'/blog/lib.php'); - return PAGE_BLOG_VIEW; - } - // Do any validation of the officially recognized bits of the data and forward to parent. // Do NOT load up "expensive" resouces (e.g. SQL data) here! function init_quick($data) { diff --git a/course/mod.php b/course/mod.php index a01b065..054e5b3 100644 --- a/course/mod.php +++ b/course/mod.php @@ -63,7 +63,7 @@ $strdeletecheck = get_string('deletecheck', '', $fullmodulename); $strdeletecheckfull = get_string('deletecheckfull', '', "$fullmodulename '$cm->name'"); - $CFG->pagepath = 'mod/'.$cm->modname.'/delete'; + $PAGE->set_pagetype('mod-' . $cm->modname . '-delete'); print_header_simple($strdeletecheck, '', build_navigation(array(array('name'=>$strdeletecheck, 'link'=>'', 'type'=>'misc')))); diff --git a/course/modedit.php b/course/modedit.php index 0c8c6ad..a68de8b 100644 --- a/course/modedit.php +++ b/course/modedit.php @@ -80,12 +80,13 @@ $pageheading = get_string('addinganew', 'moodle', $fullmodulename); } - $CFG->pagepath = 'mod/'.$module->name; + $pagepath = 'mod-' . $module->name . '-'; if (!empty($type)) { - $CFG->pagepath .= '/'.$type; + $pagepath .= $type; } else { - $CFG->pagepath .= '/mod'; + $pagepath .= 'mod'; } + $PAGE->set_pagetype($pagepath); $navlinksinstancename = ''; diff --git a/lib/blocklib.php b/lib/blocklib.php index 9f72731..5323c72 100644 --- a/lib/blocklib.php +++ b/lib/blocklib.php @@ -94,7 +94,7 @@ function blocks_get_missing(&$page, &$pageblocks) { $missingblocks = array(); $allblocks = blocks_get_record(); - $pageformat = $page->get_format_name(); + $pageformat = $page->pagetype; if(!empty($allblocks)) { foreach($allblocks as $block) { @@ -117,7 +117,7 @@ function blocks_remove_inappropriate($page) { return; } - if(($pageformat = $page->get_format_name()) == NULL) { + if(($pageformat = $page->pagetype) == NULL) { return; } @@ -325,10 +325,10 @@ function blocks_print_group(&$page, &$pageblocks, $position) { include_once($CFG->dirroot.'/my/pagelib.php'); $coursecontext = get_context_instance(CONTEXT_COURSE, $COURSE->id); - $myownblogpage = (isset($page->filtertype) && isset($page->filterselect) && $page->type=='blog-view' && $page->filtertype=='user' && $page->filterselect == $USER->id); + $myownblogpage = (isset($page->filtertype) && isset($page->filterselect) && $page->pagetype=='blog-view' && $page->filtertype=='user' && $page->filterselect == $USER->id); $managecourseblocks = has_capability('moodle/site:manageblocks', $coursecontext); - $editmymoodle = $page->type == PAGE_MY_MOODLE && has_capability('moodle/my:manageblocks', $coursecontext); + $editmymoodle = $page->pagetype == PAGE_MY_MOODLE && has_capability('moodle/my:manageblocks', $coursecontext); if ($page->blocks_default_position() == $position && $page->user_is_editing() && diff --git a/lib/pagelib.php b/lib/pagelib.php index 99ea613..5eb552b 100644 --- a/lib/pagelib.php +++ b/lib/pagelib.php @@ -56,6 +56,8 @@ class moodle_page { protected $_pagetype = null; + protected $_legacyclass = null; + /** * @return integer one of the STATE_... constants. You should not normally need * to use this in your code. It is indended for internal use by this class @@ -102,8 +104,8 @@ class moodle_page { * @return string e.g. 'my-index' or 'mod-quiz-attempt'. Same as the id attribute on . */ public function get_pagetype() { - if (is_null($this->_pagetype)) { - throw new coding_exception('$PAGE->pagetype accessed before it was known.'); + if (is_null($this->_pagetype) || isset($CFG->pagepath)) { + $this->initialise_default_pagetype(); } return $this->_pagetype; } @@ -193,7 +195,46 @@ class moodle_page { } } + /** + * Sets ->pagetype from the script name. For example, if the script that was + * run is mod/quiz/view.php, ->pagetype will be set to 'mod-quiz-view'. + * @param string $script the path to the script that should be used to + * initialise ->pagetype. If not passed the $SCRIPT global will be used. + * If legacy code has set $CFG->pagepath that will be used instead, and a + * developer warning issued. + */ + protected function initialise_default_pagetype($script = '') { + global $CFG, $SCRIPT; + + if (isset($CFG->pagepath)) { + debugging('Some code appears to have set $CFG->pagepath. That was a horrible deprecated thing. ' . + 'Don\'t do it! Try calling $PAGE->set_pagetype() instead.'); + $script = $CFG->pagepath; + unset($CFG->pagepath); + } + + if (empty($script)) { + $script = ltrim($SCRIPT, '/'); + $len = strlen($CFG->admin); + if (substr($script, 0, $len) == $CFG->admin) { + $script = 'admin' . substr($script, $len); + } + } + + $path = str_replace('.php', '', $script); + if (substr($path, -1) == '/') { + $path .= 'index'; + } + + if (empty($path) || $path == 'index') { + $this->_pagetype = 'site-index'; + } else { + $this->_pagetype = str_replace('/', '-', $path); + } + } + /// Deperecated fields and methods for backwards compatibility ================= + /** * @deprecated since Moodle 2.0 - use $PAGE->pagetype instead. * @return string page type. @@ -202,6 +243,15 @@ class moodle_page { debugging('Call to deprecated method moodle_page::get_type. Please use $PAGE->pagetype instead.'); return $this->get_pagetype(); } + + /** + * @deprecated since Moodle 2.0 - use $PAGE->pagetype instead. + * @return string this is what page_id_and_class used to return via the $getclass parameter. + */ + function get_format_name() { + return $this->get_pagetype(); + } + /** * @deprecated since Moodle 2.0 - use $PAGE->course instead. * @return object course. @@ -210,6 +260,25 @@ class moodle_page { debugging('Call to deprecated method moodle_page::get_courserecord. Please use $PAGE->course instead.'); return $this->get_course(); } + + /** + * @deprecated since Moodle 2.0 + * @return string this is what page_id_and_class used to return via the $getclass parameter. + */ + public function get_legacyclass() { + if (is_null($this->_legacyclass)) { + $pagetype = $this->pagetype; + if ($pagetype == 'site-index') { + $this->_legacyclass = 'course'; + } else if (substr($pagetype, 0, 6) == 'admin-') { + $this->_legacyclass = 'admin'; + } else { + $this->_legacyclass = substr($pagetype, 0, strrpos($pagetype, '-')); + } + } + debugging('Call to deprecated method moodle_page::get_legacyclass.'); + return $this->_legacyclass; + } } /** @@ -220,17 +289,16 @@ class moodle_page { */ function page_import_types($path) { global $CFG; - debugging('Call to deprecated function page_import_types.', DEBUG_DEVELOPER); } /** - * Factory function page_create_object(). Called with a numeric ID for a page, it autodetects - * the page type, constructs the correct object and returns it. + * @deprecated since Moodle 2.0 + * @param integer $instance legacy page instance id. + * @return the global $PAGE object. */ function page_create_instance($instance) { - page_id_and_class($id, $class); - return page_create_object($id, $instance); + return page_create_object($PAGE->pagetype, $instance); } /** @@ -309,32 +377,8 @@ class page_base extends moodle_page { */ var $full_init_done = false; - /** - * The class attribute that Moodle has to assign to the BODY tag for this page. - * @var string $body_class - */ - var $body_class = NULL; - - /** - * The id attribute that Moodle has to assign to the BODY tag for this page. - * @var string $body_id - */ - var $body_id = NULL; - /// Class Functions - // CONSTRUCTION - - // A whole battery of functions to allow standardized-name constructors in all versions of PHP. - // The constructor is actually called construct() - function __construct() { - $this->construct(); - } - - function construct() { - page_id_and_class($this->body_id, $this->body_class); - } - // USER-RELATED THINGS // By default, no user is editing anything and none CAN edit anything. Developers @@ -430,11 +474,6 @@ class page_base extends moodle_page { return $this->id; } - // "Sensible default" case here. Take it from the body id. - function get_format_name() { - return $this->body_id; - } - // Initialize the data members of the parent class function init_quick($data) { $this->type = $data->pagetype; @@ -503,7 +542,6 @@ class page_course extends page_base { // this is a _very_ expensive check - so cache it during execution // function user_allowed_editing() { - $this->init_full(); if (isset($this->_user_allowed_editing)) { @@ -511,7 +549,7 @@ class page_course extends page_base { } if (has_capability('moodle/site:manageblocks', get_context_instance(CONTEXT_SYSTEM)) - && defined('ADMIN_STICKYBLOCKS')) { + && defined('ADMIN_STICKYBLOCKS')) { $this->_user_allowed_editing = true; return true; } @@ -586,21 +624,6 @@ class page_course extends page_base { // SELF-REPORTING SECTION - // This is like the "category" of a page of this "type". For example, if the type is PAGE_COURSE_VIEW - // the format_name is the actual name of the course format. If the type were PAGE_ACTIVITY_VIEW, then - // the format_name might be that activity's name etc. - function get_format_name() { - $this->init_full(); - if (defined('ADMIN_STICKYBLOCKS')) { - return PAGE_COURSE_VIEW; - } - if($this->id == SITEID) { - return parent::get_format_name(); - } - // This needs to reflect the path hierarchy under Moodle root. - return 'course-view-'.$this->course->format; - } - // This should return a fully qualified path to the URL which is responsible for displaying us. function url_get_path() { global $CFG; diff --git a/lib/weblib.php b/lib/weblib.php index 284db8b..cac8859 100644 --- a/lib/weblib.php +++ b/lib/weblib.php @@ -2327,7 +2327,8 @@ function print_header ($title='', $heading='', $navigation='', $focus='', // Create class and id for this page - page_id_and_class($pageid, $pageclass); + $pageid = $PAGE->pagetype; + $pageclass = $PAGE->legacyclass; $pageclass .= ' course-'.$COURSE->id; @@ -6493,39 +6494,16 @@ function print_side_block_end($attributes = array(), $title='') { } - +/** + * @deprecated since Moodle 2.0 - use $PAGE->pagetype instead of the . + * @param string $getid used to return $PAGE->pagetype. + * @param string $getclass used to return $PAGE->legacyclass. + */ function page_id_and_class(&$getid, &$getclass) { - // Create class and id for this page - global $CFG, $SCRIPT; - - static $class = NULL; - static $id = NULL; - - if (empty($CFG->pagepath)) { - $CFG->pagepath = ltrim($SCRIPT, '/'); - } - - if (empty($class) || empty($id)) { - $path = str_replace('.php', '', $CFG->pagepath); - if (substr($path, -1) == '/') { - $path .= 'index'; - } - if (empty($path) || $path == 'index') { - $id = 'site-index'; - $class = 'course'; - } else if (substr($path, 0, 5) == 'admin') { - $id = str_replace('/', '-', $path); - $class = 'admin'; - } else { - $id = str_replace('/', '-', $path); - $class = explode('-', $id); - array_pop($class); - $class = implode('-', $class); - } - } - - $getid = $id; - $getclass = $class; + global $PAGE; + debugging('Call to deprecated function page_id_and_class. Please use $PAGE->pagetype instead.', DEBUG_DEVELOPER); + $getid = $PAGE->pagetype; + $getclass = $PAGE->legacyclass; } /** diff --git a/login/index.php b/login/index.php index b4c1b81..da4d187 100644 --- a/login/index.php +++ b/login/index.php @@ -12,6 +12,9 @@ $loginguest = optional_param('loginguest', 0, PARAM_BOOL); // determines whether visitors are logged in as guest automatically $testcookies = optional_param('testcookies', 0, PARAM_BOOL); // request cookie test + $context = get_context_instance(CONTEXT_SYSTEM); + $PAGE->set_context($context); + //initialize variables $errormsg = ''; $errorcode = 0; @@ -159,7 +162,7 @@ } /// Go to my-moodle page instead of homepage if mymoodleredirect enabled - if (!has_capability('moodle/site:config',get_context_instance(CONTEXT_SYSTEM)) and !empty($CFG->mymoodleredirect) and !isguest()) { + if (!has_capability('moodle/site:config', $context) and !empty($CFG->mymoodleredirect) and !isguest()) { if ($urltogo == $CFG->wwwroot or $urltogo == $CFG->wwwroot.'/' or $urltogo == $CFG->wwwroot.'/index.php') { $urltogo = $CFG->wwwroot.'/my/'; } diff --git a/mod/data/field.php b/mod/data/field.php index 7ba49e9..3f64edf 100755 --- a/mod/data/field.php +++ b/mod/data/field.php @@ -229,26 +229,21 @@ } asort($menufield); //sort in alphabetical order - + $PAGE->set_pagetype('mod-data-field-' . $newtype); if (($mode == 'new') && (!empty($newtype)) && confirm_sesskey()) { /// Adding a new field - $CFG->pagepath='mod/data/field/'.$newtype; - data_print_header($course,$cm,$data,'fields'); + data_print_header($course, $cm, $data,'fields'); $field = data_get_field_new($newtype, $data); $field->display_edit_field(); } else if ($mode == 'display' && confirm_sesskey()) { /// Display/edit existing field - $CFG->pagepath='mod/data/field/'.$newtype; - data_print_header($course,$cm,$data,'fields'); + data_print_header($course, $cm, $data,'fields'); $field = data_get_field_from_id($fid, $data); $field->display_edit_field(); } else { /// Display the main listing of all fields - - $CFG->pagepath='mod/data/field/'.$newtype; - data_print_header($course,$cm,$data,'fields'); - + data_print_header($course, $cm, $data,'fields'); if (!$DB->record_exists('data_fields', array('dataid'=>$data->id))) { notify(get_string('nofieldindatabase','data')); // nothing in database diff --git a/mod/hotpot/view.php b/mod/hotpot/view.php index 49033d6..909a2ae 100644 --- a/mod/hotpot/view.php +++ b/mod/hotpot/view.php @@ -264,11 +264,8 @@ // insert hot-potatoes.js $hp->insert_script(HOTPOT_JS); // get Moodle pageid and pageclass - $pageid = ''; - $pageclass = ''; - if (function_exists('page_id_and_class')) { - page_id_and_class($pageid, $pageclass); - } + $pageid = $PAGE->pagetype; + // extract first tag $head = ''; $pattern = '|]*)>(.*?)|is'; diff --git a/mod/lesson/action/addbranchtable.php b/mod/lesson/action/addbranchtable.php index ae518e9..b7e7309 100644 --- a/mod/lesson/action/addbranchtable.php +++ b/mod/lesson/action/addbranchtable.php @@ -7,8 +7,6 @@ * @package lesson **/ - $CFG->pagepath = 'mod/lesson/addbranchtable'; - // first get the preceeding page $pageid = required_param('pageid', PARAM_INT); diff --git a/mod/lesson/action/addpage.php b/mod/lesson/action/addpage.php index 10229e1..3093d46 100644 --- a/mod/lesson/action/addpage.php +++ b/mod/lesson/action/addpage.php @@ -6,8 +6,6 @@ * @license http://www.gnu.org/copyleft/gpl.html GNU Public License * @package lesson **/ - $CFG->pagepath = 'mod/lesson/addpage'; - // first get the preceeding page $pageid = required_param('pageid', PARAM_INT); $qtype = optional_param('qtype', LESSON_MULTICHOICE, PARAM_INT); diff --git a/my/pagelib.php b/my/pagelib.php index ce7cdd4..d6e2b9f 100644 --- a/my/pagelib.php +++ b/my/pagelib.php @@ -5,8 +5,7 @@ require_once($CFG->libdir.'/pagelib.php'); class page_my_moodle extends page_base { function user_allowed_editing() { - page_id_and_class($id,$class); - if ($id == PAGE_MY_MOODLE) { + if ($PAGE->pagetype == PAGE_MY_MOODLE) { return true; } else if (has_capability('moodle/my:manageblocks', get_context_instance(CONTEXT_SYSTEM)) && defined('ADMIN_STICKYBLOCKS')) { return true; @@ -58,8 +57,7 @@ class page_my_moodle extends page_base { function url_get_path() { global $CFG; - page_id_and_class($id,$class); - if ($id == PAGE_MY_MOODLE) { + if ($PAGE->pagetype == PAGE_MY_MOODLE) { return $CFG->wwwroot.'/my/index.php'; } elseif (defined('ADMIN_STICKYBLOCKS')){ return $CFG->wwwroot.'/'.$CFG->admin.'/stickyblocks.php'; @@ -90,10 +88,6 @@ class page_my_moodle extends page_base { } return $instance->position; } - - function get_format_name() { - return MY_MOODLE_FORMAT; - } } diff --git a/question/question.php b/question/question.php index 2e0b2ca..9148d1a 100644 --- a/question/question.php +++ b/question/question.php @@ -115,7 +115,7 @@ if ($id) { if (!isset($QTYPES[$question->qtype])) { print_error('unknownquestiontype', 'question', $returnurl, $question->qtype); } -$CFG->pagepath = 'question/type/' . $question->qtype; +$PAGE->set_pagetype('question-type-' . $question->qtype); // Create the question editing form. if ($wizardnow!=='' && !$movecontext){ diff --git a/tag/pagelib.php b/tag/pagelib.php index c1611d2..27a1306 100644 --- a/tag/pagelib.php +++ b/tag/pagelib.php @@ -51,12 +51,8 @@ class page_tag extends page_base { return $instance->position; } - function get_format_name() { - return TAG_FORMAT; - } - //----------- printing funtions ----------- - + function print_header() { global $USER, $CFG; -- 1.5.6.3 From 63732713736dcc25ec4a8ec5a2b9f26774e854a0 Mon Sep 17 00:00:00 2001 From: Tim Hunt Date: Fri, 17 Apr 2009 16:09:11 +0800 Subject: moodle_page: MDL-12212 eliminate the two different interpretations of pagetype --- admin/index.php | 1 + admin/mnet/enr_course_enrol.php | 1 - admin/mnet/enr_courses.php | 1 - admin/mnet/enr_hosts.php | 1 - lib/blocklib.php | 2 +- lib/db/upgrade.php | 8 +++++++ lib/moodlelib.php | 4 +++ lib/pagelib.php | 2 +- lib/simpletest/testpagelib_moodlepage.php | 30 +++++++++++++++++++++++----- 9 files changed, 39 insertions(+), 11 deletions(-) diff --git a/admin/index.php b/admin/index.php index fa2e763..10f335b 100644 --- a/admin/index.php +++ b/admin/index.php @@ -189,6 +189,7 @@ /// and upgrade if possible. $stradministration = get_string('administration'); + $PAGE->set_context(get_context_instance(CONTEXT_SYSTEM)); if (empty($CFG->version)) { print_error('missingconfigversion', 'debug'); diff --git a/admin/mnet/enr_course_enrol.php b/admin/mnet/enr_course_enrol.php index 7cfb03e..c1e8664 100644 --- a/admin/mnet/enr_course_enrol.php +++ b/admin/mnet/enr_course_enrol.php @@ -11,7 +11,6 @@ } admin_externalpage_setup('mnetenrol'); - $PAGE->set_pagetype('admin-mnet'); require_once("$CFG->dirroot/enrol/enrol.class.php"); /// Open the factory class $enrolment = enrolment_factory::factory('mnet'); diff --git a/admin/mnet/enr_courses.php b/admin/mnet/enr_courses.php index 0d9fd8d..9c05838 100644 --- a/admin/mnet/enr_courses.php +++ b/admin/mnet/enr_courses.php @@ -11,7 +11,6 @@ admin_externalpage_setup('mnetenrol'); - $PAGE->set_pagetype('admin-mnet'); require_once("$CFG->dirroot/enrol/enrol.class.php"); /// Open the factory class $enrolment = enrolment_factory::factory('mnet'); diff --git a/admin/mnet/enr_hosts.php b/admin/mnet/enr_hosts.php index 3a7cdfb..665628e 100644 --- a/admin/mnet/enr_hosts.php +++ b/admin/mnet/enr_hosts.php @@ -6,7 +6,6 @@ require_once($CFG->libdir.'/adminlib.php'); admin_externalpage_setup('mnetenrol'); - $PAGE->set_pagetype('admin-mnet'); require_once("$CFG->dirroot/enrol/enrol.class.php"); /// Open the factory class diff --git a/lib/blocklib.php b/lib/blocklib.php index 5323c72..913de4b 100644 --- a/lib/blocklib.php +++ b/lib/blocklib.php @@ -902,7 +902,7 @@ function blocks_get_by_page_pinned($page) { function blocks_get_by_page($page) { global $DB; - $blocks = $DB->get_records_select('block_instance', "pageid = ? AND pagetype = ?", + $blocks = $DB->get_records_select('block_instance', "pageid = ? AND ? LIKE (" . $DB->sql_concat('pagetype', "'%'") . ")", array($page->get_id(), $page->pagetype), 'position, weight'); $positions = $page->blocks_get_positions(); diff --git a/lib/db/upgrade.php b/lib/db/upgrade.php index bf10b81..937cae7 100644 --- a/lib/db/upgrade.php +++ b/lib/db/upgrade.php @@ -1703,6 +1703,14 @@ WHERE gradeitemid IS NOT NULL AND grademax IS NOT NULL"); upgrade_main_savepoint($result, 2009042700); } + if ($result && $oldversion < 2009042800) { + /// Site front page blocks need to be moved due to page name change. + $DB->set_field('block_instance', 'pagetype', 'site-index', array('pagetype' => 'course-view', 'pageid' => SITEID)); + + /// Main savepoint reached + upgrade_main_savepoint($result, 2009042800); + } + if ($result && $oldversion < 2009043000) { unset_config('grade_report_showgroups'); upgrade_main_savepoint($result, 2009043000); diff --git a/lib/moodlelib.php b/lib/moodlelib.php index 7b79909..5aaeb70 100644 --- a/lib/moodlelib.php +++ b/lib/moodlelib.php @@ -1929,6 +1929,10 @@ function require_login($courseorid=0, $autologinguest=true, $cm=null, $setwantsu } } $PAGE->set_course($course); + } else { + // If $PAGE->course, and hence $PAGE->context, have not already been set + // up properly, set them up now. + $PAGE->set_course($PAGE->course); } /// If the user is not even logged in yet then make sure they are diff --git a/lib/pagelib.php b/lib/pagelib.php index 5eb552b..05bf0e1 100644 --- a/lib/pagelib.php +++ b/lib/pagelib.php @@ -317,7 +317,7 @@ function page_create_object($type, $id = NULL) { $object->init_quick($data); $object->set_course($PAGE->course); - $object->set_pagetype($type); + //$object->set_pagetype($type); return $object; } diff --git a/lib/simpletest/testpagelib_moodlepage.php b/lib/simpletest/testpagelib_moodlepage.php index 84c5ddf..17f2636 100644 --- a/lib/simpletest/testpagelib_moodlepage.php +++ b/lib/simpletest/testpagelib_moodlepage.php @@ -37,6 +37,12 @@ if (!defined('MOODLE_INTERNAL')) { require_once($CFG->libdir . '/pagelib.php'); +class testable_moodle_page extends moodle_page { + public function initialise_default_pagetype($script = '') { + parent::initialise_default_pagetype($script); + } +} + /** * Test functions that affect filter_active table with contextid = $syscontextid. */ @@ -47,7 +53,7 @@ class moodle_page_test extends UnitTestCase { public function setUp() { global $COURSE; $this->originalcourse = $COURSE; - $this->testpage = new moodle_page(); + $this->testpage = new testable_moodle_page(); } public function tearDown() { @@ -167,11 +173,9 @@ class moodle_page_test extends UnitTestCase { $this->assert(new CheckSpecifiedFieldsExpectation($context), $this->testpage->context); } - public function test_cant_get_pagetype_before_set() { - // Set expectation. - $this->expectException(); - // Exercise SUT - $this->testpage->pagetype; + public function test_pagetype_defaults_to_script() { + // Exercise SUT and validate + $this->assertEqual('admin-report-unittest-index', $this->testpage->pagetype); } public function test_set_pagetype() { @@ -180,6 +184,20 @@ class moodle_page_test extends UnitTestCase { // Validate $this->assertEqual('a-page-type', $this->testpage->pagetype); } + + public function test_initialise_default_pagetype() { + // Exercise SUT + $this->testpage->initialise_default_pagetype('admin/report/unittest/index.php'); + // Validate + $this->assertEqual('admin-report-unittest-index', $this->testpage->pagetype); + } + + public function test_initialise_default_pagetype_fp() { + // Exercise SUT + $this->testpage->initialise_default_pagetype('index.php'); + // Validate + $this->assertEqual('site-index', $this->testpage->pagetype); + } } /** -- 1.5.6.3 From de1f9bf70d80b5fbb7377fa667e3adcf3cc34cbf Mon Sep 17 00:00:00 2001 From: Tim Hunt Date: Fri, 17 Apr 2009 16:59:19 +0800 Subject: moodle_page: MDL-12212 ->bodyclasses and initialise_standard_body_classes --- lib/pagelib.php | 80 ++++++++++++++++++++++++---- lib/simpletest/testpagelib_moodlepage.php | 20 +++++++ lib/weblib.php | 24 +-------- 3 files changed, 89 insertions(+), 35 deletions(-) diff --git a/lib/pagelib.php b/lib/pagelib.php index 05bf0e1..b74b6ea 100644 --- a/lib/pagelib.php +++ b/lib/pagelib.php @@ -48,16 +48,24 @@ class moodle_page { const STATE_DONE = 4; /**#@-*/ +/// Field declarations ========================================================= + protected $_state = self::STATE_BEFORE_HEADER; protected $_course = null; protected $_context = null; + protected $_bodyclasses = array(); + protected $_pagetype = null; protected $_legacyclass = null; +/// Getter methods ============================================================= +/// Due to the __get magic below, you normally do not call these as get_x methods, +/// but instead use the $PAGE->x syntax. + /** * @return integer one of the STATE_... constants. You should not normally need * to use this in your code. It is indended for internal use by this class @@ -111,6 +119,15 @@ class moodle_page { } /** + * @return string the class names to put on the body element in the HTML. + */ + public function get_bodyclasses() { + return implode(' ', array_keys($this->_bodyclasses)); + } + +/// Setter methods ============================================================= + + /** * Set the state. The state must be one of that STATE_... constants, and * the state is only allowed to advance one step at a time. * @param integer $state the new state. @@ -121,9 +138,13 @@ class moodle_page { $this->_state . ' and state ' . $state . ' was requestsed.'); } - if ($state == self::STATE_PRINTING_HEADER && !$this->_course) { - global $SITE; - $this->set_course($SITE); + if ($state == self::STATE_PRINTING_HEADER) { + if (!$this->_course) { + global $SITE; + $this->set_course($SITE); + } + + $this->initialise_standard_body_classes(); } $this->_state = $state; @@ -184,6 +205,16 @@ class moodle_page { } /** + * @param string $class add this class name ot the class attribute on the body tag. + */ + public function add_body_class($class) { + if ($this->_state > self::STATE_BEFORE_HEADER) { + throw new coding_exception('Cannot call moodle_page::add_body_class after output has been started.'); + } + $this->_bodyclasses[$class] = 1; + } + + /** * PHP overloading magic to make the $PAGE->course syntax work. */ public function __get($field) { @@ -195,6 +226,9 @@ class moodle_page { } } +/// Initialisation methods ===================================================== +/// These set various things up in a default way. + /** * Sets ->pagetype from the script name. For example, if the script that was * run is mod/quiz/view.php, ->pagetype will be set to 'mod-quiz-view'. @@ -233,7 +267,36 @@ class moodle_page { } } -/// Deperecated fields and methods for backwards compatibility ================= + protected function initialise_standard_body_classes() { + $pagetype = $this->pagetype; + if ($pagetype == 'site-index') { + $this->_legacyclass = 'course'; + } else if (substr($pagetype, 0, 6) == 'admin-') { + $this->_legacyclass = 'admin'; + } else { + $this->_legacyclass = substr($pagetype, 0, strrpos($pagetype, '-')); + } + $this->add_body_class($this->_legacyclass); + + $this->add_body_class('course-' . $this->_course->id); + $this->add_body_class(get_browser_version_classes()); + $this->add_body_class('dir-' . get_string('thisdirection')); + $this->add_body_class('lang-' . current_language()); + + if (!isloggedin()) { + $this->add_body_class('notloggedin'); + } + + if (!empty($USER->editing)) { + $this->add_body_class('editing'); + } + + if (!empty($CFG->blocksdrag)) { + $this->add_body_class('drag'); + } + } + +/// Deprecated fields and methods for backwards compatibility ================== /** * @deprecated since Moodle 2.0 - use $PAGE->pagetype instead. @@ -267,14 +330,7 @@ class moodle_page { */ public function get_legacyclass() { if (is_null($this->_legacyclass)) { - $pagetype = $this->pagetype; - if ($pagetype == 'site-index') { - $this->_legacyclass = 'course'; - } else if (substr($pagetype, 0, 6) == 'admin-') { - $this->_legacyclass = 'admin'; - } else { - $this->_legacyclass = substr($pagetype, 0, strrpos($pagetype, '-')); - } + $this->initialise_standard_body_classes(); } debugging('Call to deprecated method moodle_page::get_legacyclass.'); return $this->_legacyclass; diff --git a/lib/simpletest/testpagelib_moodlepage.php b/lib/simpletest/testpagelib_moodlepage.php index 17f2636..34e5259 100644 --- a/lib/simpletest/testpagelib_moodlepage.php +++ b/lib/simpletest/testpagelib_moodlepage.php @@ -198,6 +198,26 @@ class moodle_page_test extends UnitTestCase { // Validate $this->assertEqual('site-index', $this->testpage->pagetype); } + + public function test_get_body_classes_empty() { + // Validate + $this->assertEqual('', $this->testpage->bodyclasses); + } + + public function test_get_body_classes_single() { + // Exercise SUT + $this->testpage->add_body_class('aclassname'); + // Validate + $this->assertEqual('aclassname', $this->testpage->bodyclasses); + } + + public function test_get_body_classes_double() { + // Exercise SUT + $this->testpage->add_body_class('aclassname'); + $this->testpage->add_body_class('anotherclassname'); + // Validate + $this->assertEqual('aclassname anotherclassname', $this->testpage->bodyclasses); + } } /** diff --git a/lib/weblib.php b/lib/weblib.php index cac8859..adfb909 100644 --- a/lib/weblib.php +++ b/lib/weblib.php @@ -2326,30 +2326,8 @@ function print_header ($title='', $heading='', $navigation='', $focus='', $title = str_replace('"', '"', $title); // Create class and id for this page - $pageid = $PAGE->pagetype; - $pageclass = $PAGE->legacyclass; - - $pageclass .= ' course-'.$COURSE->id; - - if (!isloggedin()) { - $pageclass .= ' notloggedin'; - } - - if (!empty($USER->editing)) { - $pageclass .= ' editing'; - } - - if (!empty($CFG->blocksdrag)) { - $pageclass .= ' drag'; - } - - $pageclass .= ' ' . get_browser_version_classes(); - - $pageclass .= ' dir-'.get_string('thisdirection'); - - $pageclass .= ' lang-'.$currentlanguage; - + $pageclass = $PAGE->bodyclasses; $bodytags .= ' class="'.$pageclass.'" id="'.$pageid.'"'; require_once($CFG->libdir .'/editor/htmlEditor.class.php'); -- 1.5.6.3 From bc69e215fe26a18eb675019ef1aeda8fee1a728c Mon Sep 17 00:00:00 2001 From: Tim Hunt Date: Fri, 17 Apr 2009 17:58:45 +0800 Subject: moodle_page: MDL-12212 more ->pagepaths to kill --- admin/auth_config.php | 3 +-- admin/enrol.php | 2 -- admin/enrol_config.php | 3 +-- admin/portfolio.php | 7 +++---- admin/report/security/index.php | 3 ++- admin/repository.php | 4 +--- admin/settings.php | 2 +- admin/wsprotocols.php | 2 -- course/modedit.php | 7 ++++--- lib/blocklib.php | 2 +- lib/pagelib.php | 4 ++-- lib/weblib.php | 2 +- 12 files changed, 17 insertions(+), 24 deletions(-) diff --git a/admin/auth_config.php b/admin/auth_config.php index 542a564..4b2e9d8 100644 --- a/admin/auth_config.php +++ b/admin/auth_config.php @@ -7,8 +7,7 @@ require_once '../config.php'; require_once $CFG->libdir.'/adminlib.php'; $auth = required_param('auth', PARAM_SAFEDIR); - -$PAGE->set_pagetype('auth-' . $auth); +$PAGE->set_pagetype('admin-auth-' . $auth); admin_externalpage_setup('authsetting'.$auth); diff --git a/admin/enrol.php b/admin/enrol.php index 5f210ad..bed502b 100644 --- a/admin/enrol.php +++ b/admin/enrol.php @@ -8,8 +8,6 @@ $enrol = optional_param('enrol', $CFG->enrol, PARAM_SAFEDIR); $savesettings = optional_param('savesettings', 0, PARAM_BOOL); - $CFG->pagepath = 'enrol'; - admin_externalpage_setup('enrolment'); if (!isset($CFG->sendcoursewelcomemessage)) { diff --git a/admin/enrol_config.php b/admin/enrol_config.php index 1f7ae12..cb48a97 100644 --- a/admin/enrol_config.php +++ b/admin/enrol_config.php @@ -8,8 +8,7 @@ admin_externalpage_setup('enrolment'); $enrol = required_param('enrol', PARAM_ALPHA); - $CFG->pagepath = 'enrol/' . $enrol; - + $PAGE->set_pagetype('admin-enrol-' . $enrol); require_once("$CFG->dirroot/enrol/enrol.class.php"); /// Open the factory class diff --git a/admin/portfolio.php b/admin/portfolio.php index d79367f..a7db714 100644 --- a/admin/portfolio.php +++ b/admin/portfolio.php @@ -4,9 +4,6 @@ require_once(dirname(dirname(__FILE__)) . '/config.php'); require_once($CFG->libdir . '/portfoliolib.php'); require_once($CFG->libdir . '/adminlib.php'); - -$CFG->pagepath = 'admin/manageportfolio'; - $edit = optional_param('edit', 0, PARAM_INT); $new = optional_param('new', '', PARAM_FORMAT); $hide = optional_param('hide', 0, PARAM_INT); @@ -42,7 +39,9 @@ if (!empty($edit) || !empty($new)) { $plugin = $new; $instance = null; } - $CFG->pagepath = 'admin/manageportfolio/' . $plugin; + + $PAGE->set_pagetype('admin-portfolio-' . $plugin); + // display the edit form for this instance $mform = new portfolio_admin_form('', array('plugin' => $plugin, 'instance' => $instance)); // end setup, begin output diff --git a/admin/report/security/index.php b/admin/report/security/index.php index 877caa8..c2f64fe 100644 --- a/admin/report/security/index.php +++ b/admin/report/security/index.php @@ -88,7 +88,8 @@ if ($issue and ($result = $issue(true))) { $row[2] = $result->info; $row[3] = is_null($result->link) ? ' ' : $result->link; - $CFG->pagepath = "report/security/$issue"; // help link in footer + $PAGE->set_pagetype('admin-report-security-' . $issue); // help link in footer + // TODO, that should probably be changed to $PAGE->set_docs_link(). $table->data[] = $row; diff --git a/admin/repository.php b/admin/repository.php index c9e308c..67b04aa 100644 --- a/admin/repository.php +++ b/admin/repository.php @@ -4,8 +4,6 @@ require_once(dirname(dirname(__FILE__)) . '/config.php'); require_once($CFG->dirroot . '/repository/lib.php'); require_once($CFG->libdir . '/adminlib.php'); -$CFG->pagepath = 'admin/managerepositories'; - $edit = optional_param('edit', 0, PARAM_FORMAT); $new = optional_param('new', '', PARAM_FORMAT); $hide = optional_param('hide', '', PARAM_FORMAT); @@ -48,7 +46,7 @@ if (!empty($edit) || !empty($new)) { $typeid = $new; $repositorytype = null; } - $CFG->pagepath = 'admin/managerepository/' . $plugin; + $PAGE->set_pagetype('admin-repository-' . $plugin); // display the edit form for this instance $mform = new repository_type_form('', array('plugin' => $plugin, 'instance' => $repositorytype)); $fromform = $mform->get_data(); diff --git a/admin/settings.php b/admin/settings.php index 1521770..22d0c5b 100644 --- a/admin/settings.php +++ b/admin/settings.php @@ -55,7 +55,7 @@ if ($data = data_submitted() and confirm_sesskey()) { page_map_class(PAGE_ADMIN, 'page_admin'); $PAGE = page_create_object(PAGE_ADMIN, 0); // there must be any constant id number $PAGE->init_extra($section); -$CFG->pagepath = 'admin/setting/'.$section; +$PAGE->set_pagetype('admin-setting-' . $section); if (!isset($USER->adminediting)) { $USER->adminediting = false; diff --git a/admin/wsprotocols.php b/admin/wsprotocols.php index 401509d..3a514b0 100644 --- a/admin/wsprotocols.php +++ b/admin/wsprotocols.php @@ -4,8 +4,6 @@ require_once(dirname(dirname(__FILE__)) . '/config.php'); require_once($CFG->dirroot . '/webservice/lib.php'); require_once($CFG->libdir . '/adminlib.php'); -$CFG->pagepath = 'admin/managewsprotocols'; - $hide = optional_param('hide', '', PARAM_ALPHANUM); $username = optional_param('username', '', PARAM_ALPHANUM); $settings = optional_param('settings', '', PARAM_ALPHANUM); diff --git a/course/modedit.php b/course/modedit.php index a68de8b..2c51973 100644 --- a/course/modedit.php +++ b/course/modedit.php @@ -185,12 +185,13 @@ $navlinksinstancename = array('name' => format_string($form->name, true), 'link' => "$CFG->wwwroot/mod/$module->name/view.php?id=$cm->id", 'type' => 'activityinstance'); - $CFG->pagepath = 'mod/'.$module->name; + $pagetype = 'mod-' . $module->name . '-'; if (!empty($type)) { - $CFG->pagepath .= '/'.$type; + $pagetype .= $type; } else { - $CFG->pagepath .= '/mod'; + $pagetype .= 'mod'; } + $PAGE->set_pagetype($pagetype); } else { print_error('invalidaction'); } diff --git a/lib/blocklib.php b/lib/blocklib.php index 913de4b..51bc230 100644 --- a/lib/blocklib.php +++ b/lib/blocklib.php @@ -503,7 +503,7 @@ function blocks_execute_action($page, &$pageblocks, $blockaction, $instanceorid, echo ''; echo '
'; - $CFG->pagepath = 'blocks/' . $block->name; + $PAGE->set_pagetype('blocks-' . $block->name); print_footer(); die(); // Do not go on with the other page-related stuff } diff --git a/lib/pagelib.php b/lib/pagelib.php index b74b6ea..5713c9b 100644 --- a/lib/pagelib.php +++ b/lib/pagelib.php @@ -63,8 +63,8 @@ class moodle_page { protected $_legacyclass = null; /// Getter methods ============================================================= -/// Due to the __get magic below, you normally do not call these as get_x methods, -/// but instead use the $PAGE->x syntax. +/// Due to the __get magic below, you normally do not call these as $PAGE->get_x +/// methods, but instead use the $PAGE->x syntax. /** * @return integer one of the STATE_... constants. You should not normally need diff --git a/lib/weblib.php b/lib/weblib.php index adfb909..59918aa 100644 --- a/lib/weblib.php +++ b/lib/weblib.php @@ -6490,7 +6490,7 @@ function page_id_and_class(&$getid, &$getclass) { function print_maintenance_message () { global $CFG, $SITE; - $CFG->pagepath = "index.php"; + $PAGE->set_pagetype('maintenance-message'); print_header(strip_tags($SITE->fullname), $SITE->fullname, 'home'); print_box_start(); print_heading(get_string('sitemaintenance', 'admin')); -- 1.5.6.3 From 37692c6e347a20b0aa7f122048707c06b40bb977 Mon Sep 17 00:00:00 2001 From: Tim Hunt Date: Fri, 17 Apr 2009 18:33:32 +0800 Subject: moodle_page: MDL-14305 (and MDL-12212) class on body based on ->wwwroot --- lib/moodlelib.php | 21 +++++++------ lib/pagelib.php | 44 +++++++++++++++++++++++----- lib/simpletest/testmoodlelib.php | 14 ++++---- lib/simpletest/testpagelib_moodlepage.php | 15 ++++++++-- 4 files changed, 66 insertions(+), 28 deletions(-) diff --git a/lib/moodlelib.php b/lib/moodlelib.php index 5aaeb70..4c819c1 100644 --- a/lib/moodlelib.php +++ b/lib/moodlelib.php @@ -6464,28 +6464,29 @@ function check_php_version($version='5.2.4') { * in the body tag of the page to apply browser-specific rules without relying on CSS hacks */ function get_browser_version_classes() { - $classes = ''; + $classes = array(); + if (check_browser_version("MSIE", "0")) { - $classes .= 'ie '; + $classes[] = 'ie'; if (check_browser_version("MSIE", 8)) { - $classes .= 'ie8 '; + $classes[] = 'ie8'; } elseif (check_browser_version("MSIE", 7)) { - $classes .= 'ie7 '; + $classes[] = 'ie7'; } elseif (check_browser_version("MSIE", 6)) { - $classes .= 'ie6 '; + $classes[] = 'ie6'; } - } elseif (check_browser_version("Firefox", 0) || check_browser_version("Gecko", 0) || check_browser_version("Camino", 0)) { - $classes .= 'gecko '; + } elseif (check_browser_version("Firefox", 0) || check_browser_version("Gecko", 0) || check_browser_version("Camino", 0)) { + $classes[] = 'gecko'; if (preg_match('/rv\:([1-2])\.([0-9])/', $_SERVER['HTTP_USER_AGENT'], $matches)) { - $classes .= "gecko{$matches[1]}{$matches[2]} "; + $classes[] = "gecko{$matches[1]}{$matches[2]}"; } } elseif (check_browser_version("Safari", 0)) { - $classes .= 'safari '; + $classes[] = 'safari'; } elseif (check_browser_version("Opera", 0)) { - $classes .= 'opera '; + $classes[] = 'opera'; } diff --git a/lib/pagelib.php b/lib/pagelib.php index 5713c9b..e511ec0 100644 --- a/lib/pagelib.php +++ b/lib/pagelib.php @@ -125,6 +125,18 @@ class moodle_page { return implode(' ', array_keys($this->_bodyclasses)); } + /** + * PHP overloading magic to make the $PAGE->course syntax work. + */ + public function __get($field) { + $getmethod = 'get_' . $field; + if (method_exists($this, $getmethod)) { + return $this->$getmethod(); + } else { + throw new coding_exception('Unknown field ' . $field . ' of $PAGE.'); + } + } + /// Setter methods ============================================================= /** @@ -215,14 +227,11 @@ class moodle_page { } /** - * PHP overloading magic to make the $PAGE->course syntax work. + * @param array $classes this utility method calls add_body_class for each array element. */ - public function __get($field) { - $getmethod = 'get_' . $field; - if (method_exists($this, $getmethod)) { - return $this->$getmethod(); - } else { - throw new coding_exception('Unknown field ' . $field . ' of $PAGE.'); + public function add_body_classes($classes) { + foreach ($classes as $class) { + $this->add_body_class($class); } } @@ -268,6 +277,8 @@ class moodle_page { } protected function initialise_standard_body_classes() { + global $CFG; + $pagetype = $this->pagetype; if ($pagetype == 'site-index') { $this->_legacyclass = 'course'; @@ -279,10 +290,12 @@ class moodle_page { $this->add_body_class($this->_legacyclass); $this->add_body_class('course-' . $this->_course->id); - $this->add_body_class(get_browser_version_classes()); + $this->add_body_classes(get_browser_version_classes()); $this->add_body_class('dir-' . get_string('thisdirection')); $this->add_body_class('lang-' . current_language()); + $this->add_body_class($this->url_to_class_name($CFG->wwwroot)); + if (!isloggedin()) { $this->add_body_class('notloggedin'); } @@ -296,6 +309,21 @@ class moodle_page { } } + protected function url_to_class_name($url) { + $bits = parse_url($url); + $class = str_replace('.', '-', $bits['host']); + if (!empty($bits['port'])) { + $class .= '--' . $bits['port']; + } + if (!empty($bits['path'])) { + $path = trim($bits['path'], '/'); + if ($path) { + $class .= '--' . str_replace('/', '-', $path); + } + } + return $class; + } + /// Deprecated fields and methods for backwards compatibility ================== /** diff --git a/lib/simpletest/testmoodlelib.php b/lib/simpletest/testmoodlelib.php index f3bcdb7..886c5e0 100644 --- a/lib/simpletest/testmoodlelib.php +++ b/lib/simpletest/testmoodlelib.php @@ -205,25 +205,25 @@ class moodlelib_test extends UnitTestCase { function test_get_browser_version_classes() { $_SERVER['HTTP_USER_AGENT'] = $this->user_agents['Safari']['2.0']['Mac OS X']; - $this->assertEqual('safari ', get_browser_version_classes()); + $this->assertEqual(array('safari'), get_browser_version_classes()); $_SERVER['HTTP_USER_AGENT'] = $this->user_agents['Opera']['9.0']['Windows XP']; - $this->assertEqual('opera ', get_browser_version_classes()); + $this->assertEqual(array('opera'), get_browser_version_classes()); $_SERVER['HTTP_USER_AGENT'] = $this->user_agents['MSIE']['6.0']['Windows XP SP2']; - $this->assertEqual('ie ie6 ', get_browser_version_classes()); + $this->assertEqual(array('ie', 'ie6'), get_browser_version_classes()); $_SERVER['HTTP_USER_AGENT'] = $this->user_agents['MSIE']['7.0']['Windows XP SP2']; - $this->assertEqual('ie ie7 ', get_browser_version_classes()); + $this->assertEqual(array('ie', 'ie7'), get_browser_version_classes()); $_SERVER['HTTP_USER_AGENT'] = $this->user_agents['MSIE']['8.0']['Windows Vista']; - $this->assertEqual('ie ie8 ', get_browser_version_classes()); + $this->assertEqual(array('ie', 'ie8'), get_browser_version_classes()); $_SERVER['HTTP_USER_AGENT'] = $this->user_agents['Firefox']['2.0']['Windows XP']; - $this->assertEqual('gecko gecko18 ', get_browser_version_classes()); + $this->assertEqual(array('gecko', 'gecko18'), get_browser_version_classes()); $_SERVER['HTTP_USER_AGENT'] = $this->user_agents['Firefox']['3.0.6']['SUSE']; - $this->assertEqual('gecko gecko19 ', get_browser_version_classes()); + $this->assertEqual(array('gecko', 'gecko19'), get_browser_version_classes()); } function test_optional_param() diff --git a/lib/simpletest/testpagelib_moodlepage.php b/lib/simpletest/testpagelib_moodlepage.php index 34e5259..623c6f5 100644 --- a/lib/simpletest/testpagelib_moodlepage.php +++ b/lib/simpletest/testpagelib_moodlepage.php @@ -41,6 +41,9 @@ class testable_moodle_page extends moodle_page { public function initialise_default_pagetype($script = '') { parent::initialise_default_pagetype($script); } + public function url_to_class_name($url) { + return parent::url_to_class_name($url); + } } /** @@ -211,13 +214,19 @@ class moodle_page_test extends UnitTestCase { $this->assertEqual('aclassname', $this->testpage->bodyclasses); } - public function test_get_body_classes_double() { + public function test_get_body_classes() { // Exercise SUT - $this->testpage->add_body_class('aclassname'); - $this->testpage->add_body_class('anotherclassname'); + $this->testpage->add_body_classes(array('aclassname', 'anotherclassname')); // Validate $this->assertEqual('aclassname anotherclassname', $this->testpage->bodyclasses); } + + public function test_url_to_class_name() { + $this->assertEqual('example-com', $this->testpage->url_to_class_name('http://example.com')); + $this->assertEqual('example-com--80', $this->testpage->url_to_class_name('http://example.com:80')); + $this->assertEqual('example-com--moodle', $this->testpage->url_to_class_name('https://example.com/moodle')); + $this->assertEqual('example-com--8080--nested-moodle', $this->testpage->url_to_class_name('https://example.com:8080/nested/moodle')); + } } /** -- 1.5.6.3 From 6d7817b62e260f3002d454f6d8ee9593b622dcba Mon Sep 17 00:00:00 2001 From: Tim Hunt Date: Mon, 20 Apr 2009 14:45:12 +0800 Subject: moodle_page: MDL-12212 ->category and ->categories --- admin/roles/assign.php | 1 + course/category.php | 9 +-- lib/moodlelib.php | 2 +- lib/pagelib.php | 102 ++++++++++++++++++++++++++- lib/simpletest/testpagelib_moodlepage.php | 112 ++++++++++++++++++++++++++++- 5 files changed, 216 insertions(+), 10 deletions(-) diff --git a/admin/roles/assign.php b/admin/roles/assign.php index b7ada55..daa5d26 100755 --- a/admin/roles/assign.php +++ b/admin/roles/assign.php @@ -57,6 +57,7 @@ print_error('wrongcontextid', 'error'); } $isfrontpage = $context->contextlevel == CONTEXT_COURSE && $context->instanceid == SITEID; + $PAGE->set_context($context); $contextname = print_context_name($context); $inmeta = 0; diff --git a/course/category.php b/course/category.php index 7129a80..73f88cc 100644 --- a/course/category.php +++ b/course/category.php @@ -29,13 +29,10 @@ print_error("unknowcategory"); } - if (!$context = get_context_instance(CONTEXT_COURSECAT, $id)) { - print_error("unknowcategory"); - } + $PAGE->set_category_by_id($id); + $context = $PAGE->context; + $category = $PAGE->category; - if (!$category = $DB->get_record("course_categories", array("id"=>$id))) { - print_error("unknowcategory"); - } if (!$category->visible) { require_capability('moodle/category:viewhiddencategories', $context); } diff --git a/lib/moodlelib.php b/lib/moodlelib.php index 4c819c1..532ef40 100644 --- a/lib/moodlelib.php +++ b/lib/moodlelib.php @@ -1914,7 +1914,7 @@ function get_login_url($loginguest=false) { * in order to keep redirects working properly. MDL-14495 */ function require_login($courseorid=0, $autologinguest=true, $cm=null, $setwantsurltome=true) { - global $CFG, $SESSION, $USER, $COURSE, $FULLME, $PAGE, $DB; + global $CFG, $SESSION, $USER, $COURSE, $FULLME, $PAGE, $SITE, $DB; /// setup global $COURSE, themes, language and locale if (!empty($courseorid)) { diff --git a/lib/pagelib.php b/lib/pagelib.php index e511ec0..4995bb3 100644 --- a/lib/pagelib.php +++ b/lib/pagelib.php @@ -56,6 +56,17 @@ class moodle_page { protected $_context = null; + /** + * This holds any categories that $_course belongs to, starting with the + * particular category it belongs to, and working out through any parent + * categories to the top level. These are loaded progressively, if neaded. + * There are three states. $_categories = null initially when nothing is + * loaded; $_categories = array($id => $cat, $parentid => null) when we have + * loaded $_course->category, but not any parents; and a complete array once + * everything is loaded. + */ + protected $_categories = null; + protected $_bodyclasses = array(); protected $_pagetype = null; @@ -99,6 +110,30 @@ class moodle_page { } /** + * @return mixed the category that the page course belongs to. If there isn't one + * (that is, if this is the front page course) returns null. + */ + public function get_category() { + $this->ensure_category_loaded(); + if (!empty($this->_categories)) { + return reset($this->_categories); + } else { + return null; + } + } + + /** + * @return array an array of all the categories the page course belongs to, + * starting with the immediately containing category, and working out to + * the top-level category. This may be the empty array if we are in the + * front page course. + */ + public function get_categories() { + $this->ensure_categories_loaded(); + return $this->_categories; + } + + /** * @return object the main context to which this page belongs. */ public function get_context() { @@ -175,7 +210,7 @@ class moodle_page { * @param object the course to set as the global course. */ public function set_course($course) { - global $COURSE, $SITE; + global $COURSE; if (empty($course->id)) { throw new coding_exception('$course passed to moodle_page::set_course does not look like a proper course object.'); @@ -192,6 +227,8 @@ class moodle_page { $this->set_context(get_context_instance(CONTEXT_COURSE, $this->_course->id)); } + $this->_categories = null; + moodle_setlocale(); theme_setup(); } @@ -235,6 +272,27 @@ class moodle_page { } } + /** + * Set the course category this page belongs to manually. This automatically + * sets $PAGE->course to be the site coures. You cannot use this method if + * you have already set $PAGE->course - in that case, the category must be + * the one that the course belongs to. This also automatically sets the + * page context to the category context. + * @param integer $categoryid The id of the category to set. + */ + public function set_category_by_id($categoryid) { + global $SITE, $DB; + if (!is_null($this->_course)) { + throw new coding_exception('Attempt to manually set the course category when the course has been set. This is not allowed.'); + } + if (is_array($this->_categories)) { + throw new coding_exception('Course category has already been set. You are not allowed to change it.'); + } + $this->set_course($SITE); + $this->load_category($categoryid); + $this->set_context(get_context_instance(CONTEXT_COURSECAT, $categoryid)); + } + /// Initialisation methods ===================================================== /// These set various things up in a default way. @@ -309,6 +367,48 @@ class moodle_page { } } + protected function ensure_category_loaded() { + if (is_array($this->_categories)) { + return; // Already done. + } + if (is_null($this->_course)) { + throw new coding_exception('Attempt to get the course category for this page before the course was set.'); + } + if ($this->_course->category == 0) { + $this->_categories = array(); + } else { + $this->load_category($this->_course->category); + } + } + + protected function load_category($categoryid) { + global $DB; + $category = $DB->get_record('course_categories', array('id' => $categoryid)); + if (!$category) { + throw new moodle_exception('unknowncategory'); + } + $this->_categories[$category->id] = $category; + $parentcategoryids = explode('/', trim($category->path, '/')); + array_pop($parentcategoryids); + foreach (array_reverse($parentcategoryids) as $catid) { + $this->_categories[$catid] = null; + } + } + + protected function ensure_categories_loaded() { + global $DB; + $this->ensure_category_loaded(); + if (!is_null(end($this->_categories))) { + return; // Already done. + } + $idstoload = array_keys($this->_categories); + array_shift($idstoload); + $categories = $DB->get_records_list('course_categories', 'id', $idstoload); + foreach ($idstoload as $catid) { + $this->_categories[$catid] = $categories[$catid]; + } + } + protected function url_to_class_name($url) { $bits = parse_url($url); $class = str_replace('.', '-', $bits['host']); diff --git a/lib/simpletest/testpagelib_moodlepage.php b/lib/simpletest/testpagelib_moodlepage.php index 623c6f5..cc798a0 100644 --- a/lib/simpletest/testpagelib_moodlepage.php +++ b/lib/simpletest/testpagelib_moodlepage.php @@ -124,6 +124,26 @@ class moodle_page_test extends UnitTestCase { $this->testpage->set_course($course); } + public function test_cannot_set_category_once_output_started() { + // Setup fixture + $this->testpage->set_state(moodle_page::STATE_PRINTING_HEADER); + // Set expectation. + $this->expectException(); + // Exercise SUT + $this->testpage->set_category_by_id(123); + } + + public function test_cannot_set_category_once_course_set() { + // Setup fixture + $course = $this->create_a_course(); + $this->testpage->set_context(new stdClass); // Avoid trying to set the context. + $this->testpage->set_course($course); + // Set expectation. + $this->expectException(); + // Exercise SUT + $this->testpage->set_category_by_id(123); + } + public function test_set_state_normal_path() { $this->assertEqual(moodle_page::STATE_BEFORE_HEADER, $this->testpage->state); @@ -230,14 +250,15 @@ class moodle_page_test extends UnitTestCase { } /** - * Test functions that affect filter_active table with contextid = $syscontextid. + * Test functions that rely on the context table. */ -class moodle_page_with_db_test extends UnitTestCaseUsingDatabase { +class moodle_page_with_context_table_test extends UnitTestCaseUsingDatabase { protected $testpage; protected $originalcourse; public function setUp() { global $COURSE; + parent::setUp(); $this->originalcourse = $COURSE; $this->testpage = new moodle_page(); $this->create_test_table('context', 'lib'); @@ -248,6 +269,7 @@ class moodle_page_with_db_test extends UnitTestCaseUsingDatabase { global $COURSE; $this->testpage = NULL; $COURSE = $this->originalcourse; + parent::tearDown(); } /** Creates an object with all the fields you would expect a $course object to have. */ @@ -281,4 +303,90 @@ class moodle_page_with_db_test extends UnitTestCaseUsingDatabase { $this->assert(new CheckSpecifiedFieldsExpectation($expectedcontext), $this->testpage->context); } } + +/** + * Test functions that rely on the context table. + */ +class moodle_page_categories_test extends UnitTestCaseUsingDatabase { + protected $testpage; + protected $originalcourse; + + public function setUp() { + global $COURSE, $SITE; + parent::setUp(); + $this->originalcourse = $COURSE; + $this->testpage = new moodle_page(); + $this->create_test_tables(array('course_categories', 'context'), 'lib'); + $this->switch_to_test_db(); + + $context = new stdClass; + $context->contextlevel = CONTEXT_COURSE; + $context->instanceid = $SITE->id; + $context->path = 'not initialised'; + $context->depth = '-1'; + $this->testdb->insert_record('context', $context); + } + + public function tearDown() { + global $COURSE; + $this->testpage = NULL; + $COURSE = $this->originalcourse; + parent::tearDown(); + } + + /** Creates an object with all the fields you would expect a $course object to have. */ + protected function create_a_category_with_context($parentid = 0) { + if ($parentid) { + $parent = $this->testdb->get_record('course_categories', array('id' => $parentid)); + } else { + $parent = new stdClass; + $parent->depth = 0; + $parent->path = ''; + } + $cat = new stdClass; + $cat->name = 'Anonymous test category'; + $cat->description = ''; + $cat->parent = $parentid; + $cat->depth = $parent->depth + 1; + $cat->id = $this->testdb->insert_record('course_categories', $cat); + $cat->path = $parent->path . '/' . $cat->id; + $this->testdb->set_field('course_categories', 'path', $cat->path, array('id' => $cat->id)); + + $context = new stdClass; + $context->contextlevel = CONTEXT_COURSECAT; + $context->instanceid = $cat->id; + $context->path = 'not initialised'; + $context->depth = '-1'; + $this->testdb->insert_record('context', $context); + + return $cat; + } + + public function test_set_category_top_level() { + // Setup fixture + $cat = $this->create_a_category_with_context(); + // Exercise SUT + $this->testpage->set_category_by_id($cat->id); + // Validate + $this->assert(new CheckSpecifiedFieldsExpectation($cat), $this->testpage->category); + $expectedcontext = new stdClass; // Test it sets the context. + $expectedcontext->contextlevel = CONTEXT_COURSECAT; + $expectedcontext->instanceid = $cat->id; + $this->assert(new CheckSpecifiedFieldsExpectation($expectedcontext), $this->testpage->context); + } + + public function test_set_nested_categories() { + // Setup fixture + $topcat = $this->create_a_category_with_context(); + $subcat = $this->create_a_category_with_context($topcat->id); + // Exercise SUT + $this->testpage->set_category_by_id($subcat->id); + // Validate + $categories = $this->testpage->categories; + $this->assertEqual(2, count($categories)); + $this->assert(new CheckSpecifiedFieldsExpectation($topcat), array_pop($categories)); + $this->assert(new CheckSpecifiedFieldsExpectation($subcat), array_pop($categories)); + } +} + ?> -- 1.5.6.3 From 099e85b88a59a00941c24533a7522c09ace5a96b Mon Sep 17 00:00:00 2001 From: Tim Hunt Date: Mon, 20 Apr 2009 15:51:27 +0800 Subject: moodle_page: MDL-14306 (part of MDL-12212) class name on body with ->category If ->allowcategorythemes is set, includes all parent categories too --- admin/settings.php | 2 +- lib/adminlib.php | 2 +- lib/pagelib.php | 44 +++++++++++++++++++++++++--- lib/simpletest/testpagelib_moodlepage.php | 10 ++++++ 4 files changed, 51 insertions(+), 7 deletions(-) diff --git a/admin/settings.php b/admin/settings.php index 22d0c5b..ae1aefd 100644 --- a/admin/settings.php +++ b/admin/settings.php @@ -54,8 +54,8 @@ if ($data = data_submitted() and confirm_sesskey()) { /// very hacky page setup page_map_class(PAGE_ADMIN, 'page_admin'); $PAGE = page_create_object(PAGE_ADMIN, 0); // there must be any constant id number -$PAGE->init_extra($section); $PAGE->set_pagetype('admin-setting-' . $section); +$PAGE->init_extra($section); if (!isset($USER->adminediting)) { $USER->adminediting = false; diff --git a/lib/adminlib.php b/lib/adminlib.php index da74f47..0bcab79 100644 --- a/lib/adminlib.php +++ b/lib/adminlib.php @@ -3898,10 +3898,10 @@ function admin_externalpage_setup($section, $extrabutton='', $extraurlparams=arr page_map_class(PAGE_ADMIN, 'page_admin'); $PAGE = page_create_object(PAGE_ADMIN, 0); // there must be any constant id number + $PAGE->set_context(get_context_instance(CONTEXT_SYSTEM)); $PAGE->init_extra($section); // hack alert! $PAGE->set_extra_button($extrabutton); $PAGE->set_extra_url_params($extraurlparams, $actualurl); - $PAGE->set_context(get_context_instance(CONTEXT_SYSTEM)); $adminroot = admin_get_root(false, false); // settings not required for external pages $extpage = $adminroot->locate($section); diff --git a/lib/pagelib.php b/lib/pagelib.php index 4995bb3..35a5c48 100644 --- a/lib/pagelib.php +++ b/lib/pagelib.php @@ -220,6 +220,10 @@ class moodle_page { throw new coding_exception('Cannot call moodle_page::set_course after output has been started.'); } + if (!empty($this->_course->id) && $this->_course->id != $course->id) { + $this->_categories = null; + } + $this->_course = clone($course); $COURSE = $this->_course; @@ -227,8 +231,6 @@ class moodle_page { $this->set_context(get_context_instance(CONTEXT_COURSE, $this->_course->id)); } - $this->_categories = null; - moodle_setlocale(); theme_setup(); } @@ -354,6 +356,24 @@ class moodle_page { $this->add_body_class($this->url_to_class_name($CFG->wwwroot)); + if ($CFG->allowcategorythemes) { + $this->ensure_category_loaded(); + foreach ($this->_categories as $catid => $notused) { + $this->add_body_class('category-' . $catid); + } + } else { + $catid = 0; + if (is_array($this->_categories)) { + $catids = array_keys($this->_categories); + $catid = reset($catids); + } else if (!empty($this->_course->category)) { + $catid = $this->_course->category; + } + if ($catid) { + $this->add_body_class('category-' . $catid); + } + } + if (!isloggedin()) { $this->add_body_class('notloggedin'); } @@ -490,7 +510,7 @@ function page_create_instance($instance) { * its numeric ID. Returns a fully constructed page_base subclass you can work with. */ function page_create_object($type, $id = NULL) { - global $CFG, $PAGE; + global $CFG, $PAGE, $SITE; $data = new stdClass; $data->pagetype = $type; @@ -498,9 +518,23 @@ function page_create_object($type, $id = NULL) { $classname = page_map_class($type); $object = new $classname; - $object->init_quick($data); - $object->set_course($PAGE->course); + $course = $PAGE->course; + if ($course->id != $SITE->id) { + $object->set_course($course); + } else { + try { + $category = $PAGE->category; + } catch (coding_exception $e) { + // Was not set before, so no need to try to set it again. + $category = false; + } + if ($category) { + $object->set_category_by_id($category->id); + } else { + $object->set_course($SITE); + } + } //$object->set_pagetype($type); return $object; } diff --git a/lib/simpletest/testpagelib_moodlepage.php b/lib/simpletest/testpagelib_moodlepage.php index cc798a0..92581cc 100644 --- a/lib/simpletest/testpagelib_moodlepage.php +++ b/lib/simpletest/testpagelib_moodlepage.php @@ -144,6 +144,16 @@ class moodle_page_test extends UnitTestCase { $this->testpage->set_category_by_id(123); } + public function test_categories_array_empty_for_front_page() { + // Setup fixture + $course = $this->create_a_course(); + $course->category = 0; + $this->testpage->set_context(new stdClass); // Avoid trying to set the context. + $this->testpage->set_course($course); + // Exercise SUT and validate. + $this->assertEqual(array(), $this->testpage->categories); + } + public function test_set_state_normal_path() { $this->assertEqual(moodle_page::STATE_BEFORE_HEADER, $this->testpage->state); -- 1.5.6.3 From b3a5c32fd4213aebd1406fb0294bf420ce8e772d Mon Sep 17 00:00:00 2001 From: Tim Hunt Date: Mon, 20 Apr 2009 17:11:29 +0800 Subject: moodle_page: MDL-12212 ->docspath --- admin/report/security/index.php | 3 +- admin/report/security/lib.php | 8 +----- index.php | 3 +- lib/pagelib.php | 24 +++++++++++++++++++ lib/simpletest/testpagelib_moodlepage.php | 14 +++++++++++ lib/weblib.php | 36 +++++++++-------------------- 6 files changed, 54 insertions(+), 34 deletions(-) diff --git a/admin/report/security/index.php b/admin/report/security/index.php index c2f64fe..1e8d2d9 100644 --- a/admin/report/security/index.php +++ b/admin/report/security/index.php @@ -88,8 +88,7 @@ if ($issue and ($result = $issue(true))) { $row[2] = $result->info; $row[3] = is_null($result->link) ? ' ' : $result->link; - $PAGE->set_pagetype('admin-report-security-' . $issue); // help link in footer - // TODO, that should probably be changed to $PAGE->set_docs_link(). + $PAGE->set_docs_path('admin/report/security/' . $issue); $table->data[] = $row; diff --git a/admin/report/security/lib.php b/admin/report/security/lib.php index 4e26705..94480df 100644 --- a/admin/report/security/lib.php +++ b/admin/report/security/lib.php @@ -74,12 +74,8 @@ function report_security_doc_link($issue, $name) { return $name; } - $lang = str_replace('_utf8', '', current_language()); - - $str = "docroot/$lang/report/security/$issue\">"; - $str .= "httpswwwroot/pix/docs.gif\" alt=\"\" />$name"; - - return $str; + return '' + . '' . $name . ''; } ///============================================= diff --git a/index.php b/index.php index cc14602..a0f3548 100644 --- a/index.php +++ b/index.php @@ -87,7 +87,8 @@ $langmenu = popup_form($CFG->wwwroot .'/index.php?lang=', $langs, 'chooselang', $currlang, '', '', '', true, 'self', $langlabel); } - $PAGE = page_create_object(PAGE_COURSE_VIEW, SITEID); + $PAGE = page_create_object(PAGE_COURSE_VIEW, SITEID); + $PAGE->set_docs_path(''); $pageblocks = blocks_setup($PAGE); $editing = $PAGE->user_is_editing(); $preferred_width_left = bounded_number(BLOCK_L_MIN_WIDTH, blocks_preferred_width($pageblocks[BLOCK_POS_LEFT]), diff --git a/lib/pagelib.php b/lib/pagelib.php index 35a5c48..4537726 100644 --- a/lib/pagelib.php +++ b/lib/pagelib.php @@ -71,6 +71,8 @@ class moodle_page { protected $_pagetype = null; + protected $_docspath = null; + protected $_legacyclass = null; /// Getter methods ============================================================= @@ -161,6 +163,17 @@ class moodle_page { } /** + * @return string the class names to put on the body element in the HTML. + */ + public function get_docspath() { + if (is_string($this->_docspath)) { + return $this->_docspath; + } else { + return str_replace('-', '/', $this->pagetype); + } + } + + /** * PHP overloading magic to make the $PAGE->course syntax work. */ public function __get($field) { @@ -295,6 +308,17 @@ class moodle_page { $this->set_context(get_context_instance(CONTEXT_COURSECAT, $categoryid)); } + /** + * Set a different path to use for the 'Moodle docs for this page' link. + * By default, it uses the pagetype, which is normally the same as the + * script name. So, for example, for mod/quiz/attempt.php, pagetype is + * mod-quiz-attempt, and so docspath is mod/quiz/attempt. + * @param string $path the path to use at the end of the moodle docs URL. + */ + public function set_docs_path($path) { + $this->_docspath = $path; + } + /// Initialisation methods ===================================================== /// These set various things up in a default way. diff --git a/lib/simpletest/testpagelib_moodlepage.php b/lib/simpletest/testpagelib_moodlepage.php index 92581cc..43313e2 100644 --- a/lib/simpletest/testpagelib_moodlepage.php +++ b/lib/simpletest/testpagelib_moodlepage.php @@ -257,6 +257,20 @@ class moodle_page_test extends UnitTestCase { $this->assertEqual('example-com--moodle', $this->testpage->url_to_class_name('https://example.com/moodle')); $this->assertEqual('example-com--8080--nested-moodle', $this->testpage->url_to_class_name('https://example.com:8080/nested/moodle')); } + + public function test_set_docs_path() { + // Exercise SUT + $this->testpage->set_docs_path('a/file/path'); + // Validate + $this->assertEqual('a/file/path', $this->testpage->docspath); + } + + public function test_docs_path_defaults_from_pagetype() { + // Exercise SUT + $this->testpage->set_pagetype('a-page-type'); + // Validate + $this->assertEqual('a/page/type', $this->testpage->docspath); + } } /** diff --git a/lib/weblib.php b/lib/weblib.php index 59918aa..0ca5345 100644 --- a/lib/weblib.php +++ b/lib/weblib.php @@ -6664,33 +6664,21 @@ function convert_tabrows_to_tree($tabrows, $selected, $inactive, $activated) { * Returns a string containing a link to the user documentation for the current * page. Also contains an icon by default. Shown to teachers and admin only. * - * @param string $text The text to be displayed for the link - * @param string $iconpath The path to the icon to be displayed + * @param string $text The text to be displayed for the link + * @param string $iconpath The path to the icon to be displayed */ function page_doc_link($text='', $iconpath='') { - global $SCRIPT, $COURSE, $CFG; + global $CFG, $PAGE; - if (empty($CFG->docroot) or empty($CFG->rolesactive)) { + if (empty($CFG->docroot) || empty($CFG->rolesactive)) { return ''; } - - if (empty($COURSE->id)) { - $context = get_context_instance(CONTEXT_SYSTEM); - } else { - $context = get_context_instance(CONTEXT_COURSE, $COURSE->id); - } - - if (!has_capability('moodle/site:doclinks', $context)) { + if (!has_capability('moodle/site:doclinks', $PAGE->context)) { return ''; } - if (empty($CFG->pagepath)) { - $CFG->pagepath = ltrim($SCRIPT, '/'); - } - - $path = str_replace('.php', '', $CFG->pagepath); - - if (empty($path)) { // Not for home page + $path = $PAGE->docspath; + if (!$path) { return ''; } return doc_link($path, $text, $iconpath); @@ -6698,8 +6686,7 @@ function page_doc_link($text='', $iconpath='') { /** * @param string $path the end of the URL. - * @return The start of a MoodleDocs URL in the user's language. - * E.g. http://docs.moodle.org/en/ + * @return The MoodleDocs URL in the user's language. for example http://docs.moodle.org/en/$path */ function get_docs_url($path) { global $CFG; @@ -6710,10 +6697,9 @@ function get_docs_url($path) { * Returns a string containing a link to the user documentation. * Also contains an icon by default. Shown to teachers and admin only. * - * @param string $path The page link after doc root and language, no - * leading slash. - * @param string $text The text to be displayed for the link - * @param string $iconpath The path to the icon to be displayed + * @param string $path The page link after doc root and language, no leading slash. + * @param string $text The text to be displayed for the link + * @param string $iconpath The path to the icon to be displayed */ function doc_link($path='', $text='', $iconpath='') { global $CFG; -- 1.5.6.3 From 56474a417cb1c6223b251184e02cd13d878689bd Mon Sep 17 00:00:00 2001 From: Tim Hunt Date: Wed, 22 Apr 2009 11:07:07 +0800 Subject: moodle_url: MDL-12212 clean up moodle_url coding style --- lib/weblib.php | 85 ++++++++++++++++++++++++++++++------------------------- 1 files changed, 46 insertions(+), 39 deletions(-) diff --git a/lib/weblib.php b/lib/weblib.php index 0ca5345..6050e07 100644 --- a/lib/weblib.php +++ b/lib/weblib.php @@ -223,60 +223,60 @@ function qualified_me() { return $FULLME; } - /** * Class for creating and manipulating urls. * * See short write up here http://docs.moodle.org/en/Development:lib/weblib.php_moodle_url */ class moodle_url { - var $scheme = '';// e.g. http - var $host = ''; - var $port = ''; - var $user = ''; - var $pass = ''; - var $path = ''; - var $fragment = ''; - var $params = array(); //associative array of query string params + protected $scheme = ''; // e.g. http + protected $host = ''; + protected $port = ''; + protected $user = ''; + protected $pass = ''; + protected $path = ''; + protected $fragment = ''; + protected $params = array(); // Associative array of query string params /** * Pass no arguments to create a url that refers to this page. Use empty string to create empty url. * * @param string $url url default null means use this page url with no query string - * empty string means empty url. - * if you pass any other type of url it will be parsed into it's bits, including query string - * @param array $params these params override anything in the query string where params have the same name. + * empty string means empty url. If you pass any other type of url it will + * be parsed into it's bits, including query string + * @param array $params these params override anything in the query string + * where params have the same name. */ - function moodle_url($url = null, $params = array()){ + public function __construct($url = null, $params = array()) { global $ME; - if ($url !== ''){ - if ($url === null){ + if ($url !== '') { + if ($url === null) { $url = $ME; } $parts = parse_url($url); - if ($parts === FALSE){ + if ($parts === FALSE) { print_error('invalidurl'); } - if (isset($parts['query'])){ + if (isset($parts['query'])) { parse_str(str_replace('&', '&', $parts['query']), $this->params); } unset($parts['query']); - foreach ($parts as $key => $value){ + foreach ($parts as $key => $value) { $this->$key = $value; } $this->params($params); } } + /** * Add an array of params to the params for this page. The added params override existing ones if they * have the same name. * - * @param array $params Defaults to null. If null then return value of - * param 'name'. + * @param array $params Defaults to null. If null then return value of param 'name'. * @return array params for url. */ - function params($params = null){ - if (!is_null($params)){ + public function params($params = null) { + if (!is_null($params)) { return $this->params = $params + $this->params; } else { return $this->params; @@ -290,10 +290,10 @@ class moodle_url { * @param string $arg2 * @param string $arg3 */ - function remove_params(){ - if ($thisargs = func_get_args()){ - foreach ($thisargs as $arg){ - if (isset($this->params[$arg])){ + public function remove_params() { + if ($thisargs = func_get_args()) { + foreach ($thisargs as $arg) { + if (isset($this->params[$arg])) { unset($this->params[$arg]); } } @@ -307,40 +307,45 @@ class moodle_url { * have the same name. * * @param string $paramname name - * @param string $param value. Defaults to null. If null then return value - * of param 'name' + * @param string $param value. Defaults to null. If null then return value of param 'name' */ - function param($paramname, $param = null){ - if (!is_null($param)){ + public function param($paramname, $param = null) { + if (!is_null($param)) { $this->params = array($paramname => $param) + $this->params; } else { return $this->params[$paramname]; } } - - function get_query_string($overrideparams = array()){ + /** + * Get the params as as a query string. + * @param array $overrideparams params to add to the output params, these + * override existing ones with the same name. + * @return string query string that can be added to a url. + */ + public function get_query_string($overrideparams = array()) { $arr = array(); $params = $overrideparams + $this->params; - foreach ($params as $key => $val){ + foreach ($params as $key => $val) { $arr[] = urlencode($key)."=".urlencode($val); } return implode($arr, "&"); } + /** * Outputs params as hidden form elements. * * @param array $exclude params to ignore * @param integer $indent indentation * @param array $overrideparams params to add to the output params, these - * override existing ones with the same name. + * override existing ones with the same name. * @return string html for form elements. */ - function hidden_params_out($exclude = array(), $indent = 0, $overrideparams=array()){ + public function hidden_params_out($exclude = array(), $indent = 0, $overrideparams=array()) { $tabindent = str_repeat("\t", $indent); $str = ''; $params = $overrideparams + $this->params; - foreach ($params as $key => $val){ + foreach ($params as $key => $val) { if (FALSE === array_search($key, $exclude)) { $val = s($val); $str.= "$tabindent\n"; @@ -348,6 +353,7 @@ class moodle_url { } return $str; } + /** * Output url * @@ -355,25 +361,26 @@ class moodle_url { * @param array $overrideparams params to add to the output url, these override existing ones with the same name. * @return string url */ - function out($noquerystring = false, $overrideparams = array()) { + public function out($noquerystring = false, $overrideparams = array()) { $uri = $this->scheme ? $this->scheme.':'.((strtolower($this->scheme) == 'mailto') ? '':'//'): ''; $uri .= $this->user ? $this->user.($this->pass? ':'.$this->pass:'').'@':''; $uri .= $this->host ? $this->host : ''; $uri .= $this->port ? ':'.$this->port : ''; $uri .= $this->path ? $this->path : ''; - if (!$noquerystring){ + if (!$noquerystring) { $uri .= (count($this->params)||count($overrideparams)) ? '?'.$this->get_query_string($overrideparams) : ''; } $uri .= $this->fragment ? '#'.$this->fragment : ''; return $uri; } + /** * Output action url with sesskey * * @param boolean $noquerystring whether to output page params as a query string in the url. * @return string url */ - function out_action($overrideparams = array()) { + public function out_action($overrideparams = array()) { $overrideparams = array('sesskey'=> sesskey()) + $overrideparams; return $this->out(false, $overrideparams); } -- 1.5.6.3 From f85fa17bc10fde8e3ea5dc3c956731b7fba12b6c Mon Sep 17 00:00:00 2001 From: Tim Hunt Date: Wed, 22 Apr 2009 14:45:04 +0800 Subject: moodle_page: MDL-12212 ->url and cleanup init of $FULLME, etc. --- lib/pagelib.php | 32 ++++++ lib/setuplib.php | 148 +++++++++++++++++------------ lib/simpletest/testpagelib_moodlepage.php | 40 ++++++++ lib/weblib.php | 61 ++++++++---- 4 files changed, 200 insertions(+), 81 deletions(-) diff --git a/lib/pagelib.php b/lib/pagelib.php index 4537726..95af986 100644 --- a/lib/pagelib.php +++ b/lib/pagelib.php @@ -75,6 +75,8 @@ class moodle_page { protected $_legacyclass = null; + protected $_url = null; + /// Getter methods ============================================================= /// Due to the __get magic below, you normally do not call these as $PAGE->get_x /// methods, but instead use the $PAGE->x syntax. @@ -174,6 +176,18 @@ class moodle_page { } /** + * @return moodle_url the clean URL required to load the current page. (You + * should normally use this in preference to $ME or $FULLME.) + */ + public function get_url() { + if (is_null($this->_url)) { + debugging('This page did no call $PAGE->set_url(...). Realying on a guess.', DEBUG_DEVELOPER); + return new moodle_url($ME); + } + return $this->_url; + } + + /** * PHP overloading magic to make the $PAGE->course syntax work. */ public function __get($field) { @@ -319,6 +333,24 @@ class moodle_page { $this->_docspath = $path; } + /** + * You should call this method from every page to set the cleaned-up URL + * that should be used to return to this page. Used, for example, by the + * blocks editing UI to know where to return the user after an action. + * For example, course/view.php does: + * $id = optional_param('id', 0, PARAM_INT); + * $PAGE->set_url('course/view.php', array('id' => $id)); + * @param string $url a URL, relative to $CFG->wwwroot. + * @param array $params paramters to add ot the URL. + */ + public function set_url($url, $params = array()) { + global $CFG; + $this->_url = new moodle_url($CFG->wwwroot . '/' . $url, $params); + if (is_null($this->_pagetype)) { + $this->initialise_default_pagetype($url); + } + } + /// Initialisation methods ===================================================== /// These set various things up in a default way. diff --git a/lib/setuplib.php b/lib/setuplib.php index 3aa0a20..3e24758 100644 --- a/lib/setuplib.php +++ b/lib/setuplib.php @@ -103,45 +103,107 @@ function setup_validate_php_configuration() { } /** - * Initialises $FULLME and friends. - * @return void + * Initialises $FULLME and friends. Private function. Should only be called from + * setup.php. */ function initialise_fullme() { global $CFG, $FULLME, $ME, $SCRIPT, $FULLSCRIPT; + // Detect common config error. if (substr($CFG->wwwroot, -1) == '/') { print_error('wwwrootslash', 'error'); } - $url = parse_url($CFG->wwwroot); - if (!isset($url['path'])) { - $url['path'] = ''; + if (CLI_SCRIPT) { + initialise_fullme_cli(); + return; } - $url['path'] .= '/'; - if (CLI_SCRIPT) { - // urls do not make much sense in CLI scripts - $backtrace = debug_backtrace(); - $topfile = array_pop($backtrace); - $topfile = realpath($topfile['file']); - $dirroot = realpath($CFG->dirroot); - - if (strpos($topfile, $dirroot) !== 0) { - $SCRIPT = $FULLSCRIPT = $FULLME = $ME = null; - } else { - $relme = substr($topfile, strlen($dirroot)); - $relme = str_replace('\\', '/', $relme); // Win fix - $SCRIPT = $FULLSCRIPT = $FULLME = $ME = $relme; - } + $wwwroot = parse_url($CFG->wwwroot); + if (!isset($wwwroot['path'])) { + $wwwroot['path'] = ''; + } + $wwwroot['path'] .= '/'; + + $rurl = setup_get_remote_url(); + // Check that URL is under $CFG->wwwroot. + if (strpos($rurl['path'], $wwwroot['path']) === 0) { + $SCRIPT = substr($rurl['path'], strlen($wwwroot['path'])-1); + } else { + // Probably some weird external script + $SCRIPT = $FULLSCRIPT = $FULLME = $ME = null; return; } + // $CFG->sslproxy specifies if external SSL appliance is used + // (That is, the Moodle server uses http, with an external box translating everything to https). + if (empty($CFG->sslproxy)) { + if ($rurl['scheme'] == 'http' and $wwwroot['scheme'] == 'https') { + print_error('sslonlyaccess', 'error'); + } + } + + // $CFG->reverseproxy specifies if reverse proxy server used. + // Used in load balancing scenarios. + // Do not abuse this to try to solve lan/wan access problems!!!!! + if (empty($CFG->reverseproxy)) { + if (($rurl['host'] != $wwwroot['host']) or + (!empty($wwwroot['port']) and $rurl['port'] != $wwwroot['port'])) { + print_error('wwwrootmismatch', 'error', '', $CFG->wwwroot); + } + } + + // hopefully this will stop all those "clever" admins trying to set up moodle + // with two different addresses in intranet and Internet + if (!empty($CFG->reverseproxy) && $rurl['host'] == $wwwroot['host']) { + print_error('reverseproxyabused', 'error'); + } + + $hostandport = $rurl['scheme'] . '://' . $wwwroot['host']; + if (!empty($wwwroot['port'])) { + $hostandport .= ':'.$wwwroot['port']; + } + + $FULLSCRIPT = $hostandport . $rurl['path']; + $FULLME = $hostandport . $rurl['fullpath']; + $ME = $rurl['fullpath']; + $rurl['path'] = $rurl['fullpath']; +} + +/** + * Initialises $FULLME and friends for command line scripts. + * This is a private method for use by initialise_fullme. + */ +function initialise_fullme_cli() { + // Urls do not make much sense in CLI scripts + $backtrace = debug_backtrace(); + $topfile = array_pop($backtrace); + $topfile = realpath($topfile['file']); + $dirroot = realpath($CFG->dirroot); + + if (strpos($topfile, $dirroot) !== 0) { + // Probably some weird external script + $SCRIPT = $FULLSCRIPT = $FULLME = $ME = null; + } else { + $relativefile = substr($topfile, strlen($dirroot)); + $relativefile = str_replace('\\', '/', $relativefile); // Win fix + $SCRIPT = $FULLSCRIPT = $relativefile; + $FULLME = $ME = null; + } +} + +/** + * Get the URL that PHP/the web server thinks it is serving. Private function + * used by initialise_fullme. In your code, use $PAGE->url, $SCRIPT, etc. + * @return array in the same format that parse_url returns, with the addition of + * a 'fullpath' element, which includes any slasharguments path. + */ +function setup_get_remote_url() { $rurl = array(); - $hostport = explode(':', $_SERVER['HTTP_HOST']); - $rurl['host'] = reset($hostport); + list($rurl['host']) = explode(':', $_SERVER['HTTP_HOST']); $rurl['port'] = $_SERVER['SERVER_PORT']; - $rurl['path'] = $_SERVER['SCRIPT_NAME']; // script path without slash arguments + $rurl['path'] = $_SERVER['SCRIPT_NAME']; // Script path without slash arguments if (stripos($_SERVER['SERVER_SOFTWARE'], 'apache') !== false) { //Apache server @@ -168,45 +230,9 @@ function initialise_fullme() { $_SERVER['REQUEST_URI'] = $rurl['fullpath']; // extra IIS compatibility } else { - print_error('unsupportedwebserver', 'error', '', $_SERVER['SERVER_SOFTWARE']); + throw new moodle_exception('unsupportedwebserver', 'error', '', $_SERVER['SERVER_SOFTWARE']); } - - if (strpos($rurl['path'], $url['path']) === 0) { - $SCRIPT = substr($rurl['path'], strlen($url['path'])-1); - } else { - // probably some weird external script - $SCRIPT = $FULLSCRIPT = $FULLME = $ME = null; - return; - } - - // $CFG->sslproxy specifies if external SSL apliance is used (server using http, ext box translating everything to https) - if (empty($CFG->sslproxy)) { - if ($rurl['scheme'] == 'http' and $url['scheme'] == 'https') { - print_error('sslonlyaccess', 'error'); - } - } - - // $CFG->reverseproxy specifies if reverse proxy server used - used in advanced load balancing setups only! - // this is not supposed to solve lan/wan access problems!!!!! - if (empty($CFG->reverseproxy)) { - if (($rurl['host'] != $url['host']) or (!empty($url['port']) and $rurl['port'] != $url['port'])) { - print_error('wwwrootmismatch', 'error', '', $CFG->wwwroot); - } - } else { - if ($rurl['host'] == $url['host']) { - // hopefully this will stop all those "clever" admins trying to set up moodle with two different addresses in intranet and Internet - print_error('reverseproxyabused', 'error'); - } - } - - $FULLME = $rurl['scheme'].'://'.$url['host']; - if (!empty($url['port'])) { - $FULLME .= ':'.$url['port']; - } - $FULLSCRIPT = $FULLME.$rurl['path']; - $FULLME = $FULLME.$rurl['fullpath']; - $ME = $rurl['fullpath']; - + return $rurl; } /** diff --git a/lib/simpletest/testpagelib_moodlepage.php b/lib/simpletest/testpagelib_moodlepage.php index 43313e2..2f4d1f8 100644 --- a/lib/simpletest/testpagelib_moodlepage.php +++ b/lib/simpletest/testpagelib_moodlepage.php @@ -271,6 +271,46 @@ class moodle_page_test extends UnitTestCase { // Validate $this->assertEqual('a/page/type', $this->testpage->docspath); } + + public function test_set_url_root() { + global $CFG; + // Exercise SUT + $this->testpage->set_url(''); + // Validate + $this->assertEqual($CFG->wwwroot . '/', $this->testpage->url->out()); + } + + public function test_set_url_one_param() { + global $CFG; + // Exercise SUT + $this->testpage->set_url('mod/quiz/attempt.php', array('attempt' => 123)); + // Validate + $this->assertEqual($CFG->wwwroot . '/mod/quiz/attempt.php?attempt=123', $this->testpage->url->out()); + } + + public function test_set_url_two_params() { + global $CFG; + // Exercise SUT + $this->testpage->set_url('mod/quiz/attempt.php', array('attempt' => 123, 'page' => 7)); + // Validate + $this->assertEqual($CFG->wwwroot . '/mod/quiz/attempt.php?attempt=123&page=7', $this->testpage->url->out()); + } + + public function test_set_url_sets_page_type() { + // Exercise SUT + $this->testpage->set_url('mod/quiz/attempt.php', array('attempt' => 123, 'page' => 7)); + // Validate + $this->assertEqual('mod-quiz-attempt', $this->testpage->pagetype); + } + + public function test_set_url_does_not_change_explicit_page_type() { + // Setup fixture + $this->testpage->set_pagetype('a-page-type'); + // Exercise SUT + $this->testpage->set_url('mod/quiz/attempt.php', array('attempt' => 123, 'page' => 7)); + // Validate + $this->assertEqual('a-page-type', $this->testpage->pagetype); + } } /** diff --git a/lib/weblib.php b/lib/weblib.php index 6050e07..571bc2d 100644 --- a/lib/weblib.php +++ b/lib/weblib.php @@ -241,21 +241,38 @@ class moodle_url { /** * Pass no arguments to create a url that refers to this page. Use empty string to create empty url. * - * @param string $url url default null means use this page url with no query string - * empty string means empty url. If you pass any other type of url it will - * be parsed into it's bits, including query string + * @param mixed $url a number of different forms are accespted: + * null - create a URL that is the same as the URL used to load this page, but with no query string + * '' - and empty URL + * string - a URL, will be parsed into it's bits, including query string + * array - as returned from the PHP function parse_url + * moodle_url - make a copy of another moodle_url * @param array $params these params override anything in the query string * where params have the same name. */ public function __construct($url = null, $params = array()) { - global $ME; - if ($url !== '') { + if ($url === '') { + // Leave URL blank. + } else if (is_a($url, 'moodle_url')) { + $this->scheme = $url->scheme; + $this->host = $url->host; + $this->port = $url->port; + $this->user = $url->user; + $this->pass = $url->pass; + $this->path = $url->pass; + $this->fragment = $url->fragment; + $this->params = $url->params; + } else { if ($url === null) { + global $ME; $url = $ME; } - $parts = parse_url($url); + if (is_string($url)) { + $url = parse_url($url); + } + $parts = $url; if ($parts === FALSE) { - print_error('invalidurl'); + throw new moodle_exception('invalidurl'); } if (isset($parts['query'])) { parse_str(str_replace('&', '&', $parts['query']), $this->params); @@ -264,8 +281,8 @@ class moodle_url { foreach ($parts as $key => $value) { $this->$key = $value; } - $this->params($params); } + $this->params($params); } /** @@ -284,21 +301,25 @@ class moodle_url { } /** - * Remove all params if no arguments passed. Or else remove param $arg1, $arg2, etc. + * Remove all params if no arguments passed. Remove selected params if + * arguments are passed. Can be called as either remove_params('param1', 'param2') + * or remove_params(array('param1', 'param2')). * - * @param string $arg1 - * @param string $arg2 - * @param string $arg3 + * @param mixed $params either an array of param names, or a string param name, + * @param string $params,... any number of additional param names. */ - public function remove_params() { - if ($thisargs = func_get_args()) { - foreach ($thisargs as $arg) { - if (isset($this->params[$arg])) { - unset($this->params[$arg]); - } - } - } else { // no args + public function remove_params($params) { + if (empty($params)) { $this->params = array(); + return; + } + if (!is_array($params)) { + $params = func_get_args(); + } + foreach ($params as $param) { + if (isset($this->params[$param])) { + unset($this->params[$param]); + } } } -- 1.5.6.3 From 20a5573ae3e402b4c9502420bc198b5cada06695 Mon Sep 17 00:00:00 2001 From: Tim Hunt Date: Wed, 22 Apr 2009 16:16:46 +0800 Subject: moodle_page: MDL-12212 Eliminate legacy blocks_ methods moving blocks will now be broken until the new bockslib is done --- admin/pagelib.php | 17 --------- blog/blogpage.php | 42 ---------------------- lib/pagelib.php | 92 +++++++++++++++++------------------------------ mod/lesson/pagelib.php | 17 --------- my/pagelib.php | 17 --------- tag/pagelib.php | 17 --------- 6 files changed, 33 insertions(+), 169 deletions(-) diff --git a/admin/pagelib.php b/admin/pagelib.php index 4b99ab8..2a7ad1c 100644 --- a/admin/pagelib.php +++ b/admin/pagelib.php @@ -104,23 +104,6 @@ class page_admin extends page_base { return array_merge($this->extraurlparams, array('section' => $this->section)); } - function blocks_get_positions() { - return array(BLOCK_POS_LEFT, BLOCK_POS_RIGHT); - } - - function blocks_default_position() { - return BLOCK_POS_LEFT; - } - - function blocks_move_position(&$instance, $move) { - if($instance->position == BLOCK_POS_LEFT && $move == BLOCK_MOVE_RIGHT) { - return BLOCK_POS_RIGHT; - } else if ($instance->position == BLOCK_POS_RIGHT && $move == BLOCK_MOVE_LEFT) { - return BLOCK_POS_LEFT; - } - return $instance->position; - } - function print_header($section = '', $focus='') { global $USER, $CFG, $SITE; diff --git a/blog/blogpage.php b/blog/blogpage.php index 67c0111..aa00ba2 100644 --- a/blog/blogpage.php +++ b/blog/blogpage.php @@ -110,48 +110,6 @@ class page_blog extends page_base { return $array; } - - // Having defined all identifiers we need, here we declare which block positions we are - // going to support. - function blocks_get_positions() { - return array(BLOCK_POS_LEFT, BLOCK_POS_RIGHT); - } - - // When a new block is created in this page, which position should it go to? - function blocks_default_position() { - return BLOCK_POS_RIGHT; - } - - // When we are creating a new page, use the data at your disposal to provide a textual representation of the - // blocks that are going to get added to this new page. Delimit block names with commas (,) and use double - // colons (:) to delimit between block positions in the page. See blocks_get_positions() for additional info. - function blocks_get_default() { - global $CFG; - - $this->init_full(); - - // It's a normal blog page - if (!empty($CFG->{'defaultblocks_'. $this->pagetype})) { - $blocknames = $CFG->{'defaultblocks_'. $this->pagetype}; - } else { - /// Failsafe - in case nothing was defined. - $blocknames = 'admin,calendar_month,online_users,blog_menu'; - } - - return $blocknames; - } - - // And finally, a little block move logic. Given a block's previous position and where - // we want to move it to, return its new position. Pretty self-documenting. - function blocks_move_position(&$instance, $move) { - if ($instance->position == BLOCK_POS_LEFT && $move == BLOCK_MOVE_RIGHT) { - return BLOCK_POS_RIGHT; - } else if ($instance->position == BLOCK_POS_RIGHT && $move == BLOCK_MOVE_LEFT) { - return BLOCK_POS_LEFT; - } - return $instance->position; - } - /////////// Blog page specific functions function get_extra_header_string() { global $SESSION, $CFG, $USER; diff --git a/lib/pagelib.php b/lib/pagelib.php index 95af986..dcf6a9c 100644 --- a/lib/pagelib.php +++ b/lib/pagelib.php @@ -539,6 +539,38 @@ class moodle_page { debugging('Call to deprecated method moodle_page::get_legacyclass.'); return $this->_legacyclass; } + + /** + * @deprecated since Moodle 2.0 + * @return string the places on this page where blocks can go. + */ + function blocks_get_positions() { + debugging('Call to deprecated method moodle_page::blocks_get_positions. Use $PAGE->blocks->get_positions() instead.'); + return $PAGE->blocks->get_positions(); + } + + /** + * @deprecated since Moodle 2.0 + * @return string the default place for blocks on this page. + */ + function blocks_default_position() { + debugging('Call to deprecated method moodle_page::blocks_default_position. Use $PAGE->blocks->get_default_position() instead.'); + return $PAGE->blocks->get_default_position(); + } + + /** + * @deprecated since Moodle 2.0 - no longer used. + */ + function blocks_get_default() { + debugging('Call to deprecated method moodle_page::blocks_get_default. This method has no function any more.'); + } + + /** + * @deprecated since Moodle 2.0 - no longer used. + */ + function blocks_move_position(&$instance, $move) { + debugging('Call to deprecated method moodle_page::blocks_move_position. This method has no function any more.'); + } } /** @@ -675,32 +707,6 @@ class page_base extends moodle_page { return; } - // BLOCKS RELATED SECTION - - // By default, pages don't have any blocks. Override this in your derived class if you need blocks. - function blocks_get_positions() { - return array(); - } - - // Thus there is no default block position. If you override the above you should override this one too. - // Because this makes sense only if blocks_get_positions() is overridden and because these two should - // be overridden as a group or not at all, this one issues a warning. The sneaky part is that this warning - // will only be seen if you override blocks_get_positions() but NOT blocks_default_position(). - function blocks_default_position() { - trigger_error('Page class does not implement method blocks_default_position()', E_USER_WARNING); - return NULL; - } - - // If you don't override this, newly constructed pages of this kind won't have any blocks. - function blocks_get_default() { - return ''; - } - - // If you don't override this, your blocks will not be able to change positions - function blocks_move_position(&$instance, $move) { - return $instance->position; - } - // SELF-REPORTING SECTION // Derived classes HAVE to define their "home url" @@ -926,26 +932,10 @@ class page_course extends page_base { } } - // BLOCKS RELATED SECTION - - // Which are the positions in this page which support blocks? Return an array containing their identifiers. - // BE CAREFUL, ORDER DOES MATTER! In textual representations, lists of blocks in a page use the ':' character - // to delimit different positions in the page. The part before the first ':' in such a representation will map - // directly to the first item of the array you return here, the second to the next one and so on. This way, - // you can add more positions in the future without interfering with legacy textual representations. - function blocks_get_positions() { - return array(BLOCK_POS_LEFT, BLOCK_POS_RIGHT); - } - - // When a new block is created in this page, which position should it go to? - function blocks_default_position() { - return BLOCK_POS_RIGHT; - } - // When we are creating a new page, use the data at your disposal to provide a textual representation of the // blocks that are going to get added to this new page. Delimit block names with commas (,) and use double // colons (:) to delimit between block positions in the page. See blocks_get_positions() for additional info. - function blocks_get_default() { + function _legacy_blocks_get_default() { global $CFG; $this->init_full(); @@ -986,22 +976,6 @@ class page_course extends page_base { return $blocknames; } - - // Given an instance of a block in this page and the direction in which we want to move it, where is - // it going to go? Return the identifier of the instance's new position. This allows us to tell blocklib - // how we want the blocks to move around in this page in an arbitrarily complex way. If the move as given - // does not make sense, make sure to return the instance's original position. - // - // Since this is going to get called a LOT, pass the instance by reference purely for speed. Do **NOT** - // modify its data in any way, this will actually confuse blocklib!!! - function blocks_move_position(&$instance, $move) { - if($instance->position == BLOCK_POS_LEFT && $move == BLOCK_MOVE_RIGHT) { - return BLOCK_POS_RIGHT; - } else if ($instance->position == BLOCK_POS_RIGHT && $move == BLOCK_MOVE_LEFT) { - return BLOCK_POS_LEFT; - } - return $instance->position; - } } /** diff --git a/mod/lesson/pagelib.php b/mod/lesson/pagelib.php index afd5ad0..388ee61 100644 --- a/mod/lesson/pagelib.php +++ b/mod/lesson/pagelib.php @@ -140,23 +140,6 @@ class page_lesson extends page_generic_activity { lesson_print_messages(); } - function blocks_get_positions() { - return array(BLOCK_POS_LEFT, BLOCK_POS_RIGHT); - } - - function blocks_default_position() { - return BLOCK_POS_RIGHT; - } - - function blocks_move_position(&$instance, $move) { - if($instance->position == BLOCK_POS_LEFT && $move == BLOCK_MOVE_RIGHT) { - return BLOCK_POS_RIGHT; - } else if ($instance->position == BLOCK_POS_RIGHT && $move == BLOCK_MOVE_LEFT) { - return BLOCK_POS_LEFT; - } - return $instance->position; - } - /** * Needed to add the ID of the current lesson page * diff --git a/my/pagelib.php b/my/pagelib.php index d6e2b9f..d7db483 100644 --- a/my/pagelib.php +++ b/my/pagelib.php @@ -71,23 +71,6 @@ class page_my_moodle extends page_base { return array(); } } - - function blocks_default_position() { - return BLOCK_POS_LEFT; - } - - function blocks_get_positions() { - return array(BLOCK_POS_LEFT, BLOCK_POS_RIGHT); - } - - function blocks_move_position(&$instance, $move) { - if($instance->position == BLOCK_POS_LEFT && $move == BLOCK_MOVE_RIGHT) { - return BLOCK_POS_RIGHT; - } else if ($instance->position == BLOCK_POS_RIGHT && $move == BLOCK_MOVE_LEFT) { - return BLOCK_POS_LEFT; - } - return $instance->position; - } } diff --git a/tag/pagelib.php b/tag/pagelib.php index 27a1306..9eb8ea9 100644 --- a/tag/pagelib.php +++ b/tag/pagelib.php @@ -33,23 +33,6 @@ class page_tag extends page_base { $param['id'] = $this->id; return $param; } - - function blocks_default_position() { - return BLOCK_POS_LEFT; - } - - function blocks_get_positions() { - return array(BLOCK_POS_LEFT, BLOCK_POS_RIGHT); - } - - function blocks_move_position(&$instance, $move) { - if($instance->position == BLOCK_POS_LEFT && $move == BLOCK_MOVE_RIGHT) { - return BLOCK_POS_RIGHT; - } else if ($instance->position == BLOCK_POS_RIGHT && $move == BLOCK_MOVE_LEFT) { - return BLOCK_POS_LEFT; - } - return $instance->position; - } //----------- printing funtions ----------- -- 1.5.6.3 From 3da8340bb79d9f96e3180f00a8c76f737aa9e77e Mon Sep 17 00:00:00 2001 From: Tim Hunt Date: Wed, 22 Apr 2009 19:10:16 +0800 Subject: moodle_page: MDL-12212 Kill legacy url_... and blocks_... methods Start calling $PAGE->set_url in all the places it will be necessary Start of a stub implementation of $PAGE->blocks to stop other things breaking Remove some of the special case methods in admin_page --- admin/pagelib.php | 82 ++----------- admin/search.php | 3 +- admin/settings.php | 3 +- blocks/moodleblock.class.php | 2 +- blocks/rss_client/block_rss_client.php | 4 +- blocks/rss_client/config_instance.html | 4 +- blocks/rss_client/config_instance_tabs.php | 4 +- blog/blogpage.php | 34 +------ blog/header.php | 15 +++- course/view.php | 3 +- index.php | 4 +- lib/adminlib.php | 13 ++- lib/blocklib.php | 18 ++-- lib/pagelib.php | 168 +++++++++++----------------- lib/simpletest/testpagelib_moodlepage.php | 2 +- lib/weblib.php | 2 +- mod/chat/view.php | 3 +- mod/data/view.php | 3 +- mod/lesson/action/continue.php | 1 + mod/lesson/pagelib.php | 10 -- mod/lesson/view.php | 1 + mod/quiz/view.php | 3 +- mod/resource/lib.php | 1 + mod/survey/view.php | 1 - my/index.php | 3 +- my/pagelib.php | 18 --- tag/index.php | 1 + tag/pagelib.php | 13 -- 28 files changed, 144 insertions(+), 275 deletions(-) diff --git a/admin/pagelib.php b/admin/pagelib.php index 2a7ad1c..374b1aa 100644 --- a/admin/pagelib.php +++ b/admin/pagelib.php @@ -19,35 +19,9 @@ define('BLOCK_R_MAX_WIDTH', $rmax); page_map_class(PAGE_ADMIN, 'page_admin'); class page_admin extends page_base { - - var $section = ''; - var $visiblepathtosection; - var $extraurlparams = array(); var $extrabutton = ''; - var $url = ''; - - // hack alert! - // this function works around the inability to store the section name - // in default block, maybe we should "improve" the blocks a bit? - function init_extra($section) { - global $CFG; - - if($this->full_init_done) { - return; - } - $adminroot = admin_get_root(false, false); //settings not required - only pages - - // fetch the path parameter - $this->section = $section; - $current = $adminroot->locate($section, true); - $this->visiblepathtosection = array_reverse($current->visiblepath); - - // all done - $this->full_init_done = true; - } - - function blocks_get_default() { + function _legacy_blocks_get_default() { return 'admin_tree,admin_bookmarks'; } @@ -63,22 +37,6 @@ class page_admin extends page_base { return $USER->adminediting; } - function url_get_path() { - global $CFG; - if (!empty($this->url)) { - return $this->url; - } - - $adminroot = admin_get_root(false, false); //settings not required - only pages - - $root = $adminroot->locate($this->section); - if ($root instanceof admin_externalpage) { - return $root->url; - } else { - return ($CFG->wwwroot . '/' . $CFG->admin . '/settings.php'); - } - } - /** * Use this to pass extra HTML that is added after the turn blocks editing on/off button. * @@ -88,31 +46,19 @@ class page_admin extends page_base { $this->extrabutton = $extrabutton; } - /** - * Use this to pass extra URL parameters that, for example, the blocks editing controls need to reload the current page accurately. - * - * @param array $extraurlparams paramname => value array. - */ - function set_extra_url_params($extraurlparams, $actualurl = '') { - $this->extraurlparams = $extraurlparams; - if (!empty($actualurl)) { - $this->url = $actualurl; - } - } - - function url_get_parameters() { // only handles parameters relevant to the admin pagetype - return array_merge($this->extraurlparams, array('section' => $this->section)); - } - - function print_header($section = '', $focus='') { + function print_header($focus='') { global $USER, $CFG, $SITE; - $this->init_full($section); // we're trusting that init_full() has already been called by now; it should have. - // if not, print_header() has to be called with a $section parameter + $adminroot = admin_get_root(false, false); //settings not required - only pages + + // fetch the path parameter + $section = $this->url->param('section'); + $current = $adminroot->locate($section, true); + $visiblepathtosection = array_reverse($current->visiblepath); // The search page currently doesn't handle block editing - if ($this->section != 'search' and $this->user_allowed_editing()) { - $options = $this->url_get_parameters(); + if ($this->user_allowed_editing()) { + $options = $this->url->params(); if ($this->user_is_editing()) { $caption = get_string('blockseditoff'); $options['adminedit'] = 'off'; @@ -120,19 +66,17 @@ class page_admin extends page_base { $caption = get_string('blocksediton'); $options['adminedit'] = 'on'; } - $buttons = print_single_button($this->url_get_path(), $options, $caption, 'get', '', true); - } else { - $buttons = ' '; + $buttons = print_single_button($this->url->out(false), $options, $caption, 'get', '', true); } $buttons .= $this->extrabutton; $navlinks = array(); - foreach ($this->visiblepathtosection as $element) { + foreach ($visiblepathtosection as $element) { $navlinks[] = array('name' => $element, 'link' => null, 'type' => 'misc'); } $navigation = build_navigation($navlinks); - print_header("$SITE->shortname: " . implode(": ",$this->visiblepathtosection), $SITE->fullname, $navigation, $focus, '', true, $buttons, ''); + print_header("$SITE->shortname: " . implode(": ",$visiblepathtosection), $SITE->fullname, $navigation, $focus, '', true, $buttons, ''); } } diff --git a/admin/search.php b/admin/search.php index 2d13ba5..a1de51b 100644 --- a/admin/search.php +++ b/admin/search.php @@ -7,13 +7,14 @@ require_once($CFG->libdir.'/adminlib.php'); $query = trim(optional_param('query', '', PARAM_NOTAGS)); // Search string +$PAGE->set_context(get_context_instance(CONTEXT_SYSTEM)); $adminroot = admin_get_root(); // need all settings here $adminroot->search = $query; // So we can reference it in search boxes later in this invocation $statusmsg = ''; $errormsg = ''; $focus = ''; -admin_externalpage_setup('search'); // now hidden page +admin_externalpage_setup('search', '', array('query' => $query)); // now hidden page // now we'll deal with the case that the admin has submitted the form with changed settings if ($data = data_submitted() and confirm_sesskey()) { diff --git a/admin/settings.php b/admin/settings.php index ae1aefd..4be5405 100644 --- a/admin/settings.php +++ b/admin/settings.php @@ -12,6 +12,7 @@ $adminediting = optional_param('adminedit', -1, PARAM_BOOL); /// no guest autologin require_login(0, false); $PAGE->set_context(get_context_instance(CONTEXT_SYSTEM)); +$PAGE->set_url($CFG->admin . '/settings.php', array('section' => $section)); $adminroot = admin_get_root(); // need all settings $page = $adminroot->locate($section); @@ -106,7 +107,7 @@ if (empty($SITE->fullname)) { $preferred_width_right = bounded_number(BLOCK_R_MIN_WIDTH, blocks_preferred_width($pageblocks[BLOCK_POS_RIGHT]), BLOCK_R_MAX_WIDTH); - $PAGE->print_header('', $focus); + $PAGE->print_header($focus); echo ''; $lt = (empty($THEME->layouttable)) ? array('left', 'middle', 'right') : $THEME->layouttable; diff --git a/blocks/moodleblock.class.php b/blocks/moodleblock.class.php index c6bb802..e4471ff 100644 --- a/blocks/moodleblock.class.php +++ b/blocks/moodleblock.class.php @@ -462,7 +462,7 @@ class block_base { } else { $page = page_create_object($this->instance->pagetype, $this->instance->pageid); } - $script = $page->url_get_full(array('instanceid' => $this->instance->id, 'sesskey' => sesskey())); + $script = $page->url->out(array('instanceid' => $this->instance->id, 'sesskey' => sesskey())); if (empty($this->instance->pinned)) { $movebuttons .= '' . diff --git a/blocks/rss_client/block_rss_client.php b/blocks/rss_client/block_rss_client.php index 4fc064c..dcceaf4 100644 --- a/blocks/rss_client/block_rss_client.php +++ b/blocks/rss_client/block_rss_client.php @@ -109,7 +109,7 @@ //if ($page->user_allowed_editing()) { // for SUBMITTERS_ALL_ACCOUNT_HOLDERS we're going to run into trouble later if we show it and then they don't have write access to the page. if (isset($this->config)) { // This instance is configured - show Add/Edit feeds link. - $script = $page->url_get_full( + $script = $page->url->out( array('instanceid' => $this->instance->id, 'sesskey' => sesskey(), 'blockaction' => 'config', @@ -121,7 +121,7 @@ } else { // This instance has not been configured yet - show configure link? if (has_capability('block/rss_client:manageanyfeeds', $context)) { - $script = $page->url_get_full( + $script = $page->url->out( array('instanceid' => $this->instance->id, 'sesskey' => sesskey(), 'blockaction' => 'config', diff --git a/blocks/rss_client/config_instance.html b/blocks/rss_client/config_instance.html index 9abb4d3..83f6d76 100644 --- a/blocks/rss_client/config_instance.html +++ b/blocks/rss_client/config_instance.html @@ -103,9 +103,9 @@ print_box_start(); if (has_capability('block/rss_client:createprivatefeeds', $context) || has_capability('block/rss_client:createsharedfeeds', $context)) { - $addrsspage = $page->url_get_full(array('instanceid' => $this->instance->id, + $addrsspage = $page->url->out(array('instanceid' => $this->instance->id, 'sesskey' => sesskey(), - 'blockaction' => 'config', + 'blockaction' => 'config', 'currentaction' => 'managefeeds', 'id' => $id)); print ' '. get_string('editnewsfeeds', 'block_rss_client') .'
'; diff --git a/blocks/rss_client/config_instance_tabs.php b/blocks/rss_client/config_instance_tabs.php index 24a6447..e8541e0 100644 --- a/blocks/rss_client/config_instance_tabs.php +++ b/blocks/rss_client/config_instance_tabs.php @@ -13,12 +13,12 @@ if (empty($this->instance->pinned)) { } if (has_capability('moodle/site:manageblocks', $context)) { - $script = $page->url_get_full(array('instanceid' => $this->instance->id, 'sesskey' => sesskey(), 'blockaction' => 'config', 'currentaction' => 'configblock', 'id' => $id, 'section' => 'rss')); + $script = $page->url->out(array('instanceid' => $this->instance->id, 'sesskey' => sesskey(), 'blockaction' => 'config', 'currentaction' => 'configblock', 'id' => $id, 'section' => 'rss')); $row[] = new tabobject('configblock', $script, get_string('configblock', 'block_rss_client')); } -$script = $page->url_get_full(array('instanceid' => $this->instance->id, 'sesskey' => sesskey(), 'blockaction' => 'config', 'currentaction' => 'managefeeds', 'id' => $id, 'section' => 'rss')); +$script = $page->url->out(array('instanceid' => $this->instance->id, 'sesskey' => sesskey(), 'blockaction' => 'config', 'currentaction' => 'managefeeds', 'id' => $id, 'section' => 'rss')); $row[] = new tabobject('managefeeds', $script, get_string('managefeeds', 'block_rss_client')); diff --git a/blog/blogpage.php b/blog/blogpage.php index aa00ba2..2f3e952 100644 --- a/blog/blogpage.php +++ b/blog/blogpage.php @@ -80,36 +80,6 @@ class page_blog extends page_base { print_header($pageTitle, $pageHeading, $pageNavigation, $pageFocus, $pageMeta, true, $extraheader ); } - // This should point to the script that displays us - function url_get_path() { - global $CFG; - - return $CFG->wwwroot .'/blog/index.php'; - } - - function url_get_parameters() { - - $array = array(); - if (!$this->full_init_done) { - $array['userid'] = $this->id; - return $array; - } - - if (!empty($this->course->id)) { - $array['courseid'] = $this->course->id; - } - if (!empty($this->filtertype)) { - $array['filtertype'] = $this->filtertype; - } - if (!empty($this->filterselect)) { - $array['filterselect'] = $this->filterselect; - } - if (!empty($this->tagid)) { - $array['tagid'] = $this->tagid; - } - return $array; - } - /////////// Blog page specific functions function get_extra_header_string() { global $SESSION, $CFG, $USER; @@ -122,14 +92,14 @@ class page_blog extends page_base { $editingString = get_string('turneditingon'); } - $params = $this->url_get_parameters(); + $params = $this->url->params(); $params['edit'] = empty($SESSION->blog_editing_enabled) ? 1 : 0; $paramstring = ''; foreach ($params as $key=>$val) { $paramstring .= ''; } - $editformstring = 'frametarget.' method="get" action="'.$this->url_get_path().'">
' + $editformstring = 'frametarget.' method="get" action="'.$this->url->out(false).'">
' .$paramstring.'
'; } diff --git a/blog/header.php b/blog/header.php index e6474bf..05d5d56 100755 --- a/blog/header.php +++ b/blog/header.php @@ -50,7 +50,20 @@ $PAGE->set_course($course); $PAGE->filtertype = $filtertype; $PAGE->filterselect = $filterselect; $PAGE->tagid = $tagid; - +$array = array(); +if (!empty($course->id)) { + $array['courseid'] = $course->id; +} +if (!empty($filtertype)) { + $array['filtertype'] = $filtertype; +} +if (!empty($filterselect)) { + $array['filterselect'] = $filterselect; +} +if (!empty($tagid)) { + $array['tagid'] = $tagid; +} +$PAGE->set_url('blog/index.php', $array); $PAGE->init_full(); //init the BlogInfo object and the courserecord object $editing = false; diff --git a/course/view.php b/course/view.php index da352c3..332fb5f 100644 --- a/course/view.php +++ b/course/view.php @@ -19,8 +19,6 @@ $marker = optional_param('marker',-1 , PARAM_INT); $switchrole = optional_param('switchrole',-1, PARAM_INT); - - if (empty($id) && empty($name) && empty($idnumber)) { print_error('unspecifycourseid', 'error'); } @@ -94,6 +92,7 @@ } $PAGE = page_create_object(PAGE_COURSE_VIEW, $course->id); + $PAGE->set_url('course/view.php', array('id' => $course->id)); $pageblocks = blocks_setup($PAGE, BLOCKS_PINNED_BOTH); if ($reset_user_allowed_editing) { diff --git a/index.php b/index.php index a0f3548..c4c5a26 100644 --- a/index.php +++ b/index.php @@ -88,9 +88,11 @@ } $PAGE = page_create_object(PAGE_COURSE_VIEW, SITEID); + $PAGE->set_pagetype('site-index'); + $PAGE->set_url(''); $PAGE->set_docs_path(''); $pageblocks = blocks_setup($PAGE); - $editing = $PAGE->user_is_editing(); + $editing = $PAGE->user_is_editing(); $preferred_width_left = bounded_number(BLOCK_L_MIN_WIDTH, blocks_preferred_width($pageblocks[BLOCK_POS_LEFT]), BLOCK_L_MAX_WIDTH); $preferred_width_right = bounded_number(BLOCK_R_MIN_WIDTH, blocks_preferred_width($pageblocks[BLOCK_POS_RIGHT]), diff --git a/lib/adminlib.php b/lib/adminlib.php index 0bcab79..1cf65a5 100644 --- a/lib/adminlib.php +++ b/lib/adminlib.php @@ -3883,7 +3883,8 @@ class admin_setting_manageportfolio extends admin_setting { * @param string $actualurl if the actual page being viewed is not the normal one for this * page (e.g. admin/roles/allowassin.php, instead of admin/roles/manage.php, you can pass the alternate URL here. */ -function admin_externalpage_setup($section, $extrabutton='', $extraurlparams=array(), $actualurl='') { +function admin_externalpage_setup($section, $extrabutton = '', + $extraurlparams = array(), $actualurl = '') { global $CFG, $PAGE, $USER; require_once($CFG->libdir.'/blocklib.php'); @@ -3899,13 +3900,17 @@ function admin_externalpage_setup($section, $extrabutton='', $extraurlparams=arr page_map_class(PAGE_ADMIN, 'page_admin'); $PAGE = page_create_object(PAGE_ADMIN, 0); // there must be any constant id number $PAGE->set_context(get_context_instance(CONTEXT_SYSTEM)); - $PAGE->init_extra($section); // hack alert! $PAGE->set_extra_button($extrabutton); - $PAGE->set_extra_url_params($extraurlparams, $actualurl); $adminroot = admin_get_root(false, false); // settings not required for external pages $extpage = $adminroot->locate($section); + if (!$actualurl) { + $actualurl = $extpage->url; + } + $PAGE->set_url(str_replace($CFG->wwwroot . '/', '', $actualurl), + array_merge($extraurlparams, array('section' => $section))); + if (empty($extpage) or !($extpage instanceof admin_externalpage)) { print_error('sectionerror', 'admin', "$CFG->wwwroot/$CFG->admin/"); die; @@ -3956,7 +3961,7 @@ function admin_externalpage_print_header($focus='') { blocks_preferred_width($pageblocks[BLOCK_POS_RIGHT]), BLOCK_R_MAX_WIDTH); - $PAGE->print_header('', $focus); + $PAGE->print_header($focus); echo '
'; $lt = (empty($THEME->layouttable)) ? array('left', 'middle', 'right') : $THEME->layouttable; diff --git a/lib/blocklib.php b/lib/blocklib.php index 51bc230..2f86420 100644 --- a/lib/blocklib.php +++ b/lib/blocklib.php @@ -330,7 +330,7 @@ function blocks_print_group(&$page, &$pageblocks, $position) { $managecourseblocks = has_capability('moodle/site:manageblocks', $coursecontext); $editmymoodle = $page->pagetype == PAGE_MY_MOODLE && has_capability('moodle/my:manageblocks', $coursecontext); - if ($page->blocks_default_position() == $position && + if ($page->blocks->get_default_position() == $position && $page->user_is_editing() && ($managecourseblocks || $editmymoodle || $myownblogpage || defined('ADMIN_STICKYBLOCKS'))) { @@ -473,7 +473,7 @@ function blocks_execute_action($page, &$pageblocks, $blockaction, $instanceorid, ); // To this data, add anything the page itself needs to display - $hiddendata = array_merge($hiddendata, $page->url_get_parameters()); + $hiddendata = $page->url->params($hiddendata); if ($data = data_submitted()) { $remove = array_keys($hiddendata); @@ -493,7 +493,7 @@ function blocks_execute_action($page, &$pageblocks, $blockaction, $instanceorid, echo '
'; /// Make CSS easier print_heading($strheading); - echo '
'; + echo ''; echo '

'; foreach($hiddendata as $name => $val) { echo ''; @@ -640,7 +640,7 @@ function blocks_execute_action($page, &$pageblocks, $blockaction, $instanceorid, break; } - $newpos = $page->blocks_default_position(); + $newpos = $page->blocks->get_default_position(); if (!empty($pinned)) { $sql = "SELECT 1, MAX(weight) + 1 AS nextfree FROM {block_pinned} @@ -682,7 +682,7 @@ function blocks_execute_action($page, &$pageblocks, $blockaction, $instanceorid, if ($redirect) { // In order to prevent accidental duplicate actions, redirect to a page with a clean url - redirect($page->url_get_full()); + redirect($page->url->out()); } } @@ -843,7 +843,7 @@ function blocks_get_pinned($page) { $blocks = $DB->get_records_select('block_pinned', $select, $params, 'position, weight'); - $positions = $page->blocks_get_positions(); + $positions = $page->blocks->get_positions(); $arr = array(); foreach($positions as $key => $position) { @@ -905,7 +905,7 @@ function blocks_get_by_page($page) { $blocks = $DB->get_records_select('block_instance', "pageid = ? AND ? LIKE (" . $DB->sql_concat('pagetype', "'%'") . ")", array($page->get_id(), $page->pagetype), 'position, weight'); - $positions = $page->blocks_get_positions(); + $positions = $page->blocks->get_positions(); $arr = array(); foreach($positions as $key => $position) { $arr[$position] = array(); @@ -946,7 +946,7 @@ function blocks_print_adminblock(&$page, &$pageblocks) { } asort($menu); - $target = $page->url_get_full(array('sesskey' => sesskey(), 'blockaction' => 'add')); + $target = $page->url->out(array('sesskey' => sesskey(), 'blockaction' => 'add')); $content = popup_form($target.'&blockid=', $menu, 'add_block', '', $stradd .'...', '', '', true); print_side_block($strblocks, $content, NULL, NULL, NULL, array('class' => 'block_adminblock')); } @@ -994,7 +994,7 @@ function blocks_repopulate_page($page) { $blocknames = $page->blocks_get_default(); } - $positions = $page->blocks_get_positions(); + $positions = $page->blocks->get_positions(); $posblocks = explode(':', $blocknames); // Now one array holds the names of the positions, and the other one holds the blocks diff --git a/lib/pagelib.php b/lib/pagelib.php index dcf6a9c..e23e524 100644 --- a/lib/pagelib.php +++ b/lib/pagelib.php @@ -77,6 +77,8 @@ class moodle_page { protected $_url = null; + protected $_blocks = null; + /// Getter methods ============================================================= /// Due to the __get magic below, you normally do not call these as $PAGE->get_x /// methods, but instead use the $PAGE->x syntax. @@ -184,7 +186,17 @@ class moodle_page { debugging('This page did no call $PAGE->set_url(...). Realying on a guess.', DEBUG_DEVELOPER); return new moodle_url($ME); } - return $this->_url; + return new moodle_url($this->_url); // Return a clone for safety. + } + + /** + * @return blocks_manager the blocks manager object for this page. + */ + public function get_blocks() { + if (is_null($this->_blocks)) { + $this->_blocks = new blocks_manager(); + } + return $this->_blocks; } /** @@ -362,7 +374,7 @@ class moodle_page { * If legacy code has set $CFG->pagepath that will be used instead, and a * developer warning issued. */ - protected function initialise_default_pagetype($script = '') { + protected function initialise_default_pagetype($script = null) { global $CFG, $SCRIPT; if (isset($CFG->pagepath)) { @@ -372,7 +384,7 @@ class moodle_page { unset($CFG->pagepath); } - if (empty($script)) { + if (is_null($script)) { $script = ltrim($SCRIPT, '/'); $len = strlen($CFG->admin); if (substr($script, 0, $len) == $CFG->admin) { @@ -541,21 +553,21 @@ class moodle_page { } /** - * @deprecated since Moodle 2.0 + * @deprecated since Moodle 2.0 - use $PAGE->blocks->get_positions() instead * @return string the places on this page where blocks can go. */ function blocks_get_positions() { debugging('Call to deprecated method moodle_page::blocks_get_positions. Use $PAGE->blocks->get_positions() instead.'); - return $PAGE->blocks->get_positions(); + return $this->blocks->get_positions(); } /** - * @deprecated since Moodle 2.0 + * @deprecated since Moodle 2.0 - use $PAGE->blocks->get_default_position() instead * @return string the default place for blocks on this page. */ function blocks_default_position() { debugging('Call to deprecated method moodle_page::blocks_default_position. Use $PAGE->blocks->get_default_position() instead.'); - return $PAGE->blocks->get_default_position(); + return $this->blocks->get_default_position(); } /** @@ -571,6 +583,44 @@ class moodle_page { function blocks_move_position(&$instance, $move) { debugging('Call to deprecated method moodle_page::blocks_move_position. This method has no function any more.'); } + + /** + * @deprecated since Moodle 2.0 - use $this->url->params() instead. + * @return array URL parameters for this page. + */ + function url_get_parameters() { + debugging('Call to deprecated method moodle_page::url_get_parameters. Use $this->url->params() instead.'); + return $this->url->params(); + } + + /** + * @deprecated since Moodle 2.0 - use $this->url->params() instead. + * @return string URL for this page without parameters. + */ + function url_get_path() { + debugging('Call to deprecated method moodle_page::url_get_path. Use $this->url->out(false) instead.'); + return $this->url->out(false); + } + + /** + * @deprecated since Moodle 2.0 - use $this->url->out() instead. + * @return string full URL for this page. + */ + function url_get_full($extraparams = array()) { + debugging('Call to deprecated method moodle_page::url_get_full. Use $this->url->out() instead.'); + return $this->url->out($extraparams); + } +} + +/** Stub implementation of the blocks_manager, to stop things from breaking too badly. */ +class blocks_manager { + public function get_positions() { + return array(BLOCK_POS_LEFT, BLOCK_POS_RIGHT); + } + + public function get_default_position() { + return BLOCK_POS_RIGHT; + } } /** @@ -605,11 +655,15 @@ function page_create_object($type, $id = NULL) { $data->pageid = $id; $classname = page_map_class($type); - $object = new $classname; - $object->init_quick($data); + $legacypage = new $classname; + $legacypage->init_quick($data); + // $PAGE->set_pagetype($type); + // $PAGE->set_url(str_replace($CFG->wwwroot . '/', '', $legacypage->url_get_full_())); + // return $PAGE; + $course = $PAGE->course; if ($course->id != $SITE->id) { - $object->set_course($course); + $legacypage->set_course($course); } else { try { $category = $PAGE->category; @@ -618,13 +672,12 @@ function page_create_object($type, $id = NULL) { $category = false; } if ($category) { - $object->set_category_by_id($category->id); + $legacypage->set_category_by_id($category->id); } else { - $object->set_course($SITE); + $legacypage->set_course($SITE); } } - //$object->set_pagetype($type); - return $object; + return $legacypage; } /** @@ -709,45 +762,6 @@ class page_base extends moodle_page { // SELF-REPORTING SECTION - // Derived classes HAVE to define their "home url" - function url_get_path() { - trigger_error('Page class does not implement method url_get_path()', E_USER_WARNING); - return NULL; - } - - // It's not always required to pass any arguments to the home url, so this doesn't trigger any errors (sensible default) - function url_get_parameters() { - return array(); - } - - // This should actually NEVER be overridden unless you have GOOD reason. Works fine as it is. - function url_get_full($extraparams = array()) { - $path = $this->url_get_path(); - if(empty($path)) { - return NULL; - } - - $params = $this->url_get_parameters(); - if (!empty($params)) { - $params = array_merge($params, $extraparams); - } else { - $params = $extraparams; - } - - if(empty($params)) { - return $path; - } - - $first = true; - - foreach($params as $var => $value) { - $path .= $first? '?' : '&'; - $path .= $var .'='. urlencode($value); - $first = false; - } - - return $path; - } // Simple stuff, do not override this. function get_id() { @@ -904,37 +918,9 @@ class page_course extends page_base { // SELF-REPORTING SECTION - // This should return a fully qualified path to the URL which is responsible for displaying us. - function url_get_path() { - global $CFG; - if (defined('ADMIN_STICKYBLOCKS')) { - return $CFG->wwwroot.'/'.$CFG->admin.'/stickyblocks.php'; - } - if($this->id == SITEID) { - return $CFG->wwwroot .'/index.php'; - } - else { - return $CFG->wwwroot .'/course/view.php'; - } - } - - // This should return an associative array of any GET/POST parameters that are needed by the URL - // which displays us to make it work. If none are needed, return an empty array. - function url_get_parameters() { - if (defined('ADMIN_STICKYBLOCKS')) { - return array('pt' => ADMIN_STICKYBLOCKS); - } - if($this->id == SITEID) { - return array(); - } - else { - return array('id' => $this->id); - } - } - // When we are creating a new page, use the data at your disposal to provide a textual representation of the // blocks that are going to get added to this new page. Delimit block names with commas (,) and use double - // colons (:) to delimit between block positions in the page. See blocks_get_positions() for additional info. + // colons (:) to delimit between block positions in the page. function _legacy_blocks_get_default() { global $CFG; @@ -1020,24 +1006,6 @@ class page_generic_activity extends page_base { return isediting($this->modulerecord->course); } - function url_get_path() { - global $CFG; - return $CFG->wwwroot .'/mod/'.$this->activityname.'/view.php'; - } - - function url_get_parameters() { - $this->init_full(); - return array('id' => $this->modulerecord->id); - } - - function blocks_get_positions() { - return array(BLOCK_POS_LEFT); - } - - function blocks_default_position() { - return BLOCK_POS_LEFT; - } - function print_header($title, $morenavlinks = NULL, $bodytags = '', $meta = '') { global $USER, $CFG; diff --git a/lib/simpletest/testpagelib_moodlepage.php b/lib/simpletest/testpagelib_moodlepage.php index 2f4d1f8..7e2e300 100644 --- a/lib/simpletest/testpagelib_moodlepage.php +++ b/lib/simpletest/testpagelib_moodlepage.php @@ -38,7 +38,7 @@ if (!defined('MOODLE_INTERNAL')) { require_once($CFG->libdir . '/pagelib.php'); class testable_moodle_page extends moodle_page { - public function initialise_default_pagetype($script = '') { + public function initialise_default_pagetype($script = null) { parent::initialise_default_pagetype($script); } public function url_to_class_name($url) { diff --git a/lib/weblib.php b/lib/weblib.php index 571bc2d..fc74907 100644 --- a/lib/weblib.php +++ b/lib/weblib.php @@ -259,7 +259,7 @@ class moodle_url { $this->port = $url->port; $this->user = $url->user; $this->pass = $url->pass; - $this->path = $url->pass; + $this->path = $url->path; $this->fragment = $url->fragment; $this->params = $url->params; } else { diff --git a/mod/chat/view.php b/mod/chat/view.php index f94cf15..49f265d 100644 --- a/mod/chat/view.php +++ b/mod/chat/view.php @@ -63,7 +63,8 @@ // Initialize $PAGE, compute blocks - $PAGE = page_create_instance($chat->id); + $PAGE = page_create_instance($chat->id); + $PAGE->set_url('mod/chat/view.php', array('id' => $cm->id)); $pageblocks = blocks_setup($PAGE); $blocks_preferred_width = bounded_number(180, blocks_preferred_width($pageblocks[BLOCK_POS_LEFT]), 210); diff --git a/mod/data/view.php b/mod/data/view.php index ed15395..112a91c 100755 --- a/mod/data/view.php +++ b/mod/data/view.php @@ -256,7 +256,8 @@ // Initialize $PAGE, compute blocks - $PAGE = page_create_instance($data->id); + $PAGE = page_create_instance($data->id); + $PAGE->set_url('mod/data/view.php', array('id' => $cm->id)); $pageblocks = blocks_setup($PAGE); $blocks_preferred_width = bounded_number(180, blocks_preferred_width($pageblocks[BLOCK_POS_LEFT]), 210); diff --git a/mod/lesson/action/continue.php b/mod/lesson/action/continue.php index d9ae2a8..68fab67 100644 --- a/mod/lesson/action/continue.php +++ b/mod/lesson/action/continue.php @@ -791,6 +791,7 @@ } $PAGE = page_create_object('mod-lesson-view', $lesson->id); + $PAGE->set_url('mod/lesson/view.php', array('id' => $cm->id, 'pageid' => $page->id)); $PAGE->set_lessonpageid($page->id); $pageblocks = blocks_setup($PAGE); diff --git a/mod/lesson/pagelib.php b/mod/lesson/pagelib.php index 388ee61..b1975b6 100644 --- a/mod/lesson/pagelib.php +++ b/mod/lesson/pagelib.php @@ -141,16 +141,6 @@ class page_lesson extends page_generic_activity { } /** - * Needed to add the ID of the current lesson page - * - * @return array - **/ - function url_get_parameters() { - $this->init_full(); - return array('id' => $this->modulerecord->id, 'pageid' => $this->lessonpageid);; - } - - /** * Set the current lesson page ID * * @return void diff --git a/mod/lesson/view.php b/mod/lesson/view.php index 6db1be9..4303fa5 100644 --- a/mod/lesson/view.php +++ b/mod/lesson/view.php @@ -509,6 +509,7 @@ } $PAGE = page_create_instance($lesson->id); + $PAGE->set_url('mod/lesson/view.php', array('id' => $cm->id, 'pageid' => $page->id)); $PAGE->set_lessonpageid($page->id); $pageblocks = blocks_setup($PAGE); diff --git a/mod/quiz/view.php b/mod/quiz/view.php index bbdc884..f0223bc 100644 --- a/mod/quiz/view.php +++ b/mod/quiz/view.php @@ -57,7 +57,8 @@ add_to_log($course->id, "quiz", "view", "view.php?id=$cm->id", $quiz->id, $cm->id); /// Initialize $PAGE, compute blocks - $PAGE = page_create_instance($quiz->id); + $PAGE = page_create_instance($quiz->id); + $PAGE->set_url('mod/quiz/view.php', array('id' => $cm->id)); $pageblocks = blocks_setup($PAGE); $blocks_preferred_width = bounded_number(180, blocks_preferred_width($pageblocks[BLOCK_POS_LEFT]), 210); diff --git a/mod/resource/lib.php b/mod/resource/lib.php index f892283..a8ec4a9 100644 --- a/mod/resource/lib.php +++ b/mod/resource/lib.php @@ -89,6 +89,7 @@ class resource_base { require_once($CFG->dirroot.'/course/lib.php'); //required by some blocks $PAGE = page_create_object(PAGE_COURSE_VIEW, $this->course->id); + $PAGE->set_url('mod/resource/view.php', array('id' => $this->cm->id)); $this->PAGE = $PAGE; $pageblocks = blocks_setup($PAGE); diff --git a/mod/survey/view.php b/mod/survey/view.php index 84c38d1..5ad0be6 100644 --- a/mod/survey/view.php +++ b/mod/survey/view.php @@ -14,7 +14,6 @@ } require_login($course->id, false, $cm); - $context = get_context_instance(CONTEXT_MODULE, $cm->id); require_capability('mod/survey:participate', $context); diff --git a/my/index.php b/my/index.php index 0d6c8ee..76774b8 100644 --- a/my/index.php +++ b/my/index.php @@ -6,7 +6,7 @@ require_once($CFG->libdir.'/blocklib.php'); require_once($CFG->dirroot.'/course/lib.php'); require_once('pagelib.php'); - + require_login(); $mymoodlestr = get_string('mymoodle','my'); @@ -24,6 +24,7 @@ $blockaction = optional_param('blockaction', '', PARAM_ALPHA); $PAGE = page_create_instance($USER->id); + $PAGE->set_url('my/index.php'); $pageblocks = blocks_setup($PAGE,BLOCKS_PINNED_BOTH); diff --git a/my/pagelib.php b/my/pagelib.php index d7db483..1c43a18 100644 --- a/my/pagelib.php +++ b/my/pagelib.php @@ -54,26 +54,8 @@ class page_my_moodle extends page_base { print_header($title, $header,$navigation,'','',true, $button, $loggedinas.$langmenu); } - - function url_get_path() { - global $CFG; - if ($PAGE->pagetype == PAGE_MY_MOODLE) { - return $CFG->wwwroot.'/my/index.php'; - } elseif (defined('ADMIN_STICKYBLOCKS')){ - return $CFG->wwwroot.'/'.$CFG->admin.'/stickyblocks.php'; - } - } - - function url_get_parameters() { - if (defined('ADMIN_STICKYBLOCKS')) { - return array('pt' => ADMIN_STICKYBLOCKS); - } else { - return array(); - } - } } - define('PAGE_MY_MOODLE', 'my-index'); define('MY_MOODLE_FORMAT', 'my'); //doing this so we don't run into problems with applicable formats. diff --git a/tag/index.php b/tag/index.php index 04dbc26..d97fb54 100644 --- a/tag/index.php +++ b/tag/index.php @@ -34,6 +34,7 @@ if (empty($tag)) { //create a new page_tag object, defined in pagelib.php $PAGE = page_create_object(PAGE_TAG_INDEX, $tag->id); +$PAGE->set_url('tag/index.php', array('id' => $tag->id)); $pageblocks = blocks_setup($PAGE,BLOCKS_PINNED_BOTH); $PAGE->tag_object = $tag; diff --git a/tag/pagelib.php b/tag/pagelib.php index 9eb8ea9..658dc00 100644 --- a/tag/pagelib.php +++ b/tag/pagelib.php @@ -21,19 +21,6 @@ class page_tag extends page_base { return (!empty($USER->editing)); } - - function url_get_path() { - global $CFG; - return $CFG->wwwroot.'/tag/index.php'; - - } - - function url_get_parameters() { - $param = array(); - $param['id'] = $this->id; - return $param; - } - //----------- printing funtions ----------- function print_header() { -- 1.5.6.3 From ab198474a3ef3230c5bf4a20bc8916311df21ac2 Mon Sep 17 00:00:00 2001 From: Tim Hunt Date: Thu, 23 Apr 2009 12:56:01 +0800 Subject: moodle_page: MDL-12212 eliminate page::edit_always --- lib/blocklib.php | 9 +-------- lib/pagelib.php | 7 ------- 2 files changed, 1 insertions(+), 15 deletions(-) diff --git a/lib/blocklib.php b/lib/blocklib.php index 2f86420..282e670 100644 --- a/lib/blocklib.php +++ b/lib/blocklib.php @@ -276,7 +276,7 @@ function blocks_print_group(&$page, &$pageblocks, $position) { $obj = $instance->obj; } - $editalways = $page->edit_always(); + $editalways = false; if (($isediting && empty($instance->pinned)) || !empty($editalways)) { @@ -827,13 +827,6 @@ function blocks_get_pinned($page) { global $DB; $visible = true; - - if (method_exists($page,'edit_always')) { - if ($page->edit_always()) { - $visible = false; - } - } - $select = "pagetype = ?"; $params = array($page->pagetype); diff --git a/lib/pagelib.php b/lib/pagelib.php index e23e524..abde579 100644 --- a/lib/pagelib.php +++ b/lib/pagelib.php @@ -777,15 +777,8 @@ class page_base extends moodle_page { function init_full() { $this->full_init_done = true; } - - - // is this page always editable, regardless of anything else? - function edit_always() { - return (has_capability('moodle/site:manageblocks', get_context_instance(CONTEXT_SYSTEM)) && defined('ADMIN_STICKYBLOCKS')); - } } - /** * Class that models the behavior of a moodle course * -- 1.5.6.3 From c8ee49c9ca3b46d4c751832629c9b51260f61ba2 Mon Sep 17 00:00:00 2001 From: Tim Hunt Date: Thu, 23 Apr 2009 14:11:19 +0800 Subject: moodle_page: MDL-12212 reimplement user_is_editing, deprecate isediting --- admin/pagelib.php | 6 --- admin/settings.php | 12 +---- blocks/admin/block_admin.php | 4 +- blocks/course_summary/block_course_summary.php | 4 +- blocks/site_main_menu/block_site_main_menu.php | 6 +- .../social_activities/block_social_activities.php | 4 +- blog/blogpage.php | 18 +------ blog/index.php | 3 +- blog/lib.php | 11 ----- course/category.php | 4 +- course/format/topics/format.php | 12 +++--- course/format/weeks/format.php | 12 +++--- course/index.php | 4 +- course/lib.php | 8 ++-- course/search.php | 4 +- lib/adminlib.php | 13 +----- lib/moodlelib.php | 12 ++--- lib/pagelib.php | 47 ++++++++------------ lib/simpletest/testpagelib_moodlepage.php | 35 +++++++++++++++ lib/weblib.php | 4 +- mod/scorm/locallib.php | 4 +- my/pagelib.php | 8 --- tag/pagelib.php | 6 --- 23 files changed, 101 insertions(+), 140 deletions(-) diff --git a/admin/pagelib.php b/admin/pagelib.php index 374b1aa..4514bba 100644 --- a/admin/pagelib.php +++ b/admin/pagelib.php @@ -31,12 +31,6 @@ class page_admin extends page_base { return has_capability('moodle/site:manageblocks', get_context_instance(CONTEXT_SYSTEM)); } - // has to be fixed. i know there's a "proper" way to do this - function user_is_editing() { - global $USER; - return $USER->adminediting; - } - /** * Use this to pass extra HTML that is added after the turn blocks editing on/off button. * diff --git a/admin/settings.php b/admin/settings.php index 4be5405..1e9d4a7 100644 --- a/admin/settings.php +++ b/admin/settings.php @@ -58,16 +58,8 @@ $PAGE = page_create_object(PAGE_ADMIN, 0); // there must be any constant id numb $PAGE->set_pagetype('admin-setting-' . $section); $PAGE->init_extra($section); -if (!isset($USER->adminediting)) { - $USER->adminediting = false; -} - -if ($PAGE->user_allowed_editing()) { - if ($adminediting == 1) { - $USER->adminediting = true; - } elseif ($adminediting == 0) { - $USER->adminediting = false; - } +if ($PAGE->user_allowed_editing() && $adminediting != -1) { + $USER->editing = $adminediting; } diff --git a/blocks/admin/block_admin.php b/blocks/admin/block_admin.php index 1b7a92d..0b78486 100644 --- a/blocks/admin/block_admin.php +++ b/blocks/admin/block_admin.php @@ -8,7 +8,7 @@ class block_admin extends block_list { function get_content() { - global $CFG, $USER, $SITE, $COURSE, $DB; + global $CFG, $USER, $SITE, $COURSE, $DB, $PAGE; if ($this->content !== NULL) { return $this->content; @@ -57,7 +57,7 @@ class block_admin extends block_list { if ($course->id !== SITEID and has_capability('moodle/course:update', $context)) { $this->content->icons[]=''; - if (isediting($this->instance->pageid)) { + if ($PAGE->user_is_editing()) { $this->content->items[]=''.get_string('turneditingoff').''; } else { $this->content->items[]=''.get_string('turneditingon').''; diff --git a/blocks/course_summary/block_course_summary.php b/blocks/course_summary/block_course_summary.php index 2846cb3..8ffc244 100644 --- a/blocks/course_summary/block_course_summary.php +++ b/blocks/course_summary/block_course_summary.php @@ -14,7 +14,7 @@ class block_course_summary extends block_base { } function get_content() { - global $CFG, $COURSE; + global $CFG, $COURSE, $PAGE; if($this->content !== NULL) { return $this->content; @@ -28,7 +28,7 @@ class block_course_summary extends block_base { $options = new object(); $options->noclean = true; // Don't clean Javascripts etc $this->content->text = format_text($COURSE->summary, FORMAT_HTML, $options); - if (isediting($COURSE->id)) { // ?? courseid param not there?? + if ($PAGE->user_is_editing()) { if($COURSE->id == SITEID) { $editpage = $CFG->wwwroot.'/'.$CFG->admin.'/settings.php?section=frontpagesettings'; } else { diff --git a/blocks/site_main_menu/block_site_main_menu.php b/blocks/site_main_menu/block_site_main_menu.php index 31f958b..144a664 100644 --- a/blocks/site_main_menu/block_site_main_menu.php +++ b/blocks/site_main_menu/block_site_main_menu.php @@ -11,7 +11,7 @@ class block_site_main_menu extends block_list { } function get_content() { - global $USER, $CFG, $COURSE, $DB; + global $USER, $CFG, $COURSE, $DB, $PAGE; if ($this->content !== NULL) { return $this->content; @@ -35,8 +35,8 @@ class block_site_main_menu extends block_list { require_once($CFG->dirroot.'/course/lib.php'); $context = get_context_instance(CONTEXT_COURSE, $course->id); - $isediting = isediting($this->instance->pageid) && has_capability('moodle/course:manageactivities', $context); - $modinfo =& get_fast_modinfo($course); + $isediting = $PAGE->user_is_editing() && has_capability('moodle/course:manageactivities', $context); + $modinfo = get_fast_modinfo($course); /// extra fast view mode if (!$isediting) { diff --git a/blocks/social_activities/block_social_activities.php b/blocks/social_activities/block_social_activities.php index 65d5c2c..06f29df 100644 --- a/blocks/social_activities/block_social_activities.php +++ b/blocks/social_activities/block_social_activities.php @@ -11,7 +11,7 @@ class block_social_activities extends block_list { } function get_content() { - global $USER, $CFG, $COURSE, $DB; + global $USER, $CFG, $COURSE, $DB, $PAGE; if ($this->content !== NULL) { return $this->content; @@ -35,7 +35,7 @@ class block_social_activities extends block_list { require_once($CFG->dirroot.'/course/lib.php'); $context = get_context_instance(CONTEXT_COURSE, $course->id); - $isediting = isediting($this->instance->pageid) && has_capability('moodle/course:manageactivities', $context); + $isediting = $PAGE->user_is_editing() && has_capability('moodle/course:manageactivities', $context); $modinfo = get_fast_modinfo($course); /// extra fast view mode diff --git a/blog/blogpage.php b/blog/blogpage.php index 2f3e952..19c8635 100644 --- a/blog/blogpage.php +++ b/blog/blogpage.php @@ -56,18 +56,6 @@ class page_blog extends page_base { return false; } - // Also, admins are considered to have "always on" editing (I wanted to avoid duplicating - // the code that turns editing on/off here; you can roll your own or copy course/view.php). - function user_is_editing() { - global $SESSION; - - if (isloggedin() && !isguest()) { - $this->editing = !empty($SESSION->blog_editing_enabled); - return $this->editing; - } - return false; - } - //over-ride parent method's print_header because blog already passes more than just the title along function print_header($pageTitle='', $pageHeading='', $pageNavigation='', $pageFocus='', $pageMeta='') { global $USER; @@ -82,18 +70,18 @@ class page_blog extends page_base { /////////// Blog page specific functions function get_extra_header_string() { - global $SESSION, $CFG, $USER; + global $CFG, $USER; $editformstring = ''; if ($this->user_allowed_editing()) { - if (!empty($SESSION->blog_editing_enabled)) { + if ($this->user_is_editing()) { $editingString = get_string('turneditingoff'); } else { $editingString = get_string('turneditingon'); } $params = $this->url->params(); - $params['edit'] = empty($SESSION->blog_editing_enabled) ? 1 : 0; + $params['edit'] = $this->user_is_editing() ? 0 : 1; $paramstring = ''; foreach ($params as $key=>$val) { $paramstring .= ''; diff --git a/blog/index.php b/blog/index.php index 565d1ca..f06fadf 100755 --- a/blog/index.php +++ b/blog/index.php @@ -29,10 +29,9 @@ if (empty($CFG->bloglevel)) { $sitecontext = get_context_instance(CONTEXT_SYSTEM); - // change block edit staus if not guest and logged in if (isloggedin() and !isguest() and $edit != -1) { - $SESSION->blog_editing_enabled = $edit; + $USER->editing = $edit; } if (empty($filtertype)) { diff --git a/blog/lib.php b/blog/lib.php index 8d90263..8f0fbc1 100755 --- a/blog/lib.php +++ b/blog/lib.php @@ -54,17 +54,6 @@ /** - * Adaptation of isediting in moodlelib.php for blog module - * @return bool - */ - function blog_isediting() { - global $SESSION; - - return !empty($SESSION->blog_editing_enabled); - } - - - /** * This function is in lib and not in BlogInfo because entries being searched * might be found in any number of blogs rather than just one. * diff --git a/course/category.php b/course/category.php index 73f88cc..394a769 100644 --- a/course/category.php +++ b/course/category.php @@ -39,9 +39,9 @@ if (update_category_button($category->id)) { if ($categoryedit !== -1) { - $USER->categoryediting = $categoryedit; + $USER->editing = $categoryedit; } - $editingon = !empty($USER->categoryediting); + $editingon = $PAGE->user_is_editing(); $navbaritem = update_category_button($category->id); // Must call this again after updating the state. } else { $navbaritem = print_course_search('', true, 'navbar'); diff --git a/course/format/topics/format.php b/course/format/topics/format.php index c1cdd51..6971c2d 100644 --- a/course/format/topics/format.php +++ b/course/format/topics/format.php @@ -125,7 +125,7 @@ $section = 0; $thissection = $sections[$section]; - if ($thissection->summary or $thissection->sequence or isediting($course->id)) { + if ($thissection->summary or $thissection->sequence or $PAGE->user_is_editing()) { // Note, no need for a 'left side' cell or DIV. // Note, 'right side' is BEFORE content. @@ -141,7 +141,7 @@ $summaryformatoptions->noclean = true; echo format_text($summarytext, FORMAT_HTML, $summaryformatoptions); - if (isediting($course->id) && has_capability('moodle/course:update', $coursecontext)) { + if ($PAGE->user_is_editing() && has_capability('moodle/course:update', $coursecontext)) { echo ''.$streditsummary.''; @@ -150,7 +150,7 @@ print_section($course, $thissection, $mods, $modnamesused); - if (isediting($course->id)) { + if ($PAGE->user_is_editing()) { print_section_add_menus($course, $section, $modnames); } @@ -227,7 +227,7 @@ ''.$strshowonlytopic.'
'; } - if (isediting($course->id) && has_capability('moodle/course:update', get_context_instance(CONTEXT_COURSE, $course->id))) { + if ($PAGE->user_is_editing() && has_capability('moodle/course:update', get_context_instance(CONTEXT_COURSE, $course->id))) { if ($course->marker == $section) { // Show the "light globe" on/off echo ''.''.$strmarkedthistopic.'
'; @@ -266,7 +266,7 @@ echo ' '; } - if (isediting($course->id) && has_capability('moodle/course:update', get_context_instance(CONTEXT_COURSE, $course->id))) { + if ($PAGE->user_is_editing() && has_capability('moodle/course:update', get_context_instance(CONTEXT_COURSE, $course->id))) { echo ' '. ''.$streditsummary.'

'; } @@ -274,7 +274,7 @@ print_section($course, $thissection, $mods, $modnamesused); - if (isediting($course->id)) { + if ($PAGE->user_is_editing()) { print_section_add_menus($course, $section, $modnames); } } diff --git a/course/format/weeks/format.php b/course/format/weeks/format.php index 4eaa588..25143e7 100644 --- a/course/format/weeks/format.php +++ b/course/format/weeks/format.php @@ -115,7 +115,7 @@ $section = 0; $thissection = $sections[$section]; - if ($thissection->summary or $thissection->sequence or isediting($course->id)) { + if ($thissection->summary or $thissection->sequence or $PAGE->user_is_editing()) { // Note, 'right side' is BEFORE content. echo '

  • '; @@ -131,7 +131,7 @@ $summaryformatoptions->noclean = true; echo format_text($summarytext, FORMAT_HTML, $summaryformatoptions); - if (isediting($course->id) && has_capability('moodle/course:update', get_context_instance(CONTEXT_COURSE, $course->id))) { + if ($PAGE->user_is_editing() && has_capability('moodle/course:update', get_context_instance(CONTEXT_COURSE, $course->id))) { echo '

    '.$streditsummary.'

    '; @@ -140,7 +140,7 @@ print_section($course, $thissection, $mods, $modnamesused); - if (isediting($course->id)) { + if ($PAGE->user_is_editing()) { print_section_add_menus($course, $section, $modnames); } @@ -223,7 +223,7 @@ ''.$strshowonlyweek.'
    '; } - if (isediting($course->id) && has_capability('moodle/course:update', get_context_instance(CONTEXT_COURSE, $course->id))) { + if ($PAGE->user_is_editing() && has_capability('moodle/course:update', get_context_instance(CONTEXT_COURSE, $course->id))) { if ($thissection->visible) { // Show the hide/show eye echo ''. ''.$strweekhide.'
    '; @@ -256,7 +256,7 @@ $summaryformatoptions->noclean = true; echo format_text($thissection->summary, FORMAT_HTML, $summaryformatoptions); - if (isediting($course->id) && has_capability('moodle/course:update', get_context_instance(CONTEXT_COURSE, $course->id))) { + if ($PAGE->user_is_editing() && has_capability('moodle/course:update', get_context_instance(CONTEXT_COURSE, $course->id))) { echo ' '. ''.$streditsummary.'

    '; } @@ -264,7 +264,7 @@ print_section($course, $thissection, $mods, $modnamesused); - if (isediting($course->id)) { + if ($PAGE->user_is_editing()) { print_section_add_menus($course, $section, $modnames); } } diff --git a/course/index.php b/course/index.php index 0613b08..5ad0156 100644 --- a/course/index.php +++ b/course/index.php @@ -26,9 +26,9 @@ if (update_category_button()) { if ($categoryedit !== -1) { - $USER->categoryediting = $categoryedit; + $USER->editing = $categoryedit; } - $adminediting = !empty($USER->categoryediting); + $adminediting = $PAGE->user_is_editing(); } else { $adminediting = false; } diff --git a/course/lib.php b/course/lib.php index 7f499b0..03938e8 100644 --- a/course/lib.php +++ b/course/lib.php @@ -1367,7 +1367,7 @@ function set_section_visible($courseid, $sectionnumber, $visibility) { * Prints a section full of activity modules */ function print_section($course, $section, $mods, $modnamesused, $absolute=false, $width="100%", $hidecompletion=false) { - global $CFG, $USER, $DB; + global $CFG, $USER, $DB, $PAGE; static $initialised; @@ -1385,7 +1385,7 @@ function print_section($course, $section, $mods, $modnamesused, $absolute=false, if (!isset($initialised)) { $groupbuttons = ($course->groupmode or (!$course->groupmodeforce)); $groupbuttonslink = (!$course->groupmodeforce); - $isediting = isediting($course->id); + $isediting = $PAGE->user_is_editing(); $ismoving = $isediting && ismoving($course->id); if ($ismoving) { $strmovehere = get_string("movehere"); @@ -2181,7 +2181,7 @@ function print_course_request_buttons($systemcontext) { * to see it. */ function update_category_button($categoryid = 0) { - global $CFG, $USER; + global $CFG, $PAGE; // Check permissions. $context = get_category_or_system_context($categoryid); @@ -2190,7 +2190,7 @@ function update_category_button($categoryid = 0) { } // Work out the appropriate action. - if (!empty($USER->categoryediting)) { + if ($PAGE->user_is_editing()) { $label = get_string('turneditingoff'); $edit = 'off'; } else { diff --git a/course/search.php b/course/search.php index 31f97c8..a15762c 100644 --- a/course/search.php +++ b/course/search.php @@ -35,9 +35,9 @@ if (update_category_button()) { if ($edit !== -1) { - $USER->categoryediting = $edit; + $USER->editing = $edit; } - $adminediting = !empty($USER->categoryediting); + $adminediting = $PAGE->user_is_editing(); } else { $adminediting = false; } diff --git a/lib/adminlib.php b/lib/adminlib.php index 1cf65a5..9799696 100644 --- a/lib/adminlib.php +++ b/lib/adminlib.php @@ -3923,17 +3923,8 @@ function admin_externalpage_setup($section, $extrabutton = '', } $adminediting = optional_param('adminedit', -1, PARAM_BOOL); - - if (!isset($USER->adminediting)) { - $USER->adminediting = false; - } - - if ($PAGE->user_allowed_editing()) { - if ($adminediting == 1) { - $USER->adminediting = true; - } elseif ($adminediting == 0) { - $USER->adminediting = false; - } + if ($PAGE->user_allowed_editing() && $adminediting != -1) { + $USER->editing = $adminediting; } } diff --git a/lib/moodlelib.php b/lib/moodlelib.php index 532ef40..05bc958 100644 --- a/lib/moodlelib.php +++ b/lib/moodlelib.php @@ -2628,6 +2628,7 @@ function isguestuser($user=NULL) { } /** + * @deprecated since Moodle 2.0 - use $PAGE->user_is_editing() instead. * Determines if the currently logged in user is in editing mode. * Note: originally this function had $userid parameter - it was not usable anyway * @@ -2635,14 +2636,9 @@ function isguestuser($user=NULL) { * @return bool */ function isediting() { - global $USER, $PAGE; - - if (empty($USER->editing)) { - return false; - } elseif (is_object($PAGE) && method_exists($PAGE,'user_allowed_editing')) { - return $PAGE->user_allowed_editing(); - } - return true;//false; + global $PAGE; + debugging('call to deprecated function isediting(). Please use $PAGE->user_is_editing() instead', DEBUG_DEVELOPER); + return $PAGE->user_is_editing(); } /** diff --git a/lib/pagelib.php b/lib/pagelib.php index abde579..b2d5b39 100644 --- a/lib/pagelib.php +++ b/lib/pagelib.php @@ -211,6 +211,25 @@ class moodle_page { } } +/// Other information getting methods ========================================== + + /** + * @return boolean should the current user see this page in editing mode. + * That is, are they allowed to edit this page, and are they currently in + * editing mode. + */ + public function user_is_editing() { + global $USER; + return !empty($USER->editing) && $this->user_allowed_editing(); + } + + /** + * @return boolean does the user have permission to see this page in editing mode. + */ + public function user_allowed_editing() { + return true; // TODO + } + /// Setter methods ============================================================= /** @@ -738,20 +757,6 @@ class page_base extends moodle_page { /// Class Functions - // USER-RELATED THINGS - - // By default, no user is editing anything and none CAN edit anything. Developers - // will have to override these settings to let Moodle know when it should grant - // editing rights to the user viewing the page. - function user_allowed_editing() { - trigger_error('Page class does not implement method user_allowed_editing()', E_USER_WARNING); - return false; - } - function user_is_editing() { - trigger_error('Page class does not implement method user_is_editing()', E_USER_WARNING); - return false; - } - // HTML OUTPUT SECTION // We have absolutely no idea what derived pages are all about @@ -860,15 +865,6 @@ class page_course extends page_base { } } - // Is the user actually editing this course page or "sticky page" right now? - function user_is_editing() { - if (has_capability('moodle/site:manageblocks', get_context_instance(CONTEXT_SYSTEM)) && defined('ADMIN_STICKYBLOCKS')) { - //always in edit mode on sticky page - return true; - } - return isediting($this->id); - } - // HTML OUTPUT SECTION // This function prints out the common part of the page's header. @@ -994,11 +990,6 @@ class page_generic_activity extends page_base { return has_capability('moodle/course:manageactivities', get_context_instance(CONTEXT_MODULE, $this->modulerecord->id)); } - function user_is_editing() { - $this->init_full(); - return isediting($this->modulerecord->course); - } - function print_header($title, $morenavlinks = NULL, $bodytags = '', $meta = '') { global $USER, $CFG; diff --git a/lib/simpletest/testpagelib_moodlepage.php b/lib/simpletest/testpagelib_moodlepage.php index 7e2e300..0240d0a 100644 --- a/lib/simpletest/testpagelib_moodlepage.php +++ b/lib/simpletest/testpagelib_moodlepage.php @@ -453,4 +453,39 @@ class moodle_page_categories_test extends UnitTestCaseUsingDatabase { } } +/** + * Test functions that affect filter_active table with contextid = $syscontextid. + */ +class moodle_page_editing_test extends UnitTestCase { + protected $testpage; + protected $originaluserediting; + + public function setUp() { + global $USER; + $this->originaluserediting = !empty($USER->editing); + $this->testpage = new testable_moodle_page(); + } + + public function tearDown() { + global $USER; + $this->testpage = NULL; + $USER->editing = $this->originaluserediting; + } + + public function test_user_is_editing_on() { + // Setup fixture + global $USER; + $USER->editing = true; + // Validate + $this->assertTrue($this->testpage->user_is_editing()); + } + + public function test_user_is_editing_off() { + // Setup fixture + global $USER; + $USER->editing = false; + // Validate + $this->assertFalse($this->testpage->user_is_editing()); + } +} ?> diff --git a/lib/weblib.php b/lib/weblib.php index fc74907..6137cfe 100644 --- a/lib/weblib.php +++ b/lib/weblib.php @@ -5091,11 +5091,11 @@ function update_module_button($cmid, $ignored, $string) { */ function update_categories_search_button($search,$page,$perpage) { - global $CFG, $USER; + global $CFG, $PAGE; // not sure if this capability is the best here if (has_capability('moodle/category:manage', get_context_instance(CONTEXT_SYSTEM))) { - if (!empty($USER->categoryediting)) { + if ($PAGE->user_is_editing()) { $string = get_string("turneditingoff"); $edit = "off"; $perpage = 30; diff --git a/mod/scorm/locallib.php b/mod/scorm/locallib.php index 2d071ba..529ac12 100755 --- a/mod/scorm/locallib.php +++ b/mod/scorm/locallib.php @@ -665,7 +665,7 @@ function scorm_get_last_attempt($scormid, $userid) { } function scorm_course_format_display($user,$course) { - global $CFG, $DB; + global $CFG, $DB, $PAGE; $strupdate = get_string('update'); $strmodule = get_string('modulename','scorm'); @@ -681,7 +681,7 @@ function scorm_course_format_display($user,$course) { $colspan = ''; $headertext = '
  • '.get_string('name').': '.format_string($scorm->name).''; if (has_capability('moodle/course:manageactivities', $context)) { - if (isediting($course->id)) { + if ($PAGE->user_is_editing()) { // Display update icon $path = $CFG->wwwroot.'/course'; $headertext .= ''. diff --git a/my/pagelib.php b/my/pagelib.php index 1c43a18..a7a718b 100644 --- a/my/pagelib.php +++ b/my/pagelib.php @@ -13,14 +13,6 @@ class page_my_moodle extends page_base { return false; } - function user_is_editing() { - global $USER; - if (has_capability('moodle/my:manageblocks', get_context_instance(CONTEXT_SYSTEM)) && defined('ADMIN_STICKYBLOCKS')) { - return true; - } - return (!empty($USER->editing)); - } - function print_header($title) { global $USER, $CFG; diff --git a/tag/pagelib.php b/tag/pagelib.php index 658dc00..44de6ad 100644 --- a/tag/pagelib.php +++ b/tag/pagelib.php @@ -15,12 +15,6 @@ class page_tag extends page_base { return has_capability('moodle/tag:editblocks', $systemcontext); } - function user_is_editing() { - global $USER; - - return (!empty($USER->editing)); - } - //----------- printing funtions ----------- function print_header() { -- 1.5.6.3 From f364dc4fcc9c3392d81de2d5cc551d035492870f Mon Sep 17 00:00:00 2001 From: Tim Hunt Date: Thu, 23 Apr 2009 14:15:19 +0800 Subject: moodle_page: MDL-12212 remove get_extra_header_string method from blog page --- blog/blogpage.php | 20 ++++---------------- 1 files changed, 4 insertions(+), 16 deletions(-) diff --git a/blog/blogpage.php b/blog/blogpage.php index 19c8635..c4ba4a4 100644 --- a/blog/blogpage.php +++ b/blog/blogpage.php @@ -58,22 +58,11 @@ class page_blog extends page_base { //over-ride parent method's print_header because blog already passes more than just the title along function print_header($pageTitle='', $pageHeading='', $pageNavigation='', $pageFocus='', $pageMeta='') { - global $USER; + global $CFG, $USER; $this->init_full(); $extraheader = ''; - if (!empty($USER) && !empty($USER->id)) { - $extraheader = $this->get_extra_header_string(); - } - print_header($pageTitle, $pageHeading, $pageNavigation, $pageFocus, $pageMeta, true, $extraheader ); - } - - /////////// Blog page specific functions - function get_extra_header_string() { - global $CFG, $USER; - - $editformstring = ''; - if ($this->user_allowed_editing()) { + if (!empty($USER) && !empty($USER->id) && $this->user_allowed_editing()) { if ($this->user_is_editing()) { $editingString = get_string('turneditingoff'); } else { @@ -87,11 +76,10 @@ class page_blog extends page_base { $paramstring .= ''; } - $editformstring = 'frametarget.' method="get" action="'.$this->url->out(false).'">
    ' + $extraheader = 'frametarget.' method="get" action="'.$this->url->out(false).'">
    ' .$paramstring.'
    '; } - - return $editformstring; + print_header($pageTitle, $pageHeading, $pageNavigation, $pageFocus, $pageMeta, true, $extraheader ); } } ?> -- 1.5.6.3 From 50d0f525983069d4c196cc556605e160692bc4fb Mon Sep 17 00:00:00 2001 From: Tim Hunt Date: Thu, 23 Apr 2009 14:20:44 +0800 Subject: moodle_page: MDL-12212 Unbreak home page when editing is on --- lib/pagelib.php | 3 ++- 1 files changed, 2 insertions(+), 1 deletions(-) diff --git a/lib/pagelib.php b/lib/pagelib.php index b2d5b39..f1159dc 100644 --- a/lib/pagelib.php +++ b/lib/pagelib.php @@ -710,7 +710,8 @@ function page_map_class($type, $classname = NULL) { if ($mappings === NULL) { $mappings = array( - PAGE_COURSE_VIEW => 'page_course' + PAGE_COURSE_VIEW => 'page_course', + 'site-index' => 'page_course' ); } -- 1.5.6.3 From 6fbdc1b52f1110e5169bca5b122c84c1f98d52bd Mon Sep 17 00:00:00 2001 From: Tim Hunt Date: Thu, 23 Apr 2009 16:35:46 +0800 Subject: moodle_page: MDL-12212 new implementation of user_allowed_editing --- lib/pagelib.php | 36 ++++++++++++++++++++++++++- lib/simpletest/testpagelib_moodlepage.php | 38 +++++++++++++++++++++++++++++ 2 files changed, 73 insertions(+), 1 deletions(-) diff --git a/lib/pagelib.php b/lib/pagelib.php index f1159dc..a0b185d 100644 --- a/lib/pagelib.php +++ b/lib/pagelib.php @@ -79,6 +79,10 @@ class moodle_page { protected $_blocks = null; + protected $_blockseditingcap = 'moodle/site:manageblocks'; + + protected $_othereditingcaps = array(); + /// Getter methods ============================================================= /// Due to the __get magic below, you normally do not call these as $PAGE->get_x /// methods, but instead use the $PAGE->x syntax. @@ -227,7 +231,7 @@ class moodle_page { * @return boolean does the user have permission to see this page in editing mode. */ public function user_allowed_editing() { - return true; // TODO + return has_any_capability($this->all_editing_caps(), $this->_context); } /// Setter methods ============================================================= @@ -382,6 +386,30 @@ class moodle_page { } } + /** + * Set the capability that allows users to edit blocks on this page. Normally + * the default of 'moodle/site:manageblocks' is used, but a few pages like + * the My Moodle page need to use a different capability like 'moodle/my:manageblocks'. + * @param string $capability a capability. + */ + public function set_blocks_editing_capability($capability) { + $this->_blockseditingcap = $capability; + } + + /** + * Some pages let you turn editing on for reasons other than editing blocks. + * If that is the case, you can pass other capabilitise that let the user + * edit this page here. + * @param string|array $capability either a capability, or an array of capabilities. + */ + public function set_other_editing_capability($capability) { + if (is_array($capability)) { + $this->_othereditingcaps = array_unique($this->_othereditingcaps + $capability); + } else { + $this->_othereditingcaps[] = $capability; + } + } + /// Initialisation methods ===================================================== /// These set various things up in a default way. @@ -531,6 +559,12 @@ class moodle_page { return $class; } + protected function all_editing_caps() { + $caps = $this->_othereditingcaps; + $caps[] = $this->_blockseditingcap; + return $caps; + } + /// Deprecated fields and methods for backwards compatibility ================== /** diff --git a/lib/simpletest/testpagelib_moodlepage.php b/lib/simpletest/testpagelib_moodlepage.php index 0240d0a..60f42cc 100644 --- a/lib/simpletest/testpagelib_moodlepage.php +++ b/lib/simpletest/testpagelib_moodlepage.php @@ -44,6 +44,9 @@ class testable_moodle_page extends moodle_page { public function url_to_class_name($url) { return parent::url_to_class_name($url); } + public function all_editing_caps() { + return parent::all_editing_caps(); + } } /** @@ -464,6 +467,7 @@ class moodle_page_editing_test extends UnitTestCase { global $USER; $this->originaluserediting = !empty($USER->editing); $this->testpage = new testable_moodle_page(); + $this->testpage->set_context(get_context_instance(CONTEXT_SYSTEM)); } public function tearDown() { @@ -472,6 +476,8 @@ class moodle_page_editing_test extends UnitTestCase { $USER->editing = $this->originaluserediting; } + // We are relying on the fact that unit tests are alwyas run by admin, to + // ensure the user_allows_editing call returns true. public function test_user_is_editing_on() { // Setup fixture global $USER; @@ -480,6 +486,8 @@ class moodle_page_editing_test extends UnitTestCase { $this->assertTrue($this->testpage->user_is_editing()); } + // We are relying on the fact that unit tests are alwyas run by admin, to + // ensure the user_allows_editing call returns true. public function test_user_is_editing_off() { // Setup fixture global $USER; @@ -487,5 +495,35 @@ class moodle_page_editing_test extends UnitTestCase { // Validate $this->assertFalse($this->testpage->user_is_editing()); } + + public function test_default_editing_capabilities() { + // Validate + $this->assertEqual(array('moodle/site:manageblocks'), $this->testpage->all_editing_caps()); + } + + public function test_other_block_editing_cap() { + // Exercise SUT + $this->testpage->set_blocks_editing_capability('moodle/my:manageblocks'); + // Validate + $this->assertEqual(array('moodle/my:manageblocks'), $this->testpage->all_editing_caps()); + } + + public function test_other_editing_cap() { + // Exercise SUT + $this->testpage->set_other_editing_capability('moodle/course:manageactivities'); + // Validate + $actualcaps = $this->testpage->all_editing_caps(); + $expectedcaps = array('moodle/course:manageactivities', 'moodle/site:manageblocks'); + $this->assert(new ArraysHaveSameValuesExpectation($expectedcaps), $actualcaps); + } + + public function test_other_editing_caps() { + // Exercise SUT + $this->testpage->set_other_editing_capability(array('moodle/course:manageactivities', 'moodle/site:other')); + // Validate + $actualcaps = $this->testpage->all_editing_caps(); + $expectedcaps = array('moodle/course:manageactivities', 'moodle/site:other', 'moodle/site:manageblocks'); + $this->assert(new ArraysHaveSameValuesExpectation($expectedcaps), $actualcaps); + } } ?> -- 1.5.6.3 From 2fa58a4f827e89783de7a0fbb9ac1c66c3193b60 Mon Sep 17 00:00:00 2001 From: Tim Hunt Date: Thu, 23 Apr 2009 17:27:37 +0800 Subject: moodle_page: MDL-12212 kill legacy page_allows_editing implementations --- admin/pagelib.php | 10 ------ blocks/moodleblock.class.php | 3 +- blog/blogpage.php | 8 ----- blog/header.php | 1 + course/view.php | 1 + index.php | 1 + lib/pagelib.php | 67 +++++------------------------------------- my/index.php | 1 + my/pagelib.php | 9 ----- tag/index.php | 1 + tag/pagelib.php | 5 --- 11 files changed, 15 insertions(+), 92 deletions(-) diff --git a/admin/pagelib.php b/admin/pagelib.php index 4514bba..62c76cd 100644 --- a/admin/pagelib.php +++ b/admin/pagelib.php @@ -21,16 +21,6 @@ page_map_class(PAGE_ADMIN, 'page_admin'); class page_admin extends page_base { var $extrabutton = ''; - function _legacy_blocks_get_default() { - return 'admin_tree,admin_bookmarks'; - } - - // seems reasonable that the only people that can edit blocks on the admin pages - // are the admins... but maybe we want a role for this? - function user_allowed_editing() { - return has_capability('moodle/site:manageblocks', get_context_instance(CONTEXT_SYSTEM)); - } - /** * Use this to pass extra HTML that is added after the turn blocks editing on/off button. * diff --git a/blocks/moodleblock.class.php b/blocks/moodleblock.class.php index e4471ff..a92a63d 100644 --- a/blocks/moodleblock.class.php +++ b/blocks/moodleblock.class.php @@ -457,7 +457,8 @@ class block_base { if (empty($this->instance->pageid)) { $this->instance->pageid = 0; } - if (!empty($PAGE->type) and ($this->instance->pagetype == $PAGE->type) and $this->instance->pageid == $PAGE->id) { + + if (($this->instance->pagetype == $PAGE->pagetype) and $this->instance->pageid == $PAGE->id) { $page = $PAGE; } else { $page = page_create_object($this->instance->pagetype, $this->instance->pageid); diff --git a/blog/blogpage.php b/blog/blogpage.php index c4ba4a4..dde6e70 100644 --- a/blog/blogpage.php +++ b/blog/blogpage.php @@ -48,14 +48,6 @@ class page_blog extends page_base { $this->full_init_done = true; } - // For this test page, only admins are going to be allowed editing (for simplicity). - function user_allowed_editing() { - if (isloggedin() && !isguest()) { - return true; - } - return false; - } - //over-ride parent method's print_header because blog already passes more than just the title along function print_header($pageTitle='', $pageHeading='', $pageNavigation='', $pageFocus='', $pageMeta='') { global $CFG, $USER; diff --git a/blog/header.php b/blog/header.php index 05d5d56..bf663f1 100755 --- a/blog/header.php +++ b/blog/header.php @@ -64,6 +64,7 @@ if (!empty($tagid)) { $array['tagid'] = $tagid; } $PAGE->set_url('blog/index.php', $array); +$PAGE->set_blocks_editing_capability('moodle/blog:create'); $PAGE->init_full(); //init the BlogInfo object and the courserecord object $editing = false; diff --git a/course/view.php b/course/view.php index 332fb5f..d68aff4 100644 --- a/course/view.php +++ b/course/view.php @@ -93,6 +93,7 @@ $PAGE = page_create_object(PAGE_COURSE_VIEW, $course->id); $PAGE->set_url('course/view.php', array('id' => $course->id)); + $PAGE->set_other_editing_capability('moodle/course:manageactivities'); $pageblocks = blocks_setup($PAGE, BLOCKS_PINNED_BOTH); if ($reset_user_allowed_editing) { diff --git a/index.php b/index.php index c4c5a26..277c102 100644 --- a/index.php +++ b/index.php @@ -89,6 +89,7 @@ $PAGE = page_create_object(PAGE_COURSE_VIEW, SITEID); $PAGE->set_pagetype('site-index'); + $PAGE->set_other_editing_capability('moodle/course:manageactivities'); $PAGE->set_url(''); $PAGE->set_docs_path(''); $pageblocks = blocks_setup($PAGE); diff --git a/lib/pagelib.php b/lib/pagelib.php index a0b185d..b65e314 100644 --- a/lib/pagelib.php +++ b/lib/pagelib.php @@ -188,6 +188,7 @@ class moodle_page { public function get_url() { if (is_null($this->_url)) { debugging('This page did no call $PAGE->set_url(...). Realying on a guess.', DEBUG_DEVELOPER); + global $ME; return new moodle_url($ME); } return new moodle_url($this->_url); // Return a clone for safety. @@ -745,7 +746,6 @@ function page_map_class($type, $classname = NULL) { if ($mappings === NULL) { $mappings = array( PAGE_COURSE_VIEW => 'page_course', - 'site-index' => 'page_course' ); } @@ -860,46 +860,6 @@ class page_course extends page_base { $this->full_init_done = true; } - // USER-RELATED THINGS - - // Can user edit the course page or "sticky page"? - // This is also about editting of blocks BUT mainly activities in course page layout, see - // update_course_icon() has very similar checks - it must use the same capabilities - // - // this is a _very_ expensive check - so cache it during execution - // - function user_allowed_editing() { - $this->init_full(); - - if (isset($this->_user_allowed_editing)) { - return $this->_user_allowed_editing; - } - - if (has_capability('moodle/site:manageblocks', get_context_instance(CONTEXT_SYSTEM)) - && defined('ADMIN_STICKYBLOCKS')) { - $this->_user_allowed_editing = true; - return true; - } - if (has_capability('moodle/course:manageactivities', $this->context)) { - $this->_user_allowed_editing = true; - return true; - } - - // Exhaustive (and expensive!) checks to see if the user - // has editing abilities to a specific module/block/group... - // This code would benefit from the ability to check specifically - // for overrides. - foreach ($this->childcontexts as $cc) { - if (($cc->contextlevel == CONTEXT_MODULE && - has_capability('moodle/course:manageactivities', $cc)) || - ($cc->contextlevel == CONTEXT_BLOCK && - has_capability('moodle/site:manageblocks', $cc))) { - $this->_user_allowed_editing = true; - return true; - } - } - } - // HTML OUTPUT SECTION // This function prints out the common part of the page's header. @@ -1018,13 +978,6 @@ class page_generic_activity extends page_base { $this->full_init_done = true; } - function user_allowed_editing() { - $this->init_full(); - // Yu: I think this is wrong, should be checking manageactivities instead - //return has_capability('moodle/site:manageblocks', get_context_instance(CONTEXT_COURSE, $this->modulerecord->course)); - return has_capability('moodle/course:manageactivities', get_context_instance(CONTEXT_MODULE, $this->modulerecord->id)); - } - function print_header($title, $morenavlinks = NULL, $bodytags = '', $meta = '') { global $USER, $CFG; @@ -1036,18 +989,14 @@ class page_generic_activity extends page_base { $title = str_replace($search, $replace, $title); } - if (empty($morenavlinks) && $this->user_allowed_editing()) { - $buttons = ''; - if (!empty($CFG->showblocksonmodpages)) { - $buttons .= ''; - } - $buttons .= '
    '.update_module_button($this->modulerecord->id, $this->course->id, get_string('modulename', $this->activityname)).'
    frametarget.' method="get" action="view.php">
    '. - ''. - ''. - '
    '; - } else { - $buttons = ' '; + $buttons = ''; + if ($this->user_allowed_editing() && !empty($CFG->showblocksonmodpages)) { + $buttons .= ''; } + $buttons .= '
    '.update_module_button($this->modulerecord->id, $this->course->id, get_string('modulename', $this->activityname)).'
    frametarget.' method="get" action="view.php">
    '. + ''. + ''. + '
    '; if (empty($morenavlinks)) { $morenavlinks = array(); diff --git a/my/index.php b/my/index.php index 76774b8..61d8c38 100644 --- a/my/index.php +++ b/my/index.php @@ -25,6 +25,7 @@ $PAGE = page_create_instance($USER->id); $PAGE->set_url('my/index.php'); + $PAGE->set_blocks_editing_capability('moodle/my:manageblocks'); $pageblocks = blocks_setup($PAGE,BLOCKS_PINNED_BOTH); diff --git a/my/pagelib.php b/my/pagelib.php index a7a718b..d708117 100644 --- a/my/pagelib.php +++ b/my/pagelib.php @@ -4,15 +4,6 @@ require_once($CFG->libdir.'/pagelib.php'); class page_my_moodle extends page_base { - function user_allowed_editing() { - if ($PAGE->pagetype == PAGE_MY_MOODLE) { - return true; - } else if (has_capability('moodle/my:manageblocks', get_context_instance(CONTEXT_SYSTEM)) && defined('ADMIN_STICKYBLOCKS')) { - return true; - } - return false; - } - function print_header($title) { global $USER, $CFG; diff --git a/tag/index.php b/tag/index.php index d97fb54..0de5259 100644 --- a/tag/index.php +++ b/tag/index.php @@ -35,6 +35,7 @@ if (empty($tag)) { //create a new page_tag object, defined in pagelib.php $PAGE = page_create_object(PAGE_TAG_INDEX, $tag->id); $PAGE->set_url('tag/index.php', array('id' => $tag->id)); +$PAGE->set_blocks_editing_capability('moodle/tag:editblocks'); $pageblocks = blocks_setup($PAGE,BLOCKS_PINNED_BOTH); $PAGE->tag_object = $tag; diff --git a/tag/pagelib.php b/tag/pagelib.php index 44de6ad..d89b025 100644 --- a/tag/pagelib.php +++ b/tag/pagelib.php @@ -10,11 +10,6 @@ class page_tag extends page_base { var $tag_object = NULL; - function user_allowed_editing() { - $systemcontext = get_context_instance(CONTEXT_SYSTEM); - return has_capability('moodle/tag:editblocks', $systemcontext); - } - //----------- printing funtions ----------- function print_header() { -- 1.5.6.3 From 5f6ffba208a9c65ee564cf162bbe7963e8746d4d Mon Sep 17 00:00:00 2001 From: Tim Hunt Date: Thu, 23 Apr 2009 18:35:09 +0800 Subject: moodle_page: MDL-12212 deprecate more of the legacy page machinery, and avoid overwriting $PAGE ever --- lib/pagelib.php | 90 +++++++++++++++++++++++++++++++++++++++++-------------- 1 files changed, 67 insertions(+), 23 deletions(-) diff --git a/lib/pagelib.php b/lib/pagelib.php index b65e314..fdc9a21 100644 --- a/lib/pagelib.php +++ b/lib/pagelib.php @@ -83,6 +83,14 @@ class moodle_page { protected $_othereditingcaps = array(); + /** + * This is simply to improve backwards compatability. If old code relies on + * a page class that implements print_header, or complex logic in + * user_allowed_editing then we stash an instance of that other class here, + * and delegate to it in certani situations. + */ + protected $_legacypageobject = null; + /// Getter methods ============================================================= /// Due to the __get magic below, you normally do not call these as $PAGE->get_x /// methods, but instead use the $PAGE->x syntax. @@ -232,6 +240,9 @@ class moodle_page { * @return boolean does the user have permission to see this page in editing mode. */ public function user_allowed_editing() { + if ($this->_legacypageobject) { + return $this->_legacypageobject->user_allowed_editing(); + } return has_any_capability($this->all_editing_caps(), $this->_context); } @@ -664,6 +675,38 @@ class moodle_page { debugging('Call to deprecated method moodle_page::url_get_full. Use $this->url->out() instead.'); return $this->url->out($extraparams); } + + /** + * @deprecated since Moodle 2.0 - just a backwards compatibility hook. + */ + function set_legacy_page_object($pageobject) { + return $this->_legacypageobject = $pageobject; + } + + /** + * @deprecated since Moodle 2.0 - page objects should no longer be doing print_header. + * @param $_,... + */ + function print_header($_) { + if (is_null($this->_legacypageobject)) { + throw new coding_exception('You have called print_header on $PAGE when there is not a legacy page class present.'); + } + debugging('You should not longer be doing print_header via a page class.', DEBUG_DEVELOPER); + $args = func_get_args(); + call_user_func_array(array($this->_legacypageobject, 'print_header'), $args); + } + + /** + * @deprecated since Moodle 2.0 + * @return the 'page id'. This concept no longer exists. + */ + function get_id() { + debugging('Call to deprecated method moodle_page::get_id(). It should not be necessary any more.', DEBUG_DEVELOPER); + if (!is_null($this->_legacypageobject)) { + return $this->_legacypageobject->get_id(); + } + return 0; + } } /** Stub implementation of the blocks_manager, to stop things from breaking too badly. */ @@ -679,7 +722,7 @@ class blocks_manager { /** * @deprecated since Moodle 2.0 - * Load any page_base subclasses from the pagelib.php library in a particular folder. + * Not needed any more. * @param $path the folder path * @return array an array of page types. */ @@ -690,6 +733,8 @@ function page_import_types($path) { /** * @deprecated since Moodle 2.0 + * Do not use this any more. The global $PAGE is automatically created for you. + * If you need custom behaviour, you should just set properties of that object. * @param integer $instance legacy page instance id. * @return the global $PAGE object. */ @@ -698,11 +743,13 @@ function page_create_instance($instance) { } /** - * Factory function page_create_object(). Called with a pagetype identifier and possibly with - * its numeric ID. Returns a fully constructed page_base subclass you can work with. + * @deprecated since Moodle 2.0 + * Do not use this any more. The global $PAGE is automatically created for you. + * If you need custom behaviour, you should just set properties of that object. */ function page_create_object($type, $id = NULL) { global $CFG, $PAGE, $SITE; + debugging('Call to deprecated function page_create_object.', DEBUG_DEVELOPER); $data = new stdClass; $data->pagetype = $type; @@ -711,9 +758,6 @@ function page_create_object($type, $id = NULL) { $classname = page_map_class($type); $legacypage = new $classname; $legacypage->init_quick($data); - // $PAGE->set_pagetype($type); - // $PAGE->set_url(str_replace($CFG->wwwroot . '/', '', $legacypage->url_get_full_())); - // return $PAGE; $course = $PAGE->course; if ($course->id != $SITE->id) { @@ -731,23 +775,25 @@ function page_create_object($type, $id = NULL) { $legacypage->set_course($SITE); } } - return $legacypage; + $legacypage->set_pagetype($type); + $legacypage->set_url(str_replace($CFG->wwwroot . '/', '', $legacypage->url_get_full())); + + $PAGE->set_pagetype($type); + $PAGE->set_legacy_page_object($legacypage); + return $PAGE; } /** - * Function page_map_class() is the way for your code to define its own page subclasses and let Moodle recognize them. - * Use it to associate the textual identifier of your Page with the actual class name that has to be instantiated. + * @deprecated since Moodle 2.0 + * You should not be writing page subclasses any more. Just set properties on the + * global $PAGE object to control its behaviour. */ function page_map_class($type, $classname = NULL) { global $CFG; - static $mappings = NULL; - - if ($mappings === NULL) { - $mappings = array( - PAGE_COURSE_VIEW => 'page_course', - ); - } + static $mappings = array( + PAGE_COURSE_VIEW => 'page_course', + ); if (!empty($type) && !empty($classname)) { $mappings[$type] = $classname; @@ -765,11 +811,10 @@ function page_map_class($type, $classname = NULL) { } /** + * @deprecated since Moodle 2.0 * Parent class from which all Moodle page classes derive * - * @author Jon Papaioannou * @package pages - * @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. */ class page_base extends moodle_page { /** @@ -820,13 +865,12 @@ class page_base extends moodle_page { } /** + * @deprecated since Moodle 2.0 * Class that models the behavior of a moodle course * - * @author Jon Papaioannou * @package pages */ class page_course extends page_base { - // Do any validation of the officially recognized bits of the data and forward to parent. // Do NOT load up "expensive" resouces (e.g. SQL data) here! function init_quick($data) { @@ -949,14 +993,14 @@ class page_course extends page_base { } /** + * @deprecated since Moodle 2.0 * Class that models the common parts of all activity modules * - * @author Jon Papaioannou * @package pages */ class page_generic_activity extends page_base { - var $activityname = NULL; - var $modulerecord = NULL; + var $activityname = NULL; + var $modulerecord = NULL; var $activityrecord = NULL; function init_full() { -- 1.5.6.3 From c467b86005ff24602061d81661c0a9f2b3ebd550 Mon Sep 17 00:00:00 2001 From: Tim Hunt Date: Thu, 23 Apr 2009 18:39:22 +0800 Subject: moodle_page: MDL-12212 eliminate page_tag::print_footer --- tag/index.php | 3 +-- tag/pagelib.php | 4 ---- 2 files changed, 1 insertions(+), 6 deletions(-) diff --git a/tag/index.php b/tag/index.php index 0de5259..ed30755 100644 --- a/tag/index.php +++ b/tag/index.php @@ -175,6 +175,5 @@ if (blocks_have_content($pageblocks, BLOCK_POS_RIGHT) || $PAGE->user_is_editing( /// Finish the page echo '
    '; -$PAGE->print_footer(); - +print_footer(); ?> diff --git a/tag/pagelib.php b/tag/pagelib.php index d89b025..4dcef9c 100644 --- a/tag/pagelib.php +++ b/tag/pagelib.php @@ -31,10 +31,6 @@ class page_tag extends page_base { } print_header_simple($title, '', $navigation, '', '', '', $button); } - - function print_footer() { - print_footer(); - } } page_map_class(PAGE_TAG_INDEX, 'page_tag'); -- 1.5.6.3 From 8417e3e7343ec632c6a140b52ceacfc184a29754 Mon Sep 17 00:00:00 2001 From: Tim Hunt Date: Fri, 24 Apr 2009 15:35:20 +0800 Subject: moodle_page: MDL-12212 ->cm and ->activityrecord fields --- lib/adminlib.php | 3 +- lib/pagelib.php | 201 +++++++++++++++++------------ lib/simpletest/testpagelib_moodlepage.php | 201 +++++++++++++++++++++++++++++ 3 files changed, 324 insertions(+), 81 deletions(-) diff --git a/lib/adminlib.php b/lib/adminlib.php index 9799696..5e6e3f0 100644 --- a/lib/adminlib.php +++ b/lib/adminlib.php @@ -3900,7 +3900,7 @@ function admin_externalpage_setup($section, $extrabutton = '', page_map_class(PAGE_ADMIN, 'page_admin'); $PAGE = page_create_object(PAGE_ADMIN, 0); // there must be any constant id number $PAGE->set_context(get_context_instance(CONTEXT_SYSTEM)); - $PAGE->set_extra_button($extrabutton); + // $PAGE->set_extra_button($extrabutton); TODO $adminroot = admin_get_root(false, false); // settings not required for external pages $extpage = $adminroot->locate($section); @@ -3908,6 +3908,7 @@ function admin_externalpage_setup($section, $extrabutton = '', if (!$actualurl) { $actualurl = $extpage->url; } + $PAGE->set_pagetype(null); $PAGE->set_url(str_replace($CFG->wwwroot . '/', '', $actualurl), array_merge($extraurlparams, array('section' => $section))); diff --git a/lib/pagelib.php b/lib/pagelib.php index fdc9a21..2b744d8 100644 --- a/lib/pagelib.php +++ b/lib/pagelib.php @@ -54,6 +54,23 @@ class moodle_page { protected $_course = null; + /** + * If this page belongs to a module, this is the row from the course_modules + * table, as fetched by get_coursemodule_from_id or get_coursemodule_from_instance, + * so the extra modname and name fields are present. + */ + protected $_cm = null; + + /** + * If $_cm is not null, then this will hold the corresponding row from the + * modname table. For example, if $_cm->modname is 'quiz', this will be a + * row from the quiz table. + */ + protected $_module = null; + + /** + * The context that this page belongs to. + */ protected $_context = null; /** @@ -128,6 +145,42 @@ class moodle_page { } /** + * @return object the course_module that this page belongs to. Will be null + * if this page is not within a module. This is a full cm object, as loaded + * by get_coursemodule_from_id or get_coursemodule_from_instance, + * so the extra modname and name fields are present. + */ + public function get_cm() { + return $this->_cm; + } + + /** + * @return object the course_module that this page belongs to. Will be null + * if this page is not within a module. This is a full cm object, as loaded + * by get_coursemodule_from_id or get_coursemodule_from_instance, + * so the extra modname and name fields are present. + */ + public function get_activityrecord() { + if (is_null($this->_module) && !is_null($this->_cm)) { + $this->load_activity_record(); + } + return $this->_module; + } + + /** + * @return object the course_module that this page belongs to. Will be null + * if this page is not within a module. This is a full cm object, as loaded + * by get_coursemodule_from_id or get_coursemodule_from_instance, + * so the extra modname and name fields are present. + */ + public function get_activityname() { + if (is_null($this->_cm)) { + return null; + } + return $this->_cm->modname; + } + + /** * @return mixed the category that the page course belongs to. If there isn't one * (that is, if this is the front page course) returns null. */ @@ -318,6 +371,50 @@ class moodle_page { } /** + * The course module that this page belongs to (if it does belong to one). + * + * @param objcet $cm a full cm objcet obtained from get_coursemodule_from_id or get_coursemodule_from_instance. + */ + public function set_cm($cm, $course = null, $module = null) { + if (!isset($cm->name) || !isset($cm->modname)) { + throw new coding_exception('The $cm you set on $PAGE must have been obtained with get_coursemodule_from_id or get_coursemodule_from_instance. That is, the ->name and -> modname fields must be present and correct.'); + } + $this->_cm = $cm; + if (!$this->_context) { + $this->set_context(get_context_instance(CONTEXT_MODULE, $cm->id)); + } + if (!$this->_course || $this->_course->id != $cm->course) { + if (!$course) { + global $DB; + $course = $DB->get_record('course', array('id' => $cm->course)); + } + if ($course->id != $cm->course) { + throw new coding_exception('The course you passed to $PAGE->set_cm does not seem to correspond to the $cm.'); + } + $this->set_course($course); + } + if ($module) { + $this->set_activity_record($module); + } + } + + /** + * @param $module a row from the main database table for the module that this + * page belongs to. For example, if ->cm is a forum, then you can pass the + * corresponding row from the forum table here if you have it (saves a database + * query sometimes). + */ + public function set_activity_record($module) { + if (is_null($this->_cm)) { + throw new coding_exception('You cannot call $PAGE->set_activity_record until after $PAGE->cm has been set.'); + } + if ($module->id != $this->_cm->instance || $module->course != $this->_course->id) { + throw new coding_exception('The activity record your are trying to set does not seem to correspond to the cm that has been set.'); + } + $this->_module = $module; + } + + /** * @param string $pagetype e.g. 'my-index' or 'mod-quiz-attempt'. Normally * you do not need to set this manually, it is automatically created from the * script name. However, on some pages this is overridden. For example, the @@ -396,6 +493,9 @@ class moodle_page { if (is_null($this->_pagetype)) { $this->initialise_default_pagetype($url); } + if (!is_null($this->_legacypageobject)) { + $this->_legacypageobject->set_url($url, $params); + } } /** @@ -514,6 +614,14 @@ class moodle_page { } } + protected function load_activity_record() { + global $DB; + if (is_null($this->_cm)) { + return; + } + $this->_module = $DB->get_record($this->_cm->modname, array('id' => $this->_cm->instance)); + } + protected function ensure_category_loaded() { if (is_array($this->_categories)) { return; // Already done. @@ -707,6 +815,14 @@ class moodle_page { } return 0; } + + /** + * @deprecated since Moodle 2.0 - user $PAGE->cm instead. + * @return $this->cm; + */ + function get_modulerecord() { + return $this->cm; + } } /** Stub implementation of the blocks_manager, to stop things from breaking too badly. */ @@ -748,12 +864,12 @@ function page_create_instance($instance) { * If you need custom behaviour, you should just set properties of that object. */ function page_create_object($type, $id = NULL) { - global $CFG, $PAGE, $SITE; + global $CFG, $PAGE, $SITE, $ME; debugging('Call to deprecated function page_create_object.', DEBUG_DEVELOPER); $data = new stdClass; $data->pagetype = $type; - $data->pageid = $id; + $data->pageid = $id; $classname = page_map_class($type); $legacypage = new $classname; @@ -776,7 +892,9 @@ function page_create_object($type, $id = NULL) { } } $legacypage->set_pagetype($type); - $legacypage->set_url(str_replace($CFG->wwwroot . '/', '', $legacypage->url_get_full())); + + $legacypage->set_url($ME); + $PAGE->set_url(str_replace($CFG->wwwroot . '/', '', $legacypage->url_get_full())); $PAGE->set_pagetype($type); $PAGE->set_legacy_page_object($legacypage); @@ -818,36 +936,17 @@ function page_map_class($type, $classname = NULL) { */ class page_base extends moodle_page { /** - * The string identifier for the type of page being described. - * @var string $type - */ - var $type = NULL; - - /** * The numeric identifier of the page being described. * @var int $id */ var $id = NULL; - /** - * Class bool to determine if the instance's full initialization has been completed. - * @var boolean $full_init_done - */ - var $full_init_done = false; - /// Class Functions // HTML OUTPUT SECTION - // We have absolutely no idea what derived pages are all about - function print_header($title, $morenavlinks=NULL) { - trigger_error('Page class does not implement method print_header()', E_USER_WARNING); - return; - } - // SELF-REPORTING SECTION - // Simple stuff, do not override this. function get_id() { return $this->id; @@ -855,12 +954,10 @@ class page_base extends moodle_page { // Initialize the data members of the parent class function init_quick($data) { - $this->type = $data->pagetype; $this->id = $data->pageid; } function init_full() { - $this->full_init_done = true; } } @@ -871,39 +968,6 @@ class page_base extends moodle_page { * @package pages */ class page_course extends page_base { - // Do any validation of the officially recognized bits of the data and forward to parent. - // Do NOT load up "expensive" resouces (e.g. SQL data) here! - function init_quick($data) { - if(empty($data->pageid) && !defined('ADMIN_STICKYBLOCKS')) { - print_error('cannotinitpage', 'debug', '', (object)array('name'=>'course', 'id'=>'?')); - } - parent::init_quick($data); - } - - // Here you should load up all heavy-duty data for your page. Basically everything that - // does not NEED to be loaded for the class to make basic decisions should NOT be loaded - // in init_quick() and instead deferred here. Of course this function had better recognize - // $this->full_init_done to prevent wasteful multiple-time data retrieval. - function init_full() { - global $COURSE, $DB; - - if($this->full_init_done) { - return; - } - if (empty($this->id)) { - $this->id = 0; // avoid db errors - } - - $this->context = get_context_instance(CONTEXT_COURSE, $this->id); - - // Preload - ensures that the context cache is populated - // in one DB query... - $this->childcontexts = get_child_contexts($this->context); - - // Mark we're done - $this->full_init_done = true; - } - // HTML OUTPUT SECTION // This function prints out the common part of the page's header. @@ -999,29 +1063,6 @@ class page_course extends page_base { * @package pages */ class page_generic_activity extends page_base { - var $activityname = NULL; - var $modulerecord = NULL; - var $activityrecord = NULL; - - function init_full() { - global $DB; - - if($this->full_init_done) { - return; - } - if(empty($this->activityname)) { - print_error('noactivityname', 'debug'); - } - if (!$this->modulerecord = get_coursemodule_from_instance($this->activityname, $this->id)) { - print_error('cannotinitpager', 'debug', '', (object)array('name'=>$this->activityname, 'id'=>$this->id)); - } - $this->activityrecord = $DB->get_record($this->activityname, array('id'=>$this->id)); - if(empty($this->activityrecord)) { - print_error('cannotinitpager', 'debug', '', (object)array('name'=>$this->activityname, 'id'=>$this->id)); - } - $this->full_init_done = true; - } - function print_header($title, $morenavlinks = NULL, $bodytags = '', $meta = '') { global $USER, $CFG; diff --git a/lib/simpletest/testpagelib_moodlepage.php b/lib/simpletest/testpagelib_moodlepage.php index 60f42cc..e6abd33 100644 --- a/lib/simpletest/testpagelib_moodlepage.php +++ b/lib/simpletest/testpagelib_moodlepage.php @@ -457,6 +457,207 @@ class moodle_page_categories_test extends UnitTestCaseUsingDatabase { } /** + * Test functions that rely on the context table. + */ +class moodle_page_cm_test extends UnitTestCaseUsingDatabase { + protected $testpage; + protected $originalcourse; + + public function setUp() { + global $COURSE, $SITE; + parent::setUp(); + $this->originalcourse = $COURSE; + $this->testpage = new moodle_page(); + $this->create_test_tables(array('course', 'context'), 'lib'); + $this->create_test_table('forum', 'mod/forum'); + $this->switch_to_test_db(); + + $context = new stdClass; + $context->contextlevel = CONTEXT_COURSE; + $context->instanceid = $SITE->id; + $context->path = 'not initialised'; + $context->depth = '-1'; + $this->testdb->insert_record('context', $context); + } + + public function tearDown() { + global $COURSE; + $this->testpage = NULL; + $COURSE = $this->originalcourse; + parent::tearDown(); + } + + /** Creates an object with all the fields you would expect a $course object to have. */ + protected function create_a_forum_with_context() { + $course = new stdClass; + $course->category = 2; + $course->fullname = 'Anonymous test course'; + $course->shortname = 'ANON'; + $course->summary = ''; + $course->id = $this->testdb->insert_record('course', $course); + + $forum = new stdClass; + $forum->course = $course->id; + $forum->name = 'Anonymouse test forum'; + $forum->intro = ''; + $forum->id = $this->testdb->insert_record('forum', $forum); + + $cm = new stdClass; + $cm->id = -1; + $cm->course = $course->id; + $cm->instance = $forum->id; + $cm->modname = 'forum'; + $cm->name = $forum->name; + + $context = new stdClass; + $context->contextlevel = CONTEXT_MODULE; + $context->instanceid = $cm->id; + $context->path = 'not initialised'; + $context->depth = '-1'; + $this->testdb->insert_record('context', $context); + + return array($cm, $course, $forum); + } + + public function test_cm_null_initially() { + // Validate + $this->assertNull($this->testpage->cm); + } + + public function test_set_cm() { + // Setup fixture + list($cm) = $this->create_a_forum_with_context(); + // Exercise SUT + $this->testpage->set_cm($cm); + // Validate + $this->assert(new CheckSpecifiedFieldsExpectation($cm), $this->testpage->cm); + } + + public function test_cannot_set_cm_without_name() { + // Setup fixture + list($cm) = $this->create_a_forum_with_context(); + // Set expectation + $this->expectException(); + // Exercise SUT + unset($cm->name); + $this->testpage->set_cm($cm); + } + + public function test_cannot_set_cm_without_modname() { + // Setup fixture + list($cm) = $this->create_a_forum_with_context(); + // Set expectation + $this->expectException(); + // Exercise SUT + unset($cm->modname); + $this->testpage->set_cm($cm); + } + + public function test_cannot_set_activity_record_before_cm() { + // Setup fixture + list($cm, $course, $forum) = $this->create_a_forum_with_context(); + // Set expectation + $this->expectException(); + // Exercise SUT + $this->testpage->set_activity_record($forum); + } + + public function test_setting_cm_sets_context() { + // Setup fixture + list($cm) = $this->create_a_forum_with_context(); + // Exercise SUT + $this->testpage->set_cm($cm); + // Validate + $expectedcontext = new stdClass; + $expectedcontext->contextlevel = CONTEXT_MODULE; + $expectedcontext->instanceid = $cm->id; + $this->assert(new CheckSpecifiedFieldsExpectation($expectedcontext), $this->testpage->context); + } + + public function test_activity_record_loaded_if_not_set() { + // Setup fixture + list($cm, $course, $forum) = $this->create_a_forum_with_context(); + // Exercise SUT + $this->testpage->set_cm($cm); + // Validate + $this->assert(new CheckSpecifiedFieldsExpectation($forum), $this->testpage->activityrecord); + } + + public function test_set_activity_record() { + // Setup fixture + list($cm, $course, $forum) = $this->create_a_forum_with_context(); + $this->testpage->set_cm($cm); + // Exercise SUT + $this->testpage->set_activity_record($forum); + // Validate + $this->assert(new CheckSpecifiedFieldsExpectation($forum), $this->testpage->activityrecord); + } + + public function test_cannot_set_inconsistent_activity_record_course() { + // Setup fixture + list($cm, $course, $forum) = $this->create_a_forum_with_context(); + $this->testpage->set_cm($cm); + // Set expectation + $this->expectException(); + // Exercise SUT + $forum->course = -1; + $this->testpage->set_activity_record($forum); + } + + public function test_cannot_set_inconsistent_activity_record_instance() { + // Setup fixture + list($cm, $course, $forum) = $this->create_a_forum_with_context(); + $this->testpage->set_cm($cm); + // Set expectation + $this->expectException(); + // Exercise SUT + $forum->id = -1; + $this->testpage->set_activity_record($forum); + } + + public function test_settin_cm_sets_course() { + // Setup fixture + list($cm, $course) = $this->create_a_forum_with_context(); + // Exercise SUT + $this->testpage->set_cm($cm); + // Validate + $this->assert(new CheckSpecifiedFieldsExpectation($course), $this->testpage->course); + } + + public function test_set_cm_with_course_and_activity_no_db() { + // Setup fixture + list($cm, $course, $forum) = $this->create_a_forum_with_context(); + $this->drop_test_table('forum'); + $this->drop_test_table('course'); + // Exercise SUT + $this->testpage->set_cm($cm, $course, $forum); + // Validate + $this->assert(new CheckSpecifiedFieldsExpectation($cm), $this->testpage->cm); + $this->assert(new CheckSpecifiedFieldsExpectation($course), $this->testpage->course); + $this->assert(new CheckSpecifiedFieldsExpectation($forum), $this->testpage->activityrecord); + } + + public function test_cannot_set_cm_with_inconsistent_course() { + // Setup fixture + list($cm, $course, $forum) = $this->create_a_forum_with_context(); + // Set expectation + $this->expectException(); + // Exercise SUT + $cm->course = -1; + $this->testpage->set_cm($cm, $course); + } + + public function test_get_activity_name() { + // Setup fixture + list($cm, $course, $forum) = $this->create_a_forum_with_context(); + // Exercise SUT + $this->testpage->set_cm($cm, $course, $forum); + // Validate + $this->assertEqual('forum', $this->testpage->activityname); + } +} + +/** * Test functions that affect filter_active table with contextid = $syscontextid. */ class moodle_page_editing_test extends UnitTestCase { -- 1.5.6.3 From 9d69d316f20158092d6021a25003d8d5f82969c7 Mon Sep 17 00:00:00 2001 From: Tim Hunt Date: Fri, 24 Apr 2009 16:14:31 +0800 Subject: moodle_page: MDL-12212 ->subpage field --- lib/pagelib.php | 19 +++++++++++++++++++ lib/simpletest/testpagelib_moodlepage.php | 7 +++++++ 2 files changed, 26 insertions(+), 0 deletions(-) diff --git a/lib/pagelib.php b/lib/pagelib.php index 2b744d8..e623fed 100644 --- a/lib/pagelib.php +++ b/lib/pagelib.php @@ -88,6 +88,8 @@ class moodle_page { protected $_pagetype = null; + protected $_subpage = null; + protected $_docspath = null; protected $_legacyclass = null; @@ -225,6 +227,13 @@ class moodle_page { } /** + * @return string|null The subpage identifier, if any. + */ + public function get_subpage() { + return $this->_subpage; + } + + /** * @return string the class names to put on the body element in the HTML. */ public function get_bodyclasses() { @@ -427,6 +436,16 @@ class moodle_page { } /** + * If context->id and pagetype are not enough to uniquely identify this page, + * then you can set a subpage id as well. For example, the tags page sets + * @param string $subpage an arbitrary identifier that, along with context->id + * and pagetype, uniquely identifies this page. + */ + public function set_subpage($subpage) { + $this->_subpage = $subpage; + } + + /** * @param string $class add this class name ot the class attribute on the body tag. */ public function add_body_class($class) { diff --git a/lib/simpletest/testpagelib_moodlepage.php b/lib/simpletest/testpagelib_moodlepage.php index e6abd33..4c69a8b 100644 --- a/lib/simpletest/testpagelib_moodlepage.php +++ b/lib/simpletest/testpagelib_moodlepage.php @@ -314,6 +314,13 @@ class moodle_page_test extends UnitTestCase { // Validate $this->assertEqual('a-page-type', $this->testpage->pagetype); } + + public function test_set_subpage() { + // Exercise SUT + $this->testpage->set_subpage('somestring'); + // Validate + $this->assertEqual('somestring', $this->testpage->subpage); + } } /** -- 1.5.6.3 From cc1c450066ee5d14e02e0543a88c16d740b687ae Mon Sep 17 00:00:00 2001 From: Tim Hunt Date: Fri, 24 Apr 2009 17:56:53 +0800 Subject: moodle_page: MDL-12212 completely remove the old tag and admin page classes --- admin/pagelib.php | 67 ------------------------------------------ admin/settings.php | 65 +++++++++++++++++++++++----------------- blocks/moodleblock.class.php | 4 ++- lib/adminlib.php | 55 ++++++++++++++++++++++------------ lib/pagelib.php | 21 +++++++++++-- lib/upgradelib.php | 4 +- tag/index.php | 19 +++++++++--- tag/pagelib.php | 38 ----------------------- 8 files changed, 110 insertions(+), 163 deletions(-) delete mode 100644 admin/pagelib.php delete mode 100644 tag/pagelib.php diff --git a/admin/pagelib.php b/admin/pagelib.php deleted file mode 100644 index 62c76cd..0000000 --- a/admin/pagelib.php +++ /dev/null @@ -1,67 +0,0 @@ -libdir.'/pagelib.php'); - -define('PAGE_ADMIN', 'admin'); - -// Bounds for block widths -// more flexible for theme designers taken from theme config.php -$lmin = (empty($THEME->block_l_min_width)) ? 0 : $THEME->block_l_min_width; -$lmax = (empty($THEME->block_l_max_width)) ? 210 : $THEME->block_l_max_width; -$rmin = (empty($THEME->block_r_min_width)) ? 0 : $THEME->block_r_min_width; -$rmax = (empty($THEME->block_r_max_width)) ? 210 : $THEME->block_r_max_width; - -define('BLOCK_L_MIN_WIDTH', $lmin); -define('BLOCK_L_MAX_WIDTH', $lmax); -define('BLOCK_R_MIN_WIDTH', $rmin); -define('BLOCK_R_MAX_WIDTH', $rmax); - -page_map_class(PAGE_ADMIN, 'page_admin'); - -class page_admin extends page_base { - var $extrabutton = ''; - - /** - * Use this to pass extra HTML that is added after the turn blocks editing on/off button. - * - * @param string $extrabutton HTML code. - */ - function set_extra_button($extrabutton) { - $this->extrabutton = $extrabutton; - } - - function print_header($focus='') { - global $USER, $CFG, $SITE; - - $adminroot = admin_get_root(false, false); //settings not required - only pages - - // fetch the path parameter - $section = $this->url->param('section'); - $current = $adminroot->locate($section, true); - $visiblepathtosection = array_reverse($current->visiblepath); - - // The search page currently doesn't handle block editing - if ($this->user_allowed_editing()) { - $options = $this->url->params(); - if ($this->user_is_editing()) { - $caption = get_string('blockseditoff'); - $options['adminedit'] = 'off'; - } else { - $caption = get_string('blocksediton'); - $options['adminedit'] = 'on'; - } - $buttons = print_single_button($this->url->out(false), $options, $caption, 'get', '', true); - } - $buttons .= $this->extrabutton; - - $navlinks = array(); - foreach ($visiblepathtosection as $element) { - $navlinks[] = array('name' => $element, 'link' => null, 'type' => 'misc'); - } - $navigation = build_navigation($navlinks); - - print_header("$SITE->shortname: " . implode(": ",$visiblepathtosection), $SITE->fullname, $navigation, $focus, '', true, $buttons, ''); - } -} - -?> diff --git a/admin/settings.php b/admin/settings.php index 1e9d4a7..da6ca83 100644 --- a/admin/settings.php +++ b/admin/settings.php @@ -5,24 +5,25 @@ require_once($CFG->libdir.'/adminlib.php'); require_once($CFG->libdir.'/blocklib.php'); require_once($CFG->dirroot.'/'.$CFG->admin.'/pagelib.php'); -$section = required_param('section', PARAM_SAFEDIR); -$return = optional_param('return','', PARAM_ALPHA); +$section = required_param('section', PARAM_SAFEDIR); +$return = optional_param('return','', PARAM_ALPHA); $adminediting = optional_param('adminedit', -1, PARAM_BOOL); /// no guest autologin require_login(0, false); $PAGE->set_context(get_context_instance(CONTEXT_SYSTEM)); $PAGE->set_url($CFG->admin . '/settings.php', array('section' => $section)); +$PAGE->set_pagetype('admin-setting-' . $section); $adminroot = admin_get_root(); // need all settings -$page = $adminroot->locate($section); +$settingspage = $adminroot->locate($section, true); -if (empty($page) or !($page instanceof admin_settingpage)) { +if (empty($settingspage) or !($settingspage instanceof admin_settingpage)) { print_error('sectionerror', 'admin', "$CFG->wwwroot/$CFG->admin/"); die; } -if (!($page->check_access())) { +if (!($settingspage->check_access())) { print_error('accessdenied', 'admin'); die; } @@ -40,7 +41,7 @@ if ($data = data_submitted() and confirm_sesskey()) { if (empty($adminroot->errors)) { switch ($return) { - case 'site': redirect("$CFG->wwwroot/"); + case 'site': redirect("$CFG->wwwroot/"); case 'admin': redirect("$CFG->wwwroot/$CFG->admin/"); } } else { @@ -48,25 +49,17 @@ if ($data = data_submitted() and confirm_sesskey()) { $firsterror = reset($adminroot->errors); $focus = $firsterror->id; } - $adminroot =& admin_get_root(true); //reload tree - $page =& $adminroot->locate($section); + $adminroot = admin_get_root(true); //reload tree + $settingspage = $adminroot->locate($section); } -/// very hacky page setup -page_map_class(PAGE_ADMIN, 'page_admin'); -$PAGE = page_create_object(PAGE_ADMIN, 0); // there must be any constant id number -$PAGE->set_pagetype('admin-setting-' . $section); -$PAGE->init_extra($section); - if ($PAGE->user_allowed_editing() && $adminediting != -1) { $USER->editing = $adminediting; } - /// print header stuff ------------------------------------------------------------ - if (empty($SITE->fullname)) { - print_header($page->visiblename, $page->visiblename, '', $focus); + print_header($settingspage->visiblename, $settingspage->visiblename, '', $focus); print_simple_box(get_string('configintrosite', 'admin'), 'center', '50%'); if ($errormsg !== '') { @@ -80,11 +73,11 @@ if (empty($SITE->fullname)) { echo '
    '; echo '
    '; - echo ''; + $PAGE->url->hidden_params_out(); echo ''; echo ''; - echo $page->output_html(); + echo $settingspage->output_html(); echo '
    '; @@ -94,12 +87,30 @@ if (empty($SITE->fullname)) { } else { $pageblocks = blocks_setup($PAGE); - $preferred_width_left = bounded_number(BLOCK_L_MIN_WIDTH, blocks_preferred_width($pageblocks[BLOCK_POS_LEFT]), - BLOCK_L_MAX_WIDTH); - $preferred_width_right = bounded_number(BLOCK_R_MIN_WIDTH, blocks_preferred_width($pageblocks[BLOCK_POS_RIGHT]), - BLOCK_R_MAX_WIDTH); + $preferred_width_left = blocks_preferred_width($pageblocks[BLOCK_POS_LEFT]); + $preferred_width_right = blocks_preferred_width($pageblocks[BLOCK_POS_RIGHT]); + + // The search page currently doesn't handle block editing + if ($PAGE->user_allowed_editing()) { + $options = $PAGE->url->params(); + if ($PAGE->user_is_editing()) { + $caption = get_string('blockseditoff'); + $options['adminedit'] = 'off'; + } else { + $caption = get_string('blocksediton'); + $options['adminedit'] = 'on'; + } + $buttons = print_single_button($PAGE->url->out(false), $options, $caption, 'get', '', true); + } + + $visiblepathtosection = array_reverse($settingspage->visiblepath); + $navlinks = array(); + foreach ($visiblepathtosection as $element) { + $navlinks[] = array('name' => $element, 'link' => null, 'type' => 'misc'); + } + $navigation = build_navigation($navlinks); - $PAGE->print_header($focus); + print_header("$SITE->shortname: " . implode(": ",$visiblepathtosection), $SITE->fullname, $navigation, $focus, '', true, $buttons, ''); echo ''; $lt = (empty($THEME->layouttable)) ? array('left', 'middle', 'right') : $THEME->layouttable; @@ -128,12 +139,12 @@ if (empty($SITE->fullname)) { echo ''; echo '
    '; - echo ''; + $PAGE->url->hidden_params_out(); echo ''; echo ''; - print_heading($page->visiblename); + print_heading($settingspage->visiblename); - echo $page->output_html(); + echo $settingspage->output_html(); echo '
    '; diff --git a/blocks/moodleblock.class.php b/blocks/moodleblock.class.php index a92a63d..cecf71f 100644 --- a/blocks/moodleblock.class.php +++ b/blocks/moodleblock.class.php @@ -461,7 +461,9 @@ class block_base { if (($this->instance->pagetype == $PAGE->pagetype) and $this->instance->pageid == $PAGE->id) { $page = $PAGE; } else { - $page = page_create_object($this->instance->pagetype, $this->instance->pageid); + $page = new moodle_page(); + $page->set_pagetype($this->instance->pagetype); + $page->pageid = $this->instance->pageid; } $script = $page->url->out(array('instanceid' => $this->instance->id, 'sesskey' => sesskey())); diff --git a/lib/adminlib.php b/lib/adminlib.php index 5e6e3f0..39d04e5 100644 --- a/lib/adminlib.php +++ b/lib/adminlib.php @@ -3888,7 +3888,6 @@ function admin_externalpage_setup($section, $extrabutton = '', global $CFG, $PAGE, $USER; require_once($CFG->libdir.'/blocklib.php'); - require_once($CFG->dirroot.'/'.$CFG->admin.'/pagelib.php'); if ($site = get_site()) { require_login(); @@ -3897,18 +3896,15 @@ function admin_externalpage_setup($section, $extrabutton = '', die; } - page_map_class(PAGE_ADMIN, 'page_admin'); - $PAGE = page_create_object(PAGE_ADMIN, 0); // there must be any constant id number - $PAGE->set_context(get_context_instance(CONTEXT_SYSTEM)); - // $PAGE->set_extra_button($extrabutton); TODO - $adminroot = admin_get_root(false, false); // settings not required for external pages $extpage = $adminroot->locate($section); + $PAGE->set_context(get_context_instance(CONTEXT_SYSTEM)); + // $PAGE->set_extra_button($extrabutton); TODO + if (!$actualurl) { $actualurl = $extpage->url; } - $PAGE->set_pagetype(null); $PAGE->set_url(str_replace($CFG->wwwroot . '/', '', $actualurl), array_merge($extraurlparams, array('section' => $section))); @@ -3946,14 +3942,37 @@ function admin_externalpage_print_header($focus='') { if (!empty($SITE->fullname) and !empty($SITE->shortname)) { $pageblocks = blocks_setup($PAGE); - $preferred_width_left = bounded_number(BLOCK_L_MIN_WIDTH, - blocks_preferred_width($pageblocks[BLOCK_POS_LEFT]), - BLOCK_L_MAX_WIDTH); - $preferred_width_right = bounded_number(BLOCK_R_MIN_WIDTH, - blocks_preferred_width($pageblocks[BLOCK_POS_RIGHT]), - BLOCK_R_MAX_WIDTH); + $preferred_width_left = blocks_preferred_width($pageblocks[BLOCK_POS_LEFT]); + $preferred_width_right = blocks_preferred_width($pageblocks[BLOCK_POS_RIGHT]); + + $adminroot = admin_get_root(false, false); //settings not required - only pages + + // fetch the path parameter + $section = $PAGE->url->param('section'); + $current = $adminroot->locate($section, true); + $visiblepathtosection = array_reverse($current->visiblepath); + + // The search page currently doesn't handle block editing + if ($PAGE->user_allowed_editing()) { + $options = $PAGE->url->params(); + if ($PAGE->user_is_editing()) { + $caption = get_string('blockseditoff'); + $options['adminedit'] = 'off'; + } else { + $caption = get_string('blocksediton'); + $options['adminedit'] = 'on'; + } + $buttons = print_single_button($PAGE->url->out(false), $options, $caption, 'get', '', true); + } + + $navlinks = array(); + foreach ($visiblepathtosection as $element) { + $navlinks[] = array('name' => $element, 'link' => null, 'type' => 'misc'); + } + $navigation = build_navigation($navlinks); + + print_header("$SITE->shortname: " . implode(": ",$visiblepathtosection), $SITE->fullname, $navigation, $focus, '', true, $buttons, ''); - $PAGE->print_header($focus); echo '
    '; $lt = (empty($THEME->layouttable)) ? array('left', 'middle', 'right') : $THEME->layouttable; @@ -4007,12 +4026,8 @@ function admin_externalpage_print_footer() { if (!empty($SITE->fullname)) { $pageblocks = blocks_setup($PAGE); - $preferred_width_left = bounded_number(BLOCK_L_MIN_WIDTH, - blocks_preferred_width($pageblocks[BLOCK_POS_LEFT]), - BLOCK_L_MAX_WIDTH); - $preferred_width_right = bounded_number(BLOCK_R_MIN_WIDTH, - blocks_preferred_width($pageblocks[BLOCK_POS_RIGHT]), - BLOCK_R_MAX_WIDTH); + $preferred_width_left = blocks_preferred_width($pageblocks[BLOCK_POS_LEFT]); + $preferred_width_right = blocks_preferred_width($pageblocks[BLOCK_POS_RIGHT]); $lt = (empty($THEME->layouttable)) ? array('left', 'middle', 'right') : $THEME->layouttable; foreach ($lt as $column) { diff --git a/lib/pagelib.php b/lib/pagelib.php index e623fed..0fdb40d 100644 --- a/lib/pagelib.php +++ b/lib/pagelib.php @@ -836,6 +836,18 @@ class moodle_page { } /** + * @deprecated since Moodle 2.0 + * @return the 'page id'. This concept no longer exists. + */ + function get_pageid() { + debugging('Call to deprecated method moodle_page::get_pageid(). It should not be necessary any more.', DEBUG_DEVELOPER); + if (!is_null($this->_legacypageobject)) { + return $this->_legacypageobject->get_id(); + } + return 0; + } + + /** * @deprecated since Moodle 2.0 - user $PAGE->cm instead. * @return $this->cm; */ @@ -891,6 +903,9 @@ function page_create_object($type, $id = NULL) { $data->pageid = $id; $classname = page_map_class($type); + if (!$classname) { + return $PAGE; + } $legacypage = new $classname; $legacypage->init_quick($data); @@ -938,10 +953,10 @@ function page_map_class($type, $classname = NULL) { if (!isset($mappings[$type])) { debugging('Page class mapping requested for unknown type: '.$type); - } - - if (empty($classname) && !class_exists($mappings[$type])) { + return null; + } else if (empty($classname) && !class_exists($mappings[$type])) { debugging('Page class mapping for id "'.$type.'" exists but class "'.$mappings[$type].'" is not defined'); + return null; } return $mappings[$type]; diff --git a/lib/upgradelib.php b/lib/upgradelib.php index 47df59a..dcaadc3 100644 --- a/lib/upgradelib.php +++ b/lib/upgradelib.php @@ -575,8 +575,8 @@ function upgrade_plugins_blocks($startcallback, $endcallback) { } } - page_map_class(PAGE_ADMIN, 'page_admin'); - $page = page_create_object(PAGE_ADMIN, 0); // there must be some id number + $page = new moodle_page(); + $page->set_pagetype('admin'); blocks_repopulate_page($page); } } diff --git a/tag/index.php b/tag/index.php index ed30755..19ee4bd 100644 --- a/tag/index.php +++ b/tag/index.php @@ -31,20 +31,29 @@ if (empty($tag)) { redirect($CFG->wwwroot.'/tag/search.php'); } - -//create a new page_tag object, defined in pagelib.php -$PAGE = page_create_object(PAGE_TAG_INDEX, $tag->id); $PAGE->set_url('tag/index.php', array('id' => $tag->id)); +$PAGE->set_subpage($tag->id); $PAGE->set_blocks_editing_capability('moodle/tag:editblocks'); $pageblocks = blocks_setup($PAGE,BLOCKS_PINNED_BOTH); -$PAGE->tag_object = $tag; if (($edit != -1) and $PAGE->user_allowed_editing()) { $USER->editing = $edit; } +$tagname = tag_display_name($tag); + +$navlinks = array(); +$navlinks[] = array('name' => get_string('tags', 'tag'), 'link' => "{$CFG->wwwroot}/tag/search.php", 'type' => ''); +$navlinks[] = array('name' => $tagname, 'link' => '', 'type' => ''); -$PAGE->print_header(); +$navigation = build_navigation($navlinks); +$title = get_string('tag', 'tag') .' - '. $tagname; + +$button = ''; +if ($PAGE->user_allowed_editing() ) { + $button = update_tag_button($tag->id); +} +print_header_simple($title, '', $navigation, '', '', '', $button); // Manage all tags links $systemcontext = get_context_instance(CONTEXT_SYSTEM); diff --git a/tag/pagelib.php b/tag/pagelib.php deleted file mode 100644 index 4dcef9c..0000000 --- a/tag/pagelib.php +++ /dev/null @@ -1,38 +0,0 @@ -libdir.'/pagelib.php'); -require_once('lib.php'); - -define('PAGE_TAG_INDEX', 'tag-index'); -define('TAG_FORMAT', 'tag'); - -class page_tag extends page_base { - - var $tag_object = NULL; - - //----------- printing funtions ----------- - - function print_header() { - - global $USER, $CFG; - - $tagname = tag_display_name($this->tag_object); - - $navlinks = array(); - $navlinks[] = array('name' => get_string('tags', 'tag'), 'link' => "{$CFG->wwwroot}/tag/search.php", 'type' => ''); - $navlinks[] = array('name' => $tagname, 'link' => '', 'type' => ''); - - $navigation = build_navigation($navlinks); - $title = get_string('tag', 'tag') .' - '. $tagname; - - $button = ''; - if( $this->user_allowed_editing() ) { - $button = update_tag_button($this->id); - } - print_header_simple($title, '', $navigation, '', '', '', $button); - } -} - -page_map_class(PAGE_TAG_INDEX, 'page_tag'); - -?> -- 1.5.6.3 From cfcc3698f83d6a4ce2a9cff541f331755c9c9149 Mon Sep 17 00:00:00 2001 From: Tim Hunt Date: Fri, 1 May 2009 18:43:28 +0800 Subject: blocklib: MDL-19010 upgrade database tables ready for now blocks system --- admin/blocks.php | 6 +- admin/replace.php | 2 +- admin/roles/tabs.php | 2 +- admin/settings.php | 1 - backup/backuplib.php | 4 +- blocks/moodleblock.class.php | 16 +- blocks/section_links/block_section_links.php | 2 +- blog/lib.php | 4 +- course/search.php | 2 +- course/view.php | 1 + lib/accesslib.php | 32 +- lib/blocklib.php | 66 +++--- lib/db/install.xml | 59 ++-- lib/db/upgrade.php | 390 ++++++++++++++++++++++++++ lib/moodlelib.php | 6 +- theme/standard/rtl.css | 2 +- theme/standard/styles_color.css | 42 ++-- theme/standard/styles_fonts.css | 18 +- theme/standard/styles_ie6.css | 2 +- theme/standard/styles_layout.css | 50 ++-- 20 files changed, 553 insertions(+), 154 deletions(-) diff --git a/admin/blocks.php b/admin/blocks.php index 99216f8..eccd748 100644 --- a/admin/blocks.php +++ b/admin/blocks.php @@ -83,7 +83,7 @@ } // First delete instances and then block - $instances = $DB->get_records('block_instance', array('blockid'=>$block->id)); + $instances = $DB->get_records('block_instance_old', array('blockid'=>$block->id)); if(!empty($instances)) { foreach($instances as $instance) { blocks_delete_instance($instance); @@ -169,8 +169,8 @@ // MDL-11167, blocks can be placed on mymoodle, or the blogs page // and it should not show up on course search page - $totalcount = $DB->count_records('block_instance', array('blockid'=>$blockid)); - $count = $DB->count_records('block_instance', array('blockid'=>$blockid, 'pagetype'=>'course-view')); + $totalcount = $DB->count_records('block_instance_old', array('blockid'=>$blockid)); + $count = $DB->count_records('block_instance_old', array('blockid'=>$blockid, 'pagetype'=>'course-view')); if ($count>0) { $blocklist = "wwwroot}/course/search.php?blocklist=$blockid&sesskey=".sesskey()."\" "; diff --git a/admin/replace.php b/admin/replace.php index bf54aff..2ee8f6f 100644 --- a/admin/replace.php +++ b/admin/replace.php @@ -43,7 +43,7 @@ print_simple_box_end(); /// Try to replace some well-known serialised contents (html blocks) notify('Replacing in html blocks...'); $sql = "SELECT bi.* - FROM {block_instance} bi + FROM {block_instance_old} bi JOIN {block} b ON b.id = bi.blockid WHERE b.name = 'html'"; if ($instances = $DB->get_records_sql($sql)) { diff --git a/admin/roles/tabs.php b/admin/roles/tabs.php index 86194b8..67de2e9 100755 --- a/admin/roles/tabs.php +++ b/admin/roles/tabs.php @@ -121,7 +121,7 @@ if ($currenttab != 'update') { break; case CONTEXT_BLOCK: - if ($blockinstance = $DB->get_record('block_instance', array('id'=>$context->instanceid))) { + if ($blockinstance = $DB->get_record('block_instance_old', array('oldid'=>$context->instanceid))) { if ($block = $DB->get_record('block', array('id'=>$blockinstance->blockid))) { $blockname = print_context_name($context); diff --git a/admin/settings.php b/admin/settings.php index da6ca83..ae239ed 100644 --- a/admin/settings.php +++ b/admin/settings.php @@ -3,7 +3,6 @@ require_once('../config.php'); require_once($CFG->libdir.'/adminlib.php'); require_once($CFG->libdir.'/blocklib.php'); -require_once($CFG->dirroot.'/'.$CFG->admin.'/pagelib.php'); $section = required_param('section', PARAM_SAFEDIR); $return = optional_param('return','', PARAM_ALPHA); diff --git a/backup/backuplib.php b/backup/backuplib.php index 43234c6..cd05d30 100644 --- a/backup/backuplib.php +++ b/backup/backuplib.php @@ -2815,13 +2815,13 @@ // add all roles assigned at block context if ($courseblocks = $DB->get_records_sql("SELECT * - FROM {block_instance} + FROM {block_instance_old} WHERE pagetype = '".PAGE_COURSE_VIEW."' AND pageid = ?", array($preferences->backup_course))) { foreach ($courseblocks as $courseblock) { - $context = get_context_instance(CONTEXT_BLOCK, $courseblock->id); + $context = get_context_instance(CONTEXT_BLOCK, $courseblock->oldid); $contexts[$context->id] = $context; } } diff --git a/blocks/moodleblock.class.php b/blocks/moodleblock.class.php index cecf71f..9064961 100644 --- a/blocks/moodleblock.class.php +++ b/blocks/moodleblock.class.php @@ -728,11 +728,13 @@ class block_base { $data = $data; $this->config = $data; - $table = 'block_instance'; + $table = 'block_instance_old'; + $field = 'oldid'; if (!empty($pinned)) { - $table = 'block_pinned'; + $table = 'block_pinned_old'; + $field = 'id'; } - return $DB->set_field($table, 'configdata', base64_encode(serialize($data)), array('id'=>$this->instance->id)); + return $DB->set_field($table, 'configdata', base64_encode(serialize($data)), array($field => $this->instance->id)); } /** @@ -743,11 +745,13 @@ class block_base { function instance_config_commit($pinned=false) { global $DB; - $table = 'block_instance'; + $table = 'block_instance_old'; + $field = 'oldid'; if (!empty($pinned)) { - $table = 'block_pinned'; + $table = 'block_pinned_old'; + $field = 'id'; } - return $DB->set_field($table, 'configdata', base64_encode(serialize($this->config)), array('id'=>$this->instance->id)); + return $DB->set_field($table, 'configdata', base64_encode(serialize($this->config)), array($field => $this->instance->id)); } /** diff --git a/blocks/section_links/block_section_links.php b/blocks/section_links/block_section_links.php index 7201d94..7117ad9 100644 --- a/blocks/section_links/block_section_links.php +++ b/blocks/section_links/block_section_links.php @@ -24,7 +24,7 @@ class block_section_links extends block_base { } function applicable_formats() { - return (array('course-view-weeks' => true, 'course-view-topics' => true, 'course-edit-weeks' => true, 'course-edit-topics' => true)); + return (array('course-view-weeks' => true, 'course-view-topics' => true)); } function get_content() { diff --git a/blog/lib.php b/blog/lib.php index 8f0fbc1..d23cd34 100755 --- a/blog/lib.php +++ b/blog/lib.php @@ -39,12 +39,12 @@ $newblock->position = 'r'; $newblock->weight = 0; $newblock->visible = 1; - $DB->insert_record('block_instance', $newblock); + $DB->insert_record('block_instance_old', $newblock); // add blog_tags menu $newblock -> blockid = $tagsblock->id; $newblock -> weight = 1; - $DB->insert_record('block_instance', $newblock); + $DB->insert_record('block_instance_old', $newblock); // finally we set the page size pref set_user_preference('blogpagesize', 10); diff --git a/course/search.php b/course/search.php index a15762c..99e149a 100644 --- a/course/search.php +++ b/course/search.php @@ -117,7 +117,7 @@ // get list of courses containing blocks if required if (!empty($blocklist) and confirm_sesskey()) { $blockid = $blocklist; - if (!$blocks = $DB->get_records('block_instance', array('blockid'=>$blockid))) { + if (!$blocks = $DB->get_records('block_instance_old', array('blockid'=>$blockid))) { print_error('blockcannotread', '', '', $blockid); } diff --git a/course/view.php b/course/view.php index d68aff4..274a6ee 100644 --- a/course/view.php +++ b/course/view.php @@ -93,6 +93,7 @@ $PAGE = page_create_object(PAGE_COURSE_VIEW, $course->id); $PAGE->set_url('course/view.php', array('id' => $course->id)); + $PAGE->set_pagetype('course-view-' . $course->format); $PAGE->set_other_editing_capability('moodle/course:manageactivities'); $pageblocks = blocks_setup($PAGE, BLOCKS_PINNED_BOTH); diff --git a/lib/accesslib.php b/lib/accesslib.php index 21125fa..3a8ac81 100755 --- a/lib/accesslib.php +++ b/lib/accesslib.php @@ -2095,14 +2095,14 @@ function create_context($contextlevel, $instanceid) { // Only non-pinned & course-page based $sql = "SELECT ctx.path, ctx.depth FROM {context} ctx - JOIN {block_instance} bi + JOIN {block_instance_old} bi ON (bi.pageid=ctx.instanceid AND ctx.contextlevel=".CONTEXT_COURSE.") - WHERE bi.id=? AND bi.pagetype='course-view'"; + WHERE bi.oldid=? AND bi.pagetype='course-view'"; $params = array($instanceid); if ($p = $DB->get_record_sql($sql, $params)) { $basepath = $p->path; $basedepth = $p->depth; - } else if ($bi = $DB->get_record('block_instance', array('id'=>$instanceid))) { + } else if ($bi = $DB->get_record('block_instance_old', array('oldid'=>$instanceid))) { if ($bi->pagetype != 'course-view') { // ok - not a course block } else if ($parent = get_context_instance(CONTEXT_COURSE, $bi->pageid)) { @@ -2296,8 +2296,8 @@ function create_contexts($contextlevel=null, $buildpaths=true) { if (empty($contextlevel) or $contextlevel == CONTEXT_BLOCK) { $sql = "INSERT INTO {context} (contextlevel, instanceid) - SELECT ".CONTEXT_BLOCK.", bi.id - FROM {block_instance} bi + SELECT ".CONTEXT_BLOCK.", bi.oldid + FROM {block_instance_old} bi WHERE NOT EXISTS (SELECT 'x' FROM {context} cx WHERE bi.id = cx.instanceid AND cx.contextlevel=".CONTEXT_BLOCK.")"; @@ -2360,8 +2360,8 @@ function cleanup_contexts() { SELECT c.contextlevel, c.instanceid FROM {context} c - LEFT OUTER JOIN {block_instance} t - ON c.instanceid = t.id + LEFT OUTER JOIN {block_instance_old} t + ON c.instanceid = t.oldid WHERE t.id IS NULL AND c.contextlevel = ".CONTEXT_BLOCK." UNION SELECT c.contextlevel, @@ -2416,8 +2416,8 @@ function preload_course_contexts($courseid) { UNION ALL SELECT x.instanceid, x.id, x.contextlevel, x.path, x.depth - FROM {block_instance} bi - JOIN {context} x ON x.instanceid=bi.id + FROM {block_instance_old} bi + JOIN {context} x ON x.instanceid=bi.oldid WHERE bi.pageid=? AND bi.pagetype='course-view' AND x.contextlevel=".CONTEXT_BLOCK." @@ -3443,7 +3443,7 @@ function print_context_name($context, $withprefix = true, $short = false) { break; case CONTEXT_BLOCK: // not necessarily 1 to 1 to course - if ($blockinstance = $DB->get_record('block_instance', array('id'=>$context->instanceid))) { + if ($blockinstance = $DB->get_record('block_instance_old', array('oldid'=>$context->instanceid))) { if ($block = $DB->get_record('block', array('id'=>$blockinstance->blockid))) { global $CFG; require_once("$CFG->dirroot/blocks/moodleblock.class.php"); @@ -3625,7 +3625,7 @@ function fetch_context_capabilities($context) { break; case CONTEXT_BLOCK: // block caps - $cb = $DB->get_record('block_instance', array('id'=>$context->instanceid)); + $cb = $DB->get_record('block_instance_old', array('oldid'=>$context->instanceid)); $block = $DB->get_record('block', array('id'=>$cb->blockid)); $extra = ""; @@ -3772,7 +3772,7 @@ function get_sorted_contexts($select, $params = array()) { LEFT JOIN {course_categories} cat ON ctx.contextlevel = 40 AND cat.id = ctx.instanceid LEFT JOIN {course} c ON ctx.contextlevel = 50 AND c.id = ctx.instanceid LEFT JOIN {course_modules} cm ON ctx.contextlevel = 70 AND cm.id = ctx.instanceid - LEFT JOIN {block_instance} bi ON ctx.contextlevel = 80 AND bi.id = ctx.instanceid + LEFT JOIN {block_instance_old} bi ON ctx.contextlevel = 80 AND bi.oldid = ctx.instanceid $select ORDER BY ctx.contextlevel, bi.position, COALESCE(cat.sortorder, c.sortorder, cm.section, bi.weight), u.lastname, u.firstname, cm.id ", $params); @@ -3837,7 +3837,7 @@ function get_child_contexts($context) { UNION SELECT ctx.* FROM {context} ctx - JOIN {block_pinned} b ON (ctx.instanceid=b.blockid AND ctx.contextlevel=".CONTEXT_BLOCK.") + JOIN {block_pinned_old} b ON (ctx.instanceid=b.blockid AND ctx.contextlevel=".CONTEXT_BLOCK.") WHERE b.pagetype='course-view'"; $params = array("{$context->path}/%", $context->instanceid); $records = $DB->get_recordset_sql($sql, $params); @@ -5863,7 +5863,7 @@ function build_context_path($force=false) { $sql = "INSERT INTO {context_temp} (id, path, depth) SELECT ctx.id, ".$DB->sql_concat('pctx.path', "'/'", 'ctx.id').", pctx.depth+1 FROM {context} ctx - JOIN {block_instance} bi ON ctx.instanceid = bi.id + JOIN {block_instance_old} bi ON ctx.instanceid = bi.oldid JOIN {context} pctx ON bi.pageid=pctx.instanceid WHERE ctx.contextlevel=".CONTEXT_BLOCK." AND pctx.contextlevel=".CONTEXT_COURSE." @@ -5882,8 +5882,8 @@ function build_context_path($force=false) { SET depth=2, path=".$DB->sql_concat("'$base/'", 'id')." WHERE contextlevel=".CONTEXT_BLOCK." AND EXISTS (SELECT 'x' - FROM {block_instance} bi - WHERE bi.id = {context}.instanceid + FROM {block_instance_old} bi + WHERE bi.oldid = {context}.instanceid AND bi.pagetype!='course-view') $emptyclause "; $DB->execute($sql); diff --git a/lib/blocklib.php b/lib/blocklib.php index 282e670..78234b9 100644 --- a/lib/blocklib.php +++ b/lib/blocklib.php @@ -164,19 +164,19 @@ function blocks_delete_instance($instance,$pinned=false) { } if (!empty($pinned)) { - $DB->delete_records('block_pinned', array('id'=>$instance->id)); + $DB->delete_records('block_pinned_old', array('id'=>$instance->id)); // And now, decrement the weight of all blocks after this one - $sql = "UPDATE {block_pinned} + $sql = "UPDATE {block_pinned_old} SET weight = weight - 1 WHERE pagetype = ? AND position = ? AND weight > ?"; $params = array($instance->pagetype, $instance->position, $instance->weight); $DB->execute($sql, $params); } else { // Now kill the db record; - $DB->delete_records('block_instance', array('id'=>$instance->id)); + $DB->delete_records('block_instance_old', array('oldid'=>$instance->id)); delete_context(CONTEXT_BLOCK, $instance->id); // And now, decrement the weight of all blocks after this one - $sql = "UPDATE {block_instance} + $sql = "UPDATE {block_instance_old} SET weight = weight - 1 WHERE pagetype = ? AND pageid = ? AND position = ? AND weight > ?"; @@ -514,9 +514,9 @@ function blocks_execute_action($page, &$pageblocks, $blockaction, $instanceorid, } $instance->visible = ($instance->visible) ? 0 : 1; if (!empty($pinned)) { - $DB->update_record('block_pinned', $instance); + $DB->update_record('block_pinned_old', $instance); } else { - $DB->update_record('block_instance', $instance); + $DB->update_record('block_instance_old', $instance); } break; case 'delete': @@ -549,16 +549,16 @@ function blocks_execute_action($page, &$pageblocks, $blockaction, $instanceorid, if(!empty($other)) { ++$other->weight; if (!empty($pinned)) { - $DB->update_record('block_pinned', $other); + $DB->update_record('block_pinned_old', $other); } else { - $DB->update_record('block_instance', $other); + $DB->update_record('block_instance_old', $other); } } --$instance->weight; if (!empty($pinned)) { - $DB->update_record('block_pinned', $instance); + $DB->update_record('block_pinned_old', $instance); } else { - $DB->update_record('block_instance', $instance); + $DB->update_record('block_instance_old', $instance); } } break; @@ -586,16 +586,16 @@ function blocks_execute_action($page, &$pageblocks, $blockaction, $instanceorid, if(!empty($other)) { --$other->weight; if (!empty($pinned)) { - $DB->update_record('block_pinned', $other); + $DB->update_record('block_pinned_old', $other); } else { - $DB->update_record('block_instance', $other); + $DB->update_record('block_instance_old', $other); } } ++$instance->weight; if (!empty($pinned)) { - $DB->update_record('block_pinned', $instance); + $DB->update_record('block_pinned_old', $instance); } else { - $DB->update_record('block_instance', $instance); + $DB->update_record('block_instance_old', $instance); } } break; @@ -643,13 +643,13 @@ function blocks_execute_action($page, &$pageblocks, $blockaction, $instanceorid, $newpos = $page->blocks->get_default_position(); if (!empty($pinned)) { $sql = "SELECT 1, MAX(weight) + 1 AS nextfree - FROM {block_pinned} + FROM {block_pinned_old} WHERE pagetype = ? AND position = ?"; $params = array($page->pagetype, $newpos); } else { $sql = "SELECT 1, MAX(weight) + 1 AS nextfree - FROM {block_instance} + FROM {block_instance_old} WHERE pageid = ? AND pagetype = ? AND position = ?"; $params = array($page->get_id(), $page->pagetype, $newpos); } @@ -666,9 +666,9 @@ function blocks_execute_action($page, &$pageblocks, $blockaction, $instanceorid, $newinstance->visible = 1; $newinstance->configdata = ''; if (!empty($pinned)) { - $newinstance->id = $DB->insert_record('block_pinned', $newinstance); + $newinstance->id = $DB->insert_record('block_pinned_old', $newinstance); } else { - $newinstance->id = $DB->insert_record('block_instance', $newinstance); + $newinstance->id = $DB->insert_record('block_instance_old', $newinstance); } // If the new instance was created, allow it to do additional setup @@ -719,13 +719,13 @@ function blocks_execute_repositioning(&$instance, $newpos, $newweight, $pinned=f // Close the weight gap we 'll leave behind if (!empty($pinned)) { - $sql = "UPDATE {block_instance} + $sql = "UPDATE {block_instance_old} SET weight = weight - 1 WHERE pagetype = ? AND position = ? AND weight > ?"; $params = array($instance->pagetype, $instance->position, $instance->weight); } else { - $sql = "UPDATE {block_instance} + $sql = "UPDATE {block_instance_old} SET weight = weight - 1 WHERE pagetype = ? AND pageid = ? AND position = ? AND weight > ?"; @@ -737,9 +737,9 @@ function blocks_execute_repositioning(&$instance, $newpos, $newweight, $pinned=f $instance->weight = $newweight; if (!empty($pinned)) { - $DB->update_record('block_pinned', $instance); + $DB->update_record('block_pinned_old', $instance); } else { - $DB->update_record('block_instance', $instance); + $DB->update_record('block_instance_old', $instance); } } @@ -773,12 +773,12 @@ function blocks_move_block($page, &$instance, $destpos, $destweight=NULL, $pinne // First we close the gap that will be left behind when we take out the // block from it's current column. if ($pinned) { - $closegapsql = "UPDATE {block_instance} + $closegapsql = "UPDATE {block_instance_old} SET weight = weight - 1 WHERE weight > ? AND position = ? AND pagetype = ?"; $params = array($instance->weight, $instance->position, $instance->pagetype); } else { - $closegapsql = "UPDATE {block_instance} + $closegapsql = "UPDATE {block_instance_old} SET weight = weight - 1 WHERE weight > ? AND position = ? AND pagetype = ? AND pageid = ?"; @@ -790,12 +790,12 @@ function blocks_move_block($page, &$instance, $destpos, $destweight=NULL, $pinne // Now let's make space for the block being moved. if ($pinned) { - $opengapsql = "UPDATE {block_instance} + $opengapsql = "UPDATE {block_instance_old} SET weight = weight + 1 WHERE weight >= ? AND position = ? AND pagetype = ?"; $params = array($destweight, $destpos, $instance->pagetype); } else { - $opengapsql = "UPDATE {block_instance} + $opengapsql = "UPDATE {block_instance_old} SET weight = weight + 1 WHERE weight >= ? AND position = ? AND pagetype = ? AND pageid = ?"; @@ -810,9 +810,9 @@ function blocks_move_block($page, &$instance, $destpos, $destweight=NULL, $pinne $instance->weight = $destweight; if ($pinned) { - $table = 'block_pinned'; + $table = 'block_pinned_old'; } else { - $table = 'block_instance'; + $table = 'block_instance_old'; } return $DB->update_record($table, $instance); } @@ -834,7 +834,7 @@ function blocks_get_pinned($page) { $select .= " AND visible = 1"; } - $blocks = $DB->get_records_select('block_pinned', $select, $params, 'position, weight'); + $blocks = $DB->get_records_select('block_pinned_old', $select, $params, 'position, weight'); $positions = $page->blocks->get_positions(); $arr = array(); @@ -895,7 +895,7 @@ function blocks_get_by_page_pinned($page) { function blocks_get_by_page($page) { global $DB; - $blocks = $DB->get_records_select('block_instance', "pageid = ? AND ? LIKE (" . $DB->sql_concat('pagetype', "'%'") . ")", + $blocks = $DB->get_records_select('block_instance_old', "pageid = ? AND ? LIKE (" . $DB->sql_concat('pagetype', "'%'") . ")", array($page->get_id(), $page->pagetype), 'position, weight'); $positions = $page->blocks->get_positions(); @@ -954,12 +954,12 @@ function blocks_print_adminblock(&$page, &$pageblocks) { */ function blocks_delete_all_on_page($pagetype, $pageid) { global $DB; - if ($instances = $DB->get_records('block_instance', array('pageid' => $pageid, 'pagetype' => $pagetype))) { + if ($instances = $DB->get_records('block_instance_old', array('pageid' => $pageid, 'pagetype' => $pagetype))) { foreach ($instances as $instance) { delete_context(CONTEXT_BLOCK, $instance->id); // Ingore any failures here. } } - return $DB->delete_records('block_instance', array('pageid' => $pageid, 'pagetype' => $pagetype)); + return $DB->delete_records('block_instance_old', array('pageid' => $pageid, 'pagetype' => $pagetype)); } // Dispite what this function is called, it seems to be mostly used to populate @@ -1017,7 +1017,7 @@ function blocks_repopulate_page($page) { if(!empty($newinstance->blockid)) { // Only add block if it was recognized - $DB->insert_record('block_instance', $newinstance); + $DB->insert_record('block_instance_old', $newinstance); ++$weight; } } diff --git a/lib/db/install.xml b/lib/db/install.xml index 5d2a59d..c7ced3c 100644 --- a/lib/db/install.xml +++ b/lib/db/install.xml @@ -1,5 +1,5 @@ - @@ -2156,7 +2156,7 @@
    - +
    @@ -2169,44 +2169,49 @@ + + +
    - +
    - - - - - - - + + + + + + + + + - - + + - +
    - +
    - - - - - - - - + + + + + + + + - - + + + - - +
    - + \ No newline at end of file diff --git a/lib/db/upgrade.php b/lib/db/upgrade.php index 937cae7..d6731e3 100644 --- a/lib/db/upgrade.php +++ b/lib/db/upgrade.php @@ -1711,6 +1711,396 @@ WHERE gradeitemid IS NOT NULL AND grademax IS NOT NULL"); upgrade_main_savepoint($result, 2009042800); } + if ($result && $oldversion < 2009042801) { + + /// Define table block_instance to be renamed to block_instance_old + $table = new xmldb_table('block_instance'); + + /// Launch rename table for block_instance + $dbman->rename_table($table, 'block_instances'); + + /// Main savepoint reached + upgrade_main_savepoint($result, 2009042801); + } + + if ($result && $oldversion < 2009042802) { + + /// Define table block_instance to be renamed to block_instance_old + $table = new xmldb_table('block_pinned'); + + /// Launch rename table for block_instance + $dbman->rename_table($table, 'block_pinned_old'); + + /// Main savepoint reached + upgrade_main_savepoint($result, 2009042802); + } + + if ($result && $oldversion < 2009042803) { + + /// Define table block_instance_old to be created + $table = new xmldb_table('block_instance_old'); + + /// Adding fields to table block_instance_old + $table->add_field('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null); + $table->add_field('oldid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null); + $table->add_field('blockid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0'); + $table->add_field('pageid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, '0'); + $table->add_field('pagetype', XMLDB_TYPE_CHAR, '20', null, XMLDB_NOTNULL, null, null, null, null); + $table->add_field('region', XMLDB_TYPE_CHAR, '10', null, XMLDB_NOTNULL, null, null, null, null); + $table->add_field('weight', XMLDB_TYPE_INTEGER, '3', null, XMLDB_NOTNULL, null, null, null, '0'); + $table->add_field('visible', XMLDB_TYPE_INTEGER, '1', null, XMLDB_NOTNULL, null, null, null, '0'); + $table->add_field('configdata', XMLDB_TYPE_TEXT, 'small', null, null, null, null, null, null); + + /// Adding keys to table block_instance_old + $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); + $table->add_key('blockid', XMLDB_KEY_FOREIGN, array('blockid'), 'block', array('id')); + + /// Adding indexes to table block_instance_old + $table->add_index('pageid', XMLDB_INDEX_NOTUNIQUE, array('pageid')); + $table->add_index('pagetype', XMLDB_INDEX_NOTUNIQUE, array('pagetype')); + + /// Conditionally launch create table for block_instance_old + if (!$dbman->table_exists($table)) { + $dbman->create_table($table); + } + + /// Main savepoint reached + upgrade_main_savepoint($result, 2009042803); + } + + if ($result && $oldversion < 2009042804) { + /// Copy current blocks data from block_instances to block_instance_old + $DB->execute('INSERT INTO {block_instance_old} (oldid, blockid, pageid, pagetype, position, weight, visible, configdata) + SELECT id, blockid, pageid, pagetype, position, weight, visible, configdata FROM {block_instances} ORDER BY id'); + + upgrade_main_savepoint($result, 2009042804); + } + + if ($result && $oldversion < 2009042805) { + + /// Define field multiple to be dropped from block + $table = new xmldb_table('block'); + $field = new xmldb_field('multiple'); + + /// Conditionally launch drop field multiple + if ($dbman->field_exists($table, $field)) { + $dbman->drop_field($table, $field); + } + + /// Main savepoint reached + upgrade_main_savepoint($result, 2009042805); + } + + if ($result && $oldversion < 2009042806) { + $table = new xmldb_table('block_instances'); + + /// Rename field weight on table block_instances to defaultweight + $field = new xmldb_field('weight', XMLDB_TYPE_INTEGER, '3', null, XMLDB_NOTNULL, null, null, null, '0', 'position'); + $dbman->rename_field($table, $field, 'defaultweight'); + + /// Rename field position on table block_instances to defaultregion + $field = new xmldb_field('position', XMLDB_TYPE_CHAR, '10', null, XMLDB_NOTNULL, null, null, null, null, 'pagetype'); + $dbman->rename_field($table, $field, 'defaultregion'); + + /// Main savepoint reached + upgrade_main_savepoint($result, 2009042806); + } + + if ($result && $oldversion < 2009042807) { + + /// Changing precision of field defaultregion on table block_instances to (16) + $table = new xmldb_table('block_instances'); + $field = new xmldb_field('defaultregion', XMLDB_TYPE_CHAR, '16', null, XMLDB_NOTNULL, null, null, null, null, 'subpagepattern'); + + /// Launch change of precision for field defaultregion + $dbman->change_field_precision($table, $field); + + /// Main savepoint reached + upgrade_main_savepoint($result, 2009042807); + } + + if ($result && $oldversion < 2009042808) { + /// Change regions to the new notation + $DB->set_field('block_instances', 'defaultregion', 'side-pre', array('defaultregion' => 'l')); + $DB->set_field('block_instances', 'defaultregion', 'side-post', array('defaultregion' => 'r')); + $DB->set_field('block_instances', 'defaultregion', 'course-view-top', array('defaultregion' => 'c')); + // This third one is a custom value from contrib/patches/center_blocks_position_patch and the + // flex page course format. Hopefully this new value is an adequate alternative. + + /// Main savepoint reached + upgrade_main_savepoint($result, 2009042808); + } + + if ($result && $oldversion < 2009042809) { + + /// Define key blockname (unique) to be added to block + $table = new xmldb_table('block'); + $key = new xmldb_key('blockname', XMLDB_KEY_UNIQUE, array('name')); + + /// Launch add key blockname + $dbman->add_key($table, $key); + + /// Main savepoint reached + upgrade_main_savepoint($result, 2009042809); + } + + if ($result && $oldversion < 2009042810) { + $table = new xmldb_table('block_instances'); + + /// Define field blockname to be added to block_instances + $field = new xmldb_field('blockname', XMLDB_TYPE_CHAR, '40', null, null, null, null, null, null, 'blockid'); + if (!$dbman->field_exists($table, $field)) { + $dbman->add_field($table, $field); + } + + /// Define field contextid to be added to block_instances + $field = new xmldb_field('contextid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, null, null, 'blockname'); + if (!$dbman->field_exists($table, $field)) { + $dbman->add_field($table, $field); + } + + /// Define field showinsubcontexts to be added to block_instances + $field = new xmldb_field('showinsubcontexts', XMLDB_TYPE_INTEGER, '4', null, null, null, null, null, null, 'contextid'); + if (!$dbman->field_exists($table, $field)) { + $dbman->add_field($table, $field); + } + + /// Define field subpagepattern to be added to block_instances + $field = new xmldb_field('subpagepattern', XMLDB_TYPE_CHAR, '16', null, null, null, null, null, null, 'pagetype'); + if (!$dbman->field_exists($table, $field)) { + $dbman->add_field($table, $field); + } + + /// Main savepoint reached + upgrade_main_savepoint($result, 2009042810); + } + + if ($result && $oldversion < 2009042811) { + $table = new xmldb_table('block_instances'); + + /// Fill in blockname from blockid + $DB->execute("UPDATE {block_instances} SET blockname = (SELECT name FROM {block} WHERE id = blockid)"); + + /// Set showinsubcontexts = 0 for all rows. + $DB->execute("UPDATE {block_instances} SET showinsubcontexts = 0"); + + /// Main savepoint reached + upgrade_main_savepoint($result, 2009042811); + } + + if ($result && $oldversion < 2009042812) { + + /// Rename field pagetype on table block_instances to pagetypepattern + $table = new xmldb_table('block_instances'); + $field = new xmldb_field('pagetype', XMLDB_TYPE_CHAR, '20', null, XMLDB_NOTNULL, null, null, null, null, 'pageid'); + + /// Launch rename field pagetype + $dbman->rename_field($table, $field, 'pagetypepattern'); + + /// Main savepoint reached + upgrade_main_savepoint($result, 2009042812); + } + + if ($result && $oldversion < 2009042813) { + /// fill in contextid and subpage, and update pagetypepattern from pagetype and pageid + + /// site-index + $frontpagecontext = get_context_instance(CONTEXT_COURSE, SITEID); + $DB->execute("UPDATE {block_instances} SET (contextid, pagetypepattern, subpagepattern) = + (" . $frontpagecontext->id . ", 'site-index', NULL) WHERE pagetypepattern = 'site-index'"); + + /// course-view + $DB->execute("UPDATE {block_instances} SET (contextid, pagetypepattern, subpagepattern) = + (( + SELECT {context}.id + FROM {context} + JOIN {course} ON instanceid = {course}.id AND contextlevel = " . CONTEXT_COURSE . " + WHERE {course}.id = pageid + ), 'course-view-*', NULL) WHERE pagetypepattern = 'course-view'"); + + /// admin + $syscontext = get_context_instance(CONTEXT_SYSTEM); + $DB->execute("UPDATE {block_instances} SET (contextid, pagetypepattern, subpagepattern) = + (" . $syscontext->id . ", 'admin-*', NULL) WHERE pagetypepattern = 'admin'"); + + /// my-index + $DB->execute("UPDATE {block_instances} SET (contextid, pagetypepattern, subpagepattern) = + (( + SELECT {context}.id + FROM {context} + JOIN {user} ON instanceid = {user}.id AND contextlevel = " . CONTEXT_USER . " + WHERE {user}.id = pageid + ), 'my-index', NULL) WHERE pagetypepattern = 'my-index'"); + + /// tag-index + $DB->execute("UPDATE {block_instances} SET (contextid, pagetypepattern, subpagepattern) = + (" . $syscontext->id . ", 'tag-index', pageid) WHERE pagetypepattern = 'tag-index'"); + + /// blog-view + $DB->execute("UPDATE {block_instances} SET (contextid, pagetypepattern, subpagepattern) = + (( + SELECT {context}.id + FROM {context} + JOIN {user} ON instanceid = {user}.id AND contextlevel = " . CONTEXT_USER . " + WHERE {user}.id = pageid + ), 'blog-index', NULL) WHERE pagetypepattern = 'blog-view'"); + + /// mod-xxx-view + $moduleswithblocks = array('chat', 'data', 'lesson', 'quiz', 'dimdim', 'game', 'wiki', 'oublog'); + foreach ($moduleswithblocks as $modname) { + if (!$dbman->table_exists($modname)) { + continue; + } + $DB->execute("UPDATE {block_instances} SET (contextid, pagetypepattern, subpagepattern) = + (( + SELECT {context}.id + FROM {context} + JOIN {course_modules} ON instanceid = {course_modules}.id AND contextlevel = " . CONTEXT_MODULE . " + JOIN {modules} ON {modules}.id = {course_modules}.module AND {modules}.name = '$modname' + JOIN {{$modname}} ON {course_modules}.instance = {{$modname}}.id + WHERE {{$modname}}.id = pageid + ), 'blog-index', NULL) WHERE pagetypepattern = 'blog-view'"); + } + + /// Main savepoint reached + upgrade_main_savepoint($result, 2009042813); + } + + if ($result && $oldversion < 2009042814) { + /// fill in any missing contextids with a dummy value, so we can add the not-null constraint. + $DB->execute("UPDATE {block_instances} SET contextid = -1 WHERE contextid IS NULL"); + + /// Main savepoint reached + upgrade_main_savepoint($result, 2009042814); + } + + if ($result && $oldversion < 2009042815) { + $table = new xmldb_table('block_instances'); + + /// Changing nullability of field blockname on table block_instances to not null + $field = new xmldb_field('blockname', XMLDB_TYPE_CHAR, '40', null, XMLDB_NOTNULL, null, null, null, null, 'id'); + $dbman->change_field_notnull($table, $field); + + /// Changing nullability of field contextid on table block_instances to not null + $field = new xmldb_field('contextid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null, 'blockname'); + $dbman->change_field_notnull($table, $field); + + /// Changing nullability of field showinsubcontexts on table block_instances to not null + $field = new xmldb_field('showinsubcontexts', XMLDB_TYPE_INTEGER, '4', null, XMLDB_NOTNULL, null, null, null, null, 'contextid'); + $dbman->change_field_notnull($table, $field); + + /// Main savepoint reached + upgrade_main_savepoint($result, 2009042815); + } + + if ($result && $oldversion < 2009042816) { + /// Add exiting sticky blocks. + $blocks = $DB->get_records('block'); + $syscontext = get_context_instance(CONTEXT_SYSTEM); + $newregions = array( + 'l' => 'side-pre', + 'r' => 'side-post', + 'c' => 'course-view-top', + ); + $stickyblocks = $DB->get_recordset('block_pinned_old'); + foreach ($stickyblocks as $stickyblock) { + $newblock = stdClass; + $newblock->blockname = $blocks[$stickyblock]->name; + $newblock->contextid = $syscontext->id; + $newblock->showinsubcontexts = 1; + switch ($stickyblock->pagetype) { + case 'course-view': + $newblock->pagetypepattern = 'course-view-*'; + break; + default: + $newblock->pagetypepattern = $stickyblock->pagetype; + } + $newblock->defaultregion = $newregions[$stickyblock->position]; + $newblock->defaultweight = $stickyblock->weight; + $newblock->configdata = $stickyblock->configdata; + $DB->insert_record('block_instances', $newblock); + } + + /// Main savepoint reached + upgrade_main_savepoint($result, 2009042816); + } + + if ($result && $oldversion < 2009042817) { + + /// Define table block_positions to be created + $table = new xmldb_table('block_positions'); + + /// Adding fields to table block_positions + $table->add_field('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null); + $table->add_field('blockinstanceid', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null, null, null); + $table->add_field('contextid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null); + $table->add_field('pagetype', XMLDB_TYPE_CHAR, '64', null, XMLDB_NOTNULL, null, null, null, null); + $table->add_field('subpage', XMLDB_TYPE_CHAR, '16', null, XMLDB_NOTNULL, null, null, null, null); + $table->add_field('visible', XMLDB_TYPE_INTEGER, '4', null, XMLDB_NOTNULL, null, null, null, '1'); + $table->add_field('region', XMLDB_TYPE_CHAR, '16', null, XMLDB_NOTNULL, null, null, null, null); + $table->add_field('weight', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null, null, null); + + /// Adding keys to table block_positions + $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); + $table->add_key('blockinstanceid', XMLDB_KEY_FOREIGN, array('blockinstanceid'), 'block_instances', array('id')); + $table->add_key('contextid', XMLDB_KEY_FOREIGN, array('contextid'), 'context', array('id')); + + /// Adding indexes to table block_positions + $table->add_index('blockinstanceid-contextid-pagetype-subpage', XMLDB_INDEX_UNIQUE, array('blockinstanceid', 'contextid', 'pagetype', 'subpage')); + + /// Conditionally launch create table for block_positions + if (!$dbman->table_exists($table)) { + $dbman->create_table($table); + } + + /// Main savepoint reached + upgrade_main_savepoint($result, 2009042817); + } + + if ($result && $oldversion < 2009042818) { + /// And block instances with visible = 0, copy that information to block_positions + $DB->execute("INSERT INTO {block_positions} (blockinstanceid, contextid, pagetype, subpage, visible, region, weight) + SELECT id, contextid, + CASE WHEN pagetypepattern = 'course-view-*' THEN + (SELECT " . $DB->sql_concat("'course-view-'", 'format') . " + FROM {course} + JOIN {context} ON {course}.id = {context}.instanceid + WHERE {context}.id = contextid) + ELSE pagetypepattern END, + CASE WHEN subpagepattern IS NULL THEN '' + ELSE subpagepattern END, + 0, defaultregion, defaultweight + FROM {block_instances} WHERE visible = 0 AND pagetypepattern <> 'admin-*'"); + + /// Main savepoint reached + upgrade_main_savepoint($result, 2009042818); + } + + if ($result && $oldversion < 2009042819) { + $table = new xmldb_table('block_instances'); + + /// Define field blockid to be dropped from block_instances + $field = new xmldb_field('blockid'); + if ($dbman->field_exists($table, $field)) { + $dbman->drop_field($table, $field); + } + + /// Define field pageid to be dropped from block_instances + $field = new xmldb_field('pageid'); + if ($dbman->field_exists($table, $field)) { + $dbman->drop_field($table, $field); + } + + /// Define field visible to be dropped from block_instances + $field = new xmldb_field('visible'); + if ($dbman->field_exists($table, $field)) { + $dbman->drop_field($table, $field); + } + + /// Main savepoint reached + upgrade_main_savepoint($result, 2009042819); + } + if ($result && $oldversion < 2009043000) { unset_config('grade_report_showgroups'); upgrade_main_savepoint($result, 2009043000); diff --git a/lib/moodlelib.php b/lib/moodlelib.php index 05bc958..5e63ebc 100644 --- a/lib/moodlelib.php +++ b/lib/moodlelib.php @@ -3603,12 +3603,12 @@ function remove_course_contents($courseid, $showfeedback=true) { /// Delete course blocks if ($blocks = $DB->get_records_sql("SELECT * - FROM {block_instance} + FROM {block_instance_old} WHERE pagetype = '".PAGE_COURSE_VIEW."' AND pageid = ?", array($course->id))) { - if ($DB->delete_records('block_instance', array('pagetype'=>PAGE_COURSE_VIEW, 'pageid'=>$course->id))) { + if ($DB->delete_records('block_instance_old', array('pagetype'=>PAGE_COURSE_VIEW, 'pageid'=>$course->id))) { if ($showfeedback) { - notify($strdeleted .' block_instance'); + notify($strdeleted .' block_instance_old'); } require_once($CFG->libdir.'/blocklib.php'); diff --git a/theme/standard/rtl.css b/theme/standard/rtl.css index a934bd4..7aa38a1 100755 --- a/theme/standard/rtl.css +++ b/theme/standard/rtl.css @@ -534,7 +534,7 @@ form.mform .fitemtitle { margin-left: 0px; } -#course-view .section td.right { +.course-view .section td.right { border-left-width: 1px; border-left-style: solid; border-right-width: 0px; diff --git a/theme/standard/styles_color.css b/theme/standard/styles_color.css index 20e7ee7..311683d 100644 --- a/theme/standard/styles_color.css +++ b/theme/standard/styles_color.css @@ -653,55 +653,55 @@ table.minicalendar { border-color:#DDDDDD; } -#course-view .weeks .section, -#course-view .topics .section, -#course-view .section td { +.course-view .weeks .section, +.course-view .topics .section, +.course-view .section td { border-color:#DDDDDD; } /* .content should match the body background, sides are white. */ -#course-view .weeks .content , -#course-view .topics .content, -#course-view .weeks .section, -#course-view .topics .section { +.course-view .weeks .content , +.course-view .topics .content, +.course-view .weeks .section, +.course-view .topics .section { background: #FAFAFA; } -#course-view .section td.side { +.course-view .section td.side { background: #FFFFFF; } -#course-view .section .side { +.course-view .section .side { } -#course-view .section .left { +.course-view .section .left { } -#course-view .section .right { +.course-view .section .right { } -#course-view .weeks .current, -#course-view .topics .current, -#course-view .current td.side { +.course-view .weeks .current, +.course-view .topics .current, +.course-view .current td.side { background: #FFD991; } -#course-view .weeks .hidden, -#course-view .topics .hidden, -#course-view .hidden td.side { +.course-view .weeks .hidden, +.course-view .topics .hidden, +.course-view .hidden td.side { background: #DDDDDD; } -#course-view .section .spacer { +.course-view .section .spacer { } -#course-view .section .weekdates { +.course-view .section .weekdates { color: #777777; } -#course-view .weeks .weekdates , -#course-view .topics .weekdates { +.course-view .weeks .weekdates , +.course-view .topics .weekdates { color: #333333; } diff --git a/theme/standard/styles_fonts.css b/theme/standard/styles_fonts.css index e7eb85a..6bf707e 100644 --- a/theme/standard/styles_fonts.css +++ b/theme/standard/styles_fonts.css @@ -140,7 +140,7 @@ h4 { } #site-index .subscribelink, -#course-view .subscribelink { +.course-view .subscribelink { font-size: 0.8em; } @@ -487,26 +487,26 @@ table.minicalendar { /*** *** Course ***/ -#course-view .section { +.course-view .section { font-size:0.95em; line-height:1.2em; } -#course-view .section .activity { +.course-view .section .activity { padding:0.2em 0; } -#course-view .section .activity a { +.course-view .section .activity a { line-height:1em; } -#course-view .section .weekdates { +.course-view .section .weekdates { margin: 0; font-weight: normal; font-size: 1em; } -#course-view .section .left { +.course-view .section .left { font-weight:bold; } @@ -569,15 +569,15 @@ h2.headingblock { color: #666666; } -#course-view .availabilityinfo { +.course-view .availabilityinfo { font-size:0.85em; color:#aaa; } -#course-view .availabilityinfo strong { +.course-view .availabilityinfo strong { font-weight:normal; color:black; } -#course-view .dimmed_text img { +.course-view .dimmed_text img { opacity:0.3; filter: alpha(opacity='30'); } diff --git a/theme/standard/styles_ie6.css b/theme/standard/styles_ie6.css index 1d38d3f..366d71f 100755 --- a/theme/standard/styles_ie6.css +++ b/theme/standard/styles_ie6.css @@ -63,7 +63,7 @@ form.mform textarea { display:inline-block; padding-left:2px; } -#course-view li.activity { +.course-view li.activity { height:0; } #mod-quiz-review #middle-column { diff --git a/theme/standard/styles_layout.css b/theme/standard/styles_layout.css index 4e4a66b..b8515af 100644 --- a/theme/standard/styles_layout.css +++ b/theme/standard/styles_layout.css @@ -2061,11 +2061,11 @@ border-width:0px; text-align:center; } -#course-view .section td { +.course-view .section td { vertical-align:top; } -#course-view .section td.content { +.course-view .section td.content { padding:5px; border-style:solid; border-width:1px; @@ -2073,44 +2073,44 @@ border-width:0px; border-right:0px; } -#course-view .section td.side { +.course-view .section td.side { padding:5px; border-style:solid; border-width:1px; } -#course-view .section td.left { +.course-view .section td.left { border-right:0px; text-align:center; width: 1.5em; } -#course-view .section td.right { +.course-view .section td.right { border-left:0px; text-align:center; width: 1.5em; } -#course-view .current .side { +.course-view .current .side { } -#course-view .section .spacer { +.course-view .section .spacer { height:0.5em; } -#course-view .section .weekdates { +.course-view .section .weekdates { } -#course-view li.activity { +.course-view li.activity { margin-right:20px; /* Space allowed for completion icons if enabled */ position:relative; } -.dir-rtl#course-view li.activity { +.dir-rtl.course-view li.activity { margin-right:0px; margin-left:20px; } -#course-view li.activity form.togglecompletion, -#course-view li.activity span.autocompletion { +.course-view li.activity form.togglecompletion, +.course-view li.activity span.autocompletion { display:inline; position:absolute; right:-20px; @@ -2118,15 +2118,15 @@ border-width:0px; z-index:10; padding:0.2em 0; } -.dir-rtl#course-view li.activity form.togglecompletion, -.dir-rtl#course-view li.activity span.autocompletion { +.dir-rtl.course-view li.activity form.togglecompletion, +.dir-rtl.course-view li.activity span.autocompletion { right:auto; left:-20px; } -#course-view li.activity form.togglecompletion div { +.course-view li.activity form.togglecompletion div { display:inline; } -#course-view .completion-saved-display { +.course-view .completion-saved-display { position:absolute; top:0; left:0; border:1px solid black; @@ -2134,12 +2134,12 @@ border-width:0px; background:white; font-size:0.85em; } -#course-view form.togglecompletion img.iconhelp, -#course-view span.autocompletion img.iconhelp { +.course-view form.togglecompletion img.iconhelp, +.course-view span.autocompletion img.iconhelp { vertical-align:top; } -#course-view ul.section, +.course-view ul.section, #site-index ul.section { margin: 0; padding: 0; @@ -2158,13 +2158,13 @@ border-width:0px; margin-top: 8px; } -/*#course-view ul.section li.activity ul li, +/*.course-view ul.section li.activity ul li, #site-index ul.section li.activity ul li { list-style: disc; }*/ /*Accessibility: No-tables course format. */ -#course-view ul.weeks , #course-view ul.topics{ +.course-view ul.weeks , .course-view ul.topics{ margin: 0; padding: 0; list-style: none; @@ -2245,11 +2245,11 @@ border-width:0px; width:80px; } -body#course-view .unread { +body.course-view .unread { margin-left: 3em; } -body#course-view .sideblock.drag .header { +body.course-view .sideblock.drag .header { cursor: move; } @@ -2291,12 +2291,12 @@ body#course-user .section h2 { } #site-index .subscribelink, -#course-view .subscribelink { +.course-view .subscribelink { text-align:right; } body#site-index .headingblock, -body#course-view .headingblock { +body.course-view .headingblock { margin-bottom: 9px; } -- 1.5.6.3 From 9567e40b2a71c9decf63fdf53fae3c0bc2d746d3 Mon Sep 17 00:00:00 2001 From: Tim Hunt Date: Thu, 30 Apr 2009 12:34:52 +0800 Subject: blocklib: MDL-19010 always include blocklib in setup.php, stip includes elsewhere --- admin/block.php | 1 - admin/blocks.php | 1 - admin/cliupgrade.php | 2 -- admin/cron.php | 1 - admin/settings.php | 1 - admin/stickyblocks.php | 1 - auth/cas/cas_ldap_sync_users.php | 1 - auth/db/auth_db_sync_users.php | 1 - auth/ldap/auth_ldap_sync_users.php | 1 - backup/backup.php | 1 - backup/restore.php | 1 - backup/try.php | 1 - blog/header.php | 2 -- blog/index.php | 1 - blog/lib.php | 2 -- course/edit.php | 1 - course/pending.php | 2 -- course/rest.php | 3 --- course/view.php | 2 -- enrol/database/enrol_database_sync.php | 3 +-- enrol/imsenterprise/enrol.php | 2 -- index.php | 1 - lib/accesslib.php | 2 -- lib/adminlib.php | 2 -- lib/blocklib.php | 1 - lib/moodlelib.php | 1 - lib/setup.php | 3 +++ lib/simpletest/testpagelib_moodlepage.php | 3 +-- lib/upgradelib.php | 1 - lib/weblib.php | 5 ----- mod/chat/view.php | 1 - mod/data/templates.php | 1 - mod/data/view.php | 1 - mod/lesson/action/continue.php | 1 - mod/lesson/view.php | 1 - mod/quiz/view.php | 1 - mod/resource/lib.php | 3 --- my/index.php | 1 - 38 files changed, 5 insertions(+), 55 deletions(-) diff --git a/admin/block.php b/admin/block.php index da61afc..4d42f74 100644 --- a/admin/block.php +++ b/admin/block.php @@ -4,7 +4,6 @@ require_once('../config.php'); require_once($CFG->libdir.'/adminlib.php'); - require_once($CFG->libdir.'/blocklib.php'); $blockid = required_param('block', PARAM_INT); diff --git a/admin/blocks.php b/admin/blocks.php index eccd748..196d838 100644 --- a/admin/blocks.php +++ b/admin/blocks.php @@ -4,7 +4,6 @@ require_once('../config.php'); require_once($CFG->libdir.'/adminlib.php'); - require_once($CFG->libdir.'/blocklib.php'); require_once($CFG->libdir.'/tablelib.php'); admin_externalpage_setup('manageblocks'); diff --git a/admin/cliupgrade.php b/admin/cliupgrade.php index 49de84a..f56d5b2 100644 --- a/admin/cliupgrade.php +++ b/admin/cliupgrade.php @@ -992,7 +992,6 @@ if ( file_exists(dirname(dirname(__FILE__)) . '/config.php')) { /// Check all blocks and load (or upgrade them if necessary) /// first old *.php update and then the new upgrade.php script - require_once("$CFG->dirroot/lib/blocklib.php"); if ( $verbose > CLI_NO ) { print_heading(get_string('upgradingblocksplugin','install'),'',1); } @@ -1053,7 +1052,6 @@ if ( file_exists(dirname(dirname(__FILE__)) . '/config.php')) { /// Set up the site if (! $site = get_site()) { // We are about to create the site "course" - require_once($CFG->libdir.'/blocklib.php'); if ( ( $interactive == CLI_FULL ) || ($interactive == CLI_SEMI && ( (!isset($INSTALL['sitefullname'])) || (!isset($INSTALL['siteshortname'])) || (!isset($INSTALL['sitesummary'])) || (!isset($INSTALL['sitenewsitems'])) )) ) { console_write('siteinfo'); diff --git a/admin/cron.php b/admin/cron.php index a06ad3d..fcc2c00 100644 --- a/admin/cron.php +++ b/admin/cron.php @@ -430,7 +430,6 @@ include_once("$CFG->dirroot/backup/backup_scheduled.php"); include_once("$CFG->dirroot/backup/backuplib.php"); include_once("$CFG->dirroot/backup/lib.php"); - require_once ("$CFG->libdir/blocklib.php"); mtrace("Running backups if required..."); if (! schedule_backup_cron()) { diff --git a/admin/settings.php b/admin/settings.php index ae239ed..c823812 100644 --- a/admin/settings.php +++ b/admin/settings.php @@ -2,7 +2,6 @@ require_once('../config.php'); require_once($CFG->libdir.'/adminlib.php'); -require_once($CFG->libdir.'/blocklib.php'); $section = required_param('section', PARAM_SAFEDIR); $return = optional_param('return','', PARAM_ALPHA); diff --git a/admin/stickyblocks.php b/admin/stickyblocks.php index 8b9eaf0..644f13f 100644 --- a/admin/stickyblocks.php +++ b/admin/stickyblocks.php @@ -3,7 +3,6 @@ require_once('../config.php'); require_once($CFG->dirroot.'/my/pagelib.php'); require_once($CFG->dirroot.'/lib/pagelib.php'); - require_once($CFG->dirroot.'/lib/blocklib.php'); $pt = optional_param('pt', null, PARAM_SAFEDIR); //alhanumeric and - diff --git a/auth/cas/cas_ldap_sync_users.php b/auth/cas/cas_ldap_sync_users.php index 9abc5fc..15454bc 100644 --- a/auth/cas/cas_ldap_sync_users.php +++ b/auth/cas/cas_ldap_sync_users.php @@ -32,7 +32,6 @@ define('NO_MOODLE_COOKIES', true); require_once(dirname(dirname(dirname(__FILE__))).'/config.php'); // global moodle config file. require_once($CFG->dirroot.'/course/lib.php'); -require_once($CFG->dirroot.'/lib/blocklib.php'); require_once($CFG->dirroot.'/mod/resource/lib.php'); require_once($CFG->dirroot.'/mod/forum/lib.php'); require_once($CFG->dirroot.'/lib/moodlelib.php'); diff --git a/auth/db/auth_db_sync_users.php b/auth/db/auth_db_sync_users.php index 8ed5de0..d6eb5e7 100644 --- a/auth/db/auth_db_sync_users.php +++ b/auth/db/auth_db_sync_users.php @@ -31,7 +31,6 @@ define('NO_MOODLE_COOKIES', true); require_once(dirname(dirname(dirname(__FILE__))).'/config.php'); // global moodle config file. -require_once($CFG->libdir.'/blocklib.php'); require_once($CFG->dirroot.'/course/lib.php'); require_once($CFG->dirroot.'/mod/resource/lib.php'); require_once($CFG->dirroot.'/mod/forum/lib.php'); diff --git a/auth/ldap/auth_ldap_sync_users.php b/auth/ldap/auth_ldap_sync_users.php index 528d355..22a38d5 100755 --- a/auth/ldap/auth_ldap_sync_users.php +++ b/auth/ldap/auth_ldap_sync_users.php @@ -30,7 +30,6 @@ define('NO_MOODLE_COOKIES', true); require_once(dirname(dirname(dirname(__FILE__))).'/config.php'); // global moodle config file. -require_once($CFG->libdir.'/blocklib.php'); require_once($CFG->dirroot.'/course/lib.php'); require_once($CFG->dirroot.'/mod/resource/lib.php'); require_once($CFG->dirroot.'/mod/forum/lib.php'); diff --git a/backup/backup.php b/backup/backup.php index 3c969b4..ba02d5c 100644 --- a/backup/backup.php +++ b/backup/backup.php @@ -6,7 +6,6 @@ require_once ("../config.php"); require_once ("lib.php"); require_once ("backuplib.php"); - require_once ("$CFG->libdir/blocklib.php"); require_once ("$CFG->libdir/adminlib.php"); $id = optional_param( 'id' ); // course id diff --git a/backup/restore.php b/backup/restore.php index 19a3024..5639776 100644 --- a/backup/restore.php +++ b/backup/restore.php @@ -10,7 +10,6 @@ require_once("lib.php"); require_once("restorelib.php"); require_once("bb/restore_bb.php"); - require_once("$CFG->libdir/blocklib.php"); require_once("$CFG->libdir/wiki_to_markdown.php" ); require_once("$CFG->libdir/adminlib.php"); diff --git a/backup/try.php b/backup/try.php index 98caa18..46b5f82 100644 --- a/backup/try.php +++ b/backup/try.php @@ -3,7 +3,6 @@ require_once ("backup_scheduled.php"); require_once ("lib.php"); require_once ("backuplib.php"); - require_once ("$CFG->libdir/blocklib.php"); require_login(); diff --git a/blog/header.php b/blog/header.php index bf663f1..6674a01 100755 --- a/blog/header.php +++ b/blog/header.php @@ -3,9 +3,7 @@ /// Sets up blocks and navigation for index.php require_once($CFG->dirroot .'/blog/lib.php'); -require_once($CFG->libdir .'/pagelib.php'); require_once($CFG->dirroot .'/blog/blogpage.php'); -require_once($CFG->libdir .'/blocklib.php'); require_once($CFG->dirroot .'/course/lib.php'); $blockaction = optional_param('blockaction','', PARAM_ALPHA); diff --git a/blog/index.php b/blog/index.php index f06fadf..a9f8b3a 100755 --- a/blog/index.php +++ b/blog/index.php @@ -8,7 +8,6 @@ require_once('../config.php'); require_once($CFG->dirroot .'/blog/lib.php'); -require_once($CFG->libdir .'/blocklib.php'); $id = optional_param('id', 0, PARAM_INT); $start = optional_param('formstart', 0, PARAM_INT); diff --git a/blog/lib.php b/blog/lib.php index d23cd34..5c31eef 100755 --- a/blog/lib.php +++ b/blog/lib.php @@ -3,8 +3,6 @@ /** * Library of functions and constants for blog */ - require_once($CFG->libdir .'/blocklib.php'); - require_once($CFG->libdir .'/pagelib.php'); require_once($CFG->dirroot .'/blog/rsslib.php'); require_once($CFG->dirroot .'/blog/blogpage.php'); require_once($CFG->dirroot.'/tag/lib.php'); diff --git a/course/edit.php b/course/edit.php index 6961566..d680a13 100644 --- a/course/edit.php +++ b/course/edit.php @@ -3,7 +3,6 @@ require_once('../config.php'); require_once($CFG->dirroot.'/enrol/enrol.class.php'); - require_once($CFG->libdir.'/blocklib.php'); require_once('lib.php'); require_once('edit_form.php'); diff --git a/course/pending.php b/course/pending.php index 2f0ef7c..8da7765 100644 --- a/course/pending.php +++ b/course/pending.php @@ -31,8 +31,6 @@ *//** */ require_once(dirname(__FILE__) . '/../config.php'); - require_once($CFG->libdir . '/pagelib.php'); - require_once($CFG->libdir . '/blocklib.php'); require_once($CFG->libdir . '/adminlib.php'); require_once($CFG->dirroot . '/course/lib.php'); require_once($CFG->dirroot . '/course/request_form.php'); diff --git a/course/rest.php b/course/rest.php index e2b7985..5e803eb 100644 --- a/course/rest.php +++ b/course/rest.php @@ -3,9 +3,6 @@ require_once('../config.php'); require_once($CFG->dirroot.'/course/lib.php'); -require_once($CFG->libdir .'/pagelib.php'); -require_once($CFG->libdir .'/blocklib.php'); - // Initialise ALL the incoming parameters here, up front. $courseid = required_param('courseId', PARAM_INT); diff --git a/course/view.php b/course/view.php index 274a6ee..d34ab66 100644 --- a/course/view.php +++ b/course/view.php @@ -4,8 +4,6 @@ require_once('../config.php'); require_once('lib.php'); - require_once($CFG->libdir.'/blocklib.php'); - require_once($CFG->libdir.'/ajax/ajaxlib.php'); require_once($CFG->dirroot.'/mod/forum/lib.php'); $id = optional_param('id', 0, PARAM_INT); diff --git a/enrol/database/enrol_database_sync.php b/enrol/database/enrol_database_sync.php index f8efcf0..df599c8 100644 --- a/enrol/database/enrol_database_sync.php +++ b/enrol/database/enrol_database_sync.php @@ -9,8 +9,7 @@ require_once(dirname(dirname(dirname(__FILE__))).'/config.php'); // global moodle config file. require_once($CFG->dirroot . '/course/lib.php'); - require_once($CFG->dirroot . '/lib/blocklib.php'); - require_once($CFG->dirroot . "/enrol/database/enrol.php"); + require_once($CFG->dirroot . '/enrol/database/enrol.php'); // ensure errors are well explained $CFG->debug=E_ALL; diff --git a/enrol/imsenterprise/enrol.php b/enrol/imsenterprise/enrol.php index 325814f..4277b3b 100644 --- a/enrol/imsenterprise/enrol.php +++ b/enrol/imsenterprise/enrol.php @@ -4,9 +4,7 @@ * @license http://www.gnu.org/copyleft/gpl.html GNU Public License * @package enrol_imsenterprise */ -require_once("$CFG->libdir/blocklib.php"); require_once($CFG->dirroot.'/group/lib.php'); -require_once($CFG->libdir.'/eventslib.php'); // The following flags are set in the configuration // $CFG->enrol_imsfilelocation: where is the file we are looking for? diff --git a/index.php b/index.php index 277c102..fde77f3 100644 --- a/index.php +++ b/index.php @@ -32,7 +32,6 @@ require_once('config.php'); require_once($CFG->dirroot .'/course/lib.php'); - require_once($CFG->libdir .'/blocklib.php'); require_once($CFG->libdir .'/filelib.php'); // Bounds for block widths diff --git a/lib/accesslib.php b/lib/accesslib.php index 3a8ac81..36750ed 100755 --- a/lib/accesslib.php +++ b/lib/accesslib.php @@ -129,8 +129,6 @@ * @package roles */ -require_once $CFG->dirroot.'/lib/blocklib.php'; - // permission definitions define('CAP_INHERIT', 0); define('CAP_ALLOW', 1); diff --git a/lib/adminlib.php b/lib/adminlib.php index 39d04e5..8debb66 100644 --- a/lib/adminlib.php +++ b/lib/adminlib.php @@ -3885,9 +3885,7 @@ class admin_setting_manageportfolio extends admin_setting { */ function admin_externalpage_setup($section, $extrabutton = '', $extraurlparams = array(), $actualurl = '') { - global $CFG, $PAGE, $USER; - require_once($CFG->libdir.'/blocklib.php'); if ($site = get_site()) { require_login(); diff --git a/lib/blocklib.php b/lib/blocklib.php index 78234b9..cf8120b 100644 --- a/lib/blocklib.php +++ b/lib/blocklib.php @@ -44,7 +44,6 @@ define('BLOCKS_PINNED_FALSE',1); define('BLOCKS_PINNED_BOTH',2); require_once($CFG->libdir.'/pagelib.php'); -require_once($CFG->dirroot.'/course/lib.php'); // needed to solve all those: Call to undefined function: print_recent_activity() when adding Recent Activity //This function retrieves a method-defined property of a class WITHOUT instantiating an object function block_method_result($blockname, $method, $param = NULL) { diff --git a/lib/moodlelib.php b/lib/moodlelib.php index 5e63ebc..872124f 100644 --- a/lib/moodlelib.php +++ b/lib/moodlelib.php @@ -3611,7 +3611,6 @@ function remove_course_contents($courseid, $showfeedback=true) { notify($strdeleted .' block_instance_old'); } - require_once($CFG->libdir.'/blocklib.php'); foreach ($blocks as $block) { /// Delete any associated contexts for this block delete_context(CONTEXT_BLOCK, $block->id); diff --git a/lib/setup.php b/lib/setup.php index 5f0c5a4..63790b7 100644 --- a/lib/setup.php +++ b/lib/setup.php @@ -171,12 +171,15 @@ global $SCRIPT; /// Load up standard libraries require_once($CFG->libdir .'/textlib.class.php'); // Functions to handle multibyte strings + require_once($CFG->libdir .'/filterlib.php'); // Functions for filtering test as it is output + require_once($CFG->libdir .'/ajax/ajaxlib.php'); // Functions for managing our use of JavaScript and YUI require_once($CFG->libdir .'/weblib.php'); // Functions for producing HTML require_once($CFG->libdir .'/dmllib.php'); // Database access require_once($CFG->libdir .'/datalib.php'); // Legacy lib with a big-mix of functions. require_once($CFG->libdir .'/accesslib.php'); // Access control functions require_once($CFG->libdir .'/deprecatedlib.php'); // Deprecated functions included for backward compatibility require_once($CFG->libdir .'/moodlelib.php'); // Other general-purpose functions + require_once($CFG->libdir .'/blocklib.php'); // Library for controlling blocks require_once($CFG->libdir .'/eventslib.php'); // Events functions require_once($CFG->libdir .'/grouplib.php'); // Groups functions require_once($CFG->libdir .'/sessionlib.php'); // All session and cookie related stuff diff --git a/lib/simpletest/testpagelib_moodlepage.php b/lib/simpletest/testpagelib_moodlepage.php index 4c69a8b..b06cdbb 100644 --- a/lib/simpletest/testpagelib_moodlepage.php +++ b/lib/simpletest/testpagelib_moodlepage.php @@ -24,8 +24,7 @@ /////////////////////////////////////////////////////////////////////////// /** - * Tests for the parts of ../filterlib.php that handle creating filter objects, - * and using them to filter strings. + * Tests for the moodle_page class in ../pagelib.php. * * @license http://www.gnu.org/copyleft/gpl.html GNU Public License * @package moodlecore diff --git a/lib/upgradelib.php b/lib/upgradelib.php index dcaadc3..6a6f5e2 100644 --- a/lib/upgradelib.php +++ b/lib/upgradelib.php @@ -443,7 +443,6 @@ function upgrade_plugins_modules($startcallback, $endcallback) { function upgrade_plugins_blocks($startcallback, $endcallback) { global $CFG, $DB; - require_once($CFG->libdir.'/blocklib.php'); require_once($CFG->dirroot.'/blocks/moodleblock.class.php'); $blocktitles = array(); // we do not want duplicate titles diff --git a/lib/weblib.php b/lib/weblib.php index 6137cfe..dcad335 100644 --- a/lib/weblib.php +++ b/lib/weblib.php @@ -38,11 +38,6 @@ * @package moodlecore */ -/// We are going to uses filterlib functions here -require_once("$CFG->libdir/filterlib.php"); - -require_once("$CFG->libdir/ajax/ajaxlib.php"); - /// Constants /// Define text formatting types ... eventually we can add Wiki, BBcode etc diff --git a/mod/chat/view.php b/mod/chat/view.php index 49f265d..4833757 100644 --- a/mod/chat/view.php +++ b/mod/chat/view.php @@ -4,7 +4,6 @@ require_once('../../config.php'); require_once('lib.php'); - require_once($CFG->libdir.'/blocklib.php'); require_once('pagelib.php'); $id = optional_param('id', 0, PARAM_INT); diff --git a/mod/data/templates.php b/mod/data/templates.php index 767ba3d..c7a8d2f 100755 --- a/mod/data/templates.php +++ b/mod/data/templates.php @@ -24,7 +24,6 @@ require_once('../../config.php'); require_once('lib.php'); - require_once($CFG->libdir.'/blocklib.php'); $id = optional_param('id', 0, PARAM_INT); // course module id $d = optional_param('d', 0, PARAM_INT); // database id diff --git a/mod/data/view.php b/mod/data/view.php index 112a91c..85e3d25 100755 --- a/mod/data/view.php +++ b/mod/data/view.php @@ -24,7 +24,6 @@ require_once('../../config.php'); require_once('lib.php'); - require_once($CFG->libdir.'/blocklib.php'); require_once("$CFG->libdir/rsslib.php"); require_once('pagelib.php'); diff --git a/mod/lesson/action/continue.php b/mod/lesson/action/continue.php index 68fab67..098d65a 100644 --- a/mod/lesson/action/continue.php +++ b/mod/lesson/action/continue.php @@ -9,7 +9,6 @@ confirm_sesskey(); require_once($CFG->dirroot.'/mod/lesson/pagelib.php'); - require_once($CFG->libdir.'/blocklib.php'); // left menu code // check to see if the user can see the left menu diff --git a/mod/lesson/view.php b/mod/lesson/view.php index 4303fa5..e506815 100644 --- a/mod/lesson/view.php +++ b/mod/lesson/view.php @@ -11,7 +11,6 @@ require_once($CFG->dirroot.'/mod/lesson/locallib.php'); require_once($CFG->dirroot.'/mod/lesson/lib.php'); require_once($CFG->dirroot.'/mod/lesson/pagelib.php'); - require_once($CFG->libdir.'/blocklib.php'); $id = required_param('id', PARAM_INT); // Course Module ID $pageid = optional_param('pageid', NULL, PARAM_INT); // Lesson Page ID diff --git a/mod/quiz/view.php b/mod/quiz/view.php index f0223bc..e69c36b 100644 --- a/mod/quiz/view.php +++ b/mod/quiz/view.php @@ -3,7 +3,6 @@ /// This page prints a particular instance of quiz require_once(dirname(__FILE__) . '/../../config.php'); - require_once($CFG->libdir.'/blocklib.php'); require_once($CFG->libdir.'/gradelib.php'); require_once($CFG->dirroot.'/mod/quiz/locallib.php'); require_once($CFG->dirroot.'/mod/quiz/pagelib.php'); diff --git a/mod/resource/lib.php b/mod/resource/lib.php index a8ec4a9..b18ba14 100644 --- a/mod/resource/lib.php +++ b/mod/resource/lib.php @@ -81,11 +81,8 @@ class resource_base { * Display the resource with the course blocks. */ function display_course_blocks_start() { - global $CFG, $USER, $THEME; - require_once($CFG->libdir.'/blocklib.php'); - require_once($CFG->libdir.'/pagelib.php'); require_once($CFG->dirroot.'/course/lib.php'); //required by some blocks $PAGE = page_create_object(PAGE_COURSE_VIEW, $this->course->id); diff --git a/my/index.php b/my/index.php index 61d8c38..7880632 100644 --- a/my/index.php +++ b/my/index.php @@ -3,7 +3,6 @@ // this is the 'my moodle' page require_once('../config.php'); - require_once($CFG->libdir.'/blocklib.php'); require_once($CFG->dirroot.'/course/lib.php'); require_once('pagelib.php'); -- 1.5.6.3 From f430aeb665b0cbfa9bf429ca2441ab6b66d48a2b Mon Sep 17 00:00:00 2001 From: Tim Hunt Date: Thu, 30 Apr 2009 14:35:28 +0800 Subject: moodle_page: MDL-12212 clarify some comments --- lib/simpletest/testpagelib_moodlepage.php | 4 +++- 1 files changed, 3 insertions(+), 1 deletions(-) diff --git a/lib/simpletest/testpagelib_moodlepage.php b/lib/simpletest/testpagelib_moodlepage.php index b06cdbb..86d9677 100644 --- a/lib/simpletest/testpagelib_moodlepage.php +++ b/lib/simpletest/testpagelib_moodlepage.php @@ -35,7 +35,9 @@ if (!defined('MOODLE_INTERNAL')) { } require_once($CFG->libdir . '/pagelib.php'); +require_once($CFG->libdir . '/blocklib.php'); +/** Test-specific subclass to make some protected things public. */ class testable_moodle_page extends moodle_page { public function initialise_default_pagetype($script = null) { parent::initialise_default_pagetype($script); @@ -49,7 +51,7 @@ class testable_moodle_page extends moodle_page { } /** - * Test functions that affect filter_active table with contextid = $syscontextid. + * Test functions that don't need to touch the database. */ class moodle_page_test extends UnitTestCase { protected $testpage; -- 1.5.6.3 From 374dcebc9fb4fa14075f63d33bac3eaa1540b2f0 Mon Sep 17 00:00:00 2001 From: Tim Hunt Date: Thu, 30 Apr 2009 15:51:55 +0800 Subject: blocklib: MDL-19010 start of block_manager - get and set regions --- config-dist.php | 7 ++ lib/blocklib.php | 113 +++++++++++++++++++++- lib/pagelib.php | 31 +++---- lib/setup.php | 7 +- lib/simpletest/testblocklib_blockmanager.php | 130 ++++++++++++++++++++++++++ 5 files changed, 264 insertions(+), 24 deletions(-) create mode 100644 lib/simpletest/testblocklib_blockmanager.php diff --git a/config-dist.php b/config-dist.php index 6f2c092..8e66e42 100644 --- a/config-dist.php +++ b/config-dist.php @@ -167,6 +167,13 @@ $CFG->admin = 'admin'; // These blocks are used when no other default setting is found. // $CFG->defaultblocks = 'participants,activity_modules,search_forums,admin,course_list:news_items,calendar_upcoming,recent_activity'; // +// You can specify a different class to be created for the $PAGE global, and to +// compute which blocks appear on each page. However, I cannot think of any good +// reason why you would need to change that. It just felt wrong to hard-code the +// the class name. You are stronly advised not to use these to settings unless +// you are absolutely sure you know what you are doing. +// $CFG->moodlepageclass = 'moodle_page'; +// $CFG->blockmanagerclass = 'block_manager'; // // Seconds for files to remain in caches. Decrease this if you are worried // about students being served outdated versions of uploaded files. diff --git a/lib/blocklib.php b/lib/blocklib.php index cf8120b..13e01ad 100644 --- a/lib/blocklib.php +++ b/lib/blocklib.php @@ -45,6 +45,109 @@ define('BLOCKS_PINNED_BOTH',2); require_once($CFG->libdir.'/pagelib.php'); +/** + * This class keeps track of the block that should appear on a moodle_page. + * The page to work with as passed to the constructor. + * The only fields of moodle_page that is uses are ->context, ->pagetype and + * ->subpage, so instead of passing a full moodle_page object, you may also + * pass a stdClass object with those three fields. These field values are read + * only at the point that the load_blocks() method is called. It is the caller's + * responsibility to ensure that those fields do not subsequently change. + */ +class block_manager { + /**#@+ Tracks the where we are in the generation of the page. */ + const STATE_BLOCKS_NOT_LOADED = 0; + const STATE_BLOCKS_LOADED = 1; + /**#@-*/ + +/// Field declarations ========================================================= + + protected $loaded = self::STATE_BLOCKS_NOT_LOADED; + + protected $page; + + protected $regions = array(); + + protected $defaultregion; + +/// 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 classe + * and http://en.wikipedia.org/wiki/Duck_typing) + */ + public function __construct($page) { + $this->page = $page; + } + +/// Getter methods ============================================================= + + /** + * @return array the internal names of the regions on this page where block may appear. + */ + public function get_regions() { + return array_keys($this->regions); + } + + /** + * @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() { + return $this->defaultregion; + } + +/// Setter methods ============================================================= + + /** + * @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. + */ + public function add_region($region) { + $this->check_not_yet_loaded(); + $this->regions[$region] = 1; + } + + /** + * @param array $regions this utility method calls add_region for each array element. + */ + public function add_regions($regions) { + foreach ($regions as $region) { + $this->add_region($region); + } + } + + /** + * @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 (!array_key_exists($defaultregion, $this->regions)) { + throw new coding_exception('Trying to set an unknown block region as the default.'); + } + $this->defaultregion = $defaultregion; + } + +/// Inner workings ============================================================= + + protected function check_not_yet_loaded() { + if ($this->loaded) { + throw new coding_exception('block_manager has already loaded the blocks, to it is too late to change things that might affect which blocks are visible.'); + } + } + + protected function mark_loaded() { + $this->loaded = self::STATE_BLOCKS_LOADED; + } +} + //This function retrieves a method-defined property of a class WITHOUT instantiating an object function block_method_result($blockname, $method, $param = NULL) { if(!block_load_class($blockname)) { @@ -329,7 +432,7 @@ function blocks_print_group(&$page, &$pageblocks, $position) { $managecourseblocks = has_capability('moodle/site:manageblocks', $coursecontext); $editmymoodle = $page->pagetype == PAGE_MY_MOODLE && has_capability('moodle/my:manageblocks', $coursecontext); - if ($page->blocks->get_default_position() == $position && + if ($page->blocks->get_default_region() == $position && $page->user_is_editing() && ($managecourseblocks || $editmymoodle || $myownblogpage || defined('ADMIN_STICKYBLOCKS'))) { @@ -639,7 +742,7 @@ function blocks_execute_action($page, &$pageblocks, $blockaction, $instanceorid, break; } - $newpos = $page->blocks->get_default_position(); + $newpos = $page->blocks->get_default_region(); if (!empty($pinned)) { $sql = "SELECT 1, MAX(weight) + 1 AS nextfree FROM {block_pinned_old} @@ -835,7 +938,7 @@ function blocks_get_pinned($page) { $blocks = $DB->get_records_select('block_pinned_old', $select, $params, 'position, weight'); - $positions = $page->blocks->get_positions(); + $positions = $page->blocks->get_regions(); $arr = array(); foreach($positions as $key => $position) { @@ -897,7 +1000,7 @@ function blocks_get_by_page($page) { $blocks = $DB->get_records_select('block_instance_old', "pageid = ? AND ? LIKE (" . $DB->sql_concat('pagetype', "'%'") . ")", array($page->get_id(), $page->pagetype), 'position, weight'); - $positions = $page->blocks->get_positions(); + $positions = $page->blocks->get_regions(); $arr = array(); foreach($positions as $key => $position) { $arr[$position] = array(); @@ -986,7 +1089,7 @@ function blocks_repopulate_page($page) { $blocknames = $page->blocks_get_default(); } - $positions = $page->blocks->get_positions(); + $positions = $page->blocks->get_regions(); $posblocks = explode(':', $blocknames); // Now one array holds the names of the positions, and the other one holds the blocks diff --git a/lib/pagelib.php b/lib/pagelib.php index 0fdb40d..c2551e9 100644 --- a/lib/pagelib.php +++ b/lib/pagelib.php @@ -268,8 +268,14 @@ class moodle_page { * @return blocks_manager the blocks manager object for this page. */ public function get_blocks() { + global $CFG; if (is_null($this->_blocks)) { - $this->_blocks = new blocks_manager(); + if (!empty($CFG->blockmanagerclass)) { + $classname = $CFG->blockmanagerclass; + } else { + $classname = 'block_manager'; + } + $this->_blocks = new $classname($this); } return $this->_blocks; } @@ -745,21 +751,21 @@ class moodle_page { } /** - * @deprecated since Moodle 2.0 - use $PAGE->blocks->get_positions() instead + * @deprecated since Moodle 2.0 - use $PAGE->blocks->get_regions() instead * @return string the places on this page where blocks can go. */ function blocks_get_positions() { - debugging('Call to deprecated method moodle_page::blocks_get_positions. Use $PAGE->blocks->get_positions() instead.'); - return $this->blocks->get_positions(); + debugging('Call to deprecated method moodle_page::blocks_get_positions. Use $PAGE->blocks->get_regions() instead.'); + return $this->blocks->get_regions(); } /** - * @deprecated since Moodle 2.0 - use $PAGE->blocks->get_default_position() instead + * @deprecated since Moodle 2.0 - use $PAGE->blocks->get_default_region() instead * @return string the default place for blocks on this page. */ function blocks_default_position() { - debugging('Call to deprecated method moodle_page::blocks_default_position. Use $PAGE->blocks->get_default_position() instead.'); - return $this->blocks->get_default_position(); + debugging('Call to deprecated method moodle_page::blocks_default_position. Use $PAGE->blocks->get_default_region() instead.'); + return $this->blocks->get_default_region(); } /** @@ -856,17 +862,6 @@ class moodle_page { } } -/** Stub implementation of the blocks_manager, to stop things from breaking too badly. */ -class blocks_manager { - public function get_positions() { - return array(BLOCK_POS_LEFT, BLOCK_POS_RIGHT); - } - - public function get_default_position() { - return BLOCK_POS_RIGHT; - } -} - /** * @deprecated since Moodle 2.0 * Not needed any more. diff --git a/lib/setup.php b/lib/setup.php index 63790b7..26dd952 100644 --- a/lib/setup.php +++ b/lib/setup.php @@ -275,7 +275,12 @@ global $SCRIPT; } /// Create the $PAGE global. - $PAGE = new moodle_page(); + if (!empty($CFG->moodlepageclass)) { + $classname = $CFG->moodlepageclass; + } else { + $classname = 'moodle_page'; + } + $PAGE = new $classname(); /// Set error reporting back to normal if ($originaldatabasedebug == -1) { diff --git a/lib/simpletest/testblocklib_blockmanager.php b/lib/simpletest/testblocklib_blockmanager.php new file mode 100644 index 0000000..5cb08c5 --- /dev/null +++ b/lib/simpletest/testblocklib_blockmanager.php @@ -0,0 +1,130 @@ +libdir . '/pagelib.php'); +require_once($CFG->libdir . '/blocklib.php'); + +/** Test-specific subclass to make some protected things public. */ +class testable_block_manager extends block_manager { + public function mark_loaded() { + parent::mark_loaded(); + } +} + +/** + * Test functions that don't need to touch the database. + */ +class moodle_page_test extends UnitTestCase { + protected $testpage; + protected $blockmanager; + + public function setUp() { + $this->testpage = new moodle_page(); + $this->blockmanager = new testable_block_manager($this->testpage); + } + + public function tearDown() { + $this->testpage = NULL; + $this->blockmanager = NULL; + } + + public function test_no_regions_initially() { + // Exercise SUT & Validate + $this->assertEqual(array(), $this->blockmanager->get_regions()); + } + + public function test_add_region() { + // Exercise SUT. + $this->blockmanager->add_region('a-region-name'); + // Validate + $this->assertEqual(array('a-region-name'), $this->blockmanager->get_regions()); + } + + public function test_add_regions() { + // Set up fixture. + $regions = array('a-region', 'another-region'); + // Exercise SUT. + $this->blockmanager->add_regions($regions); + // Validate + $this->assert(new ArraysHaveSameValuesExpectation($regions), $this->blockmanager->get_regions()); + } + + public function test_add_region_twice() { + // Exercise SUT. + $this->blockmanager->add_region('a-region-name'); + $this->blockmanager->add_region('another-region'); + // Validate + $this->assert(new ArraysHaveSameValuesExpectation(array('a-region-name', 'another-region')), + $this->blockmanager->get_regions()); + } + + public function test_cannot_add_region_after_loaded() { + // Set up fixture. + $this->blockmanager->mark_loaded(); + // Set expectation + $this->expectException(); + // Exercise SUT. + $this->blockmanager->add_region('too-late'); + } + + public function test_set_default_region() { + // Set up fixture. + $this->blockmanager->add_region('a-region-name'); + // Exercise SUT. + $this->blockmanager->set_default_region('a-region-name'); + // Validate + $this->assertEqual('a-region-name', $this->blockmanager->get_default_region()); + } + + public function test_cannot_set_unknown_region_as_default() { + // Set expectation + $this->expectException(); + // Exercise SUT. + $this->blockmanager->set_default_region('a-region-name'); + } + + public function test_cannot_change_default_region_after_loaded() { + // Set up fixture. + $this->blockmanager->mark_loaded(); + // Set expectation + $this->expectException(); + // Exercise SUT. + $this->blockmanager->set_default_region('too-late'); + } + +} + +?> -- 1.5.6.3 From f6d67a415d39929c8bb004dd8439496177e7efb4 Mon Sep 17 00:00:00 2001 From: Tim Hunt Date: Fri, 1 May 2009 18:35:53 +0800 Subject: blocklib: MDL-19010 add block and get_blocks methods --- blog/header.php | 1 - lib/blocklib.php | 345 ++++++++++++++++++++++---- lib/pagelib.php | 30 ++- lib/simpletest/testblocklib_blockmanager.php | 230 +++++++++++++++++- lib/weblib.php | 20 ++- theme/standard/config.php | 11 + 6 files changed, 576 insertions(+), 61 deletions(-) diff --git a/blog/header.php b/blog/header.php index 6674a01..03a0be6 100755 --- a/blog/header.php +++ b/blog/header.php @@ -91,7 +91,6 @@ if ($editing) { // but I'm not sure if it's worth the complexity increase... $pageblocks = blocks_get_by_page($PAGE); } - $missingblocks = blocks_get_missing($PAGE, $pageblocks); } if (!empty($tagid)) { diff --git a/lib/blocklib.php b/lib/blocklib.php index 13e01ad..f3a54a2 100644 --- a/lib/blocklib.php +++ b/lib/blocklib.php @@ -55,21 +55,21 @@ require_once($CFG->libdir.'/pagelib.php'); * responsibility to ensure that those fields do not subsequently change. */ class block_manager { - /**#@+ Tracks the where we are in the generation of the page. */ - const STATE_BLOCKS_NOT_LOADED = 0; - const STATE_BLOCKS_LOADED = 1; - /**#@-*/ /// Field declarations ========================================================= - protected $loaded = self::STATE_BLOCKS_NOT_LOADED; - protected $page; protected $regions = array(); protected $defaultregion; + protected $allblocks = null; // Will be get_records('blocks'); + + protected $addableblocks = null; // Will be a subset of $allblocks. + + protected $blocksbyregion = null; // Will be an array region-name => array(block_instances); + /// Constructor ================================================================ /** @@ -101,6 +101,86 @@ class block_manager { return $this->defaultregion; } + /** + * The list of block types that may be added to this page. + * @return array block id => 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; + } + + $pageformat = $page->pagetype; + foreach($allblocks as $block) { + if ($block->visible && + ($block->multiple || !$this->is_block_present($block->id)) && + blocks_name_allowed_in_format($block->name, $pageformat)) { + $this->addableblocks[$block->id] = $block; + } + } + + return $this->addableblocks; + } + + public function is_block_present($blocktypeid) { + // TODO + } + + /** + * @param string $blockname the name of ta 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; + } + + /** + * @param string $region a region name + * @return boolean true if this retion exists on this page. + */ + public function is_known_region($region) { + return array_key_exists($region, $this->regions); + } + + /** + * @param $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->check_region_is_known($region); + return $this->blocksbyregion[$region]; + } + + /** + * Get the list of all 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; + } + /// Setter methods ============================================================= /** @@ -129,26 +209,191 @@ class block_manager { */ public function set_default_region($defaultregion) { $this->check_not_yet_loaded(); - if (!array_key_exists($defaultregion, $this->regions)) { - throw new coding_exception('Trying to set an unknown block region as the default.'); - } + $this->check_region_is_known($defaultregion); $this->defaultregion = $defaultregion; } +/// Actions ==================================================================== + + /** + * This method actually loads the blocks for our page from the database. + */ + public function load_blocks($includeinvisible = NULL) { + global $DB; + $this->check_not_yet_loaded(); + + if (is_null($includeinvisible)) { + $includeinvisible = $this->page->user_is_editing(); + } + if ($includeinvisible) { + $visiblecheck = 'AND (bp.visible = 1 OR bp.visible IS NULL)'; + } else { + $visiblecheck = ''; + } + + $context = $this->page->context; + $contexttest = 'bi.contextid = :contextid2'; + $parentcontextparams = array(); + $parentcontextids = get_parent_contexts($context); + if ($parentcontextids) { + list($parentcontexttest, $parentcontextparams) = + $DB->get_in_or_equal($parentcontextids, SQL_PARAMS_NAMED, 'parentcontext0000'); + $contexttest = "($contexttest OR (bi.showinsubcontexts = 1 AND bi.contextid $parentcontexttest))"; + } + + $pagetypepatterns = $this->matching_page_type_patterns($this->page->pagetype); + list($pagetypepatterntest, $pagetypepatternparams) = + $DB->get_in_or_equal($pagetypepatterns, SQL_PARAMS_NAMED, 'pagetypepatterntest0000'); + + $params = array( + 'subpage1' => $this->page->subpage, + 'subpage2' => $this->page->subpage, + 'contextid1' => $context->id, + 'contextid2' => $context->id, + 'pagetype' => $this->page->pagetype, + ); + $sql = "SELECT + bi.id, + bi.blockname, + bi.contextid, + bi.showinsubcontexts, + bi.pagetypepattern, + bi.subpagepattern, + bp.visible, + COALESCE(bp.region, bi.defaultregion) AS region, + COALESCE(bp.weight, bi.defaultweight) AS weight, + bi.configdata + + 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 + + WHERE + $contexttest + AND bi.pagetypepattern $pagetypepatterntest + AND (bi.subpagepattern IS NULL OR bi.subpagepattern = :subpage2) + $visiblecheck + AND b.visible = 1 + + ORDER BY + COALESCE(bp.region, bi.defaultregion), + COALESCE(bp.weight, bi.defaultweight), + bi.id"; + $blockinstances = $DB->get_recordset_sql($sql, $params + $parentcontextparams + $pagetypepatternparams); + + $this->blocksbyregion = array(); + foreach ($this->regions as $region => $notused) { + $this->blocksbyregion[$region] = array(); + } + $unknown = array(); + + foreach ($blockinstances as $bi) { + if ($this->is_known_region($bi->region)) { + $this->blocksbyregion[$bi->region][] = $bi; + } else { + $unknown[] = $bi; + } + } + $this->blocksbyregion[$this->defaultregion] = array_merge($this->blocksbyregion[$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. + */ + public function add_block($blockname, $region, $weight, $showinsubcontexts, $pagetypepattern = NULL, $subpagepattern = NULL) { + global $DB; + $this->check_known_block_type($blockname); + $this->check_region_is_known($region); + + if (empty($pagetypepattern)) { + $pagetypepattern = $this->page->pagetype; + } + + $blockinstance = new stdClass; + $blockinstance->blockname = $blockname; + $blockinstance->contextid = $this->page->context->id; + $blockinstance->showinsubcontexts = !empty($showinsubcontexts); + $blockinstance->pagetypepattern = $pagetypepattern; + $blockinstance->subpagepattern = $subpagepattern; + $blockinstance->defaultregion = $region; + $blockinstance->defaultweight = $weight; + $blockinstance->configdata = ''; + $DB->insert_record('block_instances', $blockinstance); + } + /// Inner workings ============================================================= + /** + * Given a specific page type, return all the page type patterns that might + * match it. + * @param string $pagetype for example 'course-view-weeks' or 'mod-quiz-view'. + * @return array an array of all the page type patterns that might match this page type. + */ + protected function matching_page_type_patterns($pagetype) { + $patterns = array($pagetype, '*'); + $bits = explode('-', $pagetype); + if (count($bits) == 3 && $bits[0] == 'mod') { + if ($bits[2] == 'view') { + $patterns[] = 'mod-*-view'; + } else if ($bits[2] == 'index') { + $patterns[] = 'mod-*-index'; + } + } + while (count($bits) > 0) { + $patterns[] = implode('-', $bits) . '-*'; + array_pop($bits); + } + return $patterns; + } + protected function check_not_yet_loaded() { - if ($this->loaded) { + if (!is_null($this->blocksbyregion)) { throw new coding_exception('block_manager has already loaded the blocks, to it is too late to change things that might affect which blocks are visible.'); } } - protected function mark_loaded() { - $this->loaded = self::STATE_BLOCKS_LOADED; + protected function check_is_loaded() { + if (is_null($this->blocksbyregion)) { + throw new coding_exception('block_manager has not yet loaded the blocks, to it is too soon to request the information you asked for.'); + } + } + + protected function check_known_block_type($blockname, $includeinvisible = false) { + if (!$this->is_known_block_type($blockname, $includeinvisible)) { + if ($this->is_known_block_type($blockname, true)) { + throw new coding_exception('Unknown block type ' . $blockname); + } else { + throw new coding_exception('Block type ' . $blockname . ' has been disabled by the administrator.'); + } + } + } + + protected function check_region_is_known($region) { + if (!$this->is_known_region($region)) { + throw new coding_exception('Trying to reference an unknown block region ' . $region); + } } } -//This function retrieves a method-defined property of a class WITHOUT instantiating an object +/// Helper functions for working with block classes ============================ + +/** + * Call a class method (one that does not requrie a block instance) on a block class. + * @param string $blockname the name of the block. + * @param string $method the method name. + * @param array $param parameters to pass to the method. + * @return mixed whatever the method returns. + */ function block_method_result($blockname, $method, $param = NULL) { if(!block_load_class($blockname)) { return NULL; @@ -156,7 +401,12 @@ function block_method_result($blockname, $method, $param = NULL) { return call_user_func(array('block_'.$blockname, $method), $param); } -//This function creates a new object of the specified block class +/** + * Creates a new object of the specified block class. + * @param string $blockname the name of the block. + * @param $instance block_instances DB table row (optional). + * @return block_base the requested block instance. + */ function block_instance($blockname, $instance = NULL) { if(!block_load_class($blockname)) { return false; @@ -169,8 +419,11 @@ function block_instance($blockname, $instance = NULL) { return $retval; } -//This function loads the necessary class files for a block -//Whenever you want to load a block, use this first +/** + * Load the block class for a particular type of block. + * @param string $blockname the name of the block. + * @return boolean success or failure. + */ function block_load_class($blockname) { global $CFG; @@ -190,26 +443,18 @@ function block_load_class($blockname) { return class_exists($classname); } -// This function returns an array with the IDs of any blocks that you can add to your page. -// Parameters are passed by reference for speed; they are not modified at all. -function blocks_get_missing(&$page, &$pageblocks) { - - $missingblocks = array(); - $allblocks = blocks_get_record(); - $pageformat = $page->pagetype; +/// Functions that have been deprecated by block_manager ======================= - if(!empty($allblocks)) { - foreach($allblocks as $block) { - if($block->visible && (!blocks_find_block($block->id, $pageblocks) || $block->multiple)) { - // And if it's applicable for display in this format... - if(blocks_name_allowed_in_format($block->name, $pageformat)) { - // ...add it to the missing blocks - $missingblocks[] = $block->id; - } - } - } - } - return $missingblocks; +/** + * @deprecated since Moodle 2.0 - use $page->blocks->get + * This function returns an array with the IDs of any blocks that you can add to your page. + * Parameters are passed by reference for speed; they are not modified at all. + * @param $page the page object. + * @param $pageblocks Not used. + * @return array of block type ids. + */ +function blocks_get_missing(&$page, &$pageblocks) { + return array_keys($page->blocks->get_addable_blocks()); } function blocks_remove_inappropriate($page) { @@ -475,20 +720,22 @@ function blocks_preferred_width(&$instances) { return $width; } -function blocks_get_record($blockid = NULL, $invalidate = false) { - global $DB; - - static $cache = NULL; - - if($invalidate || empty($cache)) { - $cache = $DB->get_records('block'); - } - - if($blockid === NULL) { - return $cache; +/** + * Get the block record for a particulr blockid. + * @param $blockid block type id. If null, an array of all block types is returned. + * @param $notusedanymore No longer used. + * @return array|object row from block table, or all rows. + */ +function blocks_get_record($blockid = NULL, $notusedanymore = false) { + global $PAGE; + $blocks = $PAGE->blocks->get_installed_blocks(); + if ($blockid === NULL) { + return $blocks; + } else if (isset($blocks[$blockid])) { + return $blocks[$blockid]; + } else { + return false; } - - return (isset($cache[$blockid])? $cache[$blockid] : false); } function blocks_find_block($blockid, $blocksarray) { @@ -1021,7 +1268,7 @@ function blocks_get_by_page($page) { function blocks_print_adminblock(&$page, &$pageblocks) { global $USER; - $missingblocks = blocks_get_missing($page, $pageblocks); + $missingblocks = array_keys($page->blocks->get_addable_blocks()); if (!empty($missingblocks)) { $strblocks = '

    '; diff --git a/lib/pagelib.php b/lib/pagelib.php index c2551e9..d498094 100644 --- a/lib/pagelib.php +++ b/lib/pagelib.php @@ -88,7 +88,7 @@ class moodle_page { protected $_pagetype = null; - protected $_subpage = null; + protected $_subpage = ''; protected $_docspath = null; @@ -328,12 +328,7 @@ class moodle_page { } if ($state == self::STATE_PRINTING_HEADER) { - if (!$this->_course) { - global $SITE; - $this->set_course($SITE); - } - - $this->initialise_standard_body_classes(); + $this->starting_output(); } $this->_state = $state; @@ -448,7 +443,11 @@ class moodle_page { * and pagetype, uniquely identifies this page. */ public function set_subpage($subpage) { - $this->_subpage = $subpage; + if (empty($subpage)) { + $this->_subpage = ''; + } else { + $this->_subpage = $subpage; + } } /** @@ -551,6 +550,21 @@ class moodle_page { /// These set various things up in a default way. /** + * This method is called when the page first moves out of the STATE_BEFORE_HEADER + * state. This is our last change to initialise things. + */ + protected function starting_output() { + if (!$this->_course) { + global $SITE; + $this->set_course($SITE); + } + + $this->initialise_standard_body_classes(); + + $this->blocks->load_blocks(); + } + + /** * Sets ->pagetype from the script name. For example, if the script that was * run is mod/quiz/view.php, ->pagetype will be set to 'mod-quiz-view'. * @param string $script the path to the script that should be used to diff --git a/lib/simpletest/testblocklib_blockmanager.php b/lib/simpletest/testblocklib_blockmanager.php index 5cb08c5..d4f2a4e 100644 --- a/lib/simpletest/testblocklib_blockmanager.php +++ b/lib/simpletest/testblocklib_blockmanager.php @@ -40,14 +40,20 @@ require_once($CFG->libdir . '/blocklib.php'); /** Test-specific subclass to make some protected things public. */ class testable_block_manager extends block_manager { public function mark_loaded() { - parent::mark_loaded(); + $this->blocksbyregion = array(); + } + public function get_loaded_blocks() { + return $this->blocksbyregion; + } + public function matching_page_type_patterns($pagetype) { + return parent::matching_page_type_patterns($pagetype); } } /** * Test functions that don't need to touch the database. */ -class moodle_page_test extends UnitTestCase { +class moodle_block_manager_test extends UnitTestCase { protected $testpage; protected $blockmanager; @@ -125,6 +131,226 @@ class moodle_page_test extends UnitTestCase { $this->blockmanager->set_default_region('too-late'); } + public function test_matching_page_type_patterns() { + $this->assert(new ArraysHaveSameValuesExpectation( + array('site-index', 'site-index-*', 'site-*', '*')), + $this->blockmanager->matching_page_type_patterns('site-index')); + + $this->assert(new ArraysHaveSameValuesExpectation( + array('mod-quiz-report-overview', 'mod-quiz-report-overview-*', 'mod-quiz-report-*', 'mod-quiz-*', 'mod-*', '*')), + $this->blockmanager->matching_page_type_patterns('mod-quiz-report-overview')); + + $this->assert(new ArraysHaveSameValuesExpectation( + array('mod-fourm-view', 'mod-*-view', 'mod-fourm-view-*', 'mod-fourm-*', 'mod-*', '*')), + $this->blockmanager->matching_page_type_patterns('mod-fourm-view')); + + $this->assert(new ArraysHaveSameValuesExpectation( + array('mod-fourm-index', 'mod-*-index', 'mod-fourm-index-*', 'mod-fourm-*', 'mod-*', '*')), + $this->blockmanager->matching_page_type_patterns('mod-fourm-index')); + } } +/** + * Test methods that load and save data from block_instances and block_positions. + */ +class moodle_block_manager_test_saving_loading extends UnitTestCaseUsingDatabase { + + public function setUp() { + parent::setUp(); + $this->create_test_tables(array('block', 'block_instances', 'block_positions'), 'lib'); + $this->switch_to_test_db(); + } + + public function tearDown() { + parent::tearDown(); + } + + protected function get_a_page_and_block_manager($regions, $context, $pagetype, $subpage = '') { + $page = new moodle_page; + $page->set_context($context); + $page->set_pagetype($pagetype); + $page->set_subpage($subpage); + + $blockmanager = new testable_block_manager($page); + $blockmanager->add_regions($regions); + $blockmanager->set_default_region($regions[0]); + + return array($page, $blockmanager); + } + + protected function get_a_known_block_type() { + global $DB; + $block = new stdClass; + $block->name = 'ablocktype'; + $this->testdb->insert_record('block', $block); + return $block->name; + } + + protected function assertContainsBlocksOfType($typearray, $blockarray) { + if (!$this->assertEqual(count($typearray), count($blockarray), "Blocks array contains the wrong number of elements %s.")) { + return; + } + $types = array_values($typearray); + $i = 0; + foreach ($blockarray as $block) { + $blocktype = $types[$i]; + $this->assertEqual($blocktype, $block->blockname, "Block types do not match at postition $i %s."); + $i++; + } + } + + public function test_empty_initially() { + // Set up fixture. + list($page, $blockmanager) = $this->get_a_page_and_block_manager(array('a-region'), + get_context_instance(CONTEXT_SYSTEM), 'page-type'); + // Exercise SUT. + $blockmanager->load_blocks(); + // Validate. + $blocks = $blockmanager->get_loaded_blocks(); + $this->assertEqual(array('a-region' => array()), $blocks); + } + + public function test_adding_and_retrieving_one_block() { + // Set up fixture. + $regionname = 'a-region'; + $blockname = $this->get_a_known_block_type(); + + list($page, $blockmanager) = $this->get_a_page_and_block_manager(array($regionname), + get_context_instance(CONTEXT_SYSTEM), 'page-type'); + + // Exercise SUT. + $blockmanager->add_block($blockname, $regionname, 0, false); + $blockmanager->load_blocks(); + // Validate. + $blocks = $blockmanager->get_blocks_for_region($regionname); + $this->assertContainsBlocksOfType(array($blockname), $blocks); + } + + public function test_adding_and_retrieving_two_blocks() { + // Set up fixture. + $regionname = 'a-region'; + $blockname = $this->get_a_known_block_type(); + + list($page, $blockmanager) = $this->get_a_page_and_block_manager(array($regionname), + get_context_instance(CONTEXT_SYSTEM), 'page-type'); + + // Exercise SUT. + $blockmanager->add_block($blockname, $regionname, 0, false); + $blockmanager->add_block($blockname, $regionname, 1, false); + $blockmanager->load_blocks(); + // Validate. + $blocks = $blockmanager->get_blocks_for_region($regionname); + $this->assertContainsBlocksOfType(array($blockname, $blockname), $blocks); + } + + public function test_block_not_included_in_different_context() { + // Set up fixture. + $syscontext = get_context_instance(CONTEXT_SYSTEM); + $fakecontext = new stdClass; + $fakecontext->id = $syscontext->id + 1; + $regionname = 'a-region'; + $blockname = $this->get_a_known_block_type(); + + list($addpage, $addbm) = $this->get_a_page_and_block_manager(array($regionname), $fakecontext, 'page-type'); + list($viewpage, $viewbm) = $this->get_a_page_and_block_manager(array($regionname), $syscontext, 'page-type'); + + $addbm->add_block($blockname, $regionname, 0, false); + + // Exercise SUT. + $viewbm->load_blocks(); + // Validate. + $blocks = $viewbm->get_blocks_for_region($regionname); + $this->assertContainsBlocksOfType(array(), $blocks); + } + + public function test_block_included_in_sub_context() { + // Set up fixture. + $syscontext = get_context_instance(CONTEXT_SYSTEM); + $childcontext = new stdClass; + $childcontext->id = $syscontext->id + 1; + $childcontext->path = '/' . $syscontext->id . '/' . $childcontext->id; + $regionname = 'a-region'; + $blockname = $this->get_a_known_block_type(); + + list($addpage, $addbm) = $this->get_a_page_and_block_manager(array($regionname), $syscontext, 'page-type'); + list($viewpage, $viewbm) = $this->get_a_page_and_block_manager(array($regionname), $childcontext, 'page-type'); + + $addbm->add_block($blockname, $regionname, 0, true); + + // Exercise SUT. + $viewbm->load_blocks(); + // Validate. + $blocks = $viewbm->get_blocks_for_region($regionname); + $this->assertContainsBlocksOfType(array($blockname), $blocks); + } + + public function test_block_not_included_on_different_page_type() { + // Set up fixture. + $syscontext = get_context_instance(CONTEXT_SYSTEM); + $regionname = 'a-region'; + $blockname = $this->get_a_known_block_type(); + + list($addpage, $addbm) = $this->get_a_page_and_block_manager(array($regionname), $syscontext, 'page-type'); + list($viewpage, $viewbm) = $this->get_a_page_and_block_manager(array($regionname), $syscontext, 'other-page-type'); + + $addbm->add_block($blockname, $regionname, 0, true); + + // Exercise SUT. + $viewbm->load_blocks(); + // Validate. + $blocks = $viewbm->get_blocks_for_region($regionname); + $this->assertContainsBlocksOfType(array(), $blocks); + } + + public function test_block_not_included_on_different_sub_page() { + // Set up fixture. + $regionname = 'a-region'; + $blockname = $this->get_a_known_block_type(); + + list($page, $blockmanager) = $this->get_a_page_and_block_manager(array($regionname), + get_context_instance(CONTEXT_SYSTEM), 'page-type', 'sub-page'); + + $blockmanager->add_block($blockname, $regionname, 0, true, $page->pagetype, 'other-sub-page'); + + // Exercise SUT. + $blockmanager->load_blocks(); + // Validate. + $blocks = $blockmanager->get_blocks_for_region($regionname); + $this->assertContainsBlocksOfType(array(), $blocks); + } + + public function test_block_included_with_explicit_sub_page() { + // Set up fixture. + $regionname = 'a-region'; + $blockname = $this->get_a_known_block_type(); + + list($page, $blockmanager) = $this->get_a_page_and_block_manager(array($regionname), + get_context_instance(CONTEXT_SYSTEM), 'page-type', 'sub-page'); + + $blockmanager->add_block($blockname, $regionname, 0, true, $page->pagetype, $page->subpage); + + // Exercise SUT. + $blockmanager->load_blocks(); + // Validate. + $blocks = $blockmanager->get_blocks_for_region($regionname); + $this->assertContainsBlocksOfType(array($blockname), $blocks); + } + + public function test_block_included_with_page_type_pattern() { + // Set up fixture. + $regionname = 'a-region'; + $blockname = $this->get_a_known_block_type(); + + list($page, $blockmanager) = $this->get_a_page_and_block_manager(array($regionname), + get_context_instance(CONTEXT_SYSTEM), 'page-type', 'sub-page'); + + $blockmanager->add_block($blockname, $regionname, 0, true, 'page-*', $page->subpage); + + // Exercise SUT. + $blockmanager->load_blocks(); + // Validate. + $blocks = $blockmanager->get_blocks_for_region($regionname); + $this->assertContainsBlocksOfType(array($blockname), $blocks); + } +} ?> diff --git a/lib/weblib.php b/lib/weblib.php index dcad335..608fb52 100644 --- a/lib/weblib.php +++ b/lib/weblib.php @@ -3245,6 +3245,20 @@ function theme_setup($theme = '', $params=NULL) { $CFG->stylesheets[] = $CFG->themewww.'/standard/rtl.css'.$paramstring; $CFG->stylesheets[] = $CFG->themewww.'/'.$theme.'/rtl.css'.$paramstring; } + + /// Set up the block regions. + if (!empty($THEME->blockregions)) { + $PAGE->blocks->add_regions($THEME->blockregions); + } else { + // Support legacy themes by supplying a sensible default. + $PAGE->blocks->add_regions(array('side-pre', 'side-post')); + } + if (!empty($THEME->defaultblockregion)) { + $PAGE->blocks->set_default_region($THEME->defaultblockregion); + } else { + // Support legacy themes by supplying a sensible default. + $PAGE->blocks->set_default_region('side-post'); + } } @@ -5595,7 +5609,11 @@ function print_error($errorcode, $module='error', $link='', $a=NULL) { */ function _print_normal_error($errorcode, $module, $a, $link, $backtrace, $debuginfo=null, $showerrordebugwarning=false) { global $CFG, $SESSION, $THEME, $DB, $PAGE; - +print_object($errorcode); // DONOTCOMMIT +print_object($module); // DONOTCOMMIT +print_object($a); // DONOTCOMMIT +print_object($debuginfo); // DONOTCOMMIT +print_object($backtrace); // DONOTCOMMIT if ($DB) { //if you enable db debugging and exception is thrown, the print footer prints a lot of rubbish $DB->set_debug(0); diff --git a/theme/standard/config.php b/theme/standard/config.php index 13465c5..f182eb0 100644 --- a/theme/standard/config.php +++ b/theme/standard/config.php @@ -167,4 +167,15 @@ $THEME->custompix = false; /// use < > » - these are confusing for blind users. //////////////////////////////////////////////////////////////////////////////// + +$THEME->blockregions = array('side-pre', 'side-post'); +$THEME->defaultblockregion = 'side-post'; +/// Areas where blocks may appear on any page that uses this theme. For each +/// region you list in $THEME->blockregions you must call blocks_print_group +/// with that region id somewhere in header.html or footer.html. +/// defaultblockregion is the region where new blocks will be added, and +/// where any blocks in unrecognised regions will be shown. (Suppose someone +/// added a block when anther theme was selected). +//////////////////////////////////////////////////////////////////////////////// + ?> -- 1.5.6.3