]> git.mjollnir.org Git - moodle.git/commitdiff
block contexts: MDL-19098 every block should have a context
authortjhunt <tjhunt>
Mon, 13 Jul 2009 08:37:34 +0000 (08:37 +0000)
committertjhunt <tjhunt>
Mon, 13 Jul 2009 08:37:34 +0000 (08:37 +0000)
even non-course and sticky blocks.

The parent context is block_instances.parentcontextid.

The block context should be used for checking permissions directly
related to the block, like moodle/block:view or moodle/site:manageblocks.

However, if the block is displaying information about the current page,
for example the participants block showing who 'here', then it may be
better to use the context of the page where the bloack is appearing -
in other words $this->page->context - to check permissions about the
user's ability to see participants here.

Or, if the block is displaying something stronly related to courses,
for example, a course meny block, the block should probably use the
context for $this->page->course to check permissions.

19 files changed:
admin/replace.php
admin/roles/assign.php
admin/roles/check.php
admin/roles/lib.php
admin/roles/override.php
admin/roles/tabs.php
blocks/admin/block_admin.php
blocks/html/block_html.php
blocks/mentees/block_mentees.php
blocks/moodleblock.class.php
blocks/online_users/block_online_users.php
blocks/quiz_results/block_quiz_results.php
blocks/rss_client/block_rss_client.php
blocks/rss_client/config_instance.html
blocks/rss_client/config_instance_tabs.php
lib/accesslib.php
lib/blocklib.php
lib/db/upgrade.php
version.php

index 5f72748671baebe44b223b91c6f37b0cf9691ca6..ff145dc2721796e660b0f7a8a52ec462b6c0d9ea 100644 (file)
@@ -46,7 +46,7 @@ $instances = $DB->get_recordset('block_instances', array('blockname' => 'html'))
 foreach ($instances as $instance) {
     $blockobject = block_instance('html', $instance);
     $blockobject->config->text = str_replace($search, $replace, $blockobject->config->text);
-    $blockobject->instance_config_commit($blockobject->pinned);
+    $blockobject->instance_config_commit();
 }
 $instances->close();
 
index afcb7004fe6ceb4de029ce51d1210024099a1de3..54625a2619020b2d6e6e2289a10e6bbb88e3a806 100755 (executable)
     $extendperiod   = optional_param('extendperiod', 0, PARAM_INT);
     $extendbase     = optional_param('extendbase', 3, PARAM_INT);
 
-    $baseurl = $CFG->wwwroot . '/' . $CFG->admin . '/roles/assign.php?contextid=' . $contextid;
+    $urlparams = array('contextid' => $contextid);
     if (!empty($userid)) {
-        $baseurl .= '&amp;userid='.$userid;
+        $urlparams['userid'] = $userid;
     }
     if ($courseid && $courseid != SITEID) {
-        $baseurl .= '&amp;courseid='.$courseid;
+        $urlparams['courseid'] = $courseid;
     }
+    $PAGE->set_url($CFG->admin . '/roles/assign.php', $urlparams);
+    $baseurl = $PAGE->url->out();
 
     if (! $context = get_context_instance_by_id($contextid)) {
         print_error('wrongcontextid', 'error');
 
     /// Create the user selector objects.
         $options = array('context' => $context, 'roleid' => $roleid);
-        if ($context->contextlevel > CONTEXT_COURSE && !is_inside_frontpage($context)) {
-            $potentialuserselector = new potential_assignees_below_course('addselect', $options);
-        } else {
-            $potentialuserselector = new potential_assignees_course_and_above('addselect', $options);
-        }
+
+        $potentialuserselector = roles_get_potential_user_selector($context, 'addselect', $options);
         if ($context->contextlevel == CONTEXT_SYSTEM && is_admin_role($roleid)) {
             $currentuserselector = new existing_role_holders_site_admin('removeselect', $options);
         } else {
 
     } else if (empty($assignableroles)) {
     /// Print a message that there are no roles that can me assigned here.
-        print_heading(get_string('notabletoassignroleshere', 'role'), 'center', 3);
+        print_heading(get_string('notabletoassignroleshere', 'role'), '', 3);
 
     } else {
     /// Show UI for choosing a role to assign.
         }
 
         // Print instruction
-        print_heading(get_string('chooseroletoassign', 'role'), 'center', 3);
+        print_heading(get_string('chooseroletoassign', 'role'), '', 3);
 
         // sync metacourse enrolments if needed
         if ($inmeta) {
     if ($context->contextlevel == CONTEXT_SYSTEM || $isfrontpage) {
         admin_externalpage_print_footer();
     } else {
-        print_footer($course);
+        print_footer();
     }
 ?>
index abd55d844749dd81649bea731c4cc3803cbebc96..4153ae8db55ea87d8e5af5b359a4c5b792a333f6 100755 (executable)
     $userid = optional_param('userid', 0, PARAM_INT); // needed for user tabs
     $courseid = optional_param('courseid', 0, PARAM_INT); // needed for user tabs
 
+    $urlparams = array('contextid' => $contextid);
+    if (!empty($userid)) {
+        $urlparams['userid'] = $userid;
+    }
+    if ($courseid && $courseid != SITEID) {
+        $urlparams['courseid'] = $courseid;
+    }
+    $PAGE->set_url($CFG->admin . '/roles/check.php', $urlparams);
+
     if (! $context = get_context_instance_by_id($contextid)) {
         print_error('wrongcontextid', 'error');
     }
 /// Teachers within a course just get to see the same list of people they can
 /// assign roles to. Admins (people with moodle/role:manage) can run this report for any user.
     $options = array('context' => $context, 'roleid' => 0);
-    if ($context->contextlevel > CONTEXT_COURSE && !is_inside_frontpage($context) && !has_capability('moodle/role:manage', $context)) {
-        $userselector = new potential_assignees_below_course('reportuser', $options);
-    } else {
+    if (has_capability('moodle/role:manage', $context)) {
         $userselector = new potential_assignees_course_and_above('reportuser', $options);
+    } else {
+        $userselector = roles_get_potential_user_selector($context, 'reportuser', $options);
     }
     $userselector->set_multiselect(false);
     $userselector->set_rows(10);
             get_string('backto', '', $contextname) . '</a></div>';
     }
 
-    print_footer($course);
+    print_footer();
 ?>
index a67421f0d468ba471669bcd6bf7abc38d452caa0..792be3633e756cf69e814ebee0b857da0b9ea5cd 100644 (file)
@@ -961,7 +961,7 @@ abstract class role_assign_user_selector_base extends user_selector_base {
 /**
  * User selector subclass for the list of potential users on the assign roles page,
  * when we are assigning in a context below the course level. (CONTEXT_MODULE and
- * CONTEXT_BLOCK).
+ * some CONTEXT_BLOCK).
  *
  * In this case we replicate part of get_users_by_capability() get the users
  * with moodle/course:view (or moodle/site:doanything). We can't use
@@ -1468,4 +1468,32 @@ class role_allow_switch_page extends role_allow_role_page {
     }
 }
 
+/**
+ * Get the potential assignees selector for a given context.
+ *
+ * If this context is a course context, or inside a course context (module or
+ * some blocks) then return a potential_assignees_below_course object. Otherwise
+ * return a potential_assignees_course_and_above.
+ *
+ * @param $context a context.
+ * @param $name passed to user selector constructor.
+ * @param $options to user selector constructor.
+ * @return user_selector_base an appropriate user selector.
+ */
+function roles_get_potential_user_selector($context, $name, $options) {
+        $blockinsidecourse = false;
+        if ($context->contextlevel == CONTEXT_BLOCK) {
+            $parentcontext = get_context_instance_by_id(get_parent_contextid($context));
+            $blockinsidecourse = in_array($parentcontext->contextlevel, array(CONTEXT_MODULE, CONTEXT_COURSE));
+        }
+
+        if (($context->contextlevel == CONTEXT_MODULE || $blockinsidecourse) &&
+                !is_inside_frontpage($context)) {
+            $potentialuserselector = new potential_assignees_below_course('addselect', $options);
+        } else {
+            $potentialuserselector = new potential_assignees_course_and_above('addselect', $options);
+        }
+    return $potentialuserselector;
+}
+
 ?>
\ No newline at end of file
index d85cb30556f1488170634cc36656252302c8367b..85ce08860cff80344e4f46a99d490a938f17ab6e 100755 (executable)
     $courseid = optional_param('courseid', 0, PARAM_INT); // needed for user tabs
 
 /// Get the base URL for this and related pages into a convenient variable.
-    $baseurl = $CFG->wwwroot . '/' . $CFG->admin . '/roles/override.php?contextid=' . $contextid;
+    $urlparams = array('contextid' => $contextid);
     if (!empty($userid)) {
-        $baseurl .= '&amp;userid=' . $userid;
+        $urlparams['userid'] = $userid;
     }
     if ($courseid && $courseid != SITEID) {
-        $baseurl .= '&amp;courseid=' . $courseid;
+        $urlparams['courseid'] = $courseid;
     }
+    $PAGE->set_url($CFG->admin . '/roles/override.php', $urlparams);
+    $baseurl = $PAGE->url->out();
 
 /// Validate the contextid parameter.
     if (!$context = $DB->get_record('context', array('id'=>$contextid))) {
         }
     }
 
-    print_footer($course);
-
+    print_footer();
 ?>
\ No newline at end of file
index 1d37a0dfa4c27ea44680be3f1d5f44d69c1b5554..0d106bb60b2c3674a0b94b6c0666d41016b8a858 100755 (executable)
@@ -121,7 +121,7 @@ if ($currenttab != 'update') {
             if ($blockinstance = $DB->get_record('block_instances', array('id' => $context->instanceid))) {
                 $blockname = print_context_name($context);
 
-                $parentcontext = get_context_instance_by_id($blockinstance->contextid);
+                $parentcontext = get_context_instance_by_id($blockinstance->parentcontextid);
                 $navlinks[] = array('name' => $blockname, 'link' => null, 'type' => 'misc');
                 $navlinks[] = array('name' => $straction, 'link' => null, 'type' => 'misc');
                 switch ($parentcontext->contextlevel) {
index 9b0cddfc93b26e8005a97b4261ab5b69eac10250..bfe5f8c5d6d54d05cea64e0cd6bf0e4171c340ba 100644 (file)
@@ -18,10 +18,9 @@ class block_admin extends block_list {
         $this->content->icons = array();
         $this->content->footer = '';
 
-        $context = $this->page->context;
         $course = $this->page->course;
 
-        if (!has_capability('moodle/course:view', $context)) {  // Just return
+        if (!has_capability('moodle/course:view', $this->page->context)) {  // Just return
             return $this->content;
         }
 
@@ -32,7 +31,7 @@ class block_admin extends block_list {
         }
 
     /// Course editing on/off
-        if ($course->id !== SITEID and has_capability('moodle/course:update', $context)) {
+        if ($course->id !== SITEID and has_capability('moodle/course:update', $this->page->context)) {
             $this->content->icons[]='<img src="'.$OUTPUT->old_icon_url('i/edit') . '" class="icon" alt="" />';
             if ($this->page->user_is_editing()) {
                 $this->content->items[]='<a href="view.php?id='.$course->id.'&amp;edit=off&amp;sesskey='.sesskey().'">'.get_string('turneditingoff').'</a>';
@@ -46,11 +45,11 @@ class block_admin extends block_list {
 
     /// Assign roles to the course
         if ($course->id != SITEID) {
-            if (has_capability('moodle/role:assign', $context)) {
-                $this->content->items[]='<a href="'.$CFG->wwwroot.'/'.$CFG->admin.'/roles/assign.php?contextid='.$context->id.'">'.get_string('assignroles', 'role').'</a>';
+            if (has_capability('moodle/role:assign', $this->page->context)) {
+                $this->content->items[]='<a href="'.$CFG->wwwroot.'/'.$CFG->admin.'/roles/assign.php?contextid='.$this->page->context->id.'">'.get_string('assignroles', 'role').'</a>';
                 $this->content->icons[]='<img src="'.$OUTPUT->old_icon_url('i/roles') . '" class="icon" alt="" />';
-            } else if (get_overridable_roles($context, ROLENAME_ORIGINAL)) {
-                $this->content->items[]='<a href="'.$CFG->wwwroot.'/'.$CFG->admin.'/roles/override.php?contextid='.$context->id.'">'.get_string('overridepermissions', 'role').'</a>';
+            } else if (get_overridable_roles($this->page->context, ROLENAME_ORIGINAL)) {
+                $this->content->items[]='<a href="'.$CFG->wwwroot.'/'.$CFG->admin.'/roles/override.php?contextid='.$this->page->context->id.'">'.get_string('overridepermissions', 'role').'</a>';
                 $this->content->icons[]='<img src="'.$OUTPUT->old_icon_url('i/roles') . '" class="icon" alt="" />';
             }
         }
@@ -59,13 +58,13 @@ class block_admin extends block_list {
     /// find all accessible reports
         if ($course->id !== SITEID) {
             $reportavailable = false;
-            if (has_capability('moodle/grade:viewall', $context)) {
+            if (has_capability('moodle/grade:viewall', $this->page->context)) {
                 $reportavailable = true;
             } else if (!empty($course->showgrades)) {
                 if ($reports = get_plugin_list('gradereport')) {     // Get all installed reports
                     arsort($reports); // user is last, we want to test it first
                     foreach ($reports as $plugin => $plugindir) {
-                        if (has_capability('gradereport/'.$plugin.':view', $context)) {
+                        if (has_capability('gradereport/'.$plugin.':view', $this->page->context)) {
                             //stop when the first visible plugin is found
                             $reportavailable = true;
                             break;
@@ -82,7 +81,7 @@ class block_admin extends block_list {
 
     /// Course outcomes (to help give it more prominence because it's important)
         if (!empty($CFG->enableoutcomes)) {
-            if ($course->id!==SITEID and has_capability('moodle/course:update', $context)) {
+            if ($course->id!==SITEID and has_capability('moodle/course:update', $this->page->context)) {
                 $this->content->items[]='<a href="'.$CFG->wwwroot.'/grade/edit/outcome/course.php?id='.$course->id.'">'.get_string('outcomes', 'grades').'</a>';
                 $this->content->icons[]='<img src="'.$OUTPUT->old_icon_url('i/outcomes') . '" class="icon" alt="" />';
             }
@@ -90,11 +89,11 @@ class block_admin extends block_list {
 
     /// Manage metacourses
         if ($course->metacourse) {
-            if (has_capability('moodle/course:managemetacourse', $context)) {
+            if (has_capability('moodle/course:managemetacourse', $this->page->context)) {
                 $strchildcourses = get_string('childcourses');
                 $this->content->items[]='<a href="importstudents.php?id='.$course->id.'">'.$strchildcourses.'</a>';
                 $this->content->icons[]='<img src="'.$OUTPUT->old_icon_url('i/course') . '" class="icon" alt="" />';
-            } else if (has_capability('moodle/role:assign', $context)) {
+            } else if (has_capability('moodle/role:assign', $this->page->context)) {
                 $strchildcourses = get_string('childcourses');
                 $this->content->items[]='<span class="dimmed_text">'.$strchildcourses.'</span>';
                 $this->content->icons[]='<img src="'.$OUTPUT->old_icon_url('i/course') . '" class="icon" alt="" />';
@@ -103,38 +102,38 @@ class block_admin extends block_list {
 
 
     /// Manage groups in this course
-        if (($course->id!==SITEID) && ($course->groupmode || !$course->groupmodeforce) && has_capability('moodle/course:managegroups', $context)) {
+        if (($course->id!==SITEID) && ($course->groupmode || !$course->groupmodeforce) && has_capability('moodle/course:managegroups', $this->page->context)) {
             $strgroups = get_string('groups');
             $this->content->items[]='<a title="'.$strgroups.'" href="'.$CFG->wwwroot.'/group/index.php?id='.$course->id.'">'.$strgroups.'</a>';
             $this->content->icons[]='<img src="'.$OUTPUT->old_icon_url('i/group') . '" class="icon" alt="" />';
         }
 
     /// Backup this course
-        if ($course->id!==SITEID and has_capability('moodle/site:backup', $context)) {
+        if ($course->id!==SITEID and has_capability('moodle/site:backup', $this->page->context)) {
             $this->content->items[]='<a href="'.$CFG->wwwroot.'/backup/backup.php?id='.$course->id.'">'.get_string('backup').'</a>';
             $this->content->icons[]='<img src="'.$OUTPUT->old_icon_url('i/backup') . '" class="icon" alt="" />';
         }
 
     /// Restore to this course
-        if ($course->id !== SITEID and has_capability('moodle/site:restore', $context)) {
+        if ($course->id !== SITEID and has_capability('moodle/site:restore', $this->page->context)) {
             $this->content->items[]='<a href="'.$CFG->wwwroot.'/files/index.php?id='.$course->id.'&amp;wdir=/backupdata">'.get_string('restore').'</a>';
             $this->content->icons[]='<img src="'.$OUTPUT->old_icon_url('i/restore') . '" class="icon" alt="" />';
         }
 
     /// Import data from other courses
-        if ($course->id !== SITEID and has_capability('moodle/site:import', $context)) {
+        if ($course->id !== SITEID and has_capability('moodle/site:import', $this->page->context)) {
             $this->content->items[]='<a href="'.$CFG->wwwroot.'/course/import.php?id='.$course->id.'">'.get_string('import').'</a>';
             $this->content->icons[]='<img src="'.$OUTPUT->old_icon_url('i/restore') . '" class="icon" alt="" />';
         }
 
     /// Reset this course
-        if ($course->id!==SITEID and has_capability('moodle/course:reset', $context)) {
+        if ($course->id!==SITEID and has_capability('moodle/course:reset', $this->page->context)) {
             $this->content->items[]='<a href="'.$CFG->wwwroot.'/course/reset.php?id='.$course->id.'">'.get_string('reset').'</a>';
             $this->content->icons[]='<img src="'.$OUTPUT->old_icon_url('i/return') . '" class="icon" alt="" />';
         }
 
     /// View course reports
-        if ($course->id !== SITEID and has_capability('moodle/site:viewreports', $context)) { // basic capability for listing of reports
+        if ($course->id !== SITEID and has_capability('moodle/site:viewreports', $this->page->context)) { // basic capability for listing of reports
             $this->content->items[]='<a href="'.$CFG->wwwroot.'/course/report.php?id='.$course->id.'">'.get_string('reports').'</a>';
             $this->content->icons[]='<img src="'.$OUTPUT->old_icon_url('i/stats') . '" class="icon" alt="" />';
         }
@@ -151,12 +150,12 @@ class block_admin extends block_list {
                                     'moodle/question:movemine',
                                     'moodle/question:moveall');
             foreach ($questioncaps as $questioncap){
-                if (has_capability($questioncap, $context)){
+                if (has_capability($questioncap, $this->page->context)){
                     $questionlink = 'edit.php';
                     break;
                 }
             }
-            if (!$questionlink && has_capability('moodle/question:managecategory', $context)) {
+            if (!$questionlink && has_capability('moodle/question:managecategory', $this->page->context)) {
                $questionlink = 'category.php';
             }
             if ($questionlink) {
@@ -168,14 +167,14 @@ class block_admin extends block_list {
 
     /// Repository Instances
         require_once($CFG->dirroot.'/repository/lib.php');
-        $editabletypes = repository::get_editable_types($context);
-        if ($course->id !== SITEID && has_capability('moodle/course:update', $context) && !empty($editabletypes)) {
-            $this->content->items[]='<a href="'.$CFG->wwwroot.'/repository/manage_instances.php?contextid='.$context->id.'">'.get_string('repositories').'</a>';
+        $editabletypes = repository::get_editable_types($this->page->context);
+        if ($course->id !== SITEID && has_capability('moodle/course:update', $this->page->context) && !empty($editabletypes)) {
+            $this->content->items[]='<a href="'.$CFG->wwwroot.'/repository/manage_instances.php?contextid='.$this->page->context->id.'">'.get_string('repositories').'</a>';
             $this->content->icons[]='<img src="'.$OUTPUT->old_icon_url('i/repository') . '" alt=""/>';
         }
 
     /// Manage files
-        if ($course->id !== SITEID and has_capability('moodle/course:managefiles', $context)) {
+        if ($course->id !== SITEID and has_capability('moodle/course:managefiles', $this->page->context)) {
             $this->content->items[]='<a href="'.$CFG->wwwroot.'/files/index.php?id='.$course->id.'">'.get_string('files').'</a>';
             $this->content->icons[]='<img src="'.$OUTPUT->old_icon_url('i/files') . '" class="icon" alt=""/>';
         }
@@ -184,7 +183,7 @@ class block_admin extends block_list {
         if ($course->enrol == 'authorize' || (empty($course->enrol) && $CFG->enrol == 'authorize') && ($course->id!==SITEID)) {
             require_once($CFG->dirroot.'/enrol/authorize/const.php');
             $paymenturl = '<a href="'.$CFG->wwwroot.'/enrol/authorize/index.php?course='.$course->id.'">'.get_string('payments').'</a> ';
-            if (has_capability('enrol/authorize:managepayments', $context)) {
+            if (has_capability('enrol/authorize:managepayments', $this->page->context)) {
                 if ($cnt = $DB->count_records('enrol_authorize', array('status'=>AN_STATUS_AUTH, 'courseid'=>$course->id))) {
                     $paymenturl .= '<a href="'.$CFG->wwwroot.'/enrol/authorize/index.php?status='.AN_STATUS_AUTH.'&amp;course='.$course->id.'">'.get_string('paymentpending', 'moodle', $cnt).'</a>';
                 }
@@ -195,10 +194,10 @@ class block_admin extends block_list {
 
     /// Unenrol link
         if (empty($course->metacourse) && ($course->id!==SITEID)) {
-            if (has_capability('moodle/legacy:guest', $context, NULL, false)) {   // Are a guest now
+            if (has_capability('moodle/legacy:guest', $this->page->context, NULL, false)) {   // Are a guest now
                 $this->content->items[]='<a href="'.$CFG->wwwroot.'/course/enrol.php?id='.$course->id.'">'.get_string('enrolme', '', format_string($course->shortname)).'</a>';
                 $this->content->icons[]='<img src="'.$OUTPUT->old_icon_url('i/user') . '" class="icon" alt="" />';
-            } else if (has_capability('moodle/role:unassignself', $context, NULL, false) and get_user_roles($context, $USER->id, false)) {  // Have some role
+            } else if (has_capability('moodle/role:unassignself', $this->page->context, NULL, false) and get_user_roles($this->page->context, $USER->id, false)) {  // Have some role
                 $this->content->items[]='<a href="'.$CFG->wwwroot.'/course/unenrol.php?id='.$course->id.'">'.get_string('unenrolme', '', format_string($course->shortname)).'</a>';
                 $this->content->icons[]='<img src="'.$OUTPUT->old_icon_url('i/user') . '" class="icon" alt="" />';
             }
index e55f5785dbbb9569761e6a45fad6bc813d797e71..16be06b64dc1f95c6cfdf57d2e4fc16a2a73ef9e 100755 (executable)
@@ -25,7 +25,7 @@ class block_html extends block_base {
         }
 
         if ($this->content_is_trusted()) {
-            // fancy html allowed only on course page and in pinned blocks for security reasons
+            // fancy html allowed only on course, category and system blocks.
             $filteropt = new stdClass;
             $filteropt->noclean = true;
         } else {
@@ -88,7 +88,7 @@ class block_html extends block_base {
                     $blockobject = block_instance('html', $instance);
                     $blockobject->config->text = restore_decode_absolute_links($blockobject->config->text);
                     $blockobject->config->text = restore_decode_content_links_worker($blockobject->config->text, $restore);
-                    $blockobject->instance_config_commit($blockobject->pinned);
+                    $blockobject->instance_config_commit();
                 }
             }
         }
index cf645fe4e1a5f523ad0dbc1de10cfbe03d4fdd2a..1c7dbc745d6f84bb8b911188dae2ac78988c9067 100755 (executable)
@@ -38,10 +38,9 @@ class block_mentees extends block_base {
             foreach ($usercontexts as $usercontext) {
                 $this->content->text .= '<li><a href="'.$CFG->wwwroot.'/user/view.php?id='.$usercontext->instanceid.'&amp;course=1">'.fullname($usercontext).'</a></li>';                
             }
-            $this->content->text .= '</ul>';                    
+            $this->content->text .= '</ul>';
         }
-                                
-        
+
         $this->content->footer = '';
 
         return $this->content;
index 9f1bf0159db7a80dfd1e05aa05efb88575e4de4a..8a4626f4585b86ccdbfb32e175fc88afbf1bef64 100644 (file)
@@ -75,6 +75,12 @@ class block_base {
      */
     public $page       = NULL;
 
+    /**
+     * This blocks's context.
+     * @var stdClass
+     */
+    public $context    = NULL;
+
     /**
      * An object containing the instance configuration information for the current instance of this block.
      * @var stdObject $config
@@ -88,11 +94,6 @@ class block_base {
 
     var $cron          = NULL;
 
-    /**
-     * Indicates blocked is pinned - can not be moved, always present, does not have own context
-     */
-    var $pinned        = false;
-
 /// Class Functions
 
     /**
@@ -300,16 +301,7 @@ class block_base {
      * @return boolean
      */
     function is_empty() {
-
-        // TODO - temporary hack to get the block context only if it already exists.
-        global $DB;
-        if ($DB->record_exists('context', array('contextlevel' => CONTEXT_BLOCK, 'instanceid' => $this->instance->id))) {
-            $context = get_context_instance(CONTEXT_BLOCK, $this->instance->id);
-        } else {
-            $context = get_context_instance(CONTEXT_SYSTEM); // pinned blocks do not have own context
-        }
-
-        if ( !has_capability('moodle/block:view', $context) ) {
+        if ( !has_capability('moodle/block:view', $this->context) ) {
             return true;
         }
 
@@ -419,15 +411,7 @@ class block_base {
      * @since Moodle 2.0.
      */
     protected function get_edit_controls($output) {
-        global $CFG, $DB;
-
-        // TODO - temporary hack to get the block context only if it already exists.
-        global $DB;
-        if ($DB->record_exists('context', array('contextlevel' => CONTEXT_BLOCK, 'instanceid' => $this->instance->id))) {
-            $context = get_context_instance(CONTEXT_BLOCK, $this->instance->id);
-        } else {
-            $context = get_context_instance(CONTEXT_SYSTEM); // pinned blocks do not have own context
-        }
+        global $CFG;
 
         $returnurlparam = '&amp;returnurl=' . urlencode($this->page->url->out_returnurl());
         $actionurl = $CFG->wwwroot.'/blocks/action.php?block=' . $this->instance->id .
@@ -436,8 +420,8 @@ class block_base {
         $controls = array();
 
         // Assign roles icon.
-        if ($context->contextlevel == CONTEXT_BLOCK && has_capability('moodle/role:assign', $context)) {
-            $controls[] = array('url' => $CFG->wwwroot.'/'.$CFG->admin.'/roles/assign.php?contextid='.$context->id,
+        if (has_capability('moodle/role:assign', $this->context)) {
+            $controls[] = array('url' => $CFG->wwwroot.'/'.$CFG->admin.'/roles/assign.php?contextid='.$this->context->id,
                     'icon' => $output->old_icon_url('i/roles'), 'caption' => get_string('assignroles', 'role'));
         }
 
@@ -604,12 +588,12 @@ class block_base {
         if (!empty($instance->configdata)) {
             $this->config = unserialize(base64_decode($instance->configdata));
         }
-        // [pj] This line below is supposed to be an optimization (we don't need configdata anymore)
-        // but what it does is break in PHP5 because the same instance object will be passed to
-        // this function twice in each page view, and the second time it won't have any configdata
-        // so it won't work correctly. Thus it's commented out.
-        // unset($instance->configdata);
         $this->instance = $instance;
+        if (isset($instance->context)) {
+            $this->context = $instance->context;
+        } else {
+            $this->context = get_context_instance(CONTEXT_BLOCK, $instance->id);
+        }
         $this->page = $page;
         $this->specialization();
     }
@@ -795,16 +779,7 @@ class block_list extends block_base {
     var $content_type  = BLOCK_TYPE_LIST;
 
     function is_empty() {
-
-        // TODO - temporary hack to get the block context only if it already exists.
-        global $DB;
-        if ($DB->record_exists('context', array('contextlevel' => CONTEXT_BLOCK, 'instanceid' => $this->instance->id))) {
-            $context = get_context_instance(CONTEXT_BLOCK, $this->instance->id);
-        } else {
-            $context = get_context_instance(CONTEXT_SYSTEM); // pinned blocks do not have own context
-        }
-
-        if ( !has_capability('moodle/block:view', $context) ) {
+        if ( !has_capability('moodle/block:view', $this->context) ) {
             return true;
         }
 
index d51cdc6cbb0e158c4a69f7b59ff85a906cf9eebd..c850cc2cb4ca80775d9d07a0d29aca35bde0ae7c 100644 (file)
@@ -34,21 +34,10 @@ class block_online_users extends block_base {
         }
         $timefrom = 100 * floor((time()-$timetoshowusers) / 100); // Round to nearest 100 seconds for better query cache
 
-        // Get context so we can check capabilities.
-        $context = $this->page->context;
-
-        // TODO - temporary hack to get the block context only if it already exists.
-        global $DB;
-        if ($DB->record_exists('context', array('contextlevel' => CONTEXT_BLOCK, 'instanceid' => $this->instance->id))) {
-            $context = get_context_instance(CONTEXT_BLOCK, $this->instance->id);
-        } else {
-            $context = get_context_instance(CONTEXT_SYSTEM); // pinned blocks do not have own context
-        }
-
         //Calculate if we are in separate groups
         $isseparategroups = ($this->page->course->groupmode == SEPARATEGROUPS
                              && $this->page->course->groupmodeforce
-                             && !has_capability('moodle/site:accessallgroups', $context));
+                             && !has_capability('moodle/site:accessallgroups', $this->page->context));
 
         //Get the user current group
         $currentgroup = $isseparategroups ? groups_get_course_group($this->page->course) : NULL;
@@ -81,8 +70,8 @@ class block_online_users extends block_base {
                   GROUP BY u.id";
 
         } else { // Course-level
-            if (!has_capability('moodle/role:viewhiddenassigns', $context)) {
-                $pcontext = get_related_contexts_string($context);
+            if (!has_capability('moodle/role:viewhiddenassigns', $this->page->context)) {
+                $pcontext = get_related_contexts_string($this->page->context);
                 $rafrom  = ", {role_assignments} ra";
                 $rawhere = " AND ra.userid = u.id AND ra.contextid $pcontext AND ra.hidden = 0";
             }
@@ -111,7 +100,7 @@ class block_online_users extends block_base {
         $minutes  = floor($timetoshowusers/60);
 
         // Verify if we can see the list of users, if not just print number of users
-        if (!has_capability('block/online_users:viewlist', $context)) {
+        if (!has_capability('block/online_users:viewlist', $this->page->context)) {
             if (!$usercount = $DB->count_records_sql($csql, $params)) {
                 $usercount = get_string("none");
             }
@@ -142,7 +131,7 @@ class block_online_users extends block_base {
             //Accessibility: Don't want 'Alt' text for the user picture; DO want it for the envelope/message link (existing lang string).
             //Accessibility: Converted <div> to <ul>, inherit existing classes & styles.
             $this->content->text .= "<ul class='list'>\n";
-            if (!empty($USER->id) && has_capability('moodle/site:sendmessage', $context)
+            if (!empty($USER->id) && has_capability('moodle/site:sendmessage', $this->page->context)
                            && !empty($CFG->messaging) && !isguest()) {
                 $canshowicon = true;
             } else {
index d24acf95d236f992dcb18507a21cf2e8b963884b..d7050667e6193ca2de5cd64304f974cf430cb114 100644 (file)
@@ -50,8 +50,6 @@ class block_quiz_results extends block_base {
             $quizid = 0;
         }
 
-        $context = $this->page->context;
-
         if (empty($quizid)) {
             $this->content->text = get_string('error_emptyquizid', 'block_quiz_results');
             return $this->content;
@@ -84,15 +82,17 @@ class block_quiz_results extends block_base {
         if (!empty($this->config->usegroups)) {
             if ($inquiz) {
                 $cm = $this->page->cm;
+                $context = $this->page->context;
             } else {
                 $cm = get_coursemodule_from_instance('quiz', $quizid, $courseid);
+                $context = get_context_instance(CONTEXT_MODULE, $cm->id);
             }
             $groupmode = groups_get_activity_groupmode($cm);
-        }
 
-        if (has_capability('moodle/site:accessallgroups', $context) && $groupmode == SEPARATEGROUPS) {
-            // We 'll make an exception in this case
-            $groupmode = VISIBLEGROUPS;
+            if ($groupmode == SEPARATEGROUPS && has_capability('moodle/site:accessallgroups', $context)) {
+                // We 'll make an exception in this case
+                $groupmode = VISIBLEGROUPS;
+            }
         }
 
         switch ($groupmode) {
index 0b3b9f74c581b1426750f87bbd3dc61ee9c42a0f..3dfc24b5e3653ab27fd2ed5f1197f3053e4d914b 100644 (file)
             }
         }
 
-        // TODO - temporary hack to get the block context only if it already exists.
-        global $DB;
-        if ($DB->record_exists('context', array('contextlevel' => CONTEXT_BLOCK, 'instanceid' => $this->instance->id))) {
-            $context = get_context_instance(CONTEXT_BLOCK, $this->instance->id);
-        } else {
-            $context = get_context_instance(CONTEXT_SYSTEM); // pinned blocks do not have own context
-        }
-
-        if (has_capability('block/rss_client:createsharedfeeds', $context)
-                || has_capability('block/rss_client:createprivatefeeds', $context)) {
+        if (has_any_capability(array('block/rss_client:createsharedfeeds', 'block/rss_client:createprivatefeeds'), $this->context)) {
 
             $page = $this->page;
             //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.
                 $output .= '<div class="info"><a title="'. get_string('feedsaddedit', 'block_rss_client') .'" href="'. $script .'">'. get_string('feedsaddedit', 'block_rss_client') .'</a></div>';
             } else {
                 // This instance has not been configured yet - show configure link?
-                if (has_capability('block/rss_client:manageanyfeeds', $context)) {
+                if (has_capability('block/rss_client:manageanyfeeds', $this->context)) {
                     $script = $page->url->out(
                                     array('instanceid' => $this->instance->id,
                                           'sesskey' => sesskey(),
index 2fc69e1aadcb444dadff63ac703c505b47a353a8..9de7b3b3de3cad9dcd85ec5cdecebf5b9dd8bcfe 100644 (file)
@@ -93,17 +93,10 @@ print_box_start();
                     print $checkbox . $feedtitle .'<br />'."\n";
                 }
             } else {
-                // TODO - temporary hack to get the block context only if it already exists.
-                global $DB;
-                if ($DB->record_exists('context', array('contextlevel' => CONTEXT_BLOCK, 'instanceid' => $this->instance->id))) {
-                    $context = get_context_instance(CONTEXT_BLOCK, $this->instance->id);
-                } else {
-                    $context = get_context_instance(CONTEXT_SYSTEM); // pinned blocks do not have own context
-                }
                 print_string('nofeeds', 'block_rss_client');
 
-                if (has_capability('block/rss_client:createprivatefeeds', $context)
-                        || has_capability('block/rss_client:createsharedfeeds', $context)) {
+                if (has_capability('block/rss_client:createprivatefeeds', $this->context)
+                        || has_capability('block/rss_client:createsharedfeeds', $this->context)) {
 
                     $addrsspage = $page->url->out(array('instanceid' => $this->instance->id,
                                                             'sesskey' => sesskey(),
@@ -175,17 +168,10 @@ print_box_start();
 } else {
   global $act, $url, $rssid, $preferredtitle, $shared;
   print '</div></form></div>';   // Closes off page form
-  // TODO - temporary hack to get the block context only if it already exists.
-  global $DB;
-  if ($DB->record_exists('context', array('contextlevel' => CONTEXT_BLOCK, 'instanceid' => $this->instance->id))) {
-    $context = get_context_instance(CONTEXT_BLOCK, $this->instance->id);
-  } else {
-    $context = get_context_instance(CONTEXT_SYSTEM); // pinned blocks do not have own context
-  }
 
   print_box_start();
   rss_display_feeds($id, $USER->id, '', $context);
-  rss_print_form($act, $url, $rssid, $preferredtitle, $shared, $id, $context);
+  rss_print_form($act, $url, $rssid, $preferredtitle, $shared, $id, $this->context);
   print_box_end();
 }
 ?>
index a577497a1505478ba97e5cada31fc5cbc7e91f1c..a7ac1d45d8f142df29bfedf287bf6028b39f1a62 100644 (file)
@@ -5,15 +5,7 @@
 global $USER;
 $tabs = $row = array();
 
-    // TODO - temporary hack to get the block context only if it already exists.
-    global $DB;
-    if ($DB->record_exists('context', array('contextlevel' => CONTEXT_BLOCK, 'instanceid' => $this->instance->id))) {
-        $context = get_context_instance(CONTEXT_BLOCK, $this->instance->id);
-    } else {
-        $context = get_context_instance(CONTEXT_SYSTEM); // pinned blocks do not have own context
-    }
-
-if (has_capability('moodle/site:manageblocks', $context)) {
+if (has_capability('moodle/site:manageblocks', $this->context)) {
     $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'));
index 325bd485b509e22cf9da135520fe6cdba8918829..3124f5024adaa4568047998619a4ea58491b6558 100755 (executable)
@@ -483,8 +483,9 @@ function has_capability($capability, $context, $userid=NULL, $doanything=true) {
         if (empty($USER->id)) {
             // Session not set up yet.
             $userid = 0;
+        } else {
+            $userid = $USER->id;
         }
-        $userid = $USER->id;
     }
 
     if (is_null($context->path) or $context->depth == 0) {
@@ -2221,11 +2222,10 @@ function create_context($contextlevel, $instanceid) {
             break;
 
         case CONTEXT_BLOCK:
-            // Only non-pinned & course-page based
             $sql = "SELECT ctx.path, ctx.depth
                       FROM {context} ctx
                       JOIN {block_instances} bi ON (bi.parentcontextid=ctx.id)
-                     WHERE bi.id=? AND ctx.contextlevel=?";
+                     WHERE bi.id = ?";
             $params = array($instanceid, CONTEXT_COURSE);
             if ($p = $DB->get_record_sql($sql, $params)) {
                 $basepath  = $p->path;
@@ -2410,7 +2410,8 @@ function create_contexts($contextlevel=null, $buildpaths=true) {
 
     }
 
-    if (empty($contextlevel) or $contextlevel == CONTEXT_MODULE) {
+    if (empty($contextlevel) or $contextlevel == CONTEXT_MODULE
+                             or $contextlevel == CONTEXT_BLOCK) {
         $sql = "INSERT INTO {context} (contextlevel, instanceid)
                 SELECT ".CONTEXT_MODULE.", cm.id
                   FROM {course}_modules cm
@@ -2420,17 +2421,8 @@ function create_contexts($contextlevel=null, $buildpaths=true) {
         $DB->execute($sql);
     }
 
-    if (empty($contextlevel) or $contextlevel == CONTEXT_BLOCK) {
-        $sql = "INSERT INTO {context} (contextlevel, instanceid)
-                SELECT ".CONTEXT_BLOCK.", bi.id
-                  FROM {block_instances} bi
-                 WHERE NOT EXISTS (SELECT 'x'
-                                     FROM {context} cx
-                                    WHERE bi.id = cx.instanceid AND cx.contextlevel=".CONTEXT_BLOCK.")";
-        $DB->execute($sql);
-    }
-
-    if (empty($contextlevel) or $contextlevel == CONTEXT_USER) {
+    if (empty($contextlevel) or $contextlevel == CONTEXT_USER
+                             or $contextlevel == CONTEXT_BLOCK) {
         $sql = "INSERT INTO {context} (contextlevel, instanceid)
                 SELECT ".CONTEXT_USER.", u.id
                   FROM {user} u
@@ -2442,6 +2434,16 @@ 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_instances} bi
+                 WHERE NOT EXISTS (SELECT 'x'
+                                     FROM {context} cx
+                                    WHERE bi.id = cx.instanceid AND cx.contextlevel=".CONTEXT_BLOCK.")";
+        $DB->execute($sql);
+    }
+
     if ($buildpaths) {
         build_context_path(false);
     }
@@ -2513,10 +2515,10 @@ function cleanup_contexts() {
 }
 
 /**
- * Preloads all contexts relating to a course: course, modules, and blocks.
+ * Preloads all contexts relating to a course: course, modules. Block contexts
+ * are no longer loaded here. The contexts for all the blocks on the current
+ * page are now efficiently loaded by {@link block_manager::load_blocks()}.
  *
- * @global object
- * @global object
  * @param int $courseid Course ID
  * @return void
  */
@@ -2535,15 +2537,6 @@ function preload_course_contexts($courseid) {
               JOIN {context} x ON x.instanceid=cm.id
              WHERE cm.course=? AND x.contextlevel=".CONTEXT_MODULE."
 
-         UNION ALL
-
-            SELECT x.instanceid, x.id, x.contextlevel, x.path, x.depth
-              FROM {context} px
-              JOIN {block_instances} bi ON bi.parentcontextid = px.id
-              JOIN {context} x ON x.instanceid=bi.id
-              WHERE px.instanceid = ? AND px.contextlevel = ".CONTEXT_COURSE."
-                   AND x.contextlevel=".CONTEXT_BLOCK."
-
          UNION ALL
 
             SELECT x.instanceid, x.id, x.contextlevel, x.path, x.depth
@@ -2564,8 +2557,6 @@ function preload_course_contexts($courseid) {
  *
  * @todo Remove code branch from previous fix MDL-9016 which is no longer needed
  *
- * @global object
- * @global object
  * @param integer $level The context level, for example CONTEXT_COURSE, or CONTEXT_MODULE.
  * @param integer $instance The instance id. For $level = CONTEXT_COURSE, this would be $course->id,
  *      for $level = CONTEXT_MODULE, this would be $cm->id. And so on. Defaults to 0
@@ -3482,7 +3473,7 @@ function print_context_name($context, $withprefix = true, $short = false) {
     $name = '';
     switch ($context->contextlevel) {
 
-        case CONTEXT_SYSTEM: // by now it's a definite an inherit
+        case CONTEXT_SYSTEM:
             $name = get_string('coresystem');
             break;
 
@@ -3495,7 +3486,7 @@ function print_context_name($context, $withprefix = true, $short = false) {
             }
             break;
 
-        case CONTEXT_COURSECAT: // Coursecat -> coursecat or site
+        case CONTEXT_COURSECAT:
             if ($category = $DB->get_record('course_categories', array('id'=>$context->instanceid))) {
                 if ($withprefix){
                     $name = get_string('category').': ';
@@ -3504,7 +3495,7 @@ function print_context_name($context, $withprefix = true, $short = false) {
             }
             break;
 
-        case CONTEXT_COURSE: // 1 to 1 to course cat
+        case CONTEXT_COURSE:
             if ($context->instanceid == SITEID) {
                 $name = get_string('frontpage', 'admin');
             } else {
@@ -3521,7 +3512,7 @@ function print_context_name($context, $withprefix = true, $short = false) {
             }
             break;
 
-        case CONTEXT_MODULE: // 1 to 1 to course
+        case CONTEXT_MODULE:
             if ($cm = $DB->get_record_sql('SELECT cm.*, md.name AS modname FROM {course_modules} cm ' .
                     'JOIN {modules} md ON md.id = cm.module WHERE cm.id = ?', array($context->instanceid))) {
                 if ($mod = $DB->get_record($cm->modname, array('id' => $cm->instance))) {
@@ -3533,7 +3524,7 @@ function print_context_name($context, $withprefix = true, $short = false) {
                 }
             break;
 
-        case CONTEXT_BLOCK: // not necessarily 1 to 1 to course
+        case CONTEXT_BLOCK:
             if ($blockinstance = $DB->get_record('block_instances', array('id'=>$context->instanceid))) {
                 global $CFG;
                 require_once("$CFG->dirroot/blocks/moodleblock.class.php");
@@ -3893,14 +3884,12 @@ function get_sorted_contexts($select, $params = array()) {
  * displayed in the course page.
  *
  * For course category contexts it will return categories and courses. It will
- * NOT recurse into courses - if you want to do that, call it on the returned
- * courses.
+ * NOT recurse into courses, nor return blocks on the category pages. If you
+ * want to do that, call it on the returned courses.
  *
  * If called on a course context it _will_ populate the cache with the appropriate
  * contexts ;-)
  *
- * @global object
- * @global object
  * @param object $context.
  * @return array Array of child records
  */
@@ -3920,14 +3909,23 @@ function get_child_contexts($context) {
         break;
 
         case CONTEXT_MODULE:
-            // No children.
-            return array();
-        break;
+            // Find
+            // - blocks under this context path.
+            $sql = " SELECT ctx.*
+                       FROM {context} ctx
+                      WHERE ctx.path LIKE ?
+                            AND ctx.contextlevel = ".CONTEXT_BLOCK;
+            $params = array("{$context->path}/%", $context->instanceid);
+            $records = $DB->get_recordset_sql($sql, $params);
+            foreach ($records as $rec) {
+                cache_context($rec);
+            }
+            return $records;
+            break;
 
         case CONTEXT_COURSE:
             // Find
-            // - module instances - easy
-            // - blocks assigned to the course-view page explicitly - easy
+            // - modules and blocks under this context path.
             $sql = " SELECT ctx.*
                        FROM {context} ctx
                       WHERE ctx.path LIKE ?
@@ -3957,9 +3955,20 @@ function get_child_contexts($context) {
         break;
 
         case CONTEXT_USER:
-            // No children.
-            return array();
-        break;
+            // Find
+            // - blocks under this context path.
+            $sql = " SELECT ctx.*
+                       FROM {context} ctx
+                      WHERE ctx.path LIKE ?
+                            AND ctx.contextlevel = ".CONTEXT_BLOCK;
+            $params = array("{$context->path}/%", $context->instanceid);
+            $records = $DB->get_recordset_sql($sql, $params);
+            foreach ($records as $rec) {
+                cache_context($rec);
+            }
+            return $records;
+            break;
+            break;
 
         case CONTEXT_SYSTEM:
             // Just get all the contexts except for CONTEXT_SYSTEM level
@@ -3973,7 +3982,7 @@ function get_child_contexts($context) {
 
         default:
             print_error('unknowcontext', '', '', $context->contextlevel);
-        return false;
+            return false;
     }
 }
 
@@ -5828,10 +5837,16 @@ function role_fix_names($roleoptions, $context, $rolenamedisplay=ROLENAME_ALIAS)
     // If necessary, get the localised names.
     if ($rolenamedisplay != ROLENAME_ORIGINAL && !empty($context->id)) {
         // Make sure we have a course context.
-        if ($context->contextlevel == CONTEXT_MODULE || $context->contextlevel == CONTEXT_BLOCK) {  // find the parent course context
+        if ($context->contextlevel == CONTEXT_MODULE) {
             if ($parentcontextid = array_shift(get_parent_contexts($context))) {
                 $context = get_context_instance_by_id($parentcontextid);
             }
+        } else if ($context->contextlevel == CONTEXT_BLOCK) {
+            do {
+                if ($parentcontextid = array_shift(get_parent_contexts($context))) {
+                    $context = get_context_instance_by_id($parentcontextid);
+                }
+            } while ($parentcontextid && $context->contextlevel != CONTEXT_COURSE);
         }
 
         // The get the relevant renames, and use them.
@@ -5925,8 +5940,6 @@ function rebuild_contexts(array $fixcontexts) {
 /**
  * Populate context.path and context.depth where missing.
  *
- * @global object
- * @global object
  * @param bool $force force a complete rebuild of the path and depth fields, defaults to false
  */
 function build_context_path($force=false) {
index f6cb661198d4bc11ba11fb59708a891de7ed6c0e..f667c86b23d183fb72e53aefa0e40c91d10f4544 100644 (file)
@@ -407,6 +407,7 @@ class block_manager {
             'contextid1' => $context->id,
             'contextid2' => $context->id,
             'pagetype' => $this->page->pagetype,
+            'contextblock' => CONTEXT_BLOCK,
         );
         $sql = "SELECT
                     bi.id,
@@ -419,7 +420,11 @@ class block_manager {
                     COALESCE(bp.visible, 1) AS visible,
                     COALESCE(bp.region, bi.defaultregion) AS region,
                     COALESCE(bp.weight, bi.defaultweight) AS weight,
-                    bi.configdata
+                    bi.configdata,
+                    ctx.id AS ctxid,
+                    ctx.path AS ctxpath,
+                    ctx.depth AS ctxdepth,
+                    ctx.contextlevel AS ctxlevel
 
                 FROM {block_instances} bi
                 JOIN {block} b ON bi.blockname = b.name
@@ -427,6 +432,8 @@ class block_manager {
                                                   AND bp.contextid = :contextid1
                                                   AND bp.pagetype = :pagetype
                                                   AND bp.subpage = :subpage1
+                JOIN {context} ctx ON ctx.contextlevel = :contextblock
+                                      AND ctx.instanceid = bi.id
 
                 WHERE
                 $contexttest
@@ -444,6 +451,7 @@ class block_manager {
         $this->birecordsbyregion = $this->prepare_per_region_arrays();
         $unknown = array();
         foreach ($blockinstances as $bi) {
+            $bi = make_context_subobj($bi);
             if ($this->is_known_region($bi->region)) {
                 $this->birecordsbyregion[$bi->region][] = $bi;
             } else {
@@ -491,12 +499,11 @@ class block_manager {
         $blockinstance->configdata = '';
         $blockinstance->id = $DB->insert_record('block_instances', $blockinstance);
 
-        if ($this->page->context->contextlevel == CONTEXT_COURSE) {
-            get_context_instance(CONTEXT_BLOCK, $blockinstance->id);
-        }
+        // Ensure the block context is created.
+        get_context_instance(CONTEXT_BLOCK, $blockinstance->id);
 
         // If the new instance was created, allow it to do additional setup
-        if($block = block_instance($blockname, $blockinstance)) {
+        if ($block = block_instance($blockname, $blockinstance)) {
             $block->instance_create();
         }
     }
index 27d603694d49b5d77a6e7bf46bb6da802c5850cf..8371ff076f23fcdd232e105410a08eedeb5a0ceb 100644 (file)
@@ -2302,8 +2302,29 @@ WHERE gradeitemid IS NOT NULL AND grademax IS NOT NULL");
         upgrade_main_savepoint($result, 2009071000);
     }
 
+    if ($result && $oldversion < 2009071300) {
+
+    /// Create contexts for every block. In the past, only non-sticky course block had contexts.
+    /// This is a copy of the code in create_contexts.
+        $sql = "INSERT INTO {context} (contextlevel, instanceid)
+                SELECT " . CONTEXT_BLOCK . ", bi.id
+                  FROM {block_instances} bi
+                 WHERE NOT EXISTS (SELECT 'x'
+                                     FROM {context} ctx
+                                    WHERE bi.id = ctx.instanceid AND ctx.contextlevel=" . CONTEXT_BLOCK . ")";
+        $DB->execute($sql);
+
+    /// TODO MDL-19776 We should not really use API funcitons in upgrade.
+    /// If MDL-19776 is done, we can remove this whole upgrade block.
+        build_context_path();
+
+    /// Main savepoint reached
+        upgrade_main_savepoint($result, 2009071300);
+    }
+
     return $result;
 }
 
-//TODO: before 2.0 release
-// 1/ remove the automatic enabling of completion lib if debug enabled
\ No newline at end of file
+//TODO: Before 2.0 release
+// 1/ remove the automatic enabling of completion lib if debug enabled ( in 2008121701 block)
+// 2/ move 2009061300 block to the top of the file so that we may log upgrade queries
index 97234875aa261b51eccec3d08ddf82f903b3481b..e2fd037dae077deded73fb59e3aca67b989f8d19 100644 (file)
@@ -6,7 +6,7 @@
 // This is compared against the values stored in the database to determine
 // whether upgrades should be performed (see lib/db/*.php)
 
-    $version = 2009071000;  // YYYYMMDD   = date of the last version bump
+    $version = 2009071300;  // YYYYMMDD   = date of the last version bump
                             //         XX = daily increments
 
     $release = '2.0 dev (Build: 20090713)';  // Human-friendly version name