diff --git a/admin/filters.php b/admin/filters.php index 5c65c74085c..5f58bc7ee67 100644 --- a/admin/filters.php +++ b/admin/filters.php @@ -242,6 +242,7 @@ function get_table_row($filterinfo, $isfirstrow, $islastactive, $applytostrings) // Disable/off/on $select = new single_select(filters_action_url($filter, 'setstate'), 'newstate', $activechoices, $filterinfo->active, null, 'active' . basename($filter)); + $select->set_label(get_string('isactive', 'filters'), array('class' => 'accesshide')); $row[] = $OUTPUT->render($select); // Re-order @@ -263,6 +264,7 @@ function get_table_row($filterinfo, $isfirstrow, $islastactive, $applytostrings) // Apply to strings. $select = new single_select(filters_action_url($filter, 'setapplyto'), 'stringstoo', $applytochoices, $applytostrings, null, 'applyto' . basename($filter)); + $select->set_label(get_string('applyto', 'filters'), array('class' => 'accesshide')); $select->disabled = $filterinfo->active == TEXTFILTER_DISABLED; $row[] = $OUTPUT->render($select); diff --git a/admin/mnet/access_control.php b/admin/mnet/access_control.php index 0354f150ac6..1c0470e18f7 100644 --- a/admin/mnet/access_control.php +++ b/admin/mnet/access_control.php @@ -203,17 +203,18 @@ echo get_string('username') . ":\n"; if (!empty($formerror['username'])) { echo ' * '; } -echo ''; +echo html_writer::label(get_string('username'), 'menuusername', false, array('class' => 'accesshide')); +echo ''; // choose a remote host -echo " " . get_string('remotehost', 'mnet') . ":\n"; +echo " " . html_writer::label(get_string('remotehost', 'mnet'), 'menumnet_host_id') . ":\n"; if (!empty($formerror['mnet_host_id'])) { echo ' * '; } echo html_writer::select($mnethosts, 'mnet_host_id'); // choose an access level -echo " " . get_string('accesslevel', 'mnet') . ":\n"; +echo " " . html_writer::label(get_string('accesslevel', 'mnet'), 'menuaccessctrl') . ":\n"; if (!empty($formerror['accessctrl'])) { echo ' * '; } diff --git a/admin/portfolio.php b/admin/portfolio.php index 77aa8ea13a7..16aa66183ed 100644 --- a/admin/portfolio.php +++ b/admin/portfolio.php @@ -197,6 +197,7 @@ if (($action == 'edit') || ($action == 'new')) { $currentaction = 'hide'; } $select = new single_select(portfolio_action_url($pluginid, 'pf'), 'action', $actionchoicesforexisting, $currentaction, null, 'applyto' . $pluginid); + $select->set_label(get_string('action'), array('class' => 'accesshide')); $table->data[] = array($pluginname, $OUTPUT->render($select), $settings); } if (!in_array($plugin, $usedplugins)) { @@ -218,6 +219,7 @@ if (($action == 'edit') || ($action == 'new')) { $insaneplugins[] = $p; } else { $select = new single_select(portfolio_action_url($p, 'pf'), 'action', $actionchoicesfornew, 'delete', null, 'applyto' . $p); + $select->set_label(get_string('action'), array('class' => 'accesshide')); $table->data[] = array(portfolio_static_function($p, 'get_name'), $OUTPUT->render($select), ''); } } diff --git a/admin/repository.php b/admin/repository.php index 0adfdc6e8e2..3eb48b0da4d 100644 --- a/admin/repository.php +++ b/admin/repository.php @@ -352,7 +352,7 @@ if (($action == 'edit') || ($action == 'new')) { } $select = new single_select(repository_action_url($typename, 'repos'), 'action', $actionchoicesforexisting, $currentaction, null, 'applyto' . basename($typename)); - + $select->set_label(get_string('action'), array('class' => 'accesshide')); // Display up/down link $updown = ''; $spacer = $OUTPUT->spacer(array('height'=>15, 'width'=>15)); // should be done with CSS instead @@ -389,6 +389,7 @@ if (($action == 'edit') || ($action == 'new')) { // Check that it has not already been listed if (!in_array($plugin, $alreadyplugins)) { $select = new single_select(repository_action_url($plugin, 'repos'), 'action', $actionchoicesfornew, 'delete', null, 'applyto' . basename($plugin)); + $select->set_label(get_string('action'), array('class' => 'accesshide')); $table->data[] = array(get_string('pluginname', 'repository_'.$plugin), $OUTPUT->render($select), '', ''); } } diff --git a/admin/timezone.php b/admin/timezone.php index 8cfefc7b7a4..546b021816a 100644 --- a/admin/timezone.php +++ b/admin/timezone.php @@ -44,7 +44,7 @@ $timezones = get_list_of_timezones(); echo '
'; - echo "$strusers ($strall): "; + echo html_writer::label($strusers . ' (' . $strall . '): ', 'menuzone'); echo html_writer::select($timezones, "zone", $current, array('99'=>get_string("serverlocaltime"))); echo ""; echo ''; diff --git a/admin/tool/langimport/index.php b/admin/tool/langimport/index.php index 80d8829865f..82b5cc23f58 100644 --- a/admin/tool/langimport/index.php +++ b/admin/tool/langimport/index.php @@ -287,7 +287,7 @@ $url = new moodle_url('/admin/tool/langimport/index.php', array('mode' => DELETI echo html_writer::start_tag('td', array('valign' => 'top')); echo html_writer::start_tag('form', array('id' => 'uninstallform', 'action' => $url->out(), 'method' => 'post')); echo html_writer::start_tag('fieldset'); -echo html_writer::label(get_string('installedlangs', 'tool_langimport'), 'uninstalllang'); +echo html_writer::label(get_string('installedlangs', 'tool_langimport'), 'menuuninstalllang'); echo html_writer::empty_tag('br'); echo html_writer::select($installedlangs, 'uninstalllang', '', false, array('size' => 15)); echo html_writer::empty_tag('input', array('type' => 'hidden', 'name' => 'sesskey', 'value' => sesskey())); @@ -315,7 +315,7 @@ if (!empty($options)) { $url = new moodle_url('/admin/tool/langimport/index.php', array('mode' => INSTALLATION_OF_SELECTED_LANG)); echo html_writer::start_tag('form', array('id' => 'installform', 'action' => $url->out(), 'method' => 'post')); echo html_writer::start_tag('fieldset'); - echo html_writer::label(get_string('availablelangs','install'), 'pack'); + echo html_writer::label(get_string('availablelangs','install'), 'menupack'); echo html_writer::empty_tag('br'); echo html_writer::select($options, 'pack[]', '', false, array('size' => 15, 'multiple' => 'multiple')); echo html_writer::empty_tag('input', array('type' => 'hidden', 'name' => 'sesskey', 'value' => sesskey())); diff --git a/admin/tool/spamcleaner/index.php b/admin/tool/spamcleaner/index.php index 443f5cdffee..083527058fa 100644 --- a/admin/tool/spamcleaner/index.php +++ b/admin/tool/spamcleaner/index.php @@ -96,6 +96,7 @@ echo $OUTPUT->box_start(); // The forms section at the top
+ diff --git a/admin/tool/spamcleaner/lang/en/tool_spamcleaner.php b/admin/tool/spamcleaner/lang/en/tool_spamcleaner.php index 5a863570803..df6b4a338b0 100644 --- a/admin/tool/spamcleaner/lang/en/tool_spamcleaner.php +++ b/admin/tool/spamcleaner/lang/en/tool_spamcleaner.php @@ -38,6 +38,7 @@ $string['spamfromcomments'] = 'From comments:'; $string['spamfrommessages'] = 'From messages:'; $string['spamfromforumpost'] = 'From forum post:'; $string['spaminvalidresult'] = 'Unknown but invalid result'; +$string['spamkeyword'] = 'Keyword'; $string['spamoperation'] = 'Operation'; $string['spamresult'] = 'Results of searching user profiles containing:'; $string['spamsearch'] = 'Search for these keywords'; diff --git a/admin/tool/xmldb/actions/new_table_from_mysql/new_table_from_mysql.class.php b/admin/tool/xmldb/actions/new_table_from_mysql/new_table_from_mysql.class.php index 4dca286a024..8332d219b87 100644 --- a/admin/tool/xmldb/actions/new_table_from_mysql/new_table_from_mysql.class.php +++ b/admin/tool/xmldb/actions/new_table_from_mysql/new_table_from_mysql.class.php @@ -113,7 +113,7 @@ class new_table_from_mysql extends XMLDBAction { $o.= ' '; $o.= ' '; $o.= ' '; - $o.= ' '; + $o.= ' '; $o.= ' '; $o.= ' '; $o.= '
' . html_writer::select($selecttables, 'table') . '' .html_writer::select($aftertables, 'after') . '
' . html_writer::select($selecttables, 'table') . '' .html_writer::select($aftertables, 'after') . '
[' . $this->str['back'] . ']
'; diff --git a/admin/tool/xmldb/actions/view_structure_php/view_structure_php.class.php b/admin/tool/xmldb/actions/view_structure_php/view_structure_php.class.php index 11d779cf008..0ddf559ab34 100644 --- a/admin/tool/xmldb/actions/view_structure_php/view_structure_php.class.php +++ b/admin/tool/xmldb/actions/view_structure_php/view_structure_php.class.php @@ -114,7 +114,7 @@ class view_structure_php extends XMLDBAction { $o.= ' '; $o.= ' '; $o.= ' '; - $o.= ' '; + $o.= ' '; $o.= ' '; $o.= '
' . html_writer::select($popcommands, 'command', $commandparam, false) . ' ' .html_writer::select($poptables, 'table', $tableparam, false) . '
' . html_writer::select($popcommands, 'command', $commandparam, false) . ' ' .html_writer::select($poptables, 'table', $tableparam, false) . '
'; $o.= '
'; diff --git a/admin/tool/xmldb/actions/view_table_php/view_table_php.class.php b/admin/tool/xmldb/actions/view_table_php/view_table_php.class.php index 132c881bc10..235056f3faa 100644 --- a/admin/tool/xmldb/actions/view_table_php/view_table_php.class.php +++ b/admin/tool/xmldb/actions/view_table_php/view_table_php.class.php @@ -163,7 +163,7 @@ class view_table_php extends XMLDBAction { $o.= ' '; $o.= ' '; $o.= ' '; - $o.= ' '; + $o.= ' '; $o.= ' '; $o.= '
' . html_writer::select($popcommands, 'command', $commandparam, false) . ' ' .html_writer::select($popfields, 'fieldkeyindex', $origfieldkeyindexparam, false) . '
' . html_writer::select($popcommands, 'command', $commandparam, false) . ' ' .html_writer::select($popfields, 'fieldkeyindex', $origfieldkeyindexparam, false) . '
'; $o.= ''; diff --git a/auth/cas/config.html b/auth/cas/config.html index 4781cb90ffa..28557dda239 100644 --- a/auth/cas/config.html +++ b/auth/cas/config.html @@ -94,9 +94,9 @@ $yesno = array( get_string('no'), get_string('yes') ); - : + - + error_text($err['hostname']); } ?> @@ -105,10 +105,10 @@ $yesno = array( get_string('no'), get_string('yes') ); - : + - + error_text($err['baseuri']); } ?> @@ -117,10 +117,10 @@ $yesno = array( get_string('no'), get_string('yes') ); - : + - + error_text($err['port']); } ?> @@ -129,7 +129,7 @@ $yesno = array( get_string('no'), get_string('yes') ); - : + : - : + : language, false); ?> @@ -155,7 +155,7 @@ $yesno = array( get_string('no'), get_string('yes') ); - : + : proxycas, false); ?> @@ -165,7 +165,7 @@ $yesno = array( get_string('no'), get_string('yes') ); - : + : logoutcas, false); ?> @@ -174,7 +174,7 @@ $yesno = array( get_string('no'), get_string('yes') ); - : + : multiauth, false); ?> @@ -183,7 +183,7 @@ $yesno = array( get_string('no'), get_string('yes') ); - : + : certificate_check, false); ?> @@ -192,7 +192,7 @@ $yesno = array( get_string('no'), get_string('yes') ); - : + error_text($err['certificate_path']); ?> @@ -219,7 +219,7 @@ $yesno = array( get_string('no'), get_string('yes') ); - + - : + - + error_text($err["host"]); ?> @@ -38,9 +38,9 @@ - : + - + error_text($err["host"]); ?> @@ -49,9 +49,9 @@ - : + - + error_text($err["userid"]); ?> @@ -59,9 +59,9 @@ - : + - + error_text($err["passwd"]); ?> @@ -70,9 +70,9 @@ - : + - + error_text($err["creators"]); ?> @@ -81,9 +81,9 @@ - : + - + changepasswordurl)) { - + - + - + - +
: - + changepasswordurl)) {
: : changepasswordurl)) {
: - + changepasswordurl)) {
: - +
- + mnet_dispatcher_mode) || $CFG->mnet_dispatcher_mode !== 'strict' - + +
: - + mnet_dispatcher_mode) || $CFG->mnet_dispatcher_mode !== 'strict' - : : changepasswordurl)) { - + - + - +
: - + changepasswordurl)) {
: - + changepasswordurl)) {
: - + changepasswordurl)) { - + - + - + - + - +
: - + changepasswordurl)) {
: : changepasswordurl)) {
: - + changepasswordurl)) {
: - + changepasswordurl)) {
: - + changepasswordurl)) { - + - + - + - + - + - + - + - + + + + '; diff --git a/course/lib.php b/course/lib.php index c2bc4054a78..44255766160 100644 --- a/course/lib.php +++ b/course/lib.php @@ -4038,7 +4038,7 @@ function average_number_of_participants() { WHERE ue.enrolid = e.id AND e.courseid <> :siteid AND c.id = e.courseid - AND c.visible = 1)'; + AND c.visible = 1) total'; $params = array('siteid' => $SITE->id); $enrolmenttotal = $DB->count_records_sql($sql, $params); @@ -4071,7 +4071,7 @@ function average_number_of_courses_modules() { WHERE c.id = cm.course AND c.id <> :siteid AND cm.visible = 1 - AND c.visible = 1)'; + AND c.visible = 1) total'; $params = array('siteid' => $SITE->id); $moduletotal = $DB->count_records_sql($sql, $params); diff --git a/course/reset.php b/course/reset.php index 528c90886b8..09a440bd0cf 100644 --- a/course/reset.php +++ b/course/reset.php @@ -39,7 +39,7 @@ if (!$course = $DB->get_record('course', array('id'=>$id))) { $PAGE->set_url('/course/reset.php', array('id'=>$id)); require_login($course); -require_capability('moodle/course:update', context_course::instance($course->id)); +require_capability('moodle/course:reset', context_course::instance($course->id)); $strreset = get_string('reset'); $strresetcourse = get_string('resetcourse'); diff --git a/course/scales.php b/course/scales.php index 37d64738c2e..d212489c8b6 100644 --- a/course/scales.php +++ b/course/scales.php @@ -70,7 +70,8 @@ if ($scaleid) { echo $OUTPUT->box_start(); echo $OUTPUT->heading($scale->name); echo "
"; - echo html_writer::select($scalemenu, 'unused'); + echo html_writer::label(get_string('scales'), 'scaleunused'. $scaleid, false, array('class' => 'accesshide')); + echo html_writer::select($scalemenu, 'unused', '', array('' => 'choosedots'), array('id' => 'scaleunused'.$scaleid)); echo "
"; echo text_to_html($scale->description); echo $OUTPUT->box_end(); @@ -101,7 +102,8 @@ if ($scales = $DB->get_records("scale", array("courseid"=>$course->id), "name AS echo $OUTPUT->box_start(); echo $OUTPUT->heading($scale->name); echo "
"; - echo html_writer::select($scalemenu, 'unused'); + echo html_writer::label(get_string('scales'), 'courseunused' . $scale->id, false, array('class' => 'accesshide')); + echo html_writer::select($scalemenu, 'unused', '', array('' => 'choosedots'), array('id' => 'courseunused' . $scale->id)); echo "
"; echo text_to_html($scale->description); echo $OUTPUT->box_end(); @@ -127,7 +129,8 @@ if ($scales = $DB->get_records("scale", array("courseid"=>0), "name ASC")) { echo $OUTPUT->box_start(); echo $OUTPUT->heading($scale->name); echo "
"; - echo html_writer::select($scalemenu, 'unused'); + echo html_writer::label(get_string('scales'), 'sitescale' . $scale->id, false, array('class' => 'accesshide')); + echo html_writer::select($scalemenu, 'unused', '', array('' => 'choosedots'), array('id' => 'sitescale' . $scale->id)); echo "
"; echo text_to_html($scale->description); echo $OUTPUT->box_end(); diff --git a/course/search.php b/course/search.php index 246577cd034..8c9f85cd156 100644 --- a/course/search.php +++ b/course/search.php @@ -377,6 +377,7 @@ if ($courses) { echo "\n"; echo "\n"; // Select box should only show categories in which user has min capability to move course. + echo html_writer::label(get_string('moveselectedcoursesto'), 'movetoid', false, array('class' => 'accesshide')); echo html_writer::select($usercatlist, 'moveto', '', array(''=>get_string('moveselectedcoursesto')), array('id'=>'movetoid')); $PAGE->requires->js_init_call('M.util.init_select_autosubmit', array('movecourses', 'movetoid', false)); echo "\n\n"; diff --git a/course/yui/dragdrop/dragdrop.js b/course/yui/dragdrop/dragdrop.js index 435b3559bc1..431408d1ae1 100644 --- a/course/yui/dragdrop/dragdrop.js +++ b/course/yui/dragdrop/dragdrop.js @@ -411,4 +411,4 @@ YUI.add('moodle-course-dragdrop', function(Y) { M.course.init_section_dragdrop = function(params) { new DRAGSECTION(params); } -}, '@VERSION@', {requires:['base', 'node', 'io', 'dom', 'dd', 'dd-scroll', 'moodle-core-dragdrop', 'moodle-enrol-notification', 'moodle-course-coursebase']}); +}, '@VERSION@', {requires:['base', 'node', 'io', 'dom', 'dd', 'dd-scroll', 'moodle-core-dragdrop', 'moodle-core-notification', 'moodle-course-coursebase']}); diff --git a/enrol/cohort/yui/quickenrolment/quickenrolment.js b/enrol/cohort/yui/quickenrolment/quickenrolment.js index 7f5437ec137..6c22963ef33 100644 --- a/enrol/cohort/yui/quickenrolment/quickenrolment.js +++ b/enrol/cohort/yui/quickenrolment/quickenrolment.js @@ -381,4 +381,4 @@ YUI.add('moodle-enrol_cohort-quickenrolment', function(Y) { } } -}, '@VERSION@', {requires:['base','node', 'overlay', 'io-base', 'test', 'json-parse', 'event-delegate', 'dd-plugin', 'event-key', 'moodle-enrol-notification']}); +}, '@VERSION@', {requires:['base','node', 'overlay', 'io-base', 'test', 'json-parse', 'event-delegate', 'dd-plugin', 'event-key', 'moodle-core-notification']}); diff --git a/enrol/externallib.php b/enrol/externallib.php index cb3c7854ced..0fd4182d488 100644 --- a/enrol/externallib.php +++ b/enrol/externallib.php @@ -273,6 +273,7 @@ class core_enrol_external extends external_api { 'msn' => new external_value(PARAM_NOTAGS, 'msn number', VALUE_OPTIONAL), 'department' => new external_value(PARAM_TEXT, 'department', VALUE_OPTIONAL), 'institution' => new external_value(PARAM_TEXT, 'institution', VALUE_OPTIONAL), + 'idnumber' => new external_value(PARAM_RAW, 'An arbitrary ID code number perhaps from the institution', VALUE_OPTIONAL), 'interests' => new external_value(PARAM_TEXT, 'user interests (separated by commas)', VALUE_OPTIONAL), 'firstaccess' => new external_value(PARAM_INT, 'first access to the site (0 if never)', VALUE_OPTIONAL), 'lastaccess' => new external_value(PARAM_INT, 'last access to the site (0 if never)', VALUE_OPTIONAL), diff --git a/enrol/manual/yui/quickenrolment/quickenrolment.js b/enrol/manual/yui/quickenrolment/quickenrolment.js index 88c09ea4dab..08f8d702823 100644 --- a/enrol/manual/yui/quickenrolment/quickenrolment.js +++ b/enrol/manual/yui/quickenrolment/quickenrolment.js @@ -524,4 +524,4 @@ YUI.add('moodle-enrol_manual-quickenrolment', function(Y) { } } -}, '@VERSION@', {requires:['base','node', 'overlay', 'io-base', 'test', 'json-parse', 'event-delegate', 'dd-plugin', 'event-key', 'moodle-enrol-notification']}); +}, '@VERSION@', {requires:['base','node', 'overlay', 'io-base', 'test', 'json-parse', 'event-delegate', 'dd-plugin', 'event-key', 'moodle-core-notification']}); diff --git a/enrol/yui/notification/notification.js b/enrol/yui/notification/notification.js index 8b9144331a9..f2bf542a384 100644 --- a/enrol/yui/notification/notification.js +++ b/enrol/yui/notification/notification.js @@ -1,385 +1,7 @@ +/** + * This module provides backwards compatability and should be removed + * entirely in Moodle 2.5 + */ YUI.add('moodle-enrol-notification', function(Y) { - -var DIALOGUE_NAME = 'Moodle dialogue', - DIALOGUE_PREFIX = 'moodle-dialogue', - CONFIRM_NAME = 'Moodle confirmation dialogue', - EXCEPTION_NAME = 'Moodle exception', - AJAXEXCEPTION_NAME = 'Moodle AJAX exception', - ALERT_NAME = 'Moodle alert', - C = Y.Node.create, - BASE = 'notificationBase', - LIGHTBOX = 'lightbox', - NODELIGHTBOX = 'nodeLightbox', - COUNT = 0, - CONFIRMYES = 'yesLabel', - CONFIRMNO = 'noLabel', - TITLE = 'title', - QUESTION = 'question', - CSS = { - BASE : 'moodle-dialogue-base', - WRAP : 'moodle-dialogue-wrap', - HEADER : 'moodle-dialogue-hd', - BODY : 'moodle-dialogue-bd', - CONTENT : 'moodle-dialogue-content', - FOOTER : 'moodle-dialogue-fd', - HIDDEN : 'hidden', - LIGHTBOX : 'moodle-dialogue-lightbox' - }; - -var DIALOGUE = function(config) { - COUNT++; - var id = 'moodle-dialogue-'+COUNT; - config.notificationBase = - C('
') - .append(C('
')) - .append(C('
') - .append(C('
')) - .append(C('
')) - .append(C('
'))); - Y.one(document.body).append(config.notificationBase); - config.srcNode = '#'+id; - config.width = config.width || '400px'; - config.visible = config.visible || false; - config.center = config.centered || true; - config.centered = false; - DIALOGUE.superclass.constructor.apply(this, [config]); -}; -Y.extend(DIALOGUE, Y.Overlay, { - initializer : function(config) { - this.set(NODELIGHTBOX, this.get(BASE).one('.'+CSS.LIGHTBOX).setStyle('opacity', 0.5)); - this.after('visibleChange', this.visibilityChanged, this); - this.after('headerContentChange', function(e){ - var h = (this.get('closeButton'))?this.get(BASE).one('.'+CSS.HEADER):false; - if (h && !h.one('.closebutton')) { - var c = C('
'); - c.on('click', this.hide, this); - h.append(c); - } - }, this); - this.render(); - this.show(); - }, - visibilityChanged : function(e) { - switch (e.attrName) { - case 'visible': - if (this.get(LIGHTBOX)) { - var l = this.get(NODELIGHTBOX); - if (!e.prevVal && e.newVal) { - l.setStyle('height',l.get('docHeight')+'px').removeClass(CSS.HIDDEN); - } else if (e.prevVal && !e.newVal) { - l.addClass(CSS.HIDDEN); - } - } - if (this.get('center') && !e.prevVal && e.newVal) { - this.centerDialogue(); - } - if (this.get('draggable')) { - var titlebar = '#' + this.get('id') + ' .' + CSS.HEADER; - this.plug(Y.Plugin.Drag, {handles : [titlebar]}); - this.dd.addInvalid('div.closebutton'); - Y.one(titlebar).setStyle('cursor', 'move'); - } - break; - } - }, - centerDialogue : function() { - var bb = this.get('boundingBox'), hidden = bb.hasClass(DIALOGUE_PREFIX+'-hidden'); - if (hidden) { - bb.setStyle('top', '-1000px').removeClass(DIALOGUE_PREFIX+'-hidden'); - } - var x = Math.max(Math.round((bb.get('winWidth') - bb.get('offsetWidth'))/2), 15); - var y = Math.max(Math.round((bb.get('winHeight') - bb.get('offsetHeight'))/2), 15) + Y.one(window).get('scrollTop'); - - if (hidden) { - bb.addClass(DIALOGUE_PREFIX+'-hidden'); - } - bb.setStyle('left', x).setStyle('top', y); - } -}, { - NAME : DIALOGUE_NAME, - CSS_PREFIX : DIALOGUE_PREFIX, - ATTRS : { - notificationBase : { - - }, - nodeLightbox : { - value : null - }, - lightbox : { - validator : Y.Lang.isBoolean, - value : true - }, - closeButton : { - validator : Y.Lang.isBoolean, - value : true - }, - center : { - validator : Y.Lang.isBoolean, - value : true - }, - draggable : { - validator : Y.Lang.isBoolean, - value : false - } - } -}); - -var ALERT = function(config) { - config.closeButton = false; - ALERT.superclass.constructor.apply(this, [config]); -}; -Y.extend(ALERT, DIALOGUE, { - _enterKeypress : null, - initializer : function(config) { - this.publish('complete'); - var yes = C(''), - content = C('
') - .append(C('
'+this.get('message')+'
')) - .append(C('
') - .append(yes)); - this.get(BASE).addClass('moodle-dialogue-confirm'); - this.setStdModContent(Y.WidgetStdMod.BODY, content, Y.WidgetStdMod.REPLACE); - this.setStdModContent(Y.WidgetStdMod.HEADER, this.get(TITLE), Y.WidgetStdMod.REPLACE); - this.after('destroyedChange', function(){this.get(BASE).remove();}, this); - this._enterKeypress = Y.on('key', this.submit, window, 'down:13', this); - yes.on('click', this.submit, this); - }, - submit : function(e, outcome) { - this._enterKeypress.detach(); - this.fire('complete'); - this.hide(); - this.destroy(); - } -}, { - NAME : ALERT_NAME, - CSS_PREFIX : DIALOGUE_PREFIX, - ATTRS : { - title : { - validator : Y.Lang.isString, - value : 'Alert' - }, - message : { - validator : Y.Lang.isString, - value : 'Confirm' - }, - yesLabel : { - validator : Y.Lang.isString, - setter : function(txt) { - if (!txt) { - txt = 'Ok'; - } - return txt; - }, - value : 'Ok' - } - } -}); - -var CONFIRM = function(config) { - CONFIRM.superclass.constructor.apply(this, [config]); -}; -Y.extend(CONFIRM, DIALOGUE, { - _enterKeypress : null, - _escKeypress : null, - initializer : function(config) { - this.publish('complete'); - this.publish('complete-yes'); - this.publish('complete-no'); - var yes = C(''), - no = C(''), - content = C('
') - .append(C('
'+this.get(QUESTION)+'
')) - .append(C('
') - .append(yes) - .append(no)); - this.get(BASE).addClass('moodle-dialogue-confirm'); - this.setStdModContent(Y.WidgetStdMod.BODY, content, Y.WidgetStdMod.REPLACE); - this.setStdModContent(Y.WidgetStdMod.HEADER, this.get(TITLE), Y.WidgetStdMod.REPLACE); - this.after('destroyedChange', function(){this.get(BASE).remove();}, this); - this._enterKeypress = Y.on('key', this.submit, window, 'down:13', this, true); - this._escKeypress = Y.on('key', this.submit, window, 'down:27', this, false); - yes.on('click', this.submit, this, true); - no.on('click', this.submit, this, false); - }, - submit : function(e, outcome) { - this._enterKeypress.detach(); - this._escKeypress.detach(); - this.fire('complete', outcome); - if (outcome) { - this.fire('complete-yes'); - } else { - this.fire('complete-no'); - } - this.hide(); - this.destroy(); - } -}, { - NAME : CONFIRM_NAME, - CSS_PREFIX : DIALOGUE_PREFIX, - ATTRS : { - yesLabel : { - validator : Y.Lang.isString, - value : 'Yes' - }, - noLabel : { - validator : Y.Lang.isString, - value : 'No' - }, - title : { - validator : Y.Lang.isString, - value : 'Confirm' - }, - question : { - validator : Y.Lang.isString, - value : 'Are you sure?' - } - } -}); -Y.augment(CONFIRM, Y.EventTarget); - -var EXCEPTION = function(config) { - config.width = config.width || (M.cfg.developerdebug)?Math.floor(Y.one(document.body).get('winWidth')/3)+'px':null; - config.closeButton = true; - EXCEPTION.superclass.constructor.apply(this, [config]); -}; -Y.extend(EXCEPTION, DIALOGUE, { - _hideTimeout : null, - _keypress : null, - initializer : function(config) { - this.get(BASE).addClass('moodle-dialogue-exception'); - this.setStdModContent(Y.WidgetStdMod.HEADER, config.name, Y.WidgetStdMod.REPLACE); - var content = C('
') - .append(C('
'+this.get('message')+'
')) - .append(C('')) - .append(C('')) - .append(C('')); - if (M.cfg.developerdebug) { - content.all('.moodle-exception-param').removeClass('hidden'); - } - this.setStdModContent(Y.WidgetStdMod.BODY, content, Y.WidgetStdMod.REPLACE); - - var self = this; - var delay = this.get('hideTimeoutDelay'); - if (delay) { - this._hideTimeout = setTimeout(function(){self.hide();}, delay); - } - this.after('visibleChange', this.visibilityChanged, this); - this.after('destroyedChange', function(){this.get(BASE).remove();}, this); - this._keypress = Y.on('key', this.hide, window, 'down:13,27', this); - this.centerDialogue(); - }, - visibilityChanged : function(e) { - if (e.attrName == 'visible' && e.prevVal && !e.newVal) { - if (this._keypress) this._keypress.detach(); - var self = this; - setTimeout(function(){self.destroy();}, 1000); - } - } -}, { - NAME : EXCEPTION_NAME, - CSS_PREFIX : DIALOGUE_PREFIX, - ATTRS : { - message : { - value : '' - }, - name : { - value : '' - }, - fileName : { - value : '' - }, - lineNumber : { - value : '' - }, - stack : { - setter : function(str) { - var lines = str.split("\n"); - var pattern = new RegExp('^(.+)@('+M.cfg.wwwroot+')?(.{0,75}).*:(\\d+)$'); - for (var i in lines) { - lines[i] = lines[i].replace(pattern, "
ln: $4
$3
$1
"); - } - return lines.join(''); - }, - value : '' - }, - hideTimeoutDelay : { - validator : Y.Lang.isNumber, - value : null - } - } -}); - -var AJAXEXCEPTION = function(config) { - config.name = config.name || 'Error'; - config.closeButton = true; - AJAXEXCEPTION.superclass.constructor.apply(this, [config]); -}; -Y.extend(AJAXEXCEPTION, DIALOGUE, { - _keypress : null, - initializer : function(config) { - this.get(BASE).addClass('moodle-dialogue-exception'); - this.setStdModContent(Y.WidgetStdMod.HEADER, config.name, Y.WidgetStdMod.REPLACE); - var content = C('
') - .append(C('
'+this.get('error')+'
')) - .append(C('')) - .append(C('')) - .append(C('')); - if (M.cfg.developerdebug) { - content.all('.moodle-exception-param').removeClass('hidden'); - } - this.setStdModContent(Y.WidgetStdMod.BODY, content, Y.WidgetStdMod.REPLACE); - - var self = this; - var delay = this.get('hideTimeoutDelay'); - if (delay) { - this._hideTimeout = setTimeout(function(){self.hide();}, delay); - } - this.after('visibleChange', this.visibilityChanged, this); - this._keypress = Y.on('key', this.hide, window, 'down:13, 27', this); - this.centerDialogue(); - }, - visibilityChanged : function(e) { - if (e.attrName == 'visible' && e.prevVal && !e.newVal) { - var self = this; - this._keypress.detach(); - setTimeout(function(){self.destroy();}, 1000); - } - } -}, { - NAME : AJAXEXCEPTION_NAME, - CSS_PREFIX : DIALOGUE_PREFIX, - ATTRS : { - error : { - validator : Y.Lang.isString, - value : 'Unknown error' - }, - debuginfo : { - value : null - }, - stacktrace : { - value : null - }, - reproductionlink : { - setter : function(link) { - if (link !== null) { - link = ''+link.replace(M.cfg.wwwroot, '')+''; - } - return link; - }, - value : null - }, - hideTimeoutDelay : { - validator : Y.Lang.isNumber, - value : null - } - } -}); - -M.core = M.core || {}; -M.core.dialogue = DIALOGUE; -M.core.alert = ALERT; -M.core.confirm = CONFIRM; -M.core.exception = EXCEPTION; -M.core.ajaxException = AJAXEXCEPTION; - -}, '@VERSION@', {requires:['base','node','overlay','event-key', 'moodle-enrol-notification-skin', 'dd-plugin']}); + console.log("You are using a deprecated name. Please update your YUI module to use moodle-core-notification instead of moodle-enrol-notification"); +}, '@VERSION@', {requires:['base','node','overlay','event-key', 'moodle-core-notification']}); diff --git a/enrol/yui/otherusersmanager/otherusersmanager.js b/enrol/yui/otherusersmanager/otherusersmanager.js index 6685c1989fc..32b1ad87476 100644 --- a/enrol/yui/otherusersmanager/otherusersmanager.js +++ b/enrol/yui/otherusersmanager/otherusersmanager.js @@ -391,4 +391,4 @@ YUI.add('moodle-enrol-otherusersmanager', function(Y) { } } -}, '@VERSION@', {requires:['base','node', 'overlay', 'io-base', 'test', 'json-parse', 'event-delegate', 'dd-plugin', 'event-key', 'moodle-enrol-notification']}); \ No newline at end of file +}, '@VERSION@', {requires:['base','node', 'overlay', 'io-base', 'test', 'json-parse', 'event-delegate', 'dd-plugin', 'event-key', 'moodle-core-notification']}); diff --git a/enrol/yui/rolemanager/rolemanager.js b/enrol/yui/rolemanager/rolemanager.js index a03bc3502f5..afa52c2beb4 100644 --- a/enrol/yui/rolemanager/rolemanager.js +++ b/enrol/yui/rolemanager/rolemanager.js @@ -416,4 +416,4 @@ YUI.add('moodle-enrol-rolemanager', function(Y) { } } -}, '@VERSION@', {requires:['base','node','io-base','json-parse','test','moodle-enrol-notification']}); \ No newline at end of file +}, '@VERSION@', {requires:['base','node','io-base','json-parse','test','moodle-core-notification']}); diff --git a/filter/glossary/yui/autolinker/autolinker.js b/filter/glossary/yui/autolinker/autolinker.js index 484c42ef21b..1a1586df4a2 100644 --- a/filter/glossary/yui/autolinker/autolinker.js +++ b/filter/glossary/yui/autolinker/autolinker.js @@ -130,4 +130,4 @@ YUI.add('moodle-filter_glossary-autolinker', function(Y) { return new AUTOLINKER(config); } -}, '@VERSION@', {requires:['base','node','io-base','json-parse','event-delegate','overlay','moodle-enrol-notification']}); +}, '@VERSION@', {requires:['base','node','io-base','json-parse','event-delegate','overlay','moodle-core-notification']}); diff --git a/grade/grading/form/rubric/backup/moodle2/backup_gradingform_rubric_plugin.class.php b/grade/grading/form/rubric/backup/moodle2/backup_gradingform_rubric_plugin.class.php index 78741ec2a57..387406d93e4 100644 --- a/grade/grading/form/rubric/backup/moodle2/backup_gradingform_rubric_plugin.class.php +++ b/grade/grading/form/rubric/backup/moodle2/backup_gradingform_rubric_plugin.class.php @@ -106,8 +106,13 @@ class backup_gradingform_rubric_plugin extends backup_gradingform_plugin { // Set sources to populate the data - $filling->set_source_table('gradingform_rubric_fillings', - array('instanceid' => backup::VAR_PARENTID)); + // Binding criterionid to ensure it's existence + $filling->set_source_sql('SELECT rf.* + FROM {gradingform_rubric_fillings} rf + JOIN {grading_instances} gi ON gi.id = rf.instanceid + JOIN {gradingform_rubric_criteria} rc ON rc.id = rf.criterionid AND gi.definitionid = rc.definitionid + WHERE rf.instanceid = :instanceid', + array('instanceid' => backup::VAR_PARENTID)); // no need to annotate ids or files yet (one day when remark field supports // embedded fileds, they must be annotated here) diff --git a/grade/grading/form/rubric/backup/moodle2/restore_gradingform_rubric_plugin.class.php b/grade/grading/form/rubric/backup/moodle2/restore_gradingform_rubric_plugin.class.php index 62b5c96d9da..adb95978aa9 100644 --- a/grade/grading/form/rubric/backup/moodle2/restore_gradingform_rubric_plugin.class.php +++ b/grade/grading/form/rubric/backup/moodle2/restore_gradingform_rubric_plugin.class.php @@ -109,6 +109,9 @@ class restore_gradingform_rubric_plugin extends restore_gradingform_plugin { $data->criterionid = $this->get_mappingid('gradingform_rubric_criterion', $data->criterionid); $data->levelid = $this->get_mappingid('gradingform_rubric_level', $data->levelid); - $DB->insert_record('gradingform_rubric_fillings', $data); + if (!empty($data->criterionid)) { + $DB->insert_record('gradingform_rubric_fillings', $data); + } + } } diff --git a/grade/grading/form/rubric/lib.php b/grade/grading/form/rubric/lib.php index 71b38ecad2b..ae97eeedb0b 100644 --- a/grade/grading/form/rubric/lib.php +++ b/grade/grading/form/rubric/lib.php @@ -556,7 +556,8 @@ class gradingform_rubric_controller extends gradingform_controller { return $this->get_instance($instance); } if ($itemid && $raterid) { - if ($rs = $DB->get_records('grading_instances', array('raterid' => $raterid, 'itemid' => $itemid), 'timemodified DESC', '*', 0, 1)) { + $params = array('definitionid' => $this->definition->id, 'raterid' => $raterid, 'itemid' => $itemid); + if ($rs = $DB->get_records('grading_instances', $params, 'timemodified DESC', '*', 0, 1)) { $record = reset($rs); $currentinstance = $this->get_current_instance($raterid, $itemid); if ($record->status == gradingform_rubric_instance::INSTANCE_STATUS_INCOMPLETE && diff --git a/lang/en/message.php b/lang/en/message.php index fd25102a8f4..10c83e83de2 100644 --- a/lang/en/message.php +++ b/lang/en/message.php @@ -82,6 +82,7 @@ $string['messagehistory'] = 'Message history'; $string['messagehistoryfull'] = 'All messages'; $string['messages'] = 'Messages'; $string['messaging'] = 'Messaging'; +$string['messagingblockednoncontact'] = '{$a} will not be able to reply as you have blocked non-contacts'; $string['messagingdisabled'] = 'Messaging is disabled on this site, emails will be sent instead'; $string['mycontacts'] = 'My contacts'; $string['newonlymsg'] = 'Show only new'; @@ -140,5 +141,5 @@ $string['unreadnewmessage'] = 'New message from {$a}'; $string['unreadnewnotification'] = 'New notification'; $string['unreadnewnotifications'] = 'New notifications ({$a})'; $string['userisblockingyou'] = 'This user has blocked you from sending messages to them'; -$string['userisblockingyounoncontact'] = 'This user is only accepting messages from people listed as contacts, and you are not currently on the list.'; +$string['userisblockingyounoncontact'] = '{$a} only accepts messages from their contacts.'; $string['userssearchresults'] = 'Users found: {$a}'; diff --git a/lang/en/moodle.php b/lang/en/moodle.php index af23c90f27a..804df10d0b1 100644 --- a/lang/en/moodle.php +++ b/lang/en/moodle.php @@ -937,6 +937,7 @@ $string['liketologin'] = 'Would you like to log in now with a full user account? $string['list'] = 'List'; $string['listfiles'] = 'List of files in {$a}'; $string['listofallpeople'] = 'List of all people'; +$string['listofcourses'] = 'List of courses'; $string['local'] = 'Local'; $string['localplugindeleteconfirm'] = 'You are about to completely delete the local plugin \'{$a}\'. This will completely delete everything in the database associated with this plugin. Are you SURE you want to continue?'; $string['localplugins'] = 'Local plugins'; @@ -1032,6 +1033,7 @@ $string['messageselectadd'] = 'Send a message'; $string['migratinggrades'] = 'Migrating grades'; $string['min'] = 'min'; $string['mins'] = 'mins'; +$string['minute'] = 'minute'; $string['minutes'] = 'minutes'; $string['miscellaneous'] = 'Miscellaneous'; $string['missingcategory'] = 'You need to choose a category'; @@ -1059,6 +1061,8 @@ $string['missingteacher'] = 'Must choose something'; $string['missingurl'] = 'Missing URL'; $string['missingusername'] = 'Missing username'; $string['moddoesnotsupporttype'] = 'Module {$a->modname} does not support uploads of type {$a->type}'; +$string['month'] = 'Month'; +$string['months'] = 'Months'; $string['modified'] = 'Modified'; $string['modchooserenable'] = 'Activity chooser on'; $string['modchooserdisable'] = 'Activity chooser off'; @@ -1247,6 +1251,7 @@ $string['oldpassword'] = 'Current password'; $string['olduserdirectory'] = 'This is the OLD users directory, and is no longer needed. You may safely delete it. The files it contains have been copied to the NEW user directory.'; $string['opentoguests'] = 'Guest access'; $string['optional'] = 'optional'; +$string['options'] = 'options'; $string['order'] = 'Order'; $string['originalpath'] = 'Original path'; $string['orphanedactivities'] = 'Orphaned activities'; @@ -1464,7 +1469,7 @@ $string['screenreaderuse'] = 'Screen reader'; $string['screenreaderyes'] = 'Yes'; $string['screenreaderuse_help'] = 'If set to yes, a more accessible interface is provided in various places such as chat.'; $string['screenshot'] = 'Screenshot'; -$string['search'] = 'Search'; // TODO rename to searchforums and move to mod_forum +$string['search'] = 'Search'; // TODO MDL-34652 rename to searchforums and move to mod_forum $string['search_help'] = 'For basic searching of one or more words anywhere in the text, just type them separated by spaces. All words longer than two characters are used. For advanced searching, press the search button without typing anything in the search box to access the advanced search form.'; @@ -1493,9 +1498,15 @@ $string['sectionusedefaultname'] = 'Use default section name'; $string['seealsostats'] = 'See also: stats'; $string['select'] = 'Select'; $string['selectacountry'] = 'Select a country'; +$string['selectacourse'] = 'Select a course'; +$string['selectacoursesite'] = 'Select a course or site'; +$string['selectanaction'] = 'Select an action'; +$string['selectagroup'] = 'Select a group'; $string['selectaregion'] = 'Select a region'; +$string['selctauser'] = 'Select a user'; $string['selectall'] = 'Select all'; $string['selectamodule'] = 'Please select an activity module'; +$string['selectanoptions'] = 'Select an options'; $string['selectdefault'] = 'Select default'; $string['selectedfile'] = 'Selected file'; $string['selectednowmove'] = '{$a} files selected for moving. Now go into the destination folder and press \'Move files to here\''; @@ -1511,7 +1522,7 @@ $string['servererror'] = 'An error occurred whilst communicating with the server $string['serverlocaltime'] = 'Server\'s local time'; $string['setcategorytheme'] = 'Set category theme'; $string['settings'] = 'Settings'; -$string['shortname'] = 'Short name'; // @deprecated - use shortnamecourse or shortnameuser or some own context specific string +$string['shortname'] = 'Short name'; // @deprecated MDL-34652 - use shortnamecourse or shortnameuser or some own context specific string $string['shortnamecollisionwarning'] = '[*] = This shortname is already in use by a course and will need to be changed upon approval'; $string['shortnamecourse'] = 'Course short name'; $string['shortnamecourse_help'] = 'The short name of the course is displayed in the navigation and is used in the subject line of course email messages.'; diff --git a/lang/en/table.php b/lang/en/table.php index a4e9abd507c..c2bf4637612 100644 --- a/lang/en/table.php +++ b/lang/en/table.php @@ -27,5 +27,6 @@ $string['downloadas'] = 'Download table data as'; $string['downloadcsv'] = 'a comma separated values text file'; $string['downloadexcel'] = 'a Microsoft Excel spreadsheet'; $string['downloadods'] = 'an OpenDocument Spreadsheet (ODS)'; +$string['downloadoptions'] = 'Select download options'; $string['downloadtsv'] = 'a tab separated values text file'; $string['downloadxhtml'] = 'an unpaged XHTML document'; diff --git a/lib/adminlib.php b/lib/adminlib.php index ece35ca87c3..1d9fb8e9857 100644 --- a/lib/adminlib.php +++ b/lib/adminlib.php @@ -526,7 +526,7 @@ function set_cron_lock($name, $until, $ignorecurrent=false) { function admin_critical_warnings_present() { global $SESSION; - if (!has_capability('moodle/site:config', get_context_instance(CONTEXT_SYSTEM))) { + if (!has_capability('moodle/site:config', context_system::instance())) { return 0; } @@ -1164,7 +1164,7 @@ class admin_externalpage implements part_of_admin_tree { */ public function check_access() { global $CFG; - $context = empty($this->context) ? get_context_instance(CONTEXT_SYSTEM) : $this->context; + $context = empty($this->context) ? context_system::instance() : $this->context; foreach($this->req_capability as $cap) { if (has_capability($cap, $context)) { return true; @@ -1340,7 +1340,7 @@ class admin_settingpage implements part_of_admin_tree { */ public function check_access() { global $CFG; - $context = empty($this->context) ? get_context_instance(CONTEXT_SYSTEM) : $this->context; + $context = empty($this->context) ? context_system::instance() : $this->context; foreach($this->req_capability as $cap) { if (has_capability($cap, $context)) { return true; @@ -2854,7 +2854,7 @@ class admin_setting_users_with_capability extends admin_setting_configmultiselec if (is_array($this->choices)) { return true; } - $users = get_users_by_capability(get_context_instance(CONTEXT_SYSTEM), + $users = get_users_by_capability(context_system::instance(), $this->capability, 'u.id,u.username,u.firstname,u.lastname', 'u.lastname,u.firstname'); $this->choices = array( '$@NONE@$' => get_string('nobody'), diff --git a/lib/ajax/getnavbranch.php b/lib/ajax/getnavbranch.php index 6891a3025c0..f4edede1f33 100644 --- a/lib/ajax/getnavbranch.php +++ b/lib/ajax/getnavbranch.php @@ -42,7 +42,7 @@ try { // This identifies the block instance requesting AJAX extension $instanceid = optional_param('instance', null, PARAM_INT); - $PAGE->set_context(get_context_instance(CONTEXT_SYSTEM)); + $PAGE->set_context(context_system::instance()); // Create a global nav object $navigation = new global_navigation_for_ajax($PAGE, $branchtype, $branchid); diff --git a/lib/blocklib.php b/lib/blocklib.php index 3aabe710a76..b74272f1276 100644 --- a/lib/blocklib.php +++ b/lib/blocklib.php @@ -657,7 +657,7 @@ class block_manager { $blockinstance->id = $DB->insert_record('block_instances', $blockinstance); // Ensure the block context is created. - get_context_instance(CONTEXT_BLOCK, $blockinstance->id); + context_block::instance($blockinstance->id); // If the new instance was created, allow it to do additional setup if ($block = block_instance($blockname, $blockinstance)) { @@ -1230,8 +1230,8 @@ class block_manager { $bi->subpagepattern = $data->bui_subpagepattern; } - $systemcontext = get_context_instance(CONTEXT_SYSTEM); - $frontpagecontext = get_context_instance(CONTEXT_COURSE, SITEID); + $systemcontext = context_system::instance(); + $frontpagecontext = context_course::instance(SITEID); $parentcontext = get_context_instance_by_id($data->bui_parentcontextid); // Updating stickiness and contexts. See MDL-21375 for details. @@ -2102,7 +2102,7 @@ function blocks_add_default_system_blocks() { global $DB; $page = new moodle_page(); - $page->set_context(get_context_instance(CONTEXT_SYSTEM)); + $page->set_context(context_system::instance()); $page->blocks->add_blocks(array(BLOCK_POS_LEFT => array('navigation', 'settings')), '*', null, true); $page->blocks->add_blocks(array(BLOCK_POS_LEFT => array('admin_bookmarks')), 'admin-*', null, null, 2); diff --git a/lib/datalib.php b/lib/datalib.php index dea5c4b6f16..97e90b78cbb 100644 --- a/lib/datalib.php +++ b/lib/datalib.php @@ -158,7 +158,7 @@ function search_users($courseid, $groupid, $searchtext, $sort='', array $excepti return $DB->get_records_sql($sql, $params); } else { - $context = get_context_instance(CONTEXT_COURSE, $courseid); + $context = context_course::instance($courseid); $contextlists = get_related_contexts_string($context); $sql = "SELECT u.id, u.firstname, u.lastname, u.email @@ -412,7 +412,7 @@ function get_courses($categoryid="all", $sort="c.sortorder ASC", $fields="c.*") context_instance_preload($course); if (isset($course->visible) && $course->visible <= 0) { // for hidden courses, require visibility check - if (has_capability('moodle/course:viewhiddencourses', get_context_instance(CONTEXT_COURSE, $course->id))) { + if (has_capability('moodle/course:viewhiddencourses', context_course::instance($course->id))) { $visiblecourses [$course->id] = $course; } } else { @@ -479,7 +479,7 @@ function get_courses_page($categoryid="all", $sort="c.sortorder ASC", $fields="c context_instance_preload($course); if ($course->visible <= 0) { // for hidden courses, require visibility check - if (has_capability('moodle/course:viewhiddencourses', get_context_instance(CONTEXT_COURSE, $course->id))) { + if (has_capability('moodle/course:viewhiddencourses', context_course::instance($course->id))) { $totalcount++; if ($totalcount > $limitfrom && (!$limitnum or count($visiblecourses) < $limitnum)) { $visiblecourses [$course->id] = $course; @@ -596,7 +596,7 @@ function get_courses_wmanagers($categoryid=0, $sort="c.sortorder ASC", $fields=a // managers efficiently later... foreach ($courses as $k => $course) { context_instance_preload($course); - $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id); + $coursecontext = context_course::instance($course->id); $courses[$k] = $course; $courses[$k]->managers = array(); if ($allcats === false) { @@ -694,7 +694,7 @@ function get_courses_wmanagers($categoryid=0, $sort="c.sortorder ASC", $fields=a } } else { foreach ($courses as $k => $course) { - $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id); + $coursecontext = context_course::instance($course->id); // Note that strpos() returns 0 as "matched at pos 0" if (strpos($coursecontext->path, $ra->path.'/') === 0) { // Only add it to subpaths @@ -806,7 +806,7 @@ function get_courses_search($searchterms, $sort='fullname ASC', $page=0, $record $rs = $DB->get_recordset_sql($sql, $params); foreach($rs as $course) { context_instance_preload($course); - $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id); + $coursecontext = context_course::instance($course->id); if ($course->visible || has_capability('moodle/course:viewhiddencourses', $coursecontext)) { // Don't exit this loop till the end // we need to count all the visible courses @@ -885,7 +885,7 @@ function get_categories($parent='none', $sort=NULL, $shallow=true) { $rs = $DB->get_recordset_sql($sql, $params); foreach($rs as $cat) { context_instance_preload($cat); - $catcontext = get_context_instance(CONTEXT_COURSECAT, $cat->id); + $catcontext = context_coursecat::instance($cat->id); if ($cat->visible || has_capability('moodle/category:viewhiddencategories', $catcontext)) { $categories[$cat->id] = $cat; } @@ -949,7 +949,7 @@ function get_course_category($catid=0) { $cat->timemodified = time(); $catid = $DB->insert_record('course_categories', $cat); // make sure category context exists - get_context_instance(CONTEXT_COURSECAT, $catid); + context_coursecat::instance($catid); mark_context_dirty('/'.SYSCONTEXTID); fix_course_sortorder(); // Required to build course_categories.depth and .path. $category = $DB->get_record('course_categories', array('id'=>$catid)); @@ -1032,7 +1032,7 @@ function fix_course_sortorder() { $defaultcat = reset($topcats); foreach ($frontcourses as $course) { $DB->set_field('course', 'category', $defaultcat->id, array('id'=>$course->id)); - $context = get_context_instance(CONTEXT_COURSE, $course->id); + $context = context_course::instance($course->id); $fixcontexts[$context->id] = $context; } unset($frontcourses); @@ -1178,7 +1178,7 @@ function _fix_course_cats($children, &$sortorder, $parent, $depth, $path, &$fixc $update = true; // make sure context caches are rebuild and dirty contexts marked - $context = get_context_instance(CONTEXT_COURSECAT, $cat->id); + $context = context_coursecat::instance($cat->id); $fixcontexts[$context->id] = $context; } if ($cat->sortorder != $sortorder) { @@ -1620,7 +1620,7 @@ function coursemodule_visible_for_user($cm, $userid=0) { if (empty($userid)) { $userid = $USER->id; } - if (!$cm->visible and !has_capability('moodle/course:viewhiddenactivities', get_context_instance(CONTEXT_MODULE, $cm->id), $userid)) { + if (!$cm->visible and !has_capability('moodle/course:viewhiddenactivities', context_module::instance($cm->id), $userid)) { return false; } if ($CFG->enableavailability) { @@ -1628,7 +1628,7 @@ function coursemodule_visible_for_user($cm, $userid=0) { $ci=new condition_info($cm,CONDITION_MISSING_EXTRATABLE); if(!$ci->is_available($cm->availableinfo,false,$userid) and !has_capability('moodle/course:viewhiddenactivities', - get_context_instance(CONTEXT_MODULE, $cm->id), $userid)) { + context_module::instance($cm->id), $userid)) { return false; } } @@ -2010,7 +2010,7 @@ function user_can_create_courses() { global $DB; $catsrs = $DB->get_recordset('course_categories'); foreach ($catsrs as $cat) { - if (has_capability('moodle/course:create', get_context_instance(CONTEXT_COURSECAT, $cat->id))) { + if (has_capability('moodle/course:create', context_coursecat::instance($cat->id))) { $catsrs->close(); return true; } diff --git a/lib/db/upgrade.php b/lib/db/upgrade.php index 24d6120482f..726428213b3 100644 --- a/lib/db/upgrade.php +++ b/lib/db/upgrade.php @@ -85,7 +85,7 @@ defined('MOODLE_INTERNAL') || die(); * @return bool always true */ function xmldb_main_upgrade($oldversion) { - global $CFG, $USER, $DB, $OUTPUT; + global $CFG, $USER, $DB, $OUTPUT, $SITE; require_once($CFG->libdir.'/db/upgradelib.php'); // Core Upgrade-related functions @@ -1069,5 +1069,17 @@ function xmldb_main_upgrade($oldversion) { upgrade_main_savepoint(true, 2012072401.00); } + if ($oldversion < 2012072600.01) { + // Handle events with empty eventtype //MDL-32827 + + $DB->set_field('event', 'eventtype', 'site', array('eventtype' => '', 'courseid' => $SITE->id)); + $DB->set_field_select('event', 'eventtype', 'due', "eventtype = '' AND courseid != 0 AND groupid = 0 AND (modulename = 'assignment' OR modulename = 'assign')"); + $DB->set_field_select('event', 'eventtype', 'course', "eventtype = '' AND courseid != 0 AND groupid = 0"); + $DB->set_field_select('event', 'eventtype', 'group', "eventtype = '' AND groupid != 0"); + $DB->set_field_select('event', 'eventtype', 'user', "eventtype = '' AND userid != 0"); + + // Main savepoint reached + upgrade_main_savepoint(true, 2012072600.01); + } return true; } diff --git a/lib/deprecatedlib.php b/lib/deprecatedlib.php index 5349be5ec60..4c5a392db53 100644 --- a/lib/deprecatedlib.php +++ b/lib/deprecatedlib.php @@ -75,7 +75,7 @@ function filter_text($text, $courseid = NULL) { $courseid = $COURSE->id; } - if (!$context = get_context_instance(CONTEXT_COURSE, $courseid)) { + if (!$context = context_course::instance($courseid, IGNORE_MISSING)) { return $text; } @@ -312,7 +312,7 @@ function get_teacher() { * @return array of user */ function get_course_participants($courseid) { - return get_enrolled_users(get_context_instance(CONTEXT_COURSE, $courseid)); + return get_enrolled_users(context_course::instance($courseid)); } /** @@ -324,7 +324,7 @@ function get_course_participants($courseid) { * @return boolean */ function is_course_participant($userid, $courseid) { - return is_enrolled(get_context_instance(CONTEXT_COURSE, $courseid), $userid); + return is_enrolled(context_course::instance($courseid), $userid); } /** @@ -341,7 +341,7 @@ function is_course_participant($userid, $courseid) { function get_recent_enrolments($courseid, $timestart) { global $DB; - $context = get_context_instance(CONTEXT_COURSE, $courseid); + $context = context_course::instance($courseid); $sql = "SELECT u.id, u.firstname, u.lastname, MAX(l.time) FROM {user} u, {role_assignments} ra, {log} l @@ -2601,7 +2601,7 @@ function update_module_button($cmid, $ignored, $string) { //NOTE: DO NOT call new output method because it needs the module name we do not have here! - if (has_capability('moodle/course:manageactivities', get_context_instance(CONTEXT_MODULE, $cmid))) { + if (has_capability('moodle/course:manageactivities', context_module::instance($cmid))) { $string = get_string('updatethis', '', $string); $url = new moodle_url("$CFG->wwwroot/course/mod.php", array('update' => $cmid, 'return' => true, 'sesskey' => sesskey())); diff --git a/lib/editor/tinymce/lib.php b/lib/editor/tinymce/lib.php index a7404834068..906b361079f 100644 --- a/lib/editor/tinymce/lib.php +++ b/lib/editor/tinymce/lib.php @@ -92,7 +92,7 @@ class tinymce_texteditor extends texteditor { $lang = current_language(); $contentcss = $PAGE->theme->editor_css_url()->out(false); - $context = empty($options['context']) ? get_context_instance(CONTEXT_SYSTEM) : $options['context']; + $context = empty($options['context']) ? context_system::instance() : $options['context']; $config = get_config('editor_tinymce'); @@ -152,6 +152,7 @@ class tinymce_texteditor extends texteditor { 'theme_advanced_fonts' => $fontselectlist, 'theme_advanced_resize_horizontal' => true, 'theme_advanced_resizing' => true, + 'theme_advanced_resizing_min_height' => 30, 'min_height' => 30, 'theme_advanced_toolbar_location' => "top", 'theme_advanced_statusbar_location' => "bottom", diff --git a/lib/enrollib.php b/lib/enrollib.php index b6736c4ece1..b437a48f1b1 100644 --- a/lib/enrollib.php +++ b/lib/enrollib.php @@ -389,7 +389,7 @@ function enrol_course_updated($inserted, $course, $data) { function enrol_add_course_navigation(navigation_node $coursenode, $course) { global $CFG; - $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id); + $coursecontext = context_course::instance($course->id); $instances = enrol_get_instances($course->id, true); $plugins = enrol_get_plugins(true); @@ -604,7 +604,7 @@ function enrol_get_my_courses($fields = NULL, $sort = 'visible DESC,sortorder AS foreach ($courses as $id=>$course) { context_instance_preload($course); if (!$course->visible) { - if (!$context = get_context_instance(CONTEXT_COURSE, $id)) { + if (!$context = context_course::instance($id, IGNORE_MISSING)) { unset($courses[$id]); continue; } @@ -1018,7 +1018,7 @@ abstract class enrol_plugin { $enrol = $this->get_name(); return get_string('pluginname', 'enrol_'.$enrol); } else { - $context = get_context_instance(CONTEXT_COURSE, $instance->courseid); + $context = context_course::instance($instance->courseid); return format_string($instance->name, true, array('context'=>$context)); } } @@ -1215,7 +1215,7 @@ abstract class enrol_plugin { if ($instance->enrol !== $name) { throw new coding_exception('invalid enrol instance!'); } - $context = get_context_instance(CONTEXT_COURSE, $instance->courseid, MUST_EXIST); + $context = context_course::instance($instance->courseid, MUST_EXIST); $inserted = false; $updated = false; @@ -1352,7 +1352,7 @@ abstract class enrol_plugin { if ($instance->enrol !== $name) { throw new coding_exception('invalid enrol instance!'); } - $context = get_context_instance(CONTEXT_COURSE, $instance->courseid, MUST_EXIST); + $context = context_course::instance($instance->courseid, MUST_EXIST); if (!$ue = $DB->get_record('user_enrolments', array('enrolid'=>$instance->id, 'userid'=>$userid))) { // weird, user not enrolled @@ -1484,7 +1484,7 @@ abstract class enrol_plugin { return NULL; } - $context = get_context_instance(CONTEXT_COURSE, $instance->courseid, MUST_EXIST); + $context = context_course::instance($instance->courseid, MUST_EXIST); if (!has_capability("enrol/$name:unenrolself", $context)) { return NULL; diff --git a/lib/externallib.php b/lib/externallib.php index da21ace392e..f547850e0f6 100644 --- a/lib/externallib.php +++ b/lib/externallib.php @@ -328,7 +328,7 @@ class external_api { throw new invalid_parameter_exception('Context does not exist'); } if (empty(self::$contextrestriction)) { - self::$contextrestriction = get_context_instance(CONTEXT_SYSTEM); + self::$contextrestriction = context_system::instance(); } $rcontext = self::$contextrestriction; diff --git a/lib/filebrowser/file_browser.php b/lib/filebrowser/file_browser.php index f2105cb8d11..4b86c66f4e6 100644 --- a/lib/filebrowser/file_browser.php +++ b/lib/filebrowser/file_browser.php @@ -73,7 +73,7 @@ class file_browser { */ public function get_file_info($context = NULL, $component = NULL, $filearea = NULL, $itemid = NULL, $filepath = NULL, $filename = NULL) { if (!$context) { - $context = get_context_instance(CONTEXT_SYSTEM); + $context = context_system::instance(); } switch ($context->contextlevel) { case CONTEXT_SYSTEM: diff --git a/lib/filebrowser/file_info_context_course.php b/lib/filebrowser/file_info_context_course.php index 50876b36856..05b34890290 100644 --- a/lib/filebrowser/file_info_context_course.php +++ b/lib/filebrowser/file_info_context_course.php @@ -383,7 +383,7 @@ class file_info_context_course extends file_info { if (empty($cminfo->uservisible)) { continue; } - $modcontext = get_context_instance(CONTEXT_MODULE, $cminfo->id); + $modcontext = context_module::instance($cminfo->id, IGNORE_MISSING); if ($child = $this->browser->get_file_info($modcontext)) { $children[] = $child; } diff --git a/lib/filebrowser/file_info_context_coursecat.php b/lib/filebrowser/file_info_context_coursecat.php index 99b6d1fc240..1cded8310f1 100644 --- a/lib/filebrowser/file_info_context_coursecat.php +++ b/lib/filebrowser/file_info_context_coursecat.php @@ -65,7 +65,7 @@ class file_info_context_coursecat extends file_info { if (empty($component)) { // we can not list the category contents, so try parent, or top system if ($this->category->parent and $pc = $DB->get_record('course_categories', array('id'=>$this->category->parent))) { - $parent = get_context_instance(CONTEXT_COURSECAT, $pc->id); + $parent = context_coursecat::instance($pc->id, IGNORE_MISSING); return $this->browser->get_file_info($parent); } else { return $this->browser->get_file_info(); @@ -165,7 +165,7 @@ class file_info_context_coursecat extends file_info { $course_cats = $DB->get_records('course_categories', array('parent'=>$this->category->id), 'sortorder', 'id,visible'); foreach ($course_cats as $category) { - $context = get_context_instance(CONTEXT_COURSECAT, $category->id); + $context = context_coursecat::instance($category->id); if (!$category->visible and !has_capability('moodle/category:viewhiddencategories', $context)) { continue; } @@ -176,7 +176,7 @@ class file_info_context_coursecat extends file_info { $courses = $DB->get_records('course', array('category'=>$this->category->id), 'sortorder', 'id,visible'); foreach ($courses as $course) { - $context = get_context_instance(CONTEXT_COURSE, $course->id); + $context = context_course::instance($course->id); if (!$course->visible and !has_capability('moodle/course:viewhiddencourses', $context)) { continue; } diff --git a/lib/filebrowser/file_info_context_system.php b/lib/filebrowser/file_info_context_system.php index 375fd9872f0..a37f43ea8a1 100644 --- a/lib/filebrowser/file_info_context_system.php +++ b/lib/filebrowser/file_info_context_system.php @@ -101,7 +101,7 @@ class file_info_context_system extends file_info { $course_cats = $DB->get_records('course_categories', array('parent'=>0), 'sortorder', 'id,visible'); foreach ($course_cats as $category) { - $context = get_context_instance(CONTEXT_COURSECAT, $category->id); + $context = context_coursecat::instance($category->id); if (!$category->visible and !has_capability('moodle/category:viewhiddencategories', $context)) { continue; } @@ -115,7 +115,7 @@ class file_info_context_system extends file_info { if (!$course->visible and !has_capability('moodle/course:viewhiddencourses', $context)) { continue; } - $context = get_context_instance(CONTEXT_COURSE, $course->id); + $context = context_course::instance($course->id); if ($child = $this->browser->get_file_info($context)) { $children[] = $child; } diff --git a/lib/filelib.php b/lib/filelib.php index 3b2d4531fc8..32df4bceee7 100644 --- a/lib/filelib.php +++ b/lib/filelib.php @@ -318,7 +318,7 @@ function file_get_unused_draft_itemid() { print_error('noguest'); } - $contextid = get_context_instance(CONTEXT_USER, $USER->id)->id; + $contextid = context_user::instance($USER->id)->id; $fs = get_file_storage(); $draftitemid = rand(1, 999999999); @@ -357,7 +357,7 @@ function file_prepare_draft_area(&$draftitemid, $contextid, $component, $fileare $options['forcehttps'] = false; } - $usercontext = get_context_instance(CONTEXT_USER, $USER->id); + $usercontext = context_user::instance($USER->id); $fs = get_file_storage(); if (empty($draftitemid)) { @@ -465,7 +465,7 @@ function file_rewrite_pluginfile_urls($text, $file, $contextid, $component, $fil function file_get_draft_area_info($draftitemid) { global $CFG, $USER; - $usercontext = get_context_instance(CONTEXT_USER, $USER->id); + $usercontext = context_user::instance($USER->id); $fs = get_file_storage(); $results = array(); @@ -490,7 +490,7 @@ function file_get_draft_area_info($draftitemid) { function file_get_user_used_space() { global $DB, $USER; - $usercontext = get_context_instance(CONTEXT_USER, $USER->id); + $usercontext = context_user::instance($USER->id); $sql = "SELECT SUM(files1.filesize) AS totalbytes FROM {files} files1 JOIN (SELECT contenthash, filename, MAX(id) AS id FROM {files} @@ -526,7 +526,7 @@ function file_correct_filepath($str) { //TODO: what is this? (skodak) function file_get_drafarea_folders($draftitemid, $filepath, &$data) { global $USER, $OUTPUT, $CFG; $data->children = array(); - $context = get_context_instance(CONTEXT_USER, $USER->id); + $context = context_user::instance($USER->id); $fs = get_file_storage(); if ($files = $fs->get_directory_files($context->id, 'user', 'draft', $draftitemid, $filepath, false)) { foreach ($files as $file) { @@ -558,7 +558,7 @@ function file_get_drafarea_folders($draftitemid, $filepath, &$data) { function file_get_drafarea_files($draftitemid, $filepath = '/') { global $USER, $OUTPUT, $CFG; - $context = get_context_instance(CONTEXT_USER, $USER->id); + $context = context_user::instance($USER->id); $fs = get_file_storage(); $data = new stdClass(); @@ -711,7 +711,7 @@ function file_restore_source_field_from_draft_file($storedfile) { function file_save_draft_area_files($draftitemid, $contextid, $component, $filearea, $itemid, array $options=null, $text=null, $forcehttps=false) { global $USER; - $usercontext = get_context_instance(CONTEXT_USER, $USER->id); + $usercontext = context_user::instance($USER->id); $fs = get_file_storage(); $options = (array)$options; @@ -905,7 +905,7 @@ function file_save_draft_area_files($draftitemid, $contextid, $component, $filea function file_rewrite_urls_to_pluginfile($text, $draftitemid, $forcehttps = false) { global $CFG, $USER; - $usercontext = get_context_instance(CONTEXT_USER, $USER->id); + $usercontext = context_user::instance($USER->id); $wwwroot = $CFG->wwwroot; if ($forcehttps) { @@ -3763,7 +3763,7 @@ function file_pluginfile($relativepath, $forcedownload, $preview = null) { while (!$canview && count($courses) > 0) { $course = array_shift($courses); - if (has_capability('moodle/user:viewdetails', get_context_instance(CONTEXT_COURSE, $course->id))) { + if (has_capability('moodle/user:viewdetails', context_course::instance($course->id))) { $canview = true; } } @@ -3780,7 +3780,7 @@ function file_pluginfile($relativepath, $forcedownload, $preview = null) { } else if ($filearea === 'profile' and $context->contextlevel == CONTEXT_COURSE) { $userid = (int)array_shift($args); - $usercontext = get_context_instance(CONTEXT_USER, $userid); + $usercontext = context_user::instance($userid); if ($CFG->forcelogin) { require_login(); diff --git a/lib/filestorage/tests/zip_packer_test.php b/lib/filestorage/tests/zip_packer_test.php index 9a4475b2ead..3d1ab7f046a 100644 --- a/lib/filestorage/tests/zip_packer_test.php +++ b/lib/filestorage/tests/zip_packer_test.php @@ -140,6 +140,30 @@ class zip_packer_testcase extends advanced_testcase { foreach($archivefiles as $file) { $this->assertArrayHasKey($file->pathname, $this->files); } + + // Test invalid files parameter. + $archive = "$CFG->tempdir/archive2.zip"; + $this->assertFalse(file_exists($archive)); + + $this->assertFalse(file_exists(__DIR__.'/xx/yy/ee.txt')); + $files = array('xtest.txt'=>__DIR__.'/xx/yy/ee.txt'); + ob_start(); + $result = $packer->archive_to_pathname($files, $archive); + $d = ob_end_clean(); + $this->assertTrue($d !== ''); + $this->assertFalse($result); + + $this->assertTrue(file_exists(__DIR__.'/fixtures/test.txt')); + $files = array(); + $files['""""'] = null; // Invalid directory name. + $files['test.txt'] = __DIR__.'/fixtures/test.txt'; + ob_start(); + $result = $packer->archive_to_pathname($files, $archive); + $d = ob_end_clean(); + $this->assertTrue($d !== ''); + $this->assertTrue($result); + + @unlink($archive); } /** diff --git a/lib/filestorage/zip_packer.php b/lib/filestorage/zip_packer.php index f3b0484e6a2..90afe711a7d 100644 --- a/lib/filestorage/zip_packer.php +++ b/lib/filestorage/zip_packer.php @@ -100,26 +100,44 @@ class zip_packer extends file_packer { return false; } + $result = false; // One processed file or dir means success here. + foreach ($files as $archivepath => $file) { $archivepath = trim($archivepath, '/'); if (is_null($file)) { // empty directories have null as content - $ziparch->add_directory($archivepath.'/'); + if ($ziparch->add_directory($archivepath.'/')) { + $result = true; + } else { + debugging("Can not zip '$archivepath' directory", DEBUG_DEVELOPER); + } } else if (is_string($file)) { - $this->archive_pathname($ziparch, $archivepath, $file); + if ($this->archive_pathname($ziparch, $archivepath, $file)) { + $result = true; + } else { + debugging("Can not zip '$archivepath' file", DEBUG_DEVELOPER); + } } else if (is_array($file)) { $content = reset($file); - $ziparch->add_file_from_string($archivepath, $content); + if ($ziparch->add_file_from_string($archivepath, $content)) { + $result = true; + } else { + debugging("Can not zip '$archivepath' file", DEBUG_DEVELOPER); + } } else { - $this->archive_stored($ziparch, $archivepath, $file); + if ($this->archive_stored($ziparch, $archivepath, $file)) { + $result = true; + } else { + debugging("Can not zip '$archivepath' file", DEBUG_DEVELOPER); + } } } - return $ziparch->close(); + return ($ziparch->close() && $result); } /** @@ -128,12 +146,16 @@ class zip_packer extends file_packer { * @param zip_archive $ziparch zip archive instance * @param string $archivepath file path to archive * @param stored_file $file stored_file object + * @return bool success */ private function archive_stored($ziparch, $archivepath, $file) { - $file->archive_file($ziparch, $archivepath); + $result = $file->archive_file($ziparch, $archivepath); + if (!$result) { + return false; + } if (!$file->is_directory()) { - return; + return true; } $baselength = strlen($file->get_filepath()); @@ -147,8 +169,11 @@ class zip_packer extends file_packer { if (!$file->is_directory()) { $path = $path.$file->get_filename(); } + // Ignore result here, partial zipping is ok for now. $file->archive_file($ziparch, $path); } + + return true; } /** @@ -157,18 +182,18 @@ class zip_packer extends file_packer { * @param zip_archive $ziparch zip archive instance * @param string $archivepath file path to archive * @param string $file path name of the file + * @return bool success */ private function archive_pathname($ziparch, $archivepath, $file) { if (!file_exists($file)) { - return; + return false; } if (is_file($file)) { if (!is_readable($file)) { - return; + return false; } - $ziparch->add_file_from_pathname($archivepath, $file); - return; + return $ziparch->add_file_from_pathname($archivepath, $file); } if (is_dir($file)) { if ($archivepath !== '') { @@ -183,7 +208,7 @@ class zip_packer extends file_packer { $this->archive_pathname($ziparch, $newpath, $file->getPathname()); } unset($files); //release file handles - return; + return true; } } diff --git a/lib/filterlib.php b/lib/filterlib.php index ca75b0d1cb6..de808355b51 100644 --- a/lib/filterlib.php +++ b/lib/filterlib.php @@ -605,7 +605,7 @@ function filter_set_global_state($filter, $state, $sortorder = false) { } // See if there is an existing record. - $syscontext = get_context_instance(CONTEXT_SYSTEM); + $syscontext = context_system::instance(); $rec = $DB->get_record('filter_active', array('filter' => $filter, 'contextid' => $syscontext->id)); if (empty($rec)) { $insert = true; @@ -747,7 +747,7 @@ function filter_set_local_state($filter, $contextid, $state) { "Must be one of TEXTFILTER_ON, TEXTFILTER_OFF or TEXTFILTER_INHERIT."); } - if ($contextid == get_context_instance(CONTEXT_SYSTEM)->id) { + if ($contextid == context_system::instance()->id) { throw new coding_exception('You cannot use filter_set_local_state ' . 'with $contextid equal to the system context id.'); } @@ -847,7 +847,7 @@ function filter_get_local_config($filter, $contextid) { */ function filter_get_all_local_settings($contextid) { global $DB; - $context = get_context_instance(CONTEXT_SYSTEM); + $context = context_system::instance(); return array( $DB->get_records('filter_active', array('contextid' => $contextid), 'filter', 'filter,active'), $DB->get_records('filter_config', array('contextid' => $contextid), 'filter,name', 'filter,name,value'), @@ -940,13 +940,13 @@ function filter_preload_activities(course_modinfo $modinfo) { $cmcontexts = array(); $cmcontextids = array(); foreach ($modinfo->get_cms() as $cm) { - $modulecontext = get_context_instance(CONTEXT_MODULE, $cm->id); + $modulecontext = context_module::instance($cm->id); $cmcontextids[] = $modulecontext->id; $cmcontexts[] = $modulecontext; } // Get course context and all other parents... - $coursecontext = get_context_instance(CONTEXT_COURSE, $modinfo->get_course_id()); + $coursecontext = context_course::instance($modinfo->get_course_id()); $parentcontextids = explode('/', substr($coursecontext->path, 1)); $allcontextids = array_merge($cmcontextids, $parentcontextids); @@ -1094,7 +1094,7 @@ function filter_get_available_in_context($context) { */ function filter_get_global_states() { global $DB; - $context = get_context_instance(CONTEXT_SYSTEM); + $context = context_system::instance(); return $DB->get_records('filter_active', array('contextid' => $context->id), 'sortorder', 'filter,active,sortorder'); } diff --git a/lib/form/editor.php b/lib/form/editor.php index 5a919fb3715..32663e83e3b 100644 --- a/lib/form/editor.php +++ b/lib/form/editor.php @@ -80,7 +80,7 @@ class MoodleQuickForm_editor extends HTML_QuickForm_element { $this->_options['maxbytes'] = get_max_upload_file_size($CFG->maxbytes, $options['maxbytes']); } if (!$this->_options['context']) { - $this->_options['context'] = get_context_instance(CONTEXT_SYSTEM); + $this->_options['context'] = context_system::instance(); } $this->_options['trusted'] = trusttext_trusted($this->_options['context']); parent::HTML_QuickForm_element($elementName, $elementLabel, $attributes); @@ -361,10 +361,11 @@ class MoodleQuickForm_editor extends HTML_QuickForm_element { $str .= '
'; if (count($formats)>1) { - $str.= html_writer::select($formats, $elname.'[format]', $format, false); + $str .= html_writer::label(get_string('format'), 'menu'. $elname. 'format', false, array('class' => 'accesshide')); + $str .= html_writer::select($formats, $elname.'[format]', $format, false, array('id' => 'menu'. $elname. 'format')); } else { $keys = array_keys($formats); - $str.= html_writer::empty_tag('input', + $str .= html_writer::empty_tag('input', array('name'=>$elname.'[format]', 'type'=> 'hidden', 'value' => array_pop($keys))); } $str .= '
'; diff --git a/lib/form/filemanager.php b/lib/form/filemanager.php index 82f9090131b..c5daa9ec0c7 100644 --- a/lib/form/filemanager.php +++ b/lib/form/filemanager.php @@ -321,7 +321,7 @@ class form_filemanager implements renderable { $this->options = file_get_drafarea_files($options->itemid, '/'); // calculate file count - $usercontext = get_context_instance(CONTEXT_USER, $USER->id); + $usercontext = context_user::instance($USER->id); $files = $fs->get_area_files($usercontext->id, 'user', 'draft', $options->itemid, 'id', false); $filecount = count($files); $this->options->filecount = $filecount; diff --git a/lib/form/filepicker.php b/lib/form/filepicker.php index fb5e0f36036..da5aff8a3e1 100644 --- a/lib/form/filepicker.php +++ b/lib/form/filepicker.php @@ -126,9 +126,9 @@ class MoodleQuickForm_filepicker extends HTML_QuickForm_input { } if ($COURSE->id == SITEID) { - $context = get_context_instance(CONTEXT_SYSTEM); + $context = context_system::instance(); } else { - $context = get_context_instance(CONTEXT_COURSE, $COURSE->id); + $context = context_course::instance($COURSE->id); } $client_id = uniqid(); @@ -191,7 +191,7 @@ class MoodleQuickForm_filepicker extends HTML_QuickForm_input { // make sure max one file is present and it is not too big if (!is_null($draftitemid)) { $fs = get_file_storage(); - $usercontext = get_context_instance(CONTEXT_USER, $USER->id); + $usercontext = context_user::instance($USER->id); if ($files = $fs->get_area_files($usercontext->id, 'user', 'draft', $draftitemid, 'id DESC', false)) { $file = array_shift($files); if ($this->_options['maxbytes'] diff --git a/lib/form/tags.php b/lib/form/tags.php index bdaa1337cdd..2c60979bfc8 100644 --- a/lib/form/tags.php +++ b/lib/form/tags.php @@ -130,7 +130,7 @@ class MoodleQuickForm_tags extends MoodleQuickForm_group { // If the user can manage official tags, give them a link to manage them. $label = get_string('otags', 'tag'); - if (has_capability('moodle/tag:manage', get_context_instance(CONTEXT_SYSTEM))) { + if (has_capability('moodle/tag:manage', context_system::instance())) { $url = $CFG->wwwroot .'/tag/manage.php'; $label .= ' (' . $OUTPUT->action_link( $url, diff --git a/lib/form/url.php b/lib/form/url.php index 18c74650ea3..aa7100e35d1 100644 --- a/lib/form/url.php +++ b/lib/form/url.php @@ -97,9 +97,9 @@ class MoodleQuickForm_url extends HTML_QuickForm_text{ $strsaved = get_string('filesaved', 'repository'); $straddlink = get_string('choosealink', 'repository'); if ($COURSE->id == SITEID) { - $context = get_context_instance(CONTEXT_SYSTEM); + $context = context_system::instance(); } else { - $context = get_context_instance(CONTEXT_COURSE, $COURSE->id); + $context = context_course::instance($COURSE->id); } $client_id = uniqid(); diff --git a/lib/formslib.php b/lib/formslib.php index 38afe826588..e9da89e2f6e 100644 --- a/lib/formslib.php +++ b/lib/formslib.php @@ -395,7 +395,7 @@ abstract class moodleform { if ($rule['type'] == 'required') { $draftid = (int)$mform->getSubmitValue($elementname); $fs = get_file_storage(); - $context = get_context_instance(CONTEXT_USER, $USER->id); + $context = context_user::instance($USER->id); if (!$files = $fs->get_area_files($context->id, 'user', 'draft', $draftid, 'id DESC', false)) { $errors[$elementname] = $rule['message']; } @@ -673,7 +673,7 @@ abstract class moodleform { } $draftid = $values[$elname]; $fs = get_file_storage(); - $context = get_context_instance(CONTEXT_USER, $USER->id); + $context = context_user::instance($USER->id); if (!$files = $fs->get_area_files($context->id, 'user', 'draft', $draftid, 'id DESC', false)) { return false; } @@ -721,7 +721,7 @@ abstract class moodleform { } $draftid = $values[$elname]; $fs = get_file_storage(); - $context = get_context_instance(CONTEXT_USER, $USER->id); + $context = context_user::instance($USER->id); if (!$files = $fs->get_area_files($context->id, 'user', 'draft', $draftid, 'id DESC', false)) { return false; } @@ -784,7 +784,7 @@ abstract class moodleform { } $draftid = $values[$elname]; $fs = get_file_storage(); - $context = get_context_instance(CONTEXT_USER, $USER->id); + $context = context_user::instance($USER->id); if (!$files = $fs->get_area_files($context->id, 'user', 'draft', $draftid, 'id DESC', false)) { return null; } @@ -828,7 +828,7 @@ abstract class moodleform { return false; } $draftid = $values[$elname]; - $context = get_context_instance(CONTEXT_USER, $USER->id); + $context = context_user::instance($USER->id); if (!$files = $fs->get_area_files($context->id, 'user' ,'draft', $draftid, 'id DESC', false)) { return false; } @@ -890,7 +890,7 @@ abstract class moodleform { } $draftid = $values[$elname]; $fs = get_file_storage(); - $context = get_context_instance(CONTEXT_USER, $USER->id); + $context = context_user::instance($USER->id); if (!$files = $fs->get_area_files($context->id, 'user', 'draft', $draftid, 'id DESC', false)) { return false; } diff --git a/lib/grade/grade_outcome.php b/lib/grade/grade_outcome.php index 02e765f3300..ffb47de5dd6 100644 --- a/lib/grade/grade_outcome.php +++ b/lib/grade/grade_outcome.php @@ -106,7 +106,7 @@ class grade_outcome extends grade_object { $DB->delete_records('grade_outcomes_courses', array('outcomeid' => $this->id, 'courseid' => $this->courseid)); } if (parent::delete($source)) { - $context = get_context_instance(CONTEXT_SYSTEM); + $context = context_system::instance(); $fs = get_file_storage(); $files = $fs->get_area_files($context->id, 'grade', 'outcome', $this->id); foreach ($files as $file) { @@ -299,7 +299,7 @@ class grade_outcome extends grade_object { $options = new stdClass; $options->noclean = true; - $systemcontext = get_context_instance(CONTEXT_SYSTEM); + $systemcontext = context_system::instance(); $description = file_rewrite_pluginfile_urls($this->description, 'pluginfile.php', $systemcontext->id, 'grade', 'outcome', $this->id); return format_text($description, $this->descriptionformat, $options); } diff --git a/lib/grade/grade_scale.php b/lib/grade/grade_scale.php index d26f10a0ce0..46167a9ce2e 100644 --- a/lib/grade/grade_scale.php +++ b/lib/grade/grade_scale.php @@ -142,7 +142,7 @@ class grade_scale extends grade_object { public function delete($source=null) { global $DB; if (parent::delete($source)) { - $context = get_context_instance(CONTEXT_SYSTEM); + $context = context_system::instance(); $fs = get_file_storage(); $files = $fs->get_area_files($context->id, 'grade', 'scale', $this->id); foreach ($files as $file) { @@ -337,7 +337,7 @@ class grade_scale extends grade_object { global $CFG; require_once($CFG->libdir . '/filelib.php'); - $systemcontext = get_context_instance(CONTEXT_SYSTEM); + $systemcontext = context_system::instance(); $options = new stdClass; $options->noclean = true; $description = file_rewrite_pluginfile_urls($this->description, 'pluginfile.php', $systemcontext->id, 'grade', 'scale', $this->id); diff --git a/lib/gradelib.php b/lib/gradelib.php index 8de67cf103d..f83cffd5a52 100644 --- a/lib/gradelib.php +++ b/lib/gradelib.php @@ -758,7 +758,7 @@ function grade_format_gradevalue_percentage($value, $grade_item, $decimals, $loc * @return string */ function grade_format_gradevalue_letter($value, $grade_item) { - $context = get_context_instance(CONTEXT_COURSE, $grade_item->courseid); + $context = context_course::instance($grade_item->courseid, IGNORE_MISSING); if (!$letters = grade_get_letters($context)) { return ''; // no letters?? } @@ -939,7 +939,7 @@ function grade_recover_history_grades($userid, $courseid) { //Check the user is enrolled in this course //Dont bother checking if they have a gradeable role. They may get one later so recover //whatever grades they have now just in case. - $course_context = get_context_instance(CONTEXT_COURSE, $courseid); + $course_context = context_course::instance($courseid); if (!is_enrolled($course_context, $userid)) { debugging('Attempting to recover the grades of a user who is deleted or not enrolled. Skipping recover.'); return false; @@ -1228,7 +1228,7 @@ function remove_course_grades($courseid, $showfeedback) { $course_category = grade_category::fetch_course_category($courseid); $course_category->delete('coursedelete'); - $fs->delete_area_files(get_context_instance(CONTEXT_COURSE, $courseid)->id, 'grade', 'feedback'); + $fs->delete_area_files(context_course::instance($courseid)->id, 'grade', 'feedback'); if ($showfeedback) { echo $OUTPUT->notification($strdeleted.' - '.get_string('grades', 'grades').', '.get_string('items', 'grades').', '.get_string('categories', 'grades'), 'notifysuccess'); } @@ -1269,7 +1269,7 @@ function remove_course_grades($courseid, $showfeedback) { function grade_course_category_delete($categoryid, $newparentid, $showfeedback) { global $DB; - $context = get_context_instance(CONTEXT_COURSECAT, $categoryid); + $context = context_coursecat::instance($categoryid); $DB->delete_records('grade_letters', array('contextid'=>$context->id)); } diff --git a/lib/grouplib.php b/lib/grouplib.php index cecba9cb05c..f80064c848f 100644 --- a/lib/grouplib.php +++ b/lib/grouplib.php @@ -455,7 +455,7 @@ function groups_print_course_menu($course, $urlroot, $return=false) { } } - $context = get_context_instance(CONTEXT_COURSE, $course->id); + $context = context_course::instance($course->id); $aag = has_capability('moodle/site:accessallgroups', $context); if ($groupmode == VISIBLEGROUPS or $aag) { @@ -548,7 +548,7 @@ function groups_print_activity_menu($cm, $urlroot, $return=false, $hideallpartic } } - $context = get_context_instance(CONTEXT_MODULE, $cm->id); + $context = context_module::instance($cm->id); $aag = has_capability('moodle/site:accessallgroups', $context); if ($groupmode == VISIBLEGROUPS or $aag) { @@ -617,7 +617,7 @@ function groups_get_course_group($course, $update=false, $allowedgroups=null) { return false; } - $context = get_context_instance(CONTEXT_COURSE, $course->id); + $context = context_course::instance($course->id); if (has_capability('moodle/site:accessallgroups', $context)) { $groupmode = 'aag'; } @@ -669,7 +669,7 @@ function groups_get_activity_group($cm, $update=false, $allowedgroups=null) { return false; } - $context = get_context_instance(CONTEXT_MODULE, $cm->id); + $context = context_module::instance($cm->id); if (has_capability('moodle/site:accessallgroups', $context)) { $groupmode = 'aag'; } @@ -725,7 +725,7 @@ function groups_get_activity_allowed_groups($cm,$userid=0) { // If visible groups mode, or user has the accessallgroups capability, // then they can access all groups for the activity... - $context = get_context_instance(CONTEXT_MODULE, $cm->id); + $context = context_module::instance($cm->id); if ($groupmode == VISIBLEGROUPS or has_capability('moodle/site:accessallgroups', $context)) { return groups_get_all_groups($cm->course, 0, $cm->groupingid); } else { @@ -756,7 +756,7 @@ function groups_course_module_visible($cm, $userid=null) { if (empty($cm->groupmembersonly)) { return true; } - if (has_capability('moodle/site:accessallgroups', get_context_instance(CONTEXT_MODULE, $cm->id), $userid) or groups_has_membership($cm, $userid)) { + if (has_capability('moodle/site:accessallgroups', context_module::instance($cm->id), $userid) or groups_has_membership($cm, $userid)) { return true; } return false; diff --git a/lib/messagelib.php b/lib/messagelib.php index ba05880a4c8..b184f0dafa0 100644 --- a/lib/messagelib.php +++ b/lib/messagelib.php @@ -388,7 +388,7 @@ function message_get_my_providers() { function message_get_providers_for_user($userid) { global $DB, $CFG; - $systemcontext = get_context_instance(CONTEXT_SYSTEM); + $systemcontext = context_system::instance(); $providers = get_message_providers(); diff --git a/lib/modinfolib.php b/lib/modinfolib.php index 613aba0e92d..fc24b9b5837 100644 --- a/lib/modinfolib.php +++ b/lib/modinfolib.php @@ -973,7 +973,7 @@ class cm_info extends stdClass { $this->icon = isset($mod->icon) ? $mod->icon : ''; $this->iconcomponent = isset($mod->iconcomponent) ? $mod->iconcomponent : ''; $this->customdata = isset($mod->customdata) ? $mod->customdata : ''; - $this->context = get_context_instance(CONTEXT_MODULE, $mod->cm); + $this->context = context_module::instance($mod->cm); $this->showdescription = isset($mod->showdescription) ? $mod->showdescription : 0; $this->state = self::STATE_BASIC; @@ -1091,7 +1091,7 @@ class cm_info extends stdClass { */ private function update_user_visible() { global $CFG; - $modcontext = get_context_instance(CONTEXT_MODULE, $this->id); + $modcontext = context_module::instance($this->id); $userid = $this->modinfo->get_user_id(); $this->uservisible = true; // Check visibility/availability conditions. diff --git a/lib/moodlelib.php b/lib/moodlelib.php index 29f4362eb23..842efaceff3 100644 --- a/lib/moodlelib.php +++ b/lib/moodlelib.php @@ -666,7 +666,8 @@ function optional_param_array($parname, $default, $type) { * @param string $type PARAM_ constant * @param bool $allownull are nulls valid value? * @param string $debuginfo optional debug information - * @return mixed the $param value converted to PHP type or invalid_parameter_exception + * @return mixed the $param value converted to PHP type + * @throws invalid_parameter_exception if $param is not of given type */ function validate_param($param, $type, $allownull=NULL_NOT_ALLOWED, $debuginfo='') { if (is_null($param)) { @@ -681,7 +682,15 @@ function validate_param($param, $type, $allownull=NULL_NOT_ALLOWED, $debuginfo=' } $cleaned = clean_param($param, $type); - if ((string)$param !== (string)$cleaned) { + + if ($type == PARAM_FLOAT) { + // Do not detect precision loss here. + if (is_float($param) or is_int($param)) { + // These always fit. + } else if (!is_numeric($param) or !preg_match('/^[\+-]?[0-9]*\.?[0-9]*(e[-+]?[0-9]+)?$/i', (string)$param)) { + throw new invalid_parameter_exception($debuginfo); + } + } else if ((string)$param !== (string)$cleaned) { // conversion to string is usually lossless throw new invalid_parameter_exception($debuginfo); } @@ -1443,7 +1452,7 @@ function get_users_from_config($value, $capability, $includeadmins = true) { // we have to make sure that users still have the necessary capability, // it should be faster to fetch them all first and then test if they are present // instead of validating them one-by-one - $users = get_users_by_capability(get_context_instance(CONTEXT_SYSTEM), $capability); + $users = get_users_by_capability(context_system::instance(), $capability); if ($includeadmins) { $admins = get_admins(); foreach ($admins as $admin) { @@ -2864,10 +2873,10 @@ function require_login($courseorid = NULL, $autologinguest = true, $cm = NULL, $ } // Fetch the system context, the course context, and prefetch its child contexts - $sysctx = get_context_instance(CONTEXT_SYSTEM); - $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id, MUST_EXIST); + $sysctx = context_system::instance(); + $coursecontext = context_course::instance($course->id, MUST_EXIST); if ($cm) { - $cmcontext = get_context_instance(CONTEXT_MODULE, $cm->id, MUST_EXIST); + $cmcontext = context_module::instance($cm->id, MUST_EXIST); } else { $cmcontext = null; } @@ -4452,7 +4461,7 @@ function delete_course($courseorid, $showfeedback = true) { return false; } } - $context = get_context_instance(CONTEXT_COURSE, $courseid); + $context = context_course::instance($courseid); // frontpage course can not be deleted!! if ($courseid == SITEID) { @@ -4788,7 +4797,7 @@ function reset_course_userdata($data) { require_once($CFG->dirroot.'/group/lib.php'); $data->courseid = $data->id; - $context = get_context_instance(CONTEXT_COURSE, $data->courseid); + $context = context_course::instance($data->courseid); // calculate the time shift of dates if (!empty($data->reset_start_date)) { @@ -5618,7 +5627,7 @@ function send_password_change_info($user) { $site = get_site(); $supportuser = generate_email_supportuser(); - $systemcontext = get_context_instance(CONTEXT_SYSTEM); + $systemcontext = context_system::instance(); $data = new stdClass(); $data->firstname = $user->firstname; diff --git a/lib/navigationlib.php b/lib/navigationlib.php index e6049b824ed..0317445fd87 100644 --- a/lib/navigationlib.php +++ b/lib/navigationlib.php @@ -1131,7 +1131,7 @@ class global_navigation extends navigation_node { $addedcategories[$category->id] = $categoryparent->add($category->name, $url, self::TYPE_CATEGORY, $category->name, $category->id); if (!$category->visible) { - if (!has_capability('moodle/category:viewhiddencategories', get_context_instance(CONTEXT_COURSECAT, $category->parent))) { + if (!has_capability('moodle/category:viewhiddencategories', context_coursecat::instance($category->parent))) { $addedcategories[$category->id]->display = false; } else { $addedcategories[$category->id]->hidden = true; @@ -1230,7 +1230,7 @@ class global_navigation extends navigation_node { $isparent = false; if ($this->useridtouseforparentchecks) { if ($this->useridtouseforparentchecks != $USER->id) { - $usercontext = get_context_instance(CONTEXT_USER, $this->useridtouseforparentchecks, MUST_EXIST); + $usercontext = context_user::instance($this->useridtouseforparentchecks, MUST_EXIST); if ($DB->record_exists('role_assignments', array('userid' => $USER->id, 'contextid' => $usercontext->id)) and has_capability('moodle/user:viewdetails', $usercontext)) { $isparent = true; @@ -1601,7 +1601,7 @@ class global_navigation extends navigation_node { continue; } context_instance_preload($course); - if (!$course->visible && !is_role_switched($course->id) && !has_capability('moodle/course:viewhiddencourses', get_context_instance(CONTEXT_COURSE, $course->id))) { + if (!$course->visible && !is_role_switched($course->id) && !has_capability('moodle/course:viewhiddencourses', context_course::instance($course->id))) { continue; } $coursenodes[$course->id] = $this->add_course($course); @@ -1637,7 +1637,7 @@ class global_navigation extends navigation_node { break; } context_instance_preload($course); - if (!$course->visible && !is_role_switched($course->id) && !has_capability('moodle/course:viewhiddencourses', get_context_instance(CONTEXT_COURSE, $course->id))) { + if (!$course->visible && !is_role_switched($course->id) && !has_capability('moodle/course:viewhiddencourses', context_course::instance($course->id))) { continue; } $coursenodes[$course->id] = $this->add_course($course); @@ -1661,7 +1661,7 @@ class global_navigation extends navigation_node { continue; } context_instance_preload($course); - if (!$course->visible && !is_role_switched($course->id) && !has_capability('moodle/course:viewhiddencourses', get_context_instance(CONTEXT_COURSE, $course->id))) { + if (!$course->visible && !is_role_switched($course->id) && !has_capability('moodle/course:viewhiddencourses', context_course::instance($course->id))) { continue; } $coursenodes[$course->id] = $this->add_course($course); @@ -1843,7 +1843,7 @@ class global_navigation extends navigation_node { return; } $url = new moodle_url('/course/category.php', array('id' => $category->id)); - $context = get_context_instance(CONTEXT_COURSECAT, $category->id); + $context = context_coursecat::instance($category->id); $categoryname = format_string($category->name, true, array('context' => $context)); $categorynode = $parent->add($categoryname, $url, self::TYPE_CATEGORY, $categoryname, $category->id); if (empty($category->visible)) { @@ -2076,7 +2076,7 @@ class global_navigation extends navigation_node { } // Prepare the default name and url for the node - $activityname = format_string($activity->name, true, array('context' => get_context_instance(CONTEXT_MODULE, $activity->id))); + $activityname = format_string($activity->name, true, array('context' => context_module::instance($activity->id))); $action = new moodle_url($activity->url); // Check if the onclick property is set (puke!) @@ -2223,7 +2223,7 @@ class global_navigation extends navigation_node { $iscurrentuser = ($user->id == $USER->id); - $usercontext = get_context_instance(CONTEXT_USER, $user->id); + $usercontext = context_user::instance($user->id); // Get the course set against the page, by default this will be the site $course = $this->page->course; @@ -2231,11 +2231,11 @@ class global_navigation extends navigation_node { if ($course->id != $SITE->id && (!$iscurrentuser || $forceforcontext)) { $coursenode = $this->load_course($course); $baseargs['course'] = $course->id; - $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id); + $coursecontext = context_course::instance($course->id); $issitecourse = false; } else { // Load all categories and get the context for the system - $coursecontext = get_context_instance(CONTEXT_SYSTEM); + $coursecontext = context_system::instance(); $issitecourse = true; } @@ -2244,7 +2244,7 @@ class global_navigation extends navigation_node { // If it's the current user the information will go under the profile root node $usernode = $this->rootnodes['myprofile']; $course = get_site(); - $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id); + $coursecontext = context_course::instance($course->id); $issitecourse = true; } else { if (!$issitecourse) { @@ -2327,7 +2327,7 @@ class global_navigation extends navigation_node { $usernode->add(get_string('messages', 'message'), $url, self::TYPE_SETTING, null, 'messages'); } - $context = get_context_instance(CONTEXT_USER, $USER->id); + $context = context_user::instance($USER->id); if ($iscurrentuser && has_capability('moodle/user:manageownfiles', $context)) { $url = new moodle_url('/user/files.php'); $usernode->add(get_string('myfiles'), $url, self::TYPE_SETTING); @@ -2399,7 +2399,7 @@ class global_navigation extends navigation_node { $userscoursesnode = $usernode->add(get_string('courses')); foreach ($userscourses as $usercourse) { - $usercoursecontext = get_context_instance(CONTEXT_COURSE, $usercourse->id); + $usercoursecontext = context_course::instance($usercourse->id); $usercourseshortname = format_string($usercourse->shortname, true, array('context' => $usercoursecontext)); $usercoursenode = $userscoursesnode->add($usercourseshortname, new moodle_url('/user/view.php', array('id'=>$user->id, 'course'=>$usercourse->id)), self::TYPE_CONTAINER); @@ -2497,7 +2497,7 @@ class global_navigation extends navigation_node { return $this->addedcourses[$course->id]; } - $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id); + $coursecontext = context_course::instance($course->id); if ($course->id != $SITE->id && !$course->visible) { if (is_role_switched($course->id)) { @@ -2544,7 +2544,7 @@ class global_navigation extends navigation_node { $coursenode = $parent->add($shortname, $url, self::TYPE_COURSE, $shortname, $course->id); $coursenode->nodetype = self::NODETYPE_BRANCH; $coursenode->hidden = (!$course->visible); - $coursenode->title(format_string($course->fullname, true, array('context' => get_context_instance(CONTEXT_COURSE, $course->id)))); + $coursenode->title(format_string($course->fullname, true, array('context' => context_course::instance($course->id)))); if (!$forcegeneric) { $this->addedcourses[$course->id] = $coursenode; } @@ -2595,7 +2595,7 @@ class global_navigation extends navigation_node { } $filterselect = clean_param($filterselect, PARAM_INT); if (($CFG->bloglevel == BLOG_GLOBAL_LEVEL or ($CFG->bloglevel == BLOG_SITE_LEVEL and (isloggedin() and !isguestuser()))) - and has_capability('moodle/blog:view', get_context_instance(CONTEXT_SYSTEM))) { + and has_capability('moodle/blog:view', context_system::instance())) { $blogsurls = new moodle_url('/blog/index.php', array('courseid' => $filterselect)); $participants->add(get_string('blogscourse','blog'), $blogsurls->out()); } @@ -2660,7 +2660,7 @@ class global_navigation extends navigation_node { // Blogs if (!empty($CFG->bloglevel) and ($CFG->bloglevel == BLOG_GLOBAL_LEVEL or ($CFG->bloglevel == BLOG_SITE_LEVEL and (isloggedin() and !isguestuser()))) - and has_capability('moodle/blog:view', get_context_instance(CONTEXT_SYSTEM))) { + and has_capability('moodle/blog:view', context_system::instance())) { $blogsurls = new moodle_url('/blog/index.php', array('courseid' => $filterselect)); $coursenode->add(get_string('blogssite','blog'), $blogsurls->out()); } @@ -2856,7 +2856,7 @@ class global_navigation_for_ajax extends global_navigation { case self::TYPE_COURSE : $course = $DB->get_record('course', array('id' => $this->instanceid), '*', MUST_EXIST); require_course_login($course, true, null, false, true); - $this->page->set_context(get_context_instance(CONTEXT_COURSE, $course->id)); + $this->page->set_context(context_course::instance($course->id)); $coursenode = $this->add_course($course); $this->add_course_essentials($coursenode, $course); if ($this->format_display_course_content($course->format)) { @@ -2870,7 +2870,7 @@ class global_navigation_for_ajax extends global_navigation { WHERE cs.id = ?'; $course = $DB->get_record_sql($sql, array($this->instanceid), MUST_EXIST); require_course_login($course, true, null, false, true); - $this->page->set_context(get_context_instance(CONTEXT_COURSE, $course->id)); + $this->page->set_context(context_course::instance($course->id)); $coursenode = $this->add_course($course); $this->add_course_essentials($coursenode, $course); $sections = $this->load_course_sections($course, $coursenode); @@ -2887,7 +2887,7 @@ class global_navigation_for_ajax extends global_navigation { $modinfo = get_fast_modinfo($course); $cm = $modinfo->get_cm($this->instanceid); require_course_login($course, true, $cm, false, true); - $this->page->set_context(get_context_instance(CONTEXT_MODULE, $cm->id)); + $this->page->set_context(context_module::instance($cm->id)); $coursenode = $this->load_course($course); if ($course->id == $SITE->id) { $modulenode = $this->load_activity($cm, $course, $coursenode->find($cm->id, self::TYPE_ACTIVITY)); @@ -3540,7 +3540,7 @@ class settings_navigation extends navigation_node { global $CFG; $course = $this->page->course; - $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id); + $coursecontext = context_course::instance($course->id); // note: do not test if enrolled or viewing here because we need the enrol link in Course administration section @@ -4017,13 +4017,13 @@ class settings_navigation extends navigation_node { $course = $SITE; } - $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id); // Course context + $coursecontext = context_course::instance($course->id); // Course context $systemcontext = get_system_context(); $currentuser = ($USER->id == $userid); if ($currentuser) { $user = $USER; - $usercontext = get_context_instance(CONTEXT_USER, $user->id); // User context + $usercontext = context_user::instance($user->id); // User context } else { $select = context_helper::get_preload_record_columns_sql('ctx'); $sql = "SELECT u.*, $select @@ -4038,7 +4038,7 @@ class settings_navigation extends navigation_node { context_helper::preload_from_record($user); // Check that the user can view the profile - $usercontext = get_context_instance(CONTEXT_USER, $user->id); // User context + $usercontext = context_user::instance($user->id); // User context $canviewuser = has_capability('moodle/user:viewdetails', $usercontext); if ($course->id == $SITE->id) { @@ -4199,7 +4199,7 @@ class settings_navigation extends navigation_node { if ($currentuser && !empty($CFG->bloglevel)) { $blog = $usersetting->add(get_string('blogs', 'blog'), null, navigation_node::TYPE_CONTAINER, null, 'blogs'); $blog->add(get_string('preferences', 'blog'), new moodle_url('/blog/preferences.php'), navigation_node::TYPE_SETTING); - if (!empty($CFG->useexternalblogs) && $CFG->maxexternalblogsperuser > 0 && has_capability('moodle/blog:manageexternal', get_context_instance(CONTEXT_SYSTEM))) { + if (!empty($CFG->useexternalblogs) && $CFG->maxexternalblogsperuser > 0 && has_capability('moodle/blog:manageexternal', context_system::instance())) { $blog->add(get_string('externalblogs', 'blog'), new moodle_url('/blog/external_blogs.php'), navigation_node::TYPE_SETTING); $blog->add(get_string('addnewexternalblog', 'blog'), new moodle_url('/blog/external_blog_edit.php'), navigation_node::TYPE_SETTING); } @@ -4340,7 +4340,7 @@ class settings_navigation extends navigation_node { global $SITE, $CFG; $course = clone($SITE); - $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id); // Course context + $coursecontext = context_course::instance($course->id); // Course context $frontpage = $this->add(get_string('frontpagesettings'), null, self::TYPE_SETTING, null, 'frontpage'); if ($forceopen) { diff --git a/lib/outputcomponents.php b/lib/outputcomponents.php index 35edf3b780e..7abde25c951 100644 --- a/lib/outputcomponents.php +++ b/lib/outputcomponents.php @@ -92,7 +92,7 @@ class file_picker implements renderable { $options->currentfile = ''; if (!empty($options->itemid)) { $fs = get_file_storage(); - $usercontext = get_context_instance(CONTEXT_USER, $USER->id); + $usercontext = context_user::instance($USER->id); if (empty($options->filename)) { if ($files = $fs->get_area_files($usercontext->id, 'user', 'draft', $options->itemid, 'id DESC', false)) { $file = reset($files); @@ -714,6 +714,11 @@ class single_select implements renderable { */ var $label = ''; + /** + * @var array Button label's attributes + */ + var $labelattributes = array(); + /** * @var string Form submit method post or get */ @@ -806,9 +811,12 @@ class single_select implements renderable { * Sets select's label * * @param string $label + * @param array $attributes (optional) */ - public function set_label($label) { + public function set_label($label, $attributes = array()) { $this->label = $label; + $this->labelattributes = $attributes; + } } @@ -850,6 +858,11 @@ class url_select implements renderable { */ var $label = ''; + /** + * @var array Button label's attributes + */ + var $labelattributes = array(); + /** * @var string Wrapping div class */ @@ -922,9 +935,11 @@ class url_select implements renderable { * Sets select's label * * @param string $label + * @param array $attributes (optional) */ - public function set_label($label) { + public function set_label($label, $attributes = array()) { $this->label = $label; + $this->labelattributes = $attributes; } } @@ -2790,4 +2805,4 @@ class custom_menu extends custom_menu_item { } return ($itema > $itemb) ? +1 : -1; } -} \ No newline at end of file +} diff --git a/lib/outputrenderers.php b/lib/outputrenderers.php index d099429c1d6..17cd590268a 100644 --- a/lib/outputrenderers.php +++ b/lib/outputrenderers.php @@ -457,7 +457,7 @@ class core_renderer extends renderer_base { if (!empty($CFG->debugpageinfo)) { $output .= '
This page is: ' . $this->page->debug_summary() . '
'; } - if (debugging(null, DEBUG_DEVELOPER) and has_capability('moodle/site:config', get_context_instance(CONTEXT_SYSTEM))) { // Only in developer mode + if (debugging(null, DEBUG_DEVELOPER) and has_capability('moodle/site:config', context_system::instance())) { // Only in developer mode // Add link to profiling report if necessary if (function_exists('profiling_is_running') && profiling_is_running()) { $txt = get_string('profiledscript', 'admin'); @@ -535,7 +535,7 @@ class core_renderer extends renderer_base { // $course->id is not defined during installation return ''; } else if (isloggedin()) { - $context = get_context_instance(CONTEXT_COURSE, $course->id); + $context = context_course::instance($course->id); $fullname = fullname($USER, true); // Since Moodle 2.0 this link always goes to the public profile page (not the course profile page) @@ -579,7 +579,7 @@ class core_renderer extends renderer_base { } else { $loggedinas .= get_string('failedloginattemptsall', '', $count); } - if (file_exists("$CFG->dirroot/report/log/index.php") and has_capability('report/log:view', get_context_instance(CONTEXT_SYSTEM))) { + if (file_exists("$CFG->dirroot/report/log/index.php") and has_capability('report/log:view', context_system::instance())) { $loggedinas .= ' ('.get_string('logs').')'; } @@ -1332,7 +1332,7 @@ class core_renderer extends renderer_base { } if ($select->label) { - $output .= html_writer::label($select->label, $select->attributes['id']); + $output .= html_writer::label($select->label, $select->attributes['id'], false, $select->labelattributes); } if ($select->helpicon instanceof help_icon) { @@ -1340,7 +1340,6 @@ class core_renderer extends renderer_base { } else if ($select->helpicon instanceof old_help_icon) { $output .= $this->render($select->helpicon); } - $output .= html_writer::select($select->options, $select->name, $select->selected, $select->nothing, $select->attributes); $go = html_writer::empty_tag('input', array('type'=>'submit', 'value'=>get_string('go'))); @@ -1410,7 +1409,7 @@ class core_renderer extends renderer_base { $output = ''; if ($select->label) { - $output .= html_writer::label($select->label, $select->attributes['id']); + $output .= html_writer::label($select->label, $select->attributes['id'], false, $select->labelattributes); } if ($select->helpicon instanceof help_icon) { @@ -1627,6 +1626,7 @@ class core_renderer extends renderer_base { $scalearray = array(RATING_UNSET_RATING => $strrate.'...') + $rating->settings->scale->scaleitems; $scaleattrs = array('class'=>'postratingmenu ratinginput','id'=>'menurating'.$rating->itemid); + $ratinghtml .= html_writer::label($rating->rating, 'menurating'.$rating->itemid, false, array('class' => 'accesshide')); $ratinghtml .= html_writer::select($scalearray, 'rating', $rating->rating, false, $scaleattrs); //output submit button @@ -2075,7 +2075,7 @@ EOD; */ public function update_module_button($cmid, $modulename) { global $CFG; - if (has_capability('moodle/course:manageactivities', get_context_instance(CONTEXT_MODULE, $cmid))) { + if (has_capability('moodle/course:manageactivities', context_module::instance($cmid))) { $modulename = get_string('modulename', $modulename); $string = get_string('updatethis', '', $modulename); $url = new moodle_url("$CFG->wwwroot/course/mod.php", array('update' => $cmid, 'return' => true, 'sesskey' => sesskey())); diff --git a/lib/pagelib.php b/lib/pagelib.php index 277e6c55d7f..107911bb2eb 100644 --- a/lib/pagelib.php +++ b/lib/pagelib.php @@ -449,7 +449,7 @@ class moodle_page { .'to call require_login() or $PAGE->set_context(). The page may not display ' .'correctly as a result'); } - $this->_context = get_context_instance(CONTEXT_SYSTEM); + $this->_context = context_system::instance(); } return $this->_context; } @@ -862,7 +862,7 @@ class moodle_page { } if (!$this->_context) { - $this->set_context(get_context_instance(CONTEXT_COURSE, $this->_course->id)); + $this->set_context(context_course::instance($this->_course->id)); } } @@ -876,7 +876,7 @@ class moodle_page { // extremely ugly hack which sets context to some value in order to prevent warnings, // use only for core error handling!!!! if (!$this->_context) { - $this->_context = get_context_instance(CONTEXT_SYSTEM); + $this->_context = context_system::instance(); } return; } @@ -933,7 +933,7 @@ class moodle_page { // unfortunately the context setting is a mess, let's try to work around some common block problems and show some debug messages if (empty($this->_context) or $this->_context->contextlevel != CONTEXT_BLOCK) { - $context = get_context_instance(CONTEXT_MODULE, $cm->id); + $context = context_module::instance($cm->id); $this->set_context($context); } @@ -1096,7 +1096,7 @@ class moodle_page { $this->ensure_theme_not_set(); $this->set_course($SITE); $this->load_category($categoryid); - $this->set_context(get_context_instance(CONTEXT_COURSECAT, $categoryid)); + $this->set_context(context_coursecat::instance($categoryid)); } /** diff --git a/lib/portfoliolib.php b/lib/portfoliolib.php index 45e9a78b497..0cac1453db5 100644 --- a/lib/portfoliolib.php +++ b/lib/portfoliolib.php @@ -462,7 +462,8 @@ function portfolio_instance_select($instances, $callerformats, $callbackclass, $ $pinsane = portfolio_plugin_sanity_check(); $count = 0; - $selectoutput = "\n" . '' . "\n"; $existingexports = portfolio_existing_exports_by_plugin($USER->id); foreach ($instances as $instance) { $formats = portfolio_supported_formats_intersect($callerformats, $instance->supported_formats()); @@ -1096,7 +1097,7 @@ function portfolio_insane_notify_admins($insane, $instances=false) { $site = get_site(); $a = new StdClass; - $a->sitename = format_string($site->fullname, true, array('context' => get_context_instance(CONTEXT_COURSE, SITEID))); + $a->sitename = format_string($site->fullname, true, array('context' => context_course::instance(SITEID))); $a->fixurl = "$CFG->wwwroot/$CFG->admin/settings.php?section=manageportfolios"; $a->htmllist = portfolio_report_insane($insane, $instances, true); $a->textlist = ''; diff --git a/lib/questionlib.php b/lib/questionlib.php index 1a24e8cf19f..149f3514468 100644 --- a/lib/questionlib.php +++ b/lib/questionlib.php @@ -355,7 +355,7 @@ function question_delete_course($course, $feedback=true) { //Cache some strings $strcatdeleted = get_string('unusedcategorydeleted', 'quiz'); - $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id); + $coursecontext = context_course::instance($course->id); $categoriescourse = $DB->get_records('question_categories', array('contextid' => $coursecontext->id), 'parent', 'id, parent, name, contextid'); @@ -407,7 +407,7 @@ function question_delete_course($course, $feedback=true) { function question_delete_course_category($category, $newcategory, $feedback=true) { global $DB, $OUTPUT; - $context = get_context_instance(CONTEXT_COURSECAT, $category->id); + $context = context_coursecat::instance($category->id); if (empty($newcategory)) { $feedbackdata = array(); // To store feedback to be showed at the end of the process $rescueqcategory = null; // See the code around the call to question_save_from_deletion. @@ -464,7 +464,7 @@ function question_delete_course_category($category, $newcategory, $feedback=true } else { // Move question categories ot the new context. - if (!$newcontext = get_context_instance(CONTEXT_COURSECAT, $newcategory->id)) { + if (!$newcontext = context_coursecat::instance($newcategory->id)) { return false; } $DB->set_field('question_categories', 'contextid', $newcontext->id, @@ -529,7 +529,7 @@ function question_delete_activity($cm, $feedback=true) { //Cache some strings $strcatdeleted = get_string('unusedcategorydeleted', 'quiz'); - $modcontext = get_context_instance(CONTEXT_MODULE, $cm->id); + $modcontext = context_module::instance($cm->id); if ($categoriesmods = $DB->get_records('question_categories', array('contextid' => $modcontext->id), 'parent', 'id, parent, name, contextid')) { //Sort categories following their tree (parent-child) relationships @@ -992,7 +992,7 @@ function question_category_select_menu($contexts, $top = false, $currentcat = 0, foreach ($categoriesarray as $group => $opts) { $options[] = array($group => $opts); } - + echo html_writer::label($selected, 'menucategory', false, array('class' => 'accesshide')); echo html_writer::select($options, 'category', $selected, $choose); } diff --git a/lib/resourcelib.php b/lib/resourcelib.php index c2d796f78d7..6cf51b49299 100644 --- a/lib/resourcelib.php +++ b/lib/resourcelib.php @@ -67,10 +67,10 @@ function resourcelib_try_file_migration($filepath, $cmid, $courseid, $component, return false; } - if (!$context = get_context_instance(CONTEXT_MODULE, $cmid)) { + if (!$context = context_module::instance($cmid)) { return false; } - if (!$coursecontext = get_context_instance(CONTEXT_COURSE, $courseid)) { + if (!$coursecontext = context_course::instance($courseid)) { return false; } diff --git a/lib/statslib.php b/lib/statslib.php index 4091dad30e2..6b2220fbe25 100644 --- a/lib/statslib.php +++ b/lib/statslib.php @@ -104,7 +104,7 @@ function stats_cron_daily($maxdays=1) { $now = time(); - $fpcontext = get_context_instance(CONTEXT_COURSE, SITEID, MUST_EXIST); + $fpcontext = context_course::instance(SITEID, MUST_EXIST); // read last execution date from db if (!$timestart = get_config(NULL, 'statslastdaily')) { @@ -1332,7 +1332,7 @@ function stats_get_report_options($courseid,$mode) { switch ($mode) { case STATS_MODE_GENERAL: $reportoptions[STATS_REPORT_ACTIVITY] = get_string('statsreport'.STATS_REPORT_ACTIVITY); - if ($courseid != SITEID && $context = get_context_instance(CONTEXT_COURSE, $courseid)) { + if ($courseid != SITEID && $context = context_course::instance($courseid)) { $sql = 'SELECT r.id, r.name FROM {role} r JOIN {stats_daily} s ON s.roleid = r.id WHERE s.courseid = :courseid GROUP BY r.id, r.name'; if ($roles = $DB->get_records_sql($sql, array('courseid' => $courseid))) { foreach ($roles as $role) { @@ -1350,13 +1350,13 @@ function stats_get_report_options($courseid,$mode) { case STATS_MODE_DETAILED: $reportoptions[STATS_REPORT_USER_ACTIVITY] = get_string('statsreport'.STATS_REPORT_USER_ACTIVITY); $reportoptions[STATS_REPORT_USER_ALLACTIVITY] = get_string('statsreport'.STATS_REPORT_USER_ALLACTIVITY); - if (has_capability('report/stats:view', get_context_instance(CONTEXT_SYSTEM))) { + if (has_capability('report/stats:view', context_system::instance())) { $site = get_site(); $reportoptions[STATS_REPORT_USER_LOGINS] = get_string('statsreport'.STATS_REPORT_USER_LOGINS); } break; case STATS_MODE_RANKED: - if (has_capability('report/stats:view', get_context_instance(CONTEXT_SYSTEM))) { + if (has_capability('report/stats:view', context_system::instance())) { $reportoptions[STATS_REPORT_ACTIVE_COURSES] = get_string('statsreport'.STATS_REPORT_ACTIVE_COURSES); $reportoptions[STATS_REPORT_ACTIVE_COURSES_WEIGHTED] = get_string('statsreport'.STATS_REPORT_ACTIVE_COURSES_WEIGHTED); $reportoptions[STATS_REPORT_PARTICIPATORY_COURSES] = get_string('statsreport'.STATS_REPORT_PARTICIPATORY_COURSES); diff --git a/lib/tablelib.php b/lib/tablelib.php index b8105642cfd..04daa06e6bd 100644 --- a/lib/tablelib.php +++ b/lib/tablelib.php @@ -918,6 +918,7 @@ class flexible_table { $html = ''; $html .= '
'; $html .= ''; + $html .= html_writer::label(get_string('downloadoptions', 'table'), 'menudownload', false, array('class' => 'accesshide')); $html .= html_writer::select($downloadoptions, 'download', $this->defaultdownloadformat, false); $html .= '
'; diff --git a/lib/tests/accesslib_test.php b/lib/tests/accesslib_test.php index 97712b1321d..52d700fea28 100644 --- a/lib/tests/accesslib_test.php +++ b/lib/tests/accesslib_test.php @@ -2336,14 +2336,14 @@ class accesslib_testcase extends advanced_testcase { accesslib_clear_all_caches(false); $DB->delete_records('cache_flags', array()); $course = $DB->get_record('course', array('id'=>$testcourses[2])); - $context = get_context_instance(CONTEXT_COURSE, $course->id); + $context = context_course::instance($course->id); $oldpath = $context->path; $miscid = $DB->get_field_sql("SELECT MIN(id) FROM {course_categories}"); $categorycontext = context_coursecat::instance($miscid); $course->category = $miscid; $DB->update_record('course', $course); context_moved($context, $categorycontext); - $context = get_context_instance(CONTEXT_COURSE, $course->id); + $context = context_course::instance($course->id); $this->assertEquals($context->get_parent_context(), $categorycontext); $this->assertTrue($DB->record_exists('context', array('contextlevel'=>CONTEXT_COURSE, 'instanceid'=>$testcourses[2]))); @@ -2353,7 +2353,7 @@ class accesslib_testcase extends advanced_testcase { $name = get_contextlevel_name(CONTEXT_COURSE); $this->assertFalse(empty($name)); - $context = get_context_instance(CONTEXT_COURSE, $testcourses[2]); + $context = context_course::instance($testcourses[2]); $name = print_context_name($context); $this->assertFalse(empty($name)); @@ -2361,7 +2361,7 @@ class accesslib_testcase extends advanced_testcase { $this->assertFalse($url instanceof modole_url); $page = $DB->get_record('page', array('id'=>$testpages[7])); - $context = get_context_instance(CONTEXT_MODULE, $page->id); + $context = context_module::instance($page->id); $coursecontext = get_course_context($context); $this->assertEquals($coursecontext->contextlevel, CONTEXT_COURSE); $this->assertEquals(get_courseid_from_context($context), $page->course); diff --git a/lib/tests/blocklib_test.php b/lib/tests/blocklib_test.php index 704d3871fad..471e908cf05 100644 --- a/lib/tests/blocklib_test.php +++ b/lib/tests/blocklib_test.php @@ -56,7 +56,7 @@ class moodle_block_manager_testcase extends basic_testcase { protected function setUp() { parent::setUp(); $this->testpage = new moodle_page(); - $this->testpage->set_context(get_context_instance(CONTEXT_SYSTEM)); + $this->testpage->set_context(context_system::instance()); $this->blockmanager = new testable_block_manager($this->testpage); } @@ -205,7 +205,7 @@ class moodle_block_manager_test_saving_loading_testcase extends advanced_testcas // Set up fixture. list($page, $blockmanager) = $this->get_a_page_and_block_manager(array('a-region'), - get_context_instance(CONTEXT_SYSTEM), 'page-type'); + context_system::instance(), 'page-type'); // Exercise SUT. $blockmanager->load_blocks(); // Validate. @@ -219,7 +219,7 @@ class moodle_block_manager_test_saving_loading_testcase extends advanced_testcas // Set up fixture. $regionname = 'a-region'; $blockname = $this->get_a_known_block_type(); - $context = get_context_instance(CONTEXT_SYSTEM); + $context = context_system::instance(); list($page, $blockmanager) = $this->get_a_page_and_block_manager(array($regionname), $context, 'page-type'); @@ -238,7 +238,7 @@ class moodle_block_manager_test_saving_loading_testcase extends advanced_testcas // Set up fixture. $regionname = 'a-region'; $blockname = $this->get_a_known_block_type(); - $context = get_context_instance(CONTEXT_SYSTEM); + $context = context_system::instance(); list($page, $blockmanager) = $this->get_a_page_and_block_manager(array($regionname), $context, 'page-type'); @@ -257,7 +257,7 @@ class moodle_block_manager_test_saving_loading_testcase extends advanced_testcas $this->purge_blocks(); // Set up fixture. - $syscontext = get_context_instance(CONTEXT_SYSTEM); + $syscontext = context_system::instance(); $cat = new stdClass(); $cat->name = 'testcategory'; $cat->parent = 0; @@ -286,7 +286,7 @@ class moodle_block_manager_test_saving_loading_testcase extends advanced_testcas $this->purge_blocks(); // Set up fixture. - $syscontext = get_context_instance(CONTEXT_SYSTEM); + $syscontext = context_system::instance(); $childcontext = context_coursecat::instance(1); $regionname = 'a-region'; $blockname = $this->get_a_known_block_type(); @@ -307,7 +307,7 @@ class moodle_block_manager_test_saving_loading_testcase extends advanced_testcas $this->purge_blocks(); // Set up fixture. - $syscontext = get_context_instance(CONTEXT_SYSTEM); + $syscontext = context_system::instance(); $regionname = 'a-region'; $blockname = $this->get_a_known_block_type(); @@ -329,7 +329,7 @@ class moodle_block_manager_test_saving_loading_testcase extends advanced_testcas // Set up fixture. $regionname = 'a-region'; $blockname = $this->get_a_known_block_type(); - $syscontext = get_context_instance(CONTEXT_SYSTEM); + $syscontext = context_system::instance(); list($page, $blockmanager) = $this->get_a_page_and_block_manager(array($regionname), $syscontext, 'page-type', 'sub-page'); @@ -349,7 +349,7 @@ class moodle_block_manager_test_saving_loading_testcase extends advanced_testcas // Set up fixture. $regionname = 'a-region'; $blockname = $this->get_a_known_block_type(); - $syscontext = get_context_instance(CONTEXT_SYSTEM); + $syscontext = context_system::instance(); list($page, $blockmanager) = $this->get_a_page_and_block_manager(array($regionname), $syscontext, 'page-type', 'sub-page'); @@ -369,7 +369,7 @@ class moodle_block_manager_test_saving_loading_testcase extends advanced_testcas // Set up fixture. $regionname = 'a-region'; $blockname = $this->get_a_known_block_type(); - $syscontext = get_context_instance(CONTEXT_SYSTEM); + $syscontext = context_system::instance(); list($page, $blockmanager) = $this->get_a_page_and_block_manager(array($regionname), $syscontext, 'page-type', 'sub-page'); diff --git a/lib/tests/filter_test.php b/lib/tests/filter_test.php index 1c8f0557895..b220781b47c 100644 --- a/lib/tests/filter_test.php +++ b/lib/tests/filter_test.php @@ -298,7 +298,7 @@ class filter_active_local_testcase extends advanced_testcase { */ public function test_throws_exception_when_setting_global() { // Exercise SUT. - filter_set_local_state('filter/name', get_context_instance(CONTEXT_SYSTEM)->id, TEXTFILTER_INHERIT); + filter_set_local_state('filter/name', context_system::instance()->id, TEXTFILTER_INHERIT); } public function test_local_inherit_deletes_existing() { diff --git a/lib/tests/moodlelib_test.php b/lib/tests/moodlelib_test.php index 5ce3a2cedba..2d03ffcad25 100644 --- a/lib/tests/moodlelib_test.php +++ b/lib/tests/moodlelib_test.php @@ -912,6 +912,56 @@ class moodlelib_testcase extends advanced_testcase { } catch (invalid_parameter_exception $ex) { $this->assertTrue(true); } + try { + $param = validate_param('1.0', PARAM_FLOAT); + $this->assertSame(1.0, $param); + + // Make sure valid floats do not cause exception. + validate_param(1.0, PARAM_FLOAT); + validate_param(10, PARAM_FLOAT); + validate_param('0', PARAM_FLOAT); + validate_param('119813454.545464564564546564545646556564465465456465465465645645465645645645', PARAM_FLOAT); + validate_param('011.1', PARAM_FLOAT); + validate_param('11', PARAM_FLOAT); + validate_param('+.1', PARAM_FLOAT); + validate_param('-.1', PARAM_FLOAT); + validate_param('1e10', PARAM_FLOAT); + validate_param('.1e+10', PARAM_FLOAT); + validate_param('1E-1', PARAM_FLOAT); + $this->assertTrue(true); + } catch (invalid_parameter_exception $ex) { + $this->fail('Valid float notation not accepted'); + } + try { + $param = validate_param('1,2', PARAM_FLOAT); + $this->fail('invalid_parameter_exception expected'); + } catch (invalid_parameter_exception $ex) { + $this->assertTrue(true); + } + try { + $param = validate_param('', PARAM_FLOAT); + $this->fail('invalid_parameter_exception expected'); + } catch (invalid_parameter_exception $ex) { + $this->assertTrue(true); + } + try { + $param = validate_param('.', PARAM_FLOAT); + $this->fail('invalid_parameter_exception expected'); + } catch (invalid_parameter_exception $ex) { + $this->assertTrue(true); + } + try { + $param = validate_param('e10', PARAM_FLOAT); + $this->fail('invalid_parameter_exception expected'); + } catch (invalid_parameter_exception $ex) { + $this->assertTrue(true); + } + try { + $param = validate_param('abc', PARAM_FLOAT); + $this->fail('invalid_parameter_exception expected'); + } catch (invalid_parameter_exception $ex) { + $this->assertTrue(true); + } } function test_shorten_text() { diff --git a/lib/tests/other/pdflibtestpage.php b/lib/tests/other/pdflibtestpage.php index 985d175b9f8..7c53a2ec293 100644 --- a/lib/tests/other/pdflibtestpage.php +++ b/lib/tests/other/pdflibtestpage.php @@ -26,7 +26,7 @@ require(dirname(__FILE__) . '/../../../config.php'); require_once($CFG->libdir . '/pdflib.php'); require_login(); -$context = get_context_instance(CONTEXT_SYSTEM); +$context = context_system::instance(); require_capability('moodle/site:config', $context); $getpdf = optional_param('getpdf', 0, PARAM_INT); diff --git a/lib/tests/other/todochecker.php b/lib/tests/other/todochecker.php index c22b30a94fb..9b40a2b742b 100644 --- a/lib/tests/other/todochecker.php +++ b/lib/tests/other/todochecker.php @@ -27,7 +27,7 @@ require(dirname(__FILE__) . '/../../../config.php'); require_login(); -$context = get_context_instance(CONTEXT_SYSTEM); +$context = context_system::instance(); require_capability('moodle/site:config', $context); $PAGE->set_url('/lib/tests/other/todochecker.php'); diff --git a/lib/tests/pagelib_test.php b/lib/tests/pagelib_test.php index 04814d0e506..243f2df8d50 100644 --- a/lib/tests/pagelib_test.php +++ b/lib/tests/pagelib_test.php @@ -65,7 +65,7 @@ class moodle_page_test extends advanced_testcase { public function test_setting_course_works() { // Setup fixture $course = $this->getDataGenerator()->create_course(); - $this->testpage->set_context(get_context_instance(CONTEXT_SYSTEM)); // Avoid trying to set the context. + $this->testpage->set_context(context_system::instance()); // Avoid trying to set the context. // Exercise SUT $this->testpage->set_course($course); // Validate @@ -76,7 +76,7 @@ class moodle_page_test extends advanced_testcase { global $COURSE, $PAGE; // Setup fixture $course = $this->getDataGenerator()->create_course(); - $this->testpage->set_context(get_context_instance(CONTEXT_SYSTEM)); // Avoid trying to set the context. + $this->testpage->set_context(context_system::instance()); // Avoid trying to set the context. $PAGE = $this->testpage; // Exercise SUT $this->testpage->set_course($course); @@ -89,7 +89,7 @@ class moodle_page_test extends advanced_testcase { $originalcourse = $COURSE; // Setup fixture $course = $this->getDataGenerator()->create_course(); - $this->testpage->set_context(get_context_instance(CONTEXT_SYSTEM)); // Avoid trying to set the context. + $this->testpage->set_context(context_system::instance()); // Avoid trying to set the context. // Exercise SUT $this->testpage->set_course($course); // Validate @@ -118,7 +118,7 @@ class moodle_page_test extends advanced_testcase { public function test_cannot_set_category_once_course_set() { // Setup fixture $course = $this->getDataGenerator()->create_course(); - $this->testpage->set_context(get_context_instance(CONTEXT_SYSTEM)); // Avoid trying to set the context. + $this->testpage->set_context(context_system::instance()); // Avoid trying to set the context. $this->testpage->set_course($course); // Set expectation. $this->setExpectedException('coding_exception'); @@ -129,7 +129,7 @@ class moodle_page_test extends advanced_testcase { public function test_categories_array_empty_for_front_page() { global $SITE; // Setup fixture - $this->testpage->set_context(get_context_instance(CONTEXT_SYSTEM)); // Avoid trying to set the context. + $this->testpage->set_context(context_system::instance()); // Avoid trying to set the context. $this->testpage->set_course($SITE); // Exercise SUT and validate. $this->assertEquals(array(), $this->testpage->categories); @@ -137,7 +137,7 @@ class moodle_page_test extends advanced_testcase { public function test_set_state_normal_path() { $course = $this->getDataGenerator()->create_course(); - $this->testpage->set_context(get_context_instance(CONTEXT_SYSTEM)); + $this->testpage->set_context(context_system::instance()); $this->testpage->set_course($course); $this->assertEquals(moodle_page::STATE_BEFORE_HEADER, $this->testpage->state); @@ -166,7 +166,7 @@ class moodle_page_test extends advanced_testcase { public function test_header_printed_becomes_true() { $course = $this->getDataGenerator()->create_course(); - $this->testpage->set_context(get_context_instance(CONTEXT_SYSTEM)); + $this->testpage->set_context(context_system::instance()); $this->testpage->set_course($course); // Exercise SUT @@ -564,7 +564,7 @@ class moodle_page_editing_test extends advanced_testcase { parent::setUp(); $this->setAdminUser(); $this->testpage = new testable_moodle_page(); - $this->testpage->set_context(get_context_instance(CONTEXT_SYSTEM)); + $this->testpage->set_context(context_system::instance()); $this->resetAfterTest(); } diff --git a/lib/tests/performance/filtersettingsperformancetester.php b/lib/tests/performance/filtersettingsperformancetester.php index bb387375286..6eec7b603bd 100644 --- a/lib/tests/performance/filtersettingsperformancetester.php +++ b/lib/tests/performance/filtersettingsperformancetester.php @@ -31,7 +31,7 @@ require(dirname(__FILE__) . '/../../../config.php'); require_once($CFG->libdir . '/ddllib.php'); require_login(); -$syscontext = get_context_instance(CONTEXT_SYSTEM); +$syscontext = context_system::instance(); require_capability('moodle/site:config', $syscontext); $baseurl = new moodle_url('/lib/tests/performance/filtersettingsperformancetester.php'); diff --git a/lib/upgrade.txt b/lib/upgrade.txt index 58682c5673f..d3bc9c16f35 100644 --- a/lib/upgrade.txt +++ b/lib/upgrade.txt @@ -6,6 +6,9 @@ information provided here is intended especially for developers. * Pagelib: Numerous deprecated functions were removed as classes page_base, page_course and page_generic_activity. +YUI changes: +* moodle-enrol-notification has been renamed to moodle-core-notification + === 2.3 === Database layer changes: diff --git a/lib/uploadlib.php b/lib/uploadlib.php index 960370d9ef0..7ee20cfeec8 100644 --- a/lib/uploadlib.php +++ b/lib/uploadlib.php @@ -650,7 +650,7 @@ function clam_scan_moodle_file(&$file, $course) { case 1: // bad wicked evil, we have a virus. $info = new stdClass(); if (!empty($course)) { - $info->course = format_string($course->fullname, true, array('context' => get_context_instance(CONTEXT_COURSE, $course->id))); + $info->course = format_string($course->fullname, true, array('context' => context_course::instance($course->id))); } else { $info->course = 'No course'; diff --git a/lib/weblib.php b/lib/weblib.php index d70f33cdad2..8384f373871 100644 --- a/lib/weblib.php +++ b/lib/weblib.php @@ -713,7 +713,7 @@ class moodle_url { public static function make_draftfile_url($draftid, $pathname, $filename, $forcedownload = false) { global $CFG, $USER; $urlbase = "$CFG->httpswwwroot/draftfile.php"; - $context = get_context_instance(CONTEXT_USER, $USER->id); + $context = context_user::instance($USER->id); return self::make_file_url($urlbase, "/$context->id/user/draft/$draftid".$pathname.$filename, $forcedownload); } @@ -1076,7 +1076,7 @@ function format_text($text, $format = FORMAT_MOODLE, $options = NULL, $courseid_ } } else if ($courseid_do_not_use) { // legacy courseid - $context = get_context_instance(CONTEXT_COURSE, $courseid_do_not_use); + $context = context_course::instance($courseid_do_not_use); } else { // fallback to $PAGE->context this may be problematic in CLI and other non-standard pages :-( $context = $PAGE->context; @@ -1272,7 +1272,7 @@ function format_string($string, $striplinks = true, $options = NULL) { if (is_numeric($options)) { // legacy courseid usage - $options = array('context'=>get_context_instance(CONTEXT_COURSE, $options)); + $options = array('context'=>context_course::instance($options)); } else { $options = (array)$options; // detach object, we can not modify it } @@ -1412,7 +1412,7 @@ function format_text_email($text, $format) { function format_module_intro($module, $activity, $cmid, $filter=true) { global $CFG; require_once("$CFG->libdir/filelib.php"); - $context = get_context_instance(CONTEXT_MODULE, $cmid); + $context = context_module::instance($cmid); $options = array('noclean'=>true, 'para'=>false, 'filter'=>$filter, 'context'=>$context, 'overflowdiv'=>true); $intro = file_rewrite_pluginfile_urls($activity->intro, 'pluginfile.php', $context->id, 'mod_'.$module, 'intro', null); return trim(format_text($intro, $activity->introformat, $options, null)); @@ -2076,7 +2076,7 @@ function print_group_picture($group, $courseid, $large=false, $return=false, $li } } - $context = get_context_instance(CONTEXT_COURSE, $courseid); + $context = context_course::instance($courseid); // If there is no picture, do nothing if (!$group->picture) { @@ -2132,7 +2132,7 @@ function print_recent_activity_note($time, $user, $text, $link, $return=false, $ $output = ''; if (is_null($viewfullnames)) { - $context = get_context_instance(CONTEXT_SYSTEM); + $context = context_system::instance(); $viewfullnames = has_capability('moodle/site:viewfullnames', $context); } @@ -2185,7 +2185,7 @@ function navmenulist($course, $sections, $modinfo, $strsection, $strjumpto, $wid $menu = array(); $doneheading = false; - $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id); + $coursecontext = context_course::instance($course->id); $menu[] = '
'; diff --git a/mod/feedback/analysis_to_excel.php b/mod/feedback/analysis_to_excel.php index d6320efc0f6..0096c48875d 100644 --- a/mod/feedback/analysis_to_excel.php +++ b/mod/feedback/analysis_to_excel.php @@ -51,9 +51,7 @@ if (! $feedback = $DB->get_record("feedback", array("id"=>$cm->instance))) { print_error('invalidcoursemodule'); } -if (!$context = get_context_instance(CONTEXT_MODULE, $cm->id)) { - print_error('badcontext'); -} +$context = context_module::instance($cm->id); require_login($course, true, $cm); @@ -306,7 +304,7 @@ function feedback_excelprint_detailed_items(&$worksheet, $xls_formats, $worksheet->write_number($row_offset, $col_offset, $courseid, $xls_formats->default); $col_offset++; if (isset($courseid) AND $course = $DB->get_record('course', array('id' => $courseid))) { - $coursecontext = get_context_instance(CONTEXT_COURSE, $courseid); + $coursecontext = context_course::instance($courseid); $shortname = format_string($course->shortname, true, array('context' => $coursecontext)); $worksheet->write_string($row_offset, $col_offset, $shortname, $xls_formats->default); } diff --git a/mod/feedback/complete.php b/mod/feedback/complete.php index e4c202c50d9..d4dc00b0014 100644 --- a/mod/feedback/complete.php +++ b/mod/feedback/complete.php @@ -87,9 +87,7 @@ if (! $feedback = $DB->get_record("feedback", array("id"=>$cm->instance))) { print_error('invalidcoursemodule'); } -if (!$context = get_context_instance(CONTEXT_MODULE, $cm->id)) { - print_error('badcontext'); -} +$context = context_module::instance($cm->id); $feedback_complete_cap = false; diff --git a/mod/feedback/complete_guest.php b/mod/feedback/complete_guest.php index b472c09e023..695cf413330 100644 --- a/mod/feedback/complete_guest.php +++ b/mod/feedback/complete_guest.php @@ -108,9 +108,7 @@ if (! $feedback = $DB->get_record("feedback", array("id"=>$cm->instance))) { print_error('invalidcoursemodule'); } -if (!$context = get_context_instance(CONTEXT_MODULE, $cm->id)) { - print_error('badcontext'); -} +$context = context_module::instance($cm->id); $feedback_complete_cap = false; diff --git a/mod/feedback/delete_completed.php b/mod/feedback/delete_completed.php index b2362b04287..d5eacb43a7f 100644 --- a/mod/feedback/delete_completed.php +++ b/mod/feedback/delete_completed.php @@ -50,9 +50,7 @@ if (! $feedback = $DB->get_record("feedback", array("id"=>$cm->instance))) { print_error('invalidcoursemodule'); } -if (!$context = get_context_instance(CONTEXT_MODULE, $cm->id)) { - print_error('badcontext'); -} +$context = context_module::instance($cm->id); require_login($course, true, $cm); diff --git a/mod/feedback/delete_item.php b/mod/feedback/delete_item.php index 31cc3c0faa9..d0840fb17b4 100644 --- a/mod/feedback/delete_item.php +++ b/mod/feedback/delete_item.php @@ -43,9 +43,7 @@ if (! $feedback = $DB->get_record("feedback", array("id"=>$cm->instance))) { print_error('invalidcoursemodule'); } -if (!$context = get_context_instance(CONTEXT_MODULE, $cm->id)) { - print_error('badcontext'); -} +$context = context_module::instance($cm->id); require_login($course, true, $cm); diff --git a/mod/feedback/delete_template.php b/mod/feedback/delete_template.php index d710b2b064a..289f2084324 100644 --- a/mod/feedback/delete_template.php +++ b/mod/feedback/delete_template.php @@ -67,9 +67,7 @@ if (! $feedback = $DB->get_record("feedback", array("id"=>$cm->instance))) { print_error('invalidcoursemodule'); } -if (!$context = get_context_instance(CONTEXT_MODULE, $cm->id)) { - print_error('badcontext'); -} +$context = context_module::instance($cm->id); require_login($course, true, $cm); diff --git a/mod/feedback/edit.php b/mod/feedback/edit.php index ce0e245a4af..b928c11e084 100644 --- a/mod/feedback/edit.php +++ b/mod/feedback/edit.php @@ -57,9 +57,7 @@ if (! $feedback = $DB->get_record("feedback", array("id"=>$cm->instance))) { print_error('invalidcoursemodule'); } -if (!$context = get_context_instance(CONTEXT_MODULE, $cm->id)) { - print_error('badcontext'); -} +$context = context_module::instance($cm->id); require_login($course, true, $cm); diff --git a/mod/feedback/edit_item.php b/mod/feedback/edit_item.php index 5879d61073b..8a7a3048e84 100644 --- a/mod/feedback/edit_item.php +++ b/mod/feedback/edit_item.php @@ -67,9 +67,7 @@ if (! $feedback = $DB->get_record("feedback", array("id"=>$cm->instance))) { print_error('invalidcoursemodule'); } -if (!$context = get_context_instance(CONTEXT_MODULE, $cm->id)) { - print_error('badcontext'); -} +$context = context_module::instance($cm->id); require_login($course, true, $cm); diff --git a/mod/feedback/export.php b/mod/feedback/export.php index 3b78120aa66..b4c3a9747c4 100644 --- a/mod/feedback/export.php +++ b/mod/feedback/export.php @@ -47,9 +47,7 @@ if (! $feedback = $DB->get_record("feedback", array("id"=>$cm->instance))) { print_error('invalidcoursemodule'); } -if (!$context = get_context_instance(CONTEXT_MODULE, $cm->id)) { - print_error('badcontext'); -} +$context = context_module::instance($cm->id); require_login($course, true, $cm); diff --git a/mod/feedback/import.php b/mod/feedback/import.php index 212e6cce1a2..7733292a4a5 100644 --- a/mod/feedback/import.php +++ b/mod/feedback/import.php @@ -52,9 +52,7 @@ if (! $feedback = $DB->get_record("feedback", array("id"=>$cm->instance))) { print_error('invalidcoursemodule'); } -if (!$context = get_context_instance(CONTEXT_MODULE, $cm->id)) { - print_error('badcontext'); -} +$context = context_module::instance($cm->id); require_login($course, true, $cm); diff --git a/mod/feedback/index.php b/mod/feedback/index.php index d48325784a4..327264f642c 100644 --- a/mod/feedback/index.php +++ b/mod/feedback/index.php @@ -35,9 +35,7 @@ if (!$course = $DB->get_record('course', array('id'=>$id))) { print_error('invalidcourseid'); } -if (!$context = get_context_instance(CONTEXT_COURSE, $course->id)) { - print_error('badcontext'); -} +$context = context_course::instance($course->id); require_login($course); $PAGE->set_pagelayout('incourse'); diff --git a/mod/feedback/item/info/lib.php b/mod/feedback/item/info/lib.php index fbdf2d994c2..46a9e4c3d16 100644 --- a/mod/feedback/item/info/lib.php +++ b/mod/feedback/item/info/lib.php @@ -216,7 +216,7 @@ class feedback_item_info extends feedback_item_base { $itemshowvalue = userdate($itemvalue); break; case 2: - $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id); + $coursecontext = context_course::instance($course->id); $itemvalue = format_string($course->shortname, true, array('context' => $coursecontext)); @@ -225,7 +225,7 @@ class feedback_item_info extends feedback_item_base { break; case 3: if ($coursecategory) { - $category_context = get_context_instance(CONTEXT_COURSECAT, $coursecategory->id); + $category_context = context_coursecat::instance($coursecategory->id); $itemvalue = format_string($coursecategory->name, true, array('context' => $category_context)); @@ -293,7 +293,7 @@ class feedback_item_info extends feedback_item_base { $itemshowvalue = userdate($itemvalue); break; case 2: - $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id); + $coursecontext = context_course::instance($course->id); $itemvalue = format_string($course->shortname, true, array('context' => $coursecontext)); @@ -302,7 +302,7 @@ class feedback_item_info extends feedback_item_base { break; case 3: if ($coursecategory) { - $category_context = get_context_instance(CONTEXT_COURSECAT, $coursecategory->id); + $category_context = context_coursecat::instance($coursecategory->id); $itemvalue = format_string($coursecategory->name, true, array('context' => $category_context)); diff --git a/mod/feedback/item/label/label_form.php b/mod/feedback/item/label/label_form.php index 7a44530c5ee..dd04e53ccc1 100644 --- a/mod/feedback/item/label/label_form.php +++ b/mod/feedback/item/label/label_form.php @@ -29,8 +29,6 @@ class feedback_label_form extends feedback_item_form { $positionlist = $this->_customdata['positionlist']; $position = $this->_customdata['position']; - $context = get_context_instance(CONTEXT_MODULE, $common['cmid']); - $mform =& $this->_form; $mform->addElement('hidden', 'required', 0); diff --git a/mod/feedback/item/label/lib.php b/mod/feedback/item/label/lib.php index 06db9908851..350bbcec112 100644 --- a/mod/feedback/item/label/lib.php +++ b/mod/feedback/item/label/lib.php @@ -59,7 +59,7 @@ class feedback_item_label extends feedback_item_base { 'items'=>$feedbackitems, 'feedback'=>$feedback->id); - $this->context = get_context_instance(CONTEXT_MODULE, $cm->id); + $this->context = context_module::instance($cm->id); //preparing the editor for new file-api $item->presentationformat = FORMAT_HTML; @@ -148,12 +148,12 @@ class feedback_item_label extends feedback_item_base { if ($template->ispublic) { $context = get_system_context(); } else { - $context = get_context_instance(CONTEXT_COURSE, $template->course); + $context = context_course::instance($template->course); } $filearea = 'template'; } else { $cm = get_coursemodule_from_instance('feedback', $item->feedback); - $context = get_context_instance(CONTEXT_MODULE, $cm->id); + $context = context_module::instance($cm->id); $filearea = 'item'; } @@ -232,7 +232,7 @@ class feedback_item_label extends feedback_item_base { public function postupdate($item) { global $DB; - $context = get_context_instance(CONTEXT_MODULE, $item->cmid); + $context = context_module::instance($item->cmid); $item = file_postupdate_standard_editor($item, 'presentation', $this->presentationoptions, diff --git a/mod/feedback/lib.php b/mod/feedback/lib.php index 8705bbc8d8c..d11ce100530 100644 --- a/mod/feedback/lib.php +++ b/mod/feedback/lib.php @@ -102,7 +102,7 @@ function feedback_add_instance($feedback) { $cm = get_coursemodule_from_id('feedback', $feedback->id); $feedback->coursemodule = $cm->id; } - $context = get_context_instance(CONTEXT_MODULE, $feedback->coursemodule); + $context = context_module::instance($feedback->coursemodule); $editoroptions = feedback_get_editor_options(); @@ -150,7 +150,7 @@ function feedback_update_instance($feedback) { //create or update the new events feedback_set_events($feedback); - $context = get_context_instance(CONTEXT_MODULE, $feedback->coursemodule); + $context = context_module::instance($feedback->coursemodule); $editoroptions = feedback_get_editor_options(); @@ -416,7 +416,7 @@ function feedback_get_recent_mod_activity(&$activities, &$index, return; } - $cm_context = get_context_instance(CONTEXT_MODULE, $cm->id); + $cm_context = context_module::instance($cm->id); $accessallgroups = has_capability('moodle/site:accessallgroups', $cm_context); $viewfullnames = has_capability('moodle/site:viewfullnames', $cm_context); $groupmode = groups_get_activity_groupmode($cm, $course); @@ -826,9 +826,7 @@ function feedback_get_context($cmid) { return $context; } - if (!$context = get_context_instance(CONTEXT_MODULE, $cmid)) { - print_error('badcontext'); - } + $context = context_module::instance($cmid); return $context; } @@ -869,7 +867,7 @@ function feedback_get_incomplete_users($cm, global $DB; - $context = get_context_instance(CONTEXT_MODULE, $cm->id); + $context = context_module::instance($cm->id); //first get all user who can complete this feedback $cap = 'mod/feedback:complete'; @@ -975,9 +973,7 @@ function feedback_get_complete_users($cm, global $DB; - if (!$context = get_context_instance(CONTEXT_MODULE, $cm->id)) { - print_error('badcontext'); - } + $context = context_module::instance($cm->id); $params = (array)$params; @@ -1023,9 +1019,7 @@ function feedback_get_complete_users($cm, */ function feedback_get_viewreports_users($cmid, $groups = false) { - if (!$context = get_context_instance(CONTEXT_MODULE, $cmid)) { - print_error('badcontext'); - } + $context = context_module::instance($cmid); //description of the call below: //get_users_by_capability($context, $capability, $fields='', $sort='', $limitfrom='', @@ -1051,9 +1045,7 @@ function feedback_get_viewreports_users($cmid, $groups = false) { */ function feedback_get_receivemail_users($cmid, $groups = false) { - if (!$context = get_context_instance(CONTEXT_MODULE, $cmid)) { - print_error('badcontext'); - } + $context = context_module::instance($cmid); //description of the call below: //get_users_by_capability($context, $capability, $fields='', $sort='', $limitfrom='', @@ -1126,10 +1118,10 @@ function feedback_save_as_template($feedback, $name, $ispublic = 0) { if ($ispublic) { $s_context = get_system_context(); } else { - $s_context = get_context_instance(CONTEXT_COURSE, $newtempl->course); + $s_context = context_course::instance($newtempl->course); } $cm = get_coursemodule_from_instance('feedback', $feedback->id); - $f_context = get_context_instance(CONTEXT_MODULE, $cm->id); + $f_context = context_module::instance($cm->id); //create items of this new template //depend items we are storing temporary in an mapping list array(new id => dependitem) @@ -1231,11 +1223,11 @@ function feedback_items_from_template($feedback, $templateid, $deleteold = false if ($template->ispublic) { $s_context = get_system_context(); } else { - $s_context = get_context_instance(CONTEXT_COURSE, $feedback->course); + $s_context = context_course::instance($feedback->course); } $course = $DB->get_record('course', array('id'=>$feedback->course)); $cm = get_coursemodule_from_instance('feedback', $feedback->id); - $f_context = get_context_instance(CONTEXT_MODULE, $cm->id); + $f_context = context_module::instance($cm->id); //if deleteold then delete all old items before //get all items @@ -1534,7 +1526,7 @@ function feedback_delete_item($itemid, $renumber = true, $template = false) { if ($template->ispublic) { $context = get_system_context(); } else { - $context = get_context_instance(CONTEXT_COURSE, $template->course); + $context = context_course::instance($template->course); } $templatefiles = $fs->get_area_files($context->id, 'mod_feedback', @@ -1550,7 +1542,7 @@ function feedback_delete_item($itemid, $renumber = true, $template = false) { if (!$cm = get_coursemodule_from_instance('feedback', $item->feedback)) { return false; } - $context = get_context_instance(CONTEXT_MODULE, $cm->id); + $context = context_module::instance($cm->id); $itemfiles = $fs->get_area_files($context->id, 'mod_feedback', @@ -2985,7 +2977,7 @@ function feedback_send_email_anonym($cm, $feedback, $course) { * @return string the text you want to post */ function feedback_send_email_text($info, $course) { - $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id); + $coursecontext = context_course::instance($course->id); $courseshortname = format_string($course->shortname, true, array('context' => $coursecontext)); $posttext = $courseshortname.' -> '.get_string('modulenameplural', 'feedback').' -> '. $info->feedback."\n"; @@ -3006,7 +2998,7 @@ function feedback_send_email_text($info, $course) { */ function feedback_send_email_html($info, $course, $cm) { global $CFG; - $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id); + $coursecontext = context_course::instance($course->id); $courseshortname = format_string($course->shortname, true, array('context' => $coursecontext)); $course_url = $CFG->wwwroot.'/course/view.php?id='.$course->id; $feedback_all_url = $CFG->wwwroot.'/mod/feedback/index.php?id='.$course->id; @@ -3046,7 +3038,7 @@ function feedback_extend_settings_navigation(settings_navigation $settings, global $PAGE, $DB; - if (!$context = get_context_instance(CONTEXT_MODULE, $PAGE->cm->id)) { + if (!$context = context_module::instance($PAGE->cm->id, IGNORE_MISSING)) { print_error('badcontext'); } diff --git a/mod/feedback/mapcourse.php b/mod/feedback/mapcourse.php index 8014ca7d7db..3331357b193 100644 --- a/mod/feedback/mapcourse.php +++ b/mod/feedback/mapcourse.php @@ -61,9 +61,7 @@ if (! $feedback = $DB->get_record("feedback", array("id"=>$cm->instance))) { print_error('invalidcoursemodule'); } -if (!$context = get_context_instance(CONTEXT_MODULE, $cm->id)) { - print_error('badcontext'); -} +$context = context_module::instance($cm->id); require_login($course, true, $cm); @@ -132,9 +130,9 @@ if ($coursemap = feedback_get_courses_from_sitecourse_map($feedback->id)) { $unmapurl = new moodle_url('/mod/feedback/unmapcourse.php'); foreach ($coursemap as $cmap) { - $cmapcontext = get_context_instance(CONTEXT_COURSE, $cmap->id); + $cmapcontext = context_course::instance($cmap->id); $cmapshortname = format_string($cmap->shortname, true, array('context' => $cmapcontext)); - $coursecontext = get_context_instance(CONTEXT_COURSE, $cmap->courseid); + $coursecontext = context_course::instance($cmap->courseid); $cmapfullname = format_string($cmap->fullname, true, array('context' => $coursecontext)); $unmapurl->params(array('id'=>$id, 'cmapid'=>$cmap->id)); $anker = ''; diff --git a/mod/feedback/print.php b/mod/feedback/print.php index 7f63d9ca735..ac2ed30b388 100644 --- a/mod/feedback/print.php +++ b/mod/feedback/print.php @@ -41,9 +41,7 @@ if (! $feedback = $DB->get_record("feedback", array("id"=>$cm->instance))) { print_error('invalidcoursemodule'); } -if (!$context = get_context_instance(CONTEXT_MODULE, $cm->id)) { - print_error('badcontext'); -} +$context = context_module::instance($cm->id); require_login($course, true, $cm); diff --git a/mod/feedback/show_entries.php b/mod/feedback/show_entries.php index 1ee4b80b8c5..dceb7fb52c6 100644 --- a/mod/feedback/show_entries.php +++ b/mod/feedback/show_entries.php @@ -61,9 +61,7 @@ $url = new moodle_url('/mod/feedback/show_entries.php', array('id'=>$cm->id, 'do $PAGE->set_url($url); -if (!$context = get_context_instance(CONTEXT_MODULE, $cm->id)) { - print_error('badcontext'); -} +$context = context_module::instance($cm->id); require_login($course, true, $cm); diff --git a/mod/feedback/show_entries_anonym.php b/mod/feedback/show_entries_anonym.php index 1a76475b59b..bf69bf39268 100644 --- a/mod/feedback/show_entries_anonym.php +++ b/mod/feedback/show_entries_anonym.php @@ -52,9 +52,7 @@ if (! $feedback = $DB->get_record("feedback", array("id"=>$cm->instance))) { print_error('invalidcoursemodule'); } -if (!$context = get_context_instance(CONTEXT_MODULE, $cm->id)) { - print_error('badcontext'); -} +$context = context_module::instance($cm->id); require_login($course, true, $cm); diff --git a/mod/feedback/show_nonrespondents.php b/mod/feedback/show_nonrespondents.php index de5d0c70281..d3a245cd1e1 100644 --- a/mod/feedback/show_nonrespondents.php +++ b/mod/feedback/show_nonrespondents.php @@ -65,14 +65,10 @@ $url = new moodle_url('/mod/feedback/show_nonrespondents.php', array('id'=>$cm-> $PAGE->set_url($url); -if (!$context = get_context_instance(CONTEXT_MODULE, $cm->id)) { - print_error('badcontext'); -} +$context = context_module::instance($cm->id); //we need the coursecontext to allow sending of mass mails -if (!$coursecontext = get_context_instance(CONTEXT_COURSE, $course->id)) { - print_error('badcontext'); -} +$coursecontext = context_course::instance($course->id); require_login($course, true, $cm); @@ -85,7 +81,7 @@ require_capability('mod/feedback:viewreports', $context); if ($action == 'sendmessage' AND has_capability('moodle/course:bulkmessaging', $coursecontext)) { $shortname = format_string($course->shortname, true, - array('context' => get_context_instance(CONTEXT_COURSE, $course->id))); + array('context' => $coursecontext)); $strfeedbacks = get_string("modulenameplural", "feedback"); $htmlmessage = ""; diff --git a/mod/feedback/tabs.php b/mod/feedback/tabs.php index 2a1203a272e..c6a68c69f45 100644 --- a/mod/feedback/tabs.php +++ b/mod/feedback/tabs.php @@ -35,10 +35,7 @@ if (isset($cmid) AND intval($cmid) AND $cmid > 0) { $usedid = $id; } -if (!$context = get_context_instance(CONTEXT_MODULE, $usedid)) { - print_error('badcontext'); -} - +$context = context_module::instance($usedid); $courseid = optional_param('courseid', false, PARAM_INT); // $current_tab = $SESSION->feedback->current_tab; diff --git a/mod/feedback/unmapcourse.php b/mod/feedback/unmapcourse.php index 34b78490e08..145258b3d6c 100644 --- a/mod/feedback/unmapcourse.php +++ b/mod/feedback/unmapcourse.php @@ -46,9 +46,7 @@ if (! $feedback = $DB->get_record("feedback", array("id"=>$cm->instance))) { print_error('invalidcoursemodule'); } -if (!$context = get_context_instance(CONTEXT_MODULE, $cm->id)) { - print_error('badcontext'); -} +$context = context_module::instance($cm->id); require_capability('mod/feedback:mapcourse', $context); diff --git a/mod/feedback/use_templ.php b/mod/feedback/use_templ.php index ed5bc812d49..12f62cea3ac 100644 --- a/mod/feedback/use_templ.php +++ b/mod/feedback/use_templ.php @@ -52,9 +52,7 @@ if (! $feedback = $DB->get_record("feedback", array("id"=>$cm->instance))) { print_error('invalidcoursemodule'); } -if (!$context = get_context_instance(CONTEXT_MODULE, $cm->id)) { - print_error('badcontext'); -} +$context = context_module::instance($cm->id); require_login($course, true, $cm); diff --git a/mod/feedback/view.php b/mod/feedback/view.php index aa01dd9b5d3..81a4ee02218 100644 --- a/mod/feedback/view.php +++ b/mod/feedback/view.php @@ -41,9 +41,7 @@ if (! $feedback = $DB->get_record("feedback", array("id"=>$cm->instance))) { print_error('invalidcoursemodule'); } -if (!$context = get_context_instance(CONTEXT_MODULE, $cm->id)) { - print_error('badcontext'); -} +$context = context_module::instance($cm->id); $feedback_complete_cap = false; diff --git a/mod/folder/edit.php b/mod/folder/edit.php index 0b74e47a144..f6aec48119b 100644 --- a/mod/folder/edit.php +++ b/mod/folder/edit.php @@ -32,7 +32,7 @@ require_once("$CFG->dirroot/repository/lib.php"); $id = required_param('id', PARAM_INT); // Course module ID $cm = get_coursemodule_from_id('folder', $id, 0, false, MUST_EXIST); -$context = get_context_instance(CONTEXT_MODULE, $cm->id, MUST_EXIST); +$context = context_module::instance($cm->id, MUST_EXIST); $folder = $DB->get_record('folder', array('id'=>$cm->instance), '*', MUST_EXIST); $course = $DB->get_record('course', array('id'=>$cm->course), '*', MUST_EXIST); diff --git a/mod/folder/lib.php b/mod/folder/lib.php index fde1587f516..f349146494d 100644 --- a/mod/folder/lib.php +++ b/mod/folder/lib.php @@ -98,7 +98,7 @@ function folder_add_instance($data, $mform) { // we need to use context now, so we need to make sure all needed info is already in db $DB->set_field('course_modules', 'instance', $data->id, array('id'=>$cmid)); - $context = get_context_instance(CONTEXT_MODULE, $cmid); + $context = context_module::instance($cmid); if ($draftitemid) { file_save_draft_area_files($draftitemid, $context->id, 'mod_folder', 'content', 0, array('subdirs'=>true)); @@ -125,7 +125,7 @@ function folder_update_instance($data, $mform) { $DB->update_record('folder', $data); - $context = get_context_instance(CONTEXT_MODULE, $cmid); + $context = context_module::instance($cmid); if ($draftitemid = file_get_submitted_draft_itemid('files')) { file_save_draft_area_files($draftitemid, $context->id, 'mod_folder', 'content', 0, array('subdirs'=>true)); } @@ -334,7 +334,7 @@ function folder_page_type_list($pagetype, $parentcontext, $currentcontext) { function folder_export_contents($cm, $baseurl) { global $CFG, $DB; $contents = array(); - $context = get_context_instance(CONTEXT_MODULE, $cm->id); + $context = context_module::instance($cm->id); $folder = $DB->get_record('folder', array('id'=>$cm->instance), '*', MUST_EXIST); $fs = get_file_storage(); diff --git a/mod/folder/renderer.php b/mod/folder/renderer.php index 539affef4d6..c99ca6cd436 100644 --- a/mod/folder/renderer.php +++ b/mod/folder/renderer.php @@ -98,7 +98,7 @@ class folder_tree implements renderable { $this->cm = $cm; $this->course = $course; - $this->context = get_context_instance(CONTEXT_MODULE, $cm->id); + $this->context = context_module::instance($cm->id); $fs = get_file_storage(); $this->dir = $fs->get_area_tree($this->context->id, 'mod_folder', 'content', 0); } diff --git a/mod/folder/view.php b/mod/folder/view.php index afe90f12456..4a8960acfeb 100644 --- a/mod/folder/view.php +++ b/mod/folder/view.php @@ -44,7 +44,7 @@ if ($f) { // Two ways to specify the module $course = $DB->get_record('course', array('id'=>$cm->course), '*', MUST_EXIST); require_course_login($course, true, $cm); -$context = get_context_instance(CONTEXT_MODULE, $cm->id); +$context = context_module::instance($cm->id); require_capability('mod/folder:view', $context); add_to_log($course->id, 'folder', 'view', 'view.php?id='.$cm->id, $folder->id, $cm->id); diff --git a/mod/forum/lib.php b/mod/forum/lib.php index 7c504e57c60..8ee61aed0ab 100644 --- a/mod/forum/lib.php +++ b/mod/forum/lib.php @@ -1310,23 +1310,33 @@ function forum_print_overview($courses,&$htmlarray) { return; } - - // get all forum logs in ONE query (much better!) + // Courses to search for new posts + $coursessqls = array(); $params = array(); - $sql = "SELECT instance,cmid,l.course,COUNT(l.id) as count FROM {log} l " - ." JOIN {course_modules} cm ON cm.id = cmid " - ." WHERE ("; foreach ($courses as $course) { - $sql .= '(l.course = ? AND l.time > ?) OR '; - $params[] = $course->id; - $params[] = $course->lastaccess; + + // If the user has never entered into the course all posts are pending + if ($course->lastaccess == 0) { + $coursessqls[] = '(f.course = ?)'; + $params[] = $course->id; + + // Only posts created after the course last access + } else { + $coursessqls[] = '(f.course = ? AND p.created > ?)'; + $params[] = $course->id; + $params[] = $course->lastaccess; + } } - $sql = substr($sql,0,-3); // take off the last OR - - $sql .= ") AND l.module = 'forum' AND action = 'add post' " - ." AND userid != ? GROUP BY cmid,l.course,instance"; - $params[] = $USER->id; + $coursessql = implode(' OR ', $coursessqls); + + $sql = "SELECT f.id, COUNT(*) as count " + .'FROM {forum} f ' + .'JOIN {forum_discussions} d ON d.forum = f.id ' + .'JOIN {forum_posts} p ON p.discussion = d.id ' + ."WHERE ($coursessql) " + .'AND p.userid != ? ' + .'GROUP BY f.id'; if (!$new = $DB->get_records_sql($sql, $params)) { $new = array(); // avoid warnings diff --git a/mod/glossary/approve.php b/mod/glossary/approve.php index 67fc2126936..4069376e742 100644 --- a/mod/glossary/approve.php +++ b/mod/glossary/approve.php @@ -18,7 +18,7 @@ $course = $DB->get_record('course', array('id'=> $cm->course), '*', MUST_EXIST); require_login($course, false, $cm); -$context = get_context_instance(CONTEXT_MODULE, $cm->id); +$context = context_module::instance($cm->id); require_capability('mod/glossary:approve', $context); if (!$entry->approved and confirm_sesskey()) { diff --git a/mod/glossary/deleteentry.php b/mod/glossary/deleteentry.php index a1a928bdcba..2449448a922 100644 --- a/mod/glossary/deleteentry.php +++ b/mod/glossary/deleteentry.php @@ -40,7 +40,7 @@ if (! $entry = $DB->get_record("glossary_entries", array("id"=>$entry))) { } require_login($course, false, $cm); -$context = get_context_instance(CONTEXT_MODULE, $cm->id); +$context = context_module::instance($cm->id); $manageentries = has_capability('mod/glossary:manageentries', $context); if (! $glossary = $DB->get_record("glossary", array("id"=>$cm->instance))) { @@ -67,7 +67,7 @@ if ($confirm and confirm_sesskey()) { // the operation was confirmed. if (!$newcm = get_coursemodule_from_instance('glossary', $entry->sourceglossaryid)) { print_error('invalidcoursemodule'); } - $newcontext = get_context_instance(CONTEXT_MODULE, $newcm->id); + $newcontext = context_module::instance($newcm->id); $entry->glossaryid = $entry->sourceglossaryid; $entry->sourceglossaryid = 0; diff --git a/mod/glossary/edit.php b/mod/glossary/edit.php index d69ae54e37c..00e9343c80f 100644 --- a/mod/glossary/edit.php +++ b/mod/glossary/edit.php @@ -17,7 +17,7 @@ if (!$course = $DB->get_record('course', array('id'=>$cm->course))) { require_login($course, false, $cm); -$context = get_context_instance(CONTEXT_MODULE, $cm->id); +$context = context_module::instance($cm->id); if (!$glossary = $DB->get_record('glossary', array('id'=>$cm->instance))) { print_error('invalidid', 'glossary'); diff --git a/mod/glossary/edit_form.php b/mod/glossary/edit_form.php index 5bdcefeeb88..03d964e9096 100644 --- a/mod/glossary/edit_form.php +++ b/mod/glossary/edit_form.php @@ -18,7 +18,7 @@ class mod_glossary_entry_form extends moodleform { $definitionoptions = $this->_customdata['definitionoptions']; $attachmentoptions = $this->_customdata['attachmentoptions']; - $context = get_context_instance(CONTEXT_MODULE, $cm->id); + $context = context_module::instance($cm->id); // Prepare format_string/text options $fmtoptions = array( 'context' => $context); @@ -96,7 +96,7 @@ class mod_glossary_entry_form extends moodleform { $glossary = $this->_customdata['glossary']; $cm = $this->_customdata['cm']; - $context = get_context_instance(CONTEXT_MODULE, $cm->id); + $context = context_module::instance($cm->id); $id = (int)$data['id']; $data['concept'] = trim($data['concept']); diff --git a/mod/glossary/editcategories.php b/mod/glossary/editcategories.php index 963865a9deb..1c67b47f75a 100644 --- a/mod/glossary/editcategories.php +++ b/mod/glossary/editcategories.php @@ -63,7 +63,7 @@ if ($hook > 0) { require_login($course, false, $cm); -$context = get_context_instance(CONTEXT_MODULE, $cm->id); +$context = context_module::instance($cm->id); require_capability('mod/glossary:managecategories', $context); $strglossaries = get_string("modulenameplural", "glossary"); diff --git a/mod/glossary/export.php b/mod/glossary/export.php index 204a91510d4..773fd7f7307 100644 --- a/mod/glossary/export.php +++ b/mod/glossary/export.php @@ -33,7 +33,7 @@ if (! $glossary = $DB->get_record("glossary", array("id"=>$cm->instance))) { require_login($course, false, $cm); -$context = get_context_instance(CONTEXT_MODULE, $cm->id); +$context = context_module::instance($cm->id); require_capability('mod/glossary:export', $context); $strglossaries = get_string("modulenameplural", "glossary"); diff --git a/mod/glossary/exportentry.php b/mod/glossary/exportentry.php index f4bf6e7fb66..6b38886c444 100644 --- a/mod/glossary/exportentry.php +++ b/mod/glossary/exportentry.php @@ -42,7 +42,7 @@ if (!$course = $DB->get_record('course', array('id'=>$cm->course))) { } require_course_login($course->id, true, $cm); -$context = get_context_instance(CONTEXT_MODULE, $cm->id); +$context = context_module::instance($cm->id); require_capability('mod/glossary:export', $context); $returnurl = "view.php?id=$cm->id&mode=$prevmode&hook=".urlencode($hook); @@ -56,8 +56,8 @@ if (!$maincm = get_coursemodule_from_instance('glossary', $mainglossary->id)) { print_error('invalidcoursemodule'); } -$context = get_context_instance(CONTEXT_MODULE, $cm->id); -$maincontext = get_context_instance(CONTEXT_MODULE, $maincm->id); +$context = context_module::instance($cm->id); +$maincontext = context_module::instance($maincm->id); if (!$course = $DB->get_record('course', array('id'=>$cm->course))) { print_error('coursemisconf'); diff --git a/mod/glossary/import.php b/mod/glossary/import.php index 66466dd192b..a509e0eacf9 100644 --- a/mod/glossary/import.php +++ b/mod/glossary/import.php @@ -33,7 +33,7 @@ if (! $glossary = $DB->get_record("glossary", array("id"=>$cm->instance))) { require_login($course, false, $cm); -$context = get_context_instance(CONTEXT_MODULE, $cm->id); +$context = context_module::instance($cm->id); require_capability('mod/glossary:import', $context); $strglossaries = get_string("modulenameplural", "glossary"); diff --git a/mod/glossary/index.php b/mod/glossary/index.php index 4eef6dfaac6..7979c29c3c3 100644 --- a/mod/glossary/index.php +++ b/mod/glossary/index.php @@ -18,7 +18,7 @@ if (!$course = $DB->get_record('course', array('id'=>$id))) { require_course_login($course); $PAGE->set_pagelayout('incourse'); -$context = get_context_instance(CONTEXT_COURSE, $course->id); +$context = context_course::instance($course->id); add_to_log($course->id, "glossary", "view all", "index.php?id=$course->id", ""); diff --git a/mod/glossary/lib.php b/mod/glossary/lib.php index 85c96735a83..41e588ccfb5 100644 --- a/mod/glossary/lib.php +++ b/mod/glossary/lib.php @@ -60,7 +60,7 @@ function glossary_add_instance($glossary) { $glossary->globalglossary = 0; } - if (!has_capability('mod/glossary:manageentries', get_context_instance(CONTEXT_SYSTEM))) { + if (!has_capability('mod/glossary:manageentries', context_system::instance())) { $glossary->globalglossary = 0; } @@ -97,7 +97,7 @@ function glossary_update_instance($glossary) { $glossary->globalglossary = 0; } - if (!has_capability('mod/glossary:manageentries', get_context_instance(CONTEXT_SYSTEM))) { + if (!has_capability('mod/glossary:manageentries', context_system::instance())) { // keep previous unset($glossary->globalglossary); } @@ -145,7 +145,7 @@ function glossary_delete_instance($id) { return false; } - if (!$context = get_context_instance(CONTEXT_MODULE, $cm->id)) { + if (!$context = context_module::instance($cm->id, IGNORE_MISSING)) { return false; } @@ -163,7 +163,7 @@ function glossary_delete_instance($id) { foreach ($exported as $entry) { $entry->glossaryid = $entry->sourceglossaryid; $entry->sourceglossaryid = 0; - $newcontext = get_context_instance(CONTEXT_MODULE, $entry->sourcecmid); + $newcontext = context_module::instance($entry->sourcecmid); if ($oldfiles = $fs->get_area_files($context->id, 'mod_glossary', 'attachment', $entry->id)) { foreach ($oldfiles as $oldfile) { $file_record = new stdClass(); @@ -504,7 +504,7 @@ function glossary_print_recent_activity($course, $viewfullnames, $timestart) { // generate list of approval capabilities for all glossaries in the course. $approvals = array(); foreach ($ids as $glinstanceid => $glcmid) { - $context = get_context_instance(CONTEXT_MODULE, $glcmid); + $context = context_module::instance($glcmid); if (has_capability('mod/glossary:view', $context)) { // get records glossary entries that are approved if user has no capability to approve entries. if (has_capability('mod/glossary:approve', $context)) { @@ -730,7 +730,7 @@ function glossary_rating_validate($params) { } $cm = get_coursemodule_from_instance('glossary', $info->glossaryid, $info->course, false, MUST_EXIST); - $context = get_context_instance(CONTEXT_MODULE, $cm->id, MUST_EXIST); + $context = context_module::instance($cm->id, MUST_EXIST); // if the supplied context doesnt match the item's context if ($context->id != $params['context']->id) { @@ -1001,13 +1001,13 @@ function glossary_get_entries_search($concept, $courseid) { //Check if the user is an admin $bypassadmin = 1; //This means NO (by default) - if (has_capability('moodle/course:viewhiddenactivities', get_context_instance(CONTEXT_SYSTEM))) { + if (has_capability('moodle/course:viewhiddenactivities', context_system::instance())) { $bypassadmin = 0; //This means YES } //Check if the user is a teacher $bypassteacher = 1; //This means NO (by default) - if (has_capability('mod/glossary:manageentries', get_context_instance(CONTEXT_COURSE, $courseid))) { + if (has_capability('mod/glossary:manageentries', context_course::instance($courseid))) { $bypassteacher = 0; //This means YES } @@ -1091,7 +1091,7 @@ function glossary_print_entry_default ($entry, $glossary, $cm) { $definition = '' . strip_tags($definition) . ''; - $context = get_context_instance(CONTEXT_MODULE, $cm->id); + $context = context_module::instance($cm->id); $definition = file_rewrite_pluginfile_urls($definition, 'pluginfile.php', $context->id, 'mod_glossary', 'entry', $entry->id); $options = new stdClass(); @@ -1145,7 +1145,7 @@ function glossary_print_entry_definition($entry, $glossary, $cm) { } } - $context = get_context_instance(CONTEXT_MODULE, $cm->id); + $context = context_module::instance($cm->id); $definition = file_rewrite_pluginfile_urls($definition, 'pluginfile.php', $context->id, 'mod_glossary', 'entry', $entry->id); $options = new stdClass(); @@ -1221,7 +1221,7 @@ function glossary_print_entry_aliases($course, $cm, $glossary, $entry,$mode='', function glossary_print_entry_icons($course, $cm, $glossary, $entry, $mode='',$hook='', $type = 'print') { global $USER, $CFG, $DB, $OUTPUT; - $context = get_context_instance(CONTEXT_MODULE, $cm->id); + $context = context_module::instance($cm->id); $output = false; //To decide if we must really return text in "return". Activate when needed only! $importedentry = ($entry->sourceglossaryid == $glossary->id); @@ -1278,7 +1278,7 @@ function glossary_print_entry_icons($course, $cm, $glossary, $entry, $mode='',$h $filecontext = $context; if ($entry->sourceglossaryid == $cm->instance) { if ($maincm = get_coursemodule_from_instance('glossary', $entry->glossaryid)) { - $filecontext = get_context_instance(CONTEXT_MODULE, $maincm->id); + $filecontext = context_module::instance($maincm->id); } } $fs = get_file_storage(); @@ -1426,7 +1426,7 @@ function glossary_search($course, $searchterms, $extended = 0, $glossary = NULL) $glos = $glossary->id; } - if (!has_capability('mod/glossary:manageentries', get_context_instance(CONTEXT_COURSE, $glossary->course))) { + if (!has_capability('mod/glossary:manageentries', context_course::instance($glossary->course))) { $glossarymodule = $DB->get_record("modules", array("name"=>"glossary")); $onlyvisible = " AND g.id = cm.instance AND cm.visible = 1 AND cm.module = $glossarymodule->id"; $onlyvisibletable = ", {course_modules} cm"; @@ -1530,7 +1530,7 @@ function glossary_search_entries($searchterms, $glossary, $extended) { function glossary_print_attachments($entry, $cm, $type=NULL, $align="left") { global $CFG, $DB, $OUTPUT; - if (!$context = get_context_instance(CONTEXT_MODULE, $cm->id)) { + if (!$context = context_module::instance($cm->id, IGNORE_MISSING)) { return ''; } @@ -1538,7 +1538,7 @@ function glossary_print_attachments($entry, $cm, $type=NULL, $align="left") { if (!$maincm = get_coursemodule_from_instance('glossary', $entry->glossaryid)) { return ''; } - $filecontext = get_context_instance(CONTEXT_MODULE, $maincm->id); + $filecontext = context_module::instance($maincm->id); } else { $filecontext = $context; @@ -1657,7 +1657,7 @@ function glossary_get_file_info($browser, $areas, $course, $cm, $context, $filea if (!$maincm = get_coursemodule_from_instance('glossary', $entry->glossaryid)) { return null; } - $filecontext = get_context_instance(CONTEXT_MODULE, $maincm->id); + $filecontext = context_module::instance($maincm->id); } else { return null; } @@ -1729,7 +1729,7 @@ function glossary_pluginfile($course, $cm, $context, $filearea, $args, $forcedow if (!$maincm = get_coursemodule_from_instance('glossary', $entry->glossaryid)) { return false; } - $filecontext = get_context_instance(CONTEXT_MODULE, $maincm->id); + $filecontext = context_module::instance($maincm->id); } else { return false; @@ -1865,7 +1865,7 @@ function glossary_print_author_menu($cm, $glossary,$mode, $hook, $sortkey = '', function glossary_print_categories_menu($cm, $glossary, $hook, $category) { global $CFG, $DB, $OUTPUT; - $context = get_context_instance(CONTEXT_MODULE, $cm->id); + $context = context_module::instance($cm->id); // Prepare format_string/text options $fmtoptions = array( @@ -2735,7 +2735,7 @@ function glossary_reset_userdata($data) { if (!$cm = get_coursemodule_from_instance('glossary', $glossaryid)) { continue; } - $context = get_context_instance(CONTEXT_MODULE, $cm->id); + $context = context_module::instance($cm->id); $fs->delete_area_files($context->id, 'mod_glossary', 'attachment'); //delete ratings @@ -2768,7 +2768,7 @@ function glossary_reset_userdata($data) { if (!$cm = get_coursemodule_from_instance('glossary', $glossaryid)) { continue; } - $context = get_context_instance(CONTEXT_MODULE, $cm->id); + $context = context_module::instance($cm->id); $fs->delete_area_files($context->id, 'mod_glossary', 'attachment'); //delete ratings @@ -2798,7 +2798,7 @@ function glossary_reset_userdata($data) { if (!$cm = get_coursemodule_from_instance('glossary', $glossaryid)) { continue; } - $context = get_context_instance(CONTEXT_MODULE, $cm->id); + $context = context_module::instance($cm->id); $fs->delete_area_files($context->id, 'mod_glossary', 'attachment'); //delete ratings @@ -2824,7 +2824,7 @@ function glossary_reset_userdata($data) { LEFT JOIN {user} u ON e.userid = u.id WHERE g.course = ? AND e.userid > 0"; - $course_context = get_context_instance(CONTEXT_COURSE, $data->courseid); + $course_context = context_course::instance($data->courseid); $notenrolled = array(); $rs = $DB->get_recordset_sql($entriessql, $params); if ($rs->valid()) { @@ -2835,7 +2835,7 @@ function glossary_reset_userdata($data) { $DB->delete_records('glossary_entries', array('id'=>$entry->id)); if ($cm = get_coursemodule_from_instance('glossary', $entry->glossaryid)) { - $context = get_context_instance(CONTEXT_MODULE, $cm->id); + $context = context_module::instance($cm->id); $fs->delete_area_files($context->id, 'mod_glossary', 'attachment', $entry->id); //delete ratings @@ -2857,7 +2857,7 @@ function glossary_reset_userdata($data) { if (!$cm = get_coursemodule_from_instance('glossary', $glossaryid)) { continue; } - $context = get_context_instance(CONTEXT_MODULE, $cm->id); + $context = context_module::instance($cm->id); //delete ratings $ratingdeloptions->contextid = $context->id; @@ -3064,7 +3064,7 @@ function glossary_comment_validate($comment_param) { if (!$cm = get_coursemodule_from_instance('glossary', $glossary->id, $course->id)) { throw new comment_exception('invalidcoursemodule'); } - $context = get_context_instance(CONTEXT_MODULE, $cm->id); + $context = context_module::instance($cm->id); if ($glossary->defaultapproval and !$record->approved and !has_capability('mod/glossary:approve', $context)) { throw new comment_exception('notapproved', 'glossary'); diff --git a/mod/glossary/locallib.php b/mod/glossary/locallib.php index 2f0b448936a..b82a9001b04 100644 --- a/mod/glossary/locallib.php +++ b/mod/glossary/locallib.php @@ -72,7 +72,7 @@ class glossary_full_portfolio_caller extends portfolio_module_caller_base { $this->exportdata = array('entries' => $entries, 'aliases' => $aliases, 'categoryentries' => $categoryentries); $fs = get_file_storage(); - $context = get_context_instance(CONTEXT_MODULE, $this->cm->id); + $context = context_module::instance($this->cm->id); $this->multifiles = array(); foreach (array_keys($entries) as $entry) { $this->keyedfiles[$entry] = array_merge( @@ -186,7 +186,7 @@ class glossary_full_portfolio_caller extends portfolio_module_caller_base { * @return boolean */ public function check_permissions() { - return has_capability('mod/glossary:export', get_context_instance(CONTEXT_MODULE, $this->cm->id)); + return has_capability('mod/glossary:export', context_module::instance($this->cm->id)); } /** @@ -254,10 +254,10 @@ class glossary_entry_portfolio_caller extends portfolio_module_caller_base { JOIN {glossary_categories} c ON c.id = ec.categoryid WHERE ec.entryid = ?', array($this->entryid)); - $context = get_context_instance(CONTEXT_MODULE, $this->cm->id); + $context = context_module::instance($this->cm->id); if ($this->entry->sourceglossaryid == $this->cm->instance) { if ($maincm = get_coursemodule_from_instance('glossary', $this->entry->glossaryid)) { - $context = get_context_instance(CONTEXT_MODULE, $maincm->id); + $context = context_module::instance($maincm->id); } } $this->aliases = $DB->get_record('glossary_alias', array('entryid'=>$this->entryid)); @@ -283,7 +283,7 @@ class glossary_entry_portfolio_caller extends portfolio_module_caller_base { * @return boolean */ public function check_permissions() { - $context = get_context_instance(CONTEXT_MODULE, $this->cm->id); + $context = context_module::instance($this->cm->id); return has_capability('mod/glossary:exportentry', $context) || ($this->entry->userid == $this->user->id && has_capability('mod/glossary:exportownentry', $context)); } @@ -389,7 +389,7 @@ class glossary_entry_portfolio_caller extends portfolio_module_caller_base { public static function entry_content($course, $cm, $glossary, $entry, $aliases, $format) { global $OUTPUT, $DB; $entry = clone $entry; - $context = get_context_instance(CONTEXT_MODULE, $cm->id); + $context = context_module::instance($cm->id); $options = portfolio_format_text_options(); $options->trusted = $entry->definitiontrust; $options->context = $context; @@ -427,7 +427,7 @@ class glossary_entry_portfolio_caller extends portfolio_module_caller_base { if (!$maincm = get_coursemodule_from_instance('glossary', $entry->glossaryid)) { return ''; } - $filecontext = get_context_instance(CONTEXT_MODULE, $maincm->id); + $filecontext = context_module::instance($maincm->id); } else { $filecontext = $context; diff --git a/mod/glossary/mod_form.php b/mod/glossary/mod_form.php index 4db6c90e3e9..67456061340 100644 --- a/mod/glossary/mod_form.php +++ b/mod/glossary/mod_form.php @@ -30,7 +30,7 @@ class mod_glossary_mod_form extends moodleform_mod { $mform->addRule('entbypage', null, 'required', null, 'client'); $mform->addRule('entbypage', null, 'numeric', null, 'client'); - if (has_capability('mod/glossary:manageentries', get_context_instance(CONTEXT_SYSTEM))) { + if (has_capability('mod/glossary:manageentries', context_system::instance())) { $mform->addElement('checkbox', 'globalglossary', get_string('isglobal', 'glossary')); $mform->addHelpButton('globalglossary', 'isglobal', 'glossary'); diff --git a/mod/glossary/print.php b/mod/glossary/print.php index 783c220dea8..27a6f305f00 100644 --- a/mod/glossary/print.php +++ b/mod/glossary/print.php @@ -52,7 +52,7 @@ if ( !$entriesbypage = $glossary->entbypage ) { } require_course_login($course, true, $cm); -$context = get_context_instance(CONTEXT_MODULE, $cm->id); +$context = context_module::instance($cm->id); // Prepare format_string/text options $fmtoptions = array( diff --git a/mod/glossary/rsslib.php b/mod/glossary/rsslib.php index 3966b28eee5..6a51b2f3604 100644 --- a/mod/glossary/rsslib.php +++ b/mod/glossary/rsslib.php @@ -44,7 +44,7 @@ $glossaryid = clean_param($args[3], PARAM_INT); $cm = get_coursemodule_from_instance('glossary', $glossaryid, 0, false, MUST_EXIST); - $modcontext = get_context_instance(CONTEXT_MODULE, $cm->id); + $modcontext = context_module::instance($cm->id); if ($COURSE->id == $cm->course) { $course = $COURSE; diff --git a/mod/glossary/showentry.php b/mod/glossary/showentry.php index 5170456d998..3c927a2b453 100644 --- a/mod/glossary/showentry.php +++ b/mod/glossary/showentry.php @@ -54,7 +54,7 @@ if ($entries) { } // make sure the entry is approved (or approvable by current user) if (!$entry->approved and ($USER->id != $entry->userid)) { - $context = get_context_instance(CONTEXT_MODULE, $entry->cmid); + $context = context_module::instance($entry->cmid); if (!has_capability('mod/glossary:approve', $context)) { unset($entries[$key]); continue; diff --git a/mod/glossary/showentry_ajax.php b/mod/glossary/showentry_ajax.php index 5df4c0fe59f..4e986d43fbd 100644 --- a/mod/glossary/showentry_ajax.php +++ b/mod/glossary/showentry_ajax.php @@ -54,14 +54,14 @@ if ($entries) { } // make sure the entry is approved (or approvable by current user) if (!$entry->approved and ($USER->id != $entry->userid)) { - $context = get_context_instance(CONTEXT_MODULE, $entry->cmid); + $context = context_module::instance($entry->cmid); if (!has_capability('mod/glossary:approve', $context)) { unset($entries[$key]); continue; } } - $context = get_context_instance(CONTEXT_MODULE, $entry->cmid); + $context = context_module::instance($entry->cmid); $definition = file_rewrite_pluginfile_urls($entry->definition, 'pluginfile.php', $context->id, 'mod_glossary', 'entry', $entry->id); $options = new stdClass(); diff --git a/mod/glossary/view.php b/mod/glossary/view.php index c580d6d22d2..6db375c1c23 100644 --- a/mod/glossary/view.php +++ b/mod/glossary/view.php @@ -251,7 +251,7 @@ $PAGE->set_url($url); if (!empty($CFG->enablerssfeeds) && !empty($CFG->glossary_enablerssfeeds) && $glossary->rsstype && $glossary->rssarticles) { - $rsstitle = format_string($course->shortname, true, array('context' => get_context_instance(CONTEXT_COURSE, $course->id))) . ': %fullname%'; + $rsstitle = format_string($course->shortname, true, array('context' => context_course::instance($course->id))) . ': %fullname%'; rss_add_http_header($context, 'mod_glossary', $glossary, $rsstitle); } @@ -448,7 +448,7 @@ if ($allentries) { $user = $DB->get_record("user", array("id"=>$entry->userid)); echo $OUTPUT->user_picture($user, array('courseid'=>$course->id)); - $pivottoshow = fullname($user, has_capability('moodle/site:viewfullnames', get_context_instance(CONTEXT_COURSE, $course->id))); + $pivottoshow = fullname($user, has_capability('moodle/site:viewfullnames', context_course::instance($course->id))); } else { echo '
: - + changepasswordurl)) {
: - + changepasswordurl)) {
: : changepasswordurl)) {
: - + changepasswordurl)) {
: - +
: - +
: - + convert_data and $config->convert_data != '' and !is_readable($config->convert_data)) { @@ -82,9 +82,9 @@ urn:mace:organization2:providerID, Example Organization 2, /Shibboleth.sso/WAYF/
: - - : - - : - - : - +
-

+

- id)); + require_capability('moodle/backup:backupcourse', context_course::instance($course->id)); $heading = get_string('backupcourse', 'backup', $course->shortname); break; case backup::TYPE_1SECTION : - $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id); + $coursecontext = context_course::instance($course->id); require_capability('moodle/backup:backupsection', $coursecontext); if ((string)$section->name !== '') { $sectionname = format_string($section->name, true, array('context' => $coursecontext)); @@ -72,7 +72,7 @@ switch ($type) { } break; case backup::TYPE_1ACTIVITY : - require_capability('moodle/backup:backupactivity', get_context_instance(CONTEXT_MODULE, $cm->id)); + require_capability('moodle/backup:backupactivity', context_module::instance($cm->id)); $heading = get_string('backupactivity', 'backup', $cm->name); break; default : diff --git a/backup/backupfilesedit.php b/backup/backupfilesedit.php index 0059bbc0f3b..6b81b7d1061 100644 --- a/backup/backupfilesedit.php +++ b/backup/backupfilesedit.php @@ -36,7 +36,7 @@ $filearea = optional_param('filearea', null, PARAM_AREA); $returnurl = optional_param('returnurl', null, PARAM_URL); list($context, $course, $cm) = get_context_info_array($currentcontext); -$filecontext = get_context_instance_by_id($contextid); +$filecontext = context::instance_by_id($contextid, IGNORE_MISSING); $url = new moodle_url('/backup/backupfilesedit.php', array('currentcontext'=>$currentcontext, 'contextid'=>$contextid, 'component'=>$component, 'filearea'=>$filearea)); diff --git a/backup/converter/imscc11/backuplib.php b/backup/converter/imscc11/backuplib.php index 81b9657fee5..ef876003735 100644 --- a/backup/converter/imscc11/backuplib.php +++ b/backup/converter/imscc11/backuplib.php @@ -76,7 +76,7 @@ class imscc11_store_backup_file extends backup_execution_step { $id = $dinfo[0]->id; // Id of activity/section/course (depends of type) $courseid = $dinfo[0]->courseid; // Id of the course - $ctxid = get_context_instance(CONTEXT_USER, $userid)->id; + $ctxid = context_user::instance($userid)->id; $component = 'user'; $filearea = 'backup'; $itemid = 0; diff --git a/backup/import.php b/backup/import.php index d205a64f59c..79096c07ad5 100644 --- a/backup/import.php +++ b/backup/import.php @@ -16,7 +16,7 @@ $restoretarget = optional_param('target', backup::TARGET_CURRENT_ADDING, PARAM_I // Load the course and context $course = $DB->get_record('course', array('id'=>$courseid), '*', MUST_EXIST); -$context = get_context_instance(CONTEXT_COURSE, $courseid); +$context = context_course::instance($courseid); // Must pass login require_login($course); @@ -50,7 +50,7 @@ if ($importcourseid === false) { // Load the course +context to import from $importcourse = $DB->get_record('course', array('id'=>$importcourseid), '*', MUST_EXIST); -$importcontext = get_context_instance(CONTEXT_COURSE, $importcourseid); +$importcontext = context_course::instance($importcourseid); // Make sure the user can backup from that course require_capability('moodle/backup:backuptargetimport', $importcontext); diff --git a/backup/log.php b/backup/log.php index 470bbb5376c..7cb17f8f090 100644 --- a/backup/log.php +++ b/backup/log.php @@ -6,6 +6,6 @@ require_login(); - require_capability('moodle/backup:backupcourse', get_context_instance(CONTEXT_SYSTEM)); + require_capability('moodle/backup:backupcourse', context_system::instance()); redirect("$CFG->wwwroot/report/backups/index.php", '', 'admin', 1); diff --git a/backup/moodle2/backup_activity_task.class.php b/backup/moodle2/backup_activity_task.class.php index fef94cc02a9..a5974259534 100644 --- a/backup/moodle2/backup_activity_task.class.php +++ b/backup/moodle2/backup_activity_task.class.php @@ -64,7 +64,7 @@ abstract class backup_activity_task extends backup_task { $this->sectionid = $coursemodule->section; $this->modulename = $coursemodule->modname; $this->activityid = $coursemodule->instance; - $this->contextid = get_context_instance(CONTEXT_MODULE, $this->moduleid)->id; + $this->contextid = context_module::instance($this->moduleid)->id; parent::__construct($name, $plan); } diff --git a/backup/moodle2/backup_block_task.class.php b/backup/moodle2/backup_block_task.class.php index 91e02537816..3a1fcdd9448 100644 --- a/backup/moodle2/backup_block_task.class.php +++ b/backup/moodle2/backup_block_task.class.php @@ -53,7 +53,7 @@ abstract class backup_block_task extends backup_task { $this->blockid = $blockid; $this->blockname = $block->blockname; - $this->contextid = get_context_instance(CONTEXT_BLOCK, $this->blockid)->id; + $this->contextid = context_block::instance($this->blockid)->id; $this->moduleid = $moduleid; $this->modulename = null; $this->parentcontextid = null; @@ -71,7 +71,7 @@ abstract class backup_block_task extends backup_task { $this->moduleid = $moduleid; $this->modulename = $coursemodule->modname; - $this->parentcontextid = get_context_instance(CONTEXT_MODULE, $this->moduleid)->id; + $this->parentcontextid = context_module::instance($this->moduleid)->id; } parent::__construct($name, $plan); diff --git a/backup/moodle2/backup_course_task.class.php b/backup/moodle2/backup_course_task.class.php index 6cc262baf87..5d4cd9b4f45 100644 --- a/backup/moodle2/backup_course_task.class.php +++ b/backup/moodle2/backup_course_task.class.php @@ -42,7 +42,7 @@ class backup_course_task extends backup_task { public function __construct($name, $courseid, $plan = null) { $this->courseid = $courseid; - $this->contextid = get_context_instance(CONTEXT_COURSE, $this->courseid)->id; + $this->contextid = context_course::instance($this->courseid)->id; parent::__construct($name, $plan); } diff --git a/backup/moodle2/backup_final_task.class.php b/backup/moodle2/backup_final_task.class.php index 45d491af3c0..38bccb6823b 100644 --- a/backup/moodle2/backup_final_task.class.php +++ b/backup/moodle2/backup_final_task.class.php @@ -43,7 +43,7 @@ class backup_final_task extends backup_task { global $CFG; // Set the backup::VAR_CONTEXTID setting to course context as far as next steps require that - $coursectxid = get_context_instance(CONTEXT_COURSE, $this->get_courseid())->id; + $coursectxid = context_course::instance($this->get_courseid())->id; $this->add_setting(new backup_activity_generic_setting(backup::VAR_CONTEXTID, base_setting::IS_INTEGER, $coursectxid)); // Set the backup::VAR_COURSEID setting to course, we'll need that in some steps diff --git a/backup/moodle2/backup_section_task.class.php b/backup/moodle2/backup_section_task.class.php index ab4b4c8a10d..b84d3388cd3 100644 --- a/backup/moodle2/backup_section_task.class.php +++ b/backup/moodle2/backup_section_task.class.php @@ -71,7 +71,7 @@ class backup_section_task extends backup_task { public function build() { // Set the backup::VAR_CONTEXTID setting to course context as far as next steps require that - $coursectxid = get_context_instance(CONTEXT_COURSE, $this->get_courseid())->id; + $coursectxid = context_course::instance($this->get_courseid())->id; $this->add_setting(new backup_activity_generic_setting(backup::VAR_CONTEXTID, base_setting::IS_INTEGER, $coursectxid)); // Add some extra settings that related processors are going to need diff --git a/backup/moodle2/backup_stepslib.php b/backup/moodle2/backup_stepslib.php index a73cafa587e..24d7da9b77c 100644 --- a/backup/moodle2/backup_stepslib.php +++ b/backup/moodle2/backup_stepslib.php @@ -667,7 +667,7 @@ class backup_final_scales_structure_step extends backup_structure_step { AND bi.itemname = 'scalefinal'", array(backup::VAR_BACKUPID)); // Annotate scale files (they store files in system context, so pass it instead of default one) - $scale->annotate_files('grade', 'scale', 'id', get_context_instance(CONTEXT_SYSTEM)->id); + $scale->annotate_files('grade', 'scale', 'id', context_system::instance()->id); // Return main element (scalesdef) return $scalesdef; @@ -704,7 +704,7 @@ class backup_final_outcomes_structure_step extends backup_structure_step { AND bi.itemname = 'outcomefinal'", array(backup::VAR_BACKUPID)); // Annotate outcome files (they store files in system context, so pass it instead of default one) - $outcome->annotate_files('grade', 'outcome', 'id', get_context_instance(CONTEXT_SYSTEM)->id); + $outcome->annotate_files('grade', 'outcome', 'id', context_system::instance()->id); // Return main element (outcomesdef) return $outcomesdef; @@ -1470,8 +1470,8 @@ class backup_main_structure_step extends backup_structure_step { $info['original_course_fullname'] = $originalcourseinfo->fullname; $info['original_course_shortname'] = $originalcourseinfo->shortname; $info['original_course_startdate'] = $originalcourseinfo->startdate; - $info['original_course_contextid'] = get_context_instance(CONTEXT_COURSE, $this->get_courseid())->id; - $info['original_system_contextid'] = get_context_instance(CONTEXT_SYSTEM)->id; + $info['original_course_contextid'] = context_course::instance($this->get_courseid())->id; + $info['original_system_contextid'] = context_system::instance()->id; // Get more information from controller list($dinfo, $cinfo, $sinfo) = backup_controller_dbops::get_moodle_backup_information($this->get_backupid()); @@ -1835,7 +1835,7 @@ class backup_annotate_all_user_files extends backup_execution_step { 'backupid' => $this->get_backupid(), 'itemname' => 'userfinal')); foreach ($rs as $record) { $userid = $record->itemid; - $userctx = get_context_instance(CONTEXT_USER, $userid); + $userctx = context_user::instance($userid); if (!$userctx) { continue; // User has not context, sure it's a deleted user, so cannot have files } diff --git a/backup/moodle2/restore_course_task.class.php b/backup/moodle2/restore_course_task.class.php index 97a2376d0ba..f39e6c63607 100644 --- a/backup/moodle2/restore_course_task.class.php +++ b/backup/moodle2/restore_course_task.class.php @@ -64,7 +64,7 @@ class restore_course_task extends restore_task { public function build() { // Define the task contextid (the course one) - $this->contextid = get_context_instance(CONTEXT_COURSE, $this->get_courseid())->id; + $this->contextid = context_course::instance($this->get_courseid())->id; // Executed conditionally if restoring to new course or if overwrite_conf setting is enabled if ($this->get_target() == backup::TARGET_NEW_COURSE || $this->get_setting_value('overwrite_conf') == true) { diff --git a/backup/moodle2/restore_section_task.class.php b/backup/moodle2/restore_section_task.class.php index 9d48778fed1..ab0843dad99 100644 --- a/backup/moodle2/restore_section_task.class.php +++ b/backup/moodle2/restore_section_task.class.php @@ -74,7 +74,7 @@ class restore_section_task extends restore_task { public function build() { // Define the task contextid (the course one) - $this->contextid = get_context_instance(CONTEXT_COURSE, $this->get_courseid())->id; + $this->contextid = context_course::instance($this->get_courseid())->id; // We always try to restore as much info from sections as possible, no matter of the type // of restore (new, existing, deleting, import...). MDL-27764 diff --git a/backup/moodle2/restore_stepslib.php b/backup/moodle2/restore_stepslib.php index 1bd5a48b973..520274c5e44 100644 --- a/backup/moodle2/restore_stepslib.php +++ b/backup/moodle2/restore_stepslib.php @@ -42,11 +42,11 @@ class restore_create_and_clean_temp_stuff extends restore_execution_step { } // Create the old-course-ctxid to new-course-ctxid mapping, we need that available since the beginning $itemid = $this->task->get_old_contextid(); - $newitemid = get_context_instance(CONTEXT_COURSE, $this->get_courseid())->id; + $newitemid = context_course::instance($this->get_courseid())->id; restore_dbops::set_backup_ids_record($this->get_restoreid(), 'context', $itemid, $newitemid); // Create the old-system-ctxid to new-system-ctxid mapping, we need that available since the beginning $itemid = $this->task->get_old_system_contextid(); - $newitemid = get_context_instance(CONTEXT_SYSTEM)->id; + $newitemid = context_system::instance()->id; restore_dbops::set_backup_ids_record($this->get_restoreid(), 'context', $itemid, $newitemid); // Create the old-course-id to new-course-id mapping, we need that available since the beginning $itemid = $this->task->get_old_courseid(); @@ -268,7 +268,7 @@ class restore_gradebook_structure_step extends restore_structure_step { $data = (object)$data; $oldid = $data->id; - $data->contextid = get_context_instance(CONTEXT_COURSE, $this->get_courseid())->id; + $data->contextid = context_course::instance($this->get_courseid())->id; $newitemid = $DB->insert_record('grade_letters', $data); $this->set_mapping('grade_letter', $oldid, $newitemid); @@ -888,7 +888,7 @@ class restore_scales_structure_step extends restore_structure_step { $data->courseid = $data->courseid ? $this->get_courseid() : 0; // If global scale (course=0), check the user has perms to create it // falling to course scale if not - $systemctx = get_context_instance(CONTEXT_SYSTEM); + $systemctx = context_system::instance(); if ($data->courseid == 0 && !has_capability('moodle/course:managescales', $systemctx , $this->task->get_userid())) { $data->courseid = $this->get_courseid(); } @@ -950,7 +950,7 @@ class restore_outcomes_structure_step extends restore_structure_step { $data->courseid = $data->courseid ? $this->get_courseid() : null; // If global outcome (course=null), check the user has perms to create it // falling to course outcome if not - $systemctx = get_context_instance(CONTEXT_SYSTEM); + $systemctx = context_system::instance(); if (is_null($data->courseid) && !has_capability('moodle/grade:manageoutcomes', $systemctx , $this->task->get_userid())) { $data->courseid = $this->get_courseid(); } @@ -1275,7 +1275,7 @@ class restore_course_structure_step extends restore_structure_step { $data->fullname = $fullname; $data->shortname= $shortname; - $context = get_context_instance_by_id($this->task->get_contextid()); + $context = context::instance_by_id($this->task->get_contextid()); if (has_capability('moodle/course:changeidnumber', $context, $this->task->get_userid())) { $data->idnumber = ''; } else { @@ -1769,6 +1769,23 @@ class restore_calendarevents_structure_step extends restore_structure_step { return; } } + // Handle events with empty eventtype //MDL-32827 + if(empty($data->eventtype)) { + if ($data->courseid == $SITE->id) { // Site event + $data->eventtype = "site"; + } else if ($data->courseid != 0 && $data->groupid == 0 && ($data->modulename == 'assignment' || $data->modulename == 'assign')) { + // Course assingment event + $data->eventtype = "due"; + } else if ($data->courseid != 0 && $data->groupid == 0) { // Course event + $data->eventtype = "course"; + } else if ($data->groupid) { // Group event + $data->eventtype = "group"; + } else if ($data->userid) { // User event + $data->eventtype = "user"; + } else { + return; + } + } $params = array( 'name' => $data->name, @@ -2484,7 +2501,7 @@ class restore_block_instance_structure_step extends restore_structure_step { // Save the mapping (with restorefiles support) $this->set_mapping('block_instance', $oldid, $newitemid, true); // Create the block context - $newcontextid = get_context_instance(CONTEXT_BLOCK, $newitemid)->id; + $newcontextid = context_block::instance($newitemid)->id; // Save the block contexts mapping and sent it to task $this->set_mapping('context', $oldcontextid, $newcontextid); $this->task->set_contextid($newcontextid); @@ -2619,7 +2636,7 @@ class restore_module_structure_step extends restore_structure_step { // set the new course_module id in the task $this->task->set_moduleid($newitemid); // we can now create the context safely - $ctxid = get_context_instance(CONTEXT_MODULE, $newitemid)->id; + $ctxid = context_module::instance($newitemid)->id; // set the new context id in the task $this->task->set_contextid($ctxid); // update sequence field in course_section diff --git a/backup/restorefile.php b/backup/restorefile.php index 92f8eb0ab3d..0c4095ba4c9 100644 --- a/backup/restorefile.php +++ b/backup/restorefile.php @@ -43,7 +43,7 @@ list($context, $course, $cm) = get_context_info_array($contextid); // will be used when restore if (!empty($filecontextid)) { - $filecontext = get_context_instance_by_id($filecontextid); + $filecontext = context::instance_by_id($filecontextid); } $url = new moodle_url('/backup/restorefile.php', array('contextid'=>$contextid)); @@ -116,7 +116,7 @@ if ($context->contextlevel == CONTEXT_MODULE) { echo $OUTPUT->heading_with_help(get_string('choosefilefromactivitybackup', 'backup'), 'choosefilefromuserbackup', 'backup'); echo $OUTPUT->container_start(); $treeview_options = array(); - $user_context = get_context_instance(CONTEXT_USER, $USER->id); + $user_context = context_user::instance($USER->id); $treeview_options['filecontext'] = $context; $treeview_options['currentcontext'] = $context; $treeview_options['component'] = 'backup'; @@ -142,7 +142,7 @@ echo $OUTPUT->container_end(); echo $OUTPUT->heading_with_help(get_string('choosefilefromuserbackup', 'backup'), 'choosefilefromuserbackup', 'backup'); echo $OUTPUT->container_start(); $treeview_options = array(); -$user_context = get_context_instance(CONTEXT_USER, $USER->id); +$user_context = context_user::instance($USER->id); $treeview_options['filecontext'] = $user_context; $treeview_options['currentcontext'] = $context; $treeview_options['component'] = 'user'; @@ -157,7 +157,7 @@ if (!empty($automatedbackups)) { echo $OUTPUT->heading_with_help(get_string('choosefilefromautomatedbackup', 'backup'), 'choosefilefromautomatedbackup', 'backup'); echo $OUTPUT->container_start(); $treeview_options = array(); - $user_context = get_context_instance(CONTEXT_USER, $USER->id); + $user_context = context_user::instance($USER->id); $treeview_options['filecontext'] = $context; $treeview_options['currentcontext'] = $context; $treeview_options['component'] = 'backup'; diff --git a/backup/util/checks/backup_check.class.php b/backup/util/checks/backup_check.class.php index fb7839dd399..164da0b3856 100644 --- a/backup/util/checks/backup_check.class.php +++ b/backup/util/checks/backup_check.class.php @@ -95,7 +95,7 @@ abstract class backup_check { $type = $backup_controller->get_type(); $mode = $backup_controller->get_mode(); $courseid = $backup_controller->get_courseid(); - $coursectx= get_context_instance(CONTEXT_COURSE, $courseid); + $coursectx= context_course::instance($courseid); $userid = $backup_controller->get_userid(); $id = $backup_controller->get_id(); // courseid / sectionid / cmid @@ -118,7 +118,7 @@ abstract class backup_check { break; case backup::TYPE_1ACTIVITY : get_coursemodule_from_id(null, $id, $courseid, false, MUST_EXIST); // cm exists - $modulectx = get_context_instance(CONTEXT_MODULE, $id); + $modulectx = context_module::instance($id); $typecapstocheck['moodle/backup:backupactivity'] = $modulectx; break; default : diff --git a/backup/util/checks/restore_check.class.php b/backup/util/checks/restore_check.class.php index 915112cf230..7b455f94cb5 100644 --- a/backup/util/checks/restore_check.class.php +++ b/backup/util/checks/restore_check.class.php @@ -62,7 +62,7 @@ abstract class restore_check { $type = $restore_controller->get_type(); $mode = $restore_controller->get_mode(); $courseid = $restore_controller->get_courseid(); - $coursectx= get_context_instance(CONTEXT_COURSE, $courseid); + $coursectx= context_course::instance($courseid); $userid = $restore_controller->get_userid(); // Note: all the checks along the function MUST be performed for $userid, that diff --git a/backup/util/dbops/backup_plan_dbops.class.php b/backup/util/dbops/backup_plan_dbops.class.php index 2ce9434ee3d..4ff5d8c0d62 100644 --- a/backup/util/dbops/backup_plan_dbops.class.php +++ b/backup/util/dbops/backup_plan_dbops.class.php @@ -39,7 +39,7 @@ abstract class backup_plan_dbops extends backup_dbops { global $DB; // Get the context of the module - $contextid = get_context_instance(CONTEXT_MODULE, $moduleid)->id; + $contextid = context_module::instance($moduleid)->id; // Get all the block instances which parentcontextid is the module contextid $blockids = array(); @@ -57,7 +57,7 @@ abstract class backup_plan_dbops extends backup_dbops { global $DB; // Get the context of the course - $contextid = get_context_instance(CONTEXT_COURSE, $courseid)->id; + $contextid = context_course::instance($courseid)->id; // Get all the block instances which parentcontextid is the course contextid $blockids = array(); @@ -214,7 +214,7 @@ abstract class backup_plan_dbops extends backup_dbops { switch ($type) { case backup::TYPE_1COURSE: $shortname = $DB->get_field('course', 'shortname', array('id' => $id)); - $context = get_context_instance(CONTEXT_COURSE, $id); + $context = context_course::instance($id); $shortname = format_string($shortname, true, array('context' => $context)); break; case backup::TYPE_1SECTION: diff --git a/backup/util/dbops/restore_dbops.class.php b/backup/util/dbops/restore_dbops.class.php index 1e7cbbb773b..3bd86e374db 100644 --- a/backup/util/dbops/restore_dbops.class.php +++ b/backup/util/dbops/restore_dbops.class.php @@ -346,7 +346,7 @@ abstract class restore_dbops { global $CFG, $DB; // Gather various information about roles - $coursectx = get_context_instance(CONTEXT_COURSE, $courseid); + $coursectx = context_course::instance($courseid); $assignablerolesshortname = get_assignable_roles($coursectx, ROLENAME_SHORT, false, $userid); // Note: under 1.9 we had one function restore_samerole() that performed one complete @@ -719,7 +719,7 @@ abstract class restore_dbops { switch ($contextlevel) { // For system is easy, the best context is the system context case CONTEXT_SYSTEM: - $targetcontext = get_context_instance(CONTEXT_SYSTEM); + $targetcontext = context_system::instance(); break; // For coursecat, we are going to look for stamps in all the @@ -739,8 +739,8 @@ abstract class restore_dbops { } $contexts = array(); // Build the array of contexts we are going to look - $systemctx = get_context_instance(CONTEXT_SYSTEM); - $coursectx = get_context_instance(CONTEXT_COURSE, $courseid); + $systemctx = context_system::instance(); + $coursectx = context_course::instance($courseid); $parentctxs= get_parent_contexts($coursectx); foreach ($parentctxs as $parentctx) { // Exclude system context @@ -761,14 +761,14 @@ abstract class restore_dbops { $matchingcontexts = $DB->get_records_sql($sql, $params); // Only if ONE and ONLY ONE context is found, use it as valid target if (count($matchingcontexts) == 1) { - $targetcontext = get_context_instance_by_id(reset($matchingcontexts)->contextid); + $targetcontext = context::instance_by_id(reset($matchingcontexts)->contextid); } } break; // For course is easy, the best context is the course context case CONTEXT_COURSE: - $targetcontext = get_context_instance(CONTEXT_COURSE, $courseid); + $targetcontext = context_course::instance($courseid); break; // For module is easy, there is not best context, as far as the @@ -777,7 +777,7 @@ abstract class restore_dbops { // case is handled by {@link prechek_precheck_qbanks_by_level} // in an special way case CONTEXT_MODULE: - $targetcontext = get_context_instance(CONTEXT_COURSE, $courseid); + $targetcontext = context_course::instance($courseid); break; } return $targetcontext; @@ -1065,7 +1065,7 @@ abstract class restore_dbops { // but for deleted users that don't have a context anymore (MDL-30192). We are done for them // and nothing else (custom fields, prefs, tags, files...) will be created. if (empty($user->deleted)) { - $newuserctxid = $user->deleted ? 0 : get_context_instance(CONTEXT_USER, $newuserid)->id; + $newuserctxid = $user->deleted ? 0 : context_user::instance($newuserid)->id; self::set_backup_ids_record($restoreid, 'context', $recuser->parentitemid, $newuserctxid); // Process custom fields @@ -1342,7 +1342,7 @@ abstract class restore_dbops { $mnethosts = $DB->get_records('mnet_host', array(), 'wwwroot', 'wwwroot, id'); // Calculate the context we are going to use for capability checking - $context = get_context_instance(CONTEXT_COURSE, $courseid); + $context = context_course::instance($courseid); // Calculate if we have perms to create users, by checking: // to 'moodle/restore:createuser' and 'moodle/restore:userinfo' @@ -1510,7 +1510,7 @@ abstract class restore_dbops { global $DB; // Get the course context - $coursectx = get_context_instance(CONTEXT_COURSE, $courseid); + $coursectx = context_course::instance($courseid); // Get all the mapped roles we have $rs = $DB->get_recordset('backup_ids_temp', array('backupid' => $restoreid, 'itemname' => 'role'), '', 'itemid'); foreach ($rs as $recrole) { diff --git a/backup/util/helper/backup_cron_helper.class.php b/backup/util/helper/backup_cron_helper.class.php index 00db13dc390..4bc6b6191a9 100644 --- a/backup/util/helper/backup_cron_helper.class.php +++ b/backup/util/helper/backup_cron_helper.class.php @@ -207,7 +207,7 @@ abstract class backup_cron_automated_helper { //Build the message subject $site = get_site(); - $prefix = format_string($site->shortname, true, array('context' => get_context_instance(CONTEXT_COURSE, SITEID))).": "; + $prefix = format_string($site->shortname, true, array('context' => context_course::instance(SITEID))).": "; if ($haserrors) { $prefix .= "[".strtoupper(get_string('error'))."] "; } @@ -478,7 +478,7 @@ abstract class backup_cron_automated_helper { // Clean up excess backups in the course backup filearea if ($storage == 0 || $storage == 2) { $fs = get_file_storage(); - $context = get_context_instance(CONTEXT_COURSE, $course->id); + $context = context_course::instance($course->id); $component = 'backup'; $filearea = 'automated'; $itemid = 0; diff --git a/backup/util/helper/backup_helper.class.php b/backup/util/helper/backup_helper.class.php index 59047517cfb..efc0c498635 100644 --- a/backup/util/helper/backup_helper.class.php +++ b/backup/util/helper/backup_helper.class.php @@ -226,19 +226,19 @@ abstract class backup_helper { $itemid = 0; switch ($backuptype) { case backup::TYPE_1ACTIVITY: - $ctxid = get_context_instance(CONTEXT_MODULE, $id)->id; + $ctxid = context_module::instance($id)->id; $component = 'backup'; $filearea = 'activity'; $itemid = 0; break; case backup::TYPE_1SECTION: - $ctxid = get_context_instance(CONTEXT_COURSE, $courseid)->id; + $ctxid = context_course::instance($courseid)->id; $component = 'backup'; $filearea = 'section'; $itemid = $id; break; case backup::TYPE_1COURSE: - $ctxid = get_context_instance(CONTEXT_COURSE, $courseid)->id; + $ctxid = context_course::instance($courseid)->id; $component = 'backup'; $filearea = 'course'; $itemid = 0; @@ -273,7 +273,7 @@ abstract class backup_helper { // are sent to user's "user_tohub" file area. The upload process // will be responsible for cleaning that filearea once finished if ($backupmode == backup::MODE_HUB) { - $ctxid = get_context_instance(CONTEXT_USER, $userid)->id; + $ctxid = context_user::instance($userid)->id; $component = 'user'; $filearea = 'tohub'; $itemid = 0; @@ -284,7 +284,7 @@ abstract class backup_helper { // file area. Maintenance of such area is responsibility of // the user via corresponding file manager frontend if ($backupmode == backup::MODE_GENERAL && (!$hasusers || $isannon)) { - $ctxid = get_context_instance(CONTEXT_USER, $userid)->id; + $ctxid = context_user::instance($userid)->id; $component = 'user'; $filearea = 'backup'; $itemid = 0; diff --git a/backup/util/helper/restore_prechecks_helper.class.php b/backup/util/helper/restore_prechecks_helper.class.php index 53ec22ea3df..95bc9685846 100644 --- a/backup/util/helper/restore_prechecks_helper.class.php +++ b/backup/util/helper/restore_prechecks_helper.class.php @@ -99,7 +99,7 @@ abstract class restore_prechecks_helper { // If restoring to different site and restoring users and backup has mnet users warn/error if (!$samesite && $restoreusers && $hasmnetusers) { // User is admin (can create users at sysctx), warn - if (has_capability('moodle/user:create', get_context_instance(CONTEXT_SYSTEM), $controller->get_userid())) { + if (has_capability('moodle/user:create', context_system::instance(), $controller->get_userid())) { $warnings[] = get_string('mnetrestore_extusers_admin', 'admin'); // User not admin } else { diff --git a/backup/util/plan/restore_structure_step.class.php b/backup/util/plan/restore_structure_step.class.php index 4b0ff58348e..42491cf432b 100644 --- a/backup/util/plan/restore_structure_step.class.php +++ b/backup/util/plan/restore_structure_step.class.php @@ -256,7 +256,7 @@ abstract class restore_structure_step extends restore_step { // Re-enforce 'moodle/restore:rolldates' capability for the user in the course, just in case } else if (!has_capability('moodle/restore:rolldates', - get_context_instance(CONTEXT_COURSE, $this->get_courseid()), + context_course::instance($this->get_courseid()), $this->task->get_userid())) { $cache[$this->get_restoreid()] = 0; diff --git a/backup/util/ui/backup_ui_stage.class.php b/backup/util/ui/backup_ui_stage.class.php index 799556157e0..472294af5a7 100644 --- a/backup/util/ui/backup_ui_stage.class.php +++ b/backup/util/ui/backup_ui_stage.class.php @@ -473,12 +473,12 @@ class backup_ui_stage_complete extends backup_ui_stage_final { case 'activity': $cmid = $this->get_ui()->get_controller()->get_id(); $cm = get_coursemodule_from_id(null, $cmid, $courseid); - $modcontext = get_context_instance(CONTEXT_MODULE, $cm->id); + $modcontext = context_module::instance($cm->id); $restorerul = new moodle_url('/backup/restorefile.php', array('contextid'=>$modcontext->id)); break; case 'course': default: - $coursecontext = get_context_instance(CONTEXT_COURSE, $courseid); + $coursecontext = context_course::instance($courseid); $restorerul = new moodle_url('/backup/restorefile.php', array('contextid'=>$coursecontext->id)); } diff --git a/backup/util/ui/renderer.php b/backup/util/ui/renderer.php index 9e0ab9dd4f9..2a5f3dac3e2 100644 --- a/backup/util/ui/renderer.php +++ b/backup/util/ui/renderer.php @@ -535,8 +535,8 @@ class core_backup_renderer extends plugin_renderer_base { } $row->cells = array( html_writer::empty_tag('input', array('type'=>'radio', 'name'=>'targetid', 'value'=>$course->id)), - format_string($course->shortname, true, array('context' => get_context_instance(CONTEXT_COURSE, $course->id))), - format_string($course->fullname, true, array('context' => get_context_instance(CONTEXT_COURSE, $course->id))) + format_string($course->shortname, true, array('context' => context_course::instance($course->id))), + format_string($course->fullname, true, array('context' => context_course::instance($course->id))) ); $table->data[] = $row; } @@ -605,8 +605,8 @@ class core_backup_renderer extends plugin_renderer_base { } $row->cells = array( html_writer::empty_tag('input', array('type'=>'radio', 'name'=>'importid', 'value'=>$course->id)), - format_string($course->shortname, true, array('context' => get_context_instance(CONTEXT_COURSE, $course->id))), - format_string($course->fullname, true, array('context' => get_context_instance(CONTEXT_COURSE, $course->id))) + format_string($course->shortname, true, array('context' => context_course::instance($course->id))), + format_string($course->fullname, true, array('context' => context_course::instance($course->id))) ); $table->data[] = $row; } @@ -647,7 +647,7 @@ class core_backup_renderer extends plugin_renderer_base { } $row->cells = array( html_writer::empty_tag('input', array('type'=>'radio', 'name'=>'targetid', 'value'=>$category->id)), - format_string($category->name, true, array('context' => get_context_instance(CONTEXT_COURSECAT, $category->id))), + format_string($category->name, true, array('context' => context_coursecat::instance($category->id))), format_text($category->description, $category->descriptionformat, array('overflowdiv'=>true)) ); $table->data[] = $row; diff --git a/backup/util/ui/restore_ui_components.php b/backup/util/ui/restore_ui_components.php index b95681dee5a..7ebaea8fadc 100644 --- a/backup/util/ui/restore_ui_components.php +++ b/backup/util/ui/restore_ui_components.php @@ -182,7 +182,8 @@ abstract class restore_search_base implements renderable { $resultset = $DB->get_records_sql($sql, $params, $offs, $blocksz); foreach ($resultset as $result) { context_instance_preload($result); - $context = get_context_instance($contextlevel, $result->id); + $classname = context_helper::get_class_for_level($contextlevel); + $context = $classname::instance($result->id); if (count($requiredcaps) > 0) { if (!has_all_capabilities($requiredcaps, $context, $userid)) { continue; diff --git a/backup/util/ui/restore_ui_stage.class.php b/backup/util/ui/restore_ui_stage.class.php index 7e920695502..6c282544f05 100644 --- a/backup/util/ui/restore_ui_stage.class.php +++ b/backup/util/ui/restore_ui_stage.class.php @@ -231,7 +231,7 @@ class restore_ui_stage_destination extends restore_ui_independent_stage { 'filepath'=>$this->filepath, 'contextid'=>$this->contextid, 'stage'=>restore_ui::STAGE_DESTINATION)); - $this->coursesearch = new restore_course_search(array('url'=>$url), get_context_instance_by_id($contextid)->instanceid); + $this->coursesearch = new restore_course_search(array('url'=>$url), context::instance_by_id($contextid)->instanceid); $this->categorysearch = new restore_category_search(array('url'=>$url)); } public function process() { @@ -286,7 +286,7 @@ class restore_ui_stage_destination extends restore_ui_independent_stage { 'contextid' => $this->contextid, 'filepath' => $this->filepath, 'stage' => restore_ui::STAGE_SETTINGS)); - $context = get_context_instance_by_id($this->contextid); + $context = context::instance_by_id($this->contextid); if ($context->contextlevel == CONTEXT_COURSE and has_capability('moodle/restore:restorecourse', $context)) { $currentcourse = $context->instanceid; @@ -703,7 +703,7 @@ class restore_ui_stage_process extends restore_ui_stage { $haserrors = (!empty($results['errors'])); $html .= $renderer->precheck_notices($results); if (!empty($info->role_mappings->mappings)) { - $context = get_context_instance(CONTEXT_COURSE, $this->ui->get_controller()->get_courseid()); + $context = context_course::instance($this->ui->get_controller()->get_courseid()); $assignableroles = get_assignable_roles($context, ROLENAME_ALIAS, false); $html .= $renderer->role_mappings($info->role_mappings->mappings, $assignableroles); } diff --git a/backup/util/ui/yui/confirmcancel/confirmcancel.js b/backup/util/ui/yui/confirmcancel/confirmcancel.js index 6d84615e543..77deaf1c466 100644 --- a/backup/util/ui/yui/confirmcancel/confirmcancel.js +++ b/backup/util/ui/yui/confirmcancel/confirmcancel.js @@ -27,4 +27,4 @@ M.core_backup.watch_cancel_buttons = function(config) { }); } -}, '@VERSION@', {'requires':['base','node','node-event-simulate','moodle-enrol-notification']}); +}, '@VERSION@', {'requires':['base','node','node-event-simulate','moodle-core-notification']}); diff --git a/blocks/community/yui/comments/comments.js b/blocks/community/yui/comments/comments.js index 155a823c570..817e3ac5d8a 100644 --- a/blocks/community/yui/comments/comments.js +++ b/blocks/community/yui/comments/comments.js @@ -85,5 +85,5 @@ YUI.add('moodle-block_community-comments', function(Y) { } }, '@VERSION@', { - requires:['base','overlay', 'moodle-enrol-notification'] -}); \ No newline at end of file + requires:['base','overlay', 'moodle-core-notification'] +}); diff --git a/blocks/community/yui/imagegallery/imagegallery.js b/blocks/community/yui/imagegallery/imagegallery.js index f91abb08e42..e7072aaee87 100644 --- a/blocks/community/yui/imagegallery/imagegallery.js +++ b/blocks/community/yui/imagegallery/imagegallery.js @@ -195,5 +195,5 @@ YUI.add('moodle-block_community-imagegallery', function(Y) { } }, '@VERSION@', { - requires:['base','node','overlay', 'moodle-enrol-notification'] + requires:['base','node','overlay', 'moodle-core-notification'] }); diff --git a/blocks/section_links/config_instance.html b/blocks/section_links/config_instance.html index efc2fbc4238..a2765dafd25 100644 --- a/blocks/section_links/config_instance.html +++ b/blocks/section_links/config_instance.html @@ -66,7 +66,7 @@ for($i = 1; $i < 3; $i++){ ?>
- : + @@ -77,7 +77,7 @@ for($i = 1; $i < 3; $i++){
- : + diff --git a/blocks/tags/block_tags.php b/blocks/tags/block_tags.php index 70722b6a2cd..0e2e341cb89 100644 --- a/blocks/tags/block_tags.php +++ b/blocks/tags/block_tags.php @@ -224,7 +224,6 @@ class block_tags extends block_base { if ($officialtags) { $this->content->text .= $officialtagscontent; } if ($coursetags) { $this->content->text .= $coursetagscontent; } if ($commtags) { $this->content->text .= $commtagscontent; } - // add the input form section (allowing a user to tag the current course) and navigation, or loggin message if ($loggedin) { // only show the input form on course pages for those allowed (or not barred) @@ -249,7 +248,8 @@ class block_tags extends block_base {
- + +
modtype = $DB->get_field('modules', 'name', array('id' => $cm->module)); $a->modname = $DB->get_field($a->modtype, 'name', array('id' => $cm->instance)); + $modid = $context->instanceid; } $mform->addElement('header', 'assochdr', get_string('associations', 'blog')); diff --git a/calendar/event.php b/calendar/event.php index 130e682351f..dbc0c32b370 100644 --- a/calendar/event.php +++ b/calendar/event.php @@ -123,10 +123,10 @@ if ($eventid !== 0) { $event = new stdClass(); $event->action = $action; $event->course = $courseid; + $event->courseid = $courseid; $event->timeduration = 0; if ($formoptions->eventtypes->courses) { if (!$issite) { - $event->courseid = $courseid; $event->eventtype = 'course'; } else { unset($formoptions->eventtypes->courses); diff --git a/calendar/lib.php b/calendar/lib.php index dcb5e8a987a..8812c6310bc 100644 --- a/calendar/lib.php +++ b/calendar/lib.php @@ -1619,6 +1619,7 @@ function calendar_print_month_selector($name, $selected) { for ($i=1; $i<=12; $i++) { $months[$i] = userdate(gmmktime(12, 0, 0, $i, 15, 2000), '%B'); } + echo html_writer::label(get_string('months'), 'menu'. $name, false, array('class' => 'accesshide')); echo html_writer::select($months, $name, $selected, false); } diff --git a/calendar/renderer.php b/calendar/renderer.php index 60e3a743174..45a6404a242 100644 --- a/calendar/renderer.php +++ b/calendar/renderer.php @@ -710,7 +710,9 @@ class core_calendar_renderer extends plugin_renderer_base { $select = new single_select(new moodle_url(CALENDAR_URL.'set.php', array('return' => base64_encode($returnurl->out(false)), 'var' => 'setcourse', 'sesskey'=>sesskey())), 'id', $courseoptions, $selected, null); $select->class = 'cal_courses_flt'; if ($label !== null) { - $select->label = $label; + $select->set_label($label); + } else { + $select->set_label(get_string('listofcourses'), array('class' => 'accesshide')); } return $this->output->render($select); } diff --git a/course/category.php b/course/category.php index 91efb2d199b..f88d867082b 100644 --- a/course/category.php +++ b/course/category.php @@ -422,6 +422,7 @@ if (!$courses) { make_categories_list($movetocategories, $notused, 'moodle/category:manage'); $movetocategories[$category->id] = get_string('moveselectedcoursesto'); echo '
'; + echo html_writer::label(get_string('moveselectedcoursesto'), 'movetoid', false, array('class' => 'accesshide')); echo html_writer::select($movetocategories, 'moveto', $category->id, null, array('id'=>'movetoid')); $PAGE->requires->js_init_call('M.util.init_select_autosubmit', array('movecourses', 'movetoid', false)); echo ''; diff --git a/course/index.php b/course/index.php index 3a40df856c1..66435ef0cb4 100644 --- a/course/index.php +++ b/course/index.php @@ -369,6 +369,7 @@ function print_category_edit($category, $displaylist, $parentslist, $depth=-1, $ } $popupurl = new moodle_url("index.php?move=$category->id&sesskey=".sesskey()); $select = new single_select($popupurl, 'moveto', $tempdisplaylist, $category->parent, null, "moveform$category->id"); + $select->set_label(get_string('frontpagecategorynames'), array('class' => 'accesshide')); echo $OUTPUT->render($select); } echo '
'; } diff --git a/mod/imscp/lib.php b/mod/imscp/lib.php index 812142d3772..4c4b31c9bac 100644 --- a/mod/imscp/lib.php +++ b/mod/imscp/lib.php @@ -101,7 +101,7 @@ function imscp_add_instance($data, $mform) { // we need to use context now, so we need to make sure all needed info is already in db $DB->set_field('course_modules', 'instance', $data->id, array('id'=>$cmid)); - $context = get_context_instance(CONTEXT_MODULE, $cmid); + $context = context_module::instance($cmid); $imscp = $DB->get_record('imscp', array('id'=>$data->id), '*', MUST_EXIST); if ($filename = $mform->get_new_filename('package')) { @@ -136,7 +136,7 @@ function imscp_update_instance($data, $mform) { $DB->update_record('imscp', $data); - $context = get_context_instance(CONTEXT_MODULE, $cmid); + $context = context_module::instance($cmid); $imscp = $DB->get_record('imscp', array('id'=>$data->id), '*', MUST_EXIST); if ($filename = $mform->get_new_filename('package')) { diff --git a/mod/imscp/locallib.php b/mod/imscp/locallib.php index 6eb6ebb9650..34e760ec5a8 100644 --- a/mod/imscp/locallib.php +++ b/mod/imscp/locallib.php @@ -35,7 +35,7 @@ function imscp_print_content($imscp, $cm, $course) { $items = unserialize($imscp->structure); $first = reset($items); - $context = get_context_instance(CONTEXT_MODULE, $cm->id); + $context = context_module::instance($cm->id); $urlbase = "$CFG->wwwroot/pluginfile.php"; $path = '/'.$context->id.'/mod_imscp/content/'.$imscp->revision.'/'.$first['href']; $firsturl = file_encode_url($urlbase, $path, false); @@ -61,7 +61,7 @@ function imscp_print_content($imscp, $cm, $course) { function imscp_htmllize_item($item, $imscp, $cm) { global $CFG; - $context = get_context_instance(CONTEXT_MODULE, $cm->id); + $context = context_module::instance($cm->id); $urlbase = "$CFG->wwwroot/pluginfile.php"; $path = '/'.$context->id.'/mod_imscp/content/'.$imscp->revision.'/'.$item['href']; $url = file_encode_url($urlbase, $path, false); diff --git a/mod/imscp/mod_form.php b/mod/imscp/mod_form.php index 450ab5d4543..34880b72dde 100644 --- a/mod/imscp/mod_form.php +++ b/mod/imscp/mod_form.php @@ -70,7 +70,7 @@ class mod_imscp_mod_form extends moodleform_mod { return $errors; } - $usercontext = get_context_instance(CONTEXT_USER, $USER->id); + $usercontext = context_user::instance($USER->id); $fs = get_file_storage(); if (!$files = $fs->get_area_files($usercontext->id, 'user', 'draft', $data['package'], 'id', false)) { diff --git a/mod/imscp/view.php b/mod/imscp/view.php index 8d5b7735f98..7b59b0b62f7 100644 --- a/mod/imscp/view.php +++ b/mod/imscp/view.php @@ -43,7 +43,7 @@ if ($i) { // Two ways to specify the module $course = $DB->get_record('course', array('id'=>$cm->course), '*', MUST_EXIST); require_course_login($course, true, $cm); -$context = get_context_instance(CONTEXT_MODULE, $cm->id); +$context = context_module::instance($cm->id); require_capability('mod/imscp:view', $context); add_to_log($course->id, 'imscp', 'view', 'view.php?id='.$cm->id, $imscp->id, $cm->id); diff --git a/mod/lesson/continue.php b/mod/lesson/continue.php index 5765ffa2483..1f773a5461e 100644 --- a/mod/lesson/continue.php +++ b/mod/lesson/continue.php @@ -37,7 +37,7 @@ $lesson = new lesson($DB->get_record('lesson', array('id' => $cm->instance), '*' require_login($course, false, $cm); require_sesskey(); -$context = get_context_instance(CONTEXT_MODULE, $cm->id); +$context = context_module::instance($cm->id); $canmanage = has_capability('mod/lesson:manage', $context); $lessonoutput = $PAGE->get_renderer('mod_lesson'); diff --git a/mod/lesson/edit.php b/mod/lesson/edit.php index c3466014baa..1fdeab68e16 100644 --- a/mod/lesson/edit.php +++ b/mod/lesson/edit.php @@ -35,7 +35,7 @@ $lesson = new lesson($DB->get_record('lesson', array('id' => $cm->instance), '*' require_login($course, false, $cm); -$context = get_context_instance(CONTEXT_MODULE, $cm->id); +$context = context_module::instance($cm->id); require_capability('mod/lesson:manage', $context); $mode = optional_param('mode', get_user_preferences('lesson_view', 'collapsed'), PARAM_ALPHA); diff --git a/mod/lesson/editpage.php b/mod/lesson/editpage.php index f725cae7ee2..50b7f48a793 100644 --- a/mod/lesson/editpage.php +++ b/mod/lesson/editpage.php @@ -40,7 +40,7 @@ $lesson = new lesson($DB->get_record('lesson', array('id' => $cm->instance), '*' require_login($course, false, $cm); -$context = get_context_instance(CONTEXT_MODULE, $cm->id); +$context = context_module::instance($cm->id); require_capability('mod/lesson:edit', $context); $PAGE->set_url('/mod/lesson/editpage.php', array('pageid'=>$pageid, 'id'=>$id, 'qtype'=>$qtype)); diff --git a/mod/lesson/essay.php b/mod/lesson/essay.php index e60f43e654b..e3bc0960fea 100644 --- a/mod/lesson/essay.php +++ b/mod/lesson/essay.php @@ -37,7 +37,7 @@ $course = $DB->get_record('course', array('id' => $cm->course), '*', MUST_EXIST) $lesson = new lesson($DB->get_record('lesson', array('id' => $cm->instance), '*', MUST_EXIST)); require_login($course, false, $cm); -$context = get_context_instance(CONTEXT_MODULE, $cm->id); +$context = context_module::instance($cm->id); require_capability('mod/lesson:edit', $context); $url = new moodle_url('/mod/lesson/essay.php', array('id'=>$id)); diff --git a/mod/lesson/grade.php b/mod/lesson/grade.php index 0081ccca784..7761c5ac02b 100644 --- a/mod/lesson/grade.php +++ b/mod/lesson/grade.php @@ -39,7 +39,7 @@ require_login($course, false, $cm); $PAGE->set_url('/mod/lesson/grade.php', array('id'=>$cm->id)); -if (has_capability('mod/lesson:edit', get_context_instance(CONTEXT_MODULE, $cm->id))) { +if (has_capability('mod/lesson:edit', context_module::instance($cm->id))) { redirect('report.php?id='.$cm->id); } else { redirect('view.php?id='.$cm->id); diff --git a/mod/lesson/highscores.php b/mod/lesson/highscores.php index c4e16668ca2..86c7336a18a 100644 --- a/mod/lesson/highscores.php +++ b/mod/lesson/highscores.php @@ -47,7 +47,7 @@ if ($link !== 0) { } $PAGE->set_url($url); -$context = get_context_instance(CONTEXT_MODULE, $cm->id); +$context = context_module::instance($cm->id); switch ($mode) { case 'add': diff --git a/mod/lesson/import.php b/mod/lesson/import.php index f9cb68ef170..1a9e93c673f 100644 --- a/mod/lesson/import.php +++ b/mod/lesson/import.php @@ -40,7 +40,7 @@ $course = $DB->get_record('course', array('id' => $cm->course), '*', MUST_EXIST) $lesson = new lesson($DB->get_record('lesson', array('id' => $cm->instance), '*', MUST_EXIST)); require_login($course, false, $cm); -$context = get_context_instance(CONTEXT_MODULE, $cm->id); +$context = context_module::instance($cm->id); require_capability('mod/lesson:edit', $context); $strimportquestions = get_string("importquestions", "lesson"); diff --git a/mod/lesson/importppt.php b/mod/lesson/importppt.php index 84bd61b08ee..d2ed246aa25 100644 --- a/mod/lesson/importppt.php +++ b/mod/lesson/importppt.php @@ -53,7 +53,7 @@ $mod = $cm; require_login($course, false, $cm); require_login($course, false, $cm); -$context = get_context_instance(CONTEXT_MODULE, $cm->id); +$context = context_module::instance($cm->id); require_capability('mod/lesson:edit', $context); $strimportppt = get_string("importppt", "lesson"); diff --git a/mod/lesson/index.php b/mod/lesson/index.php index 048f3ffa368..27ae03aa2b6 100644 --- a/mod/lesson/index.php +++ b/mod/lesson/index.php @@ -93,7 +93,7 @@ foreach ($lessons as $lesson) { $link = "coursemodule\">".format_string($lesson->name,true).""; } $cm = get_coursemodule_from_instance('lesson', $lesson->id); - $context = get_context_instance(CONTEXT_MODULE, $cm->id); + $context = context_module::instance($cm->id); if ($lesson->deadline == 0) { $due = $strnodeadline; diff --git a/mod/lesson/lesson.php b/mod/lesson/lesson.php index 36e0c1264e8..11e7c9d7102 100644 --- a/mod/lesson/lesson.php +++ b/mod/lesson/lesson.php @@ -45,7 +45,7 @@ require_login($course, false, $cm); $url = new moodle_url('/mod/lesson/lesson.php', array('id'=>$id,'action'=>$action)); $PAGE->set_url($url); -$context = get_context_instance(CONTEXT_MODULE, $cm->id); +$context = context_module::instance($cm->id); require_capability('mod/lesson:edit', $context); require_sesskey(); diff --git a/mod/lesson/lib.php b/mod/lesson/lib.php index 8c7b4d974a0..31daa38da68 100644 --- a/mod/lesson/lib.php +++ b/mod/lesson/lib.php @@ -50,7 +50,7 @@ function lesson_add_instance($data, $mform) { $lessonid = $DB->insert_record("lesson", $data); $data->id = $lessonid; - $context = get_context_instance(CONTEXT_MODULE, $cmid); + $context = context_module::instance($cmid); $lesson = $DB->get_record('lesson', array('id'=>$lessonid), '*', MUST_EXIST); if ($filename = $mform->get_new_filename('mediafilepicker')) { @@ -86,7 +86,7 @@ function lesson_update_instance($data, $mform) { unset($data->mediafile); $DB->update_record("lesson", $data); - $context = get_context_instance(CONTEXT_MODULE, $cmid); + $context = context_module::instance($cmid); if ($filename = $mform->get_new_filename('mediafilepicker')) { if ($file = $mform->save_stored_file('mediafilepicker', $context->id, 'mod_lesson', 'mediafile', 0, '/', $filename, true)) { $DB->set_field('lesson', 'mediafile', '/'.$file->get_filename(), array('id'=>$data->id)); @@ -295,7 +295,7 @@ function lesson_print_overview($courses, &$htmlarray) { $str .= $OUTPUT->box(get_string('lessoncloseson', 'lesson', userdate($lesson->deadline)), 'info'); // Attempt information - if (has_capability('mod/lesson:manage', get_context_instance(CONTEXT_MODULE, $lesson->coursemodule))) { + if (has_capability('mod/lesson:manage', context_module::instance($lesson->coursemodule))) { // Number of user attempts $attempts = $DB->count_records('lesson_attempts', array('lessonid'=>$lesson->id)); $str .= $OUTPUT->box(get_string('xattempts', 'lesson', $attempts), 'info'); diff --git a/mod/lesson/locallib.php b/mod/lesson/locallib.php index 11d8e78b520..9c9c07acf6a 100644 --- a/mod/lesson/locallib.php +++ b/mod/lesson/locallib.php @@ -484,7 +484,7 @@ function lesson_mediafile_block_contents($cmid, $lesson) { **/ function lesson_clock_block_contents($cmid, $lesson, $timer, $page) { // Display for timed lessons and for students only - $context = get_context_instance(CONTEXT_MODULE, $cmid); + $context = context_module::instance($cmid); if(!$lesson->timed || has_capability('mod/lesson:manage', $context)) { return null; } @@ -2373,7 +2373,7 @@ abstract class lesson_page extends lesson_base { if (!isset($this->properties->contentsformat)) { $this->properties->contentsformat = FORMAT_HTML; } - $context = get_context_instance(CONTEXT_MODULE, $PAGE->cm->id); + $context = context_module::instance($PAGE->cm->id); $contents = file_rewrite_pluginfile_urls($this->properties->contents, 'pluginfile.php', $context->id, 'mod_lesson', 'page_contents', $this->properties->id); // must do this BEFORE format_text()!!!!!! return format_text($contents, $this->properties->contentsformat, array('context'=>$context, 'noclean'=>true)); // page edit is marked with XSS, we want all content here } else { diff --git a/mod/lesson/mediafile.php b/mod/lesson/mediafile.php index 0d5b45fb656..ecf94896c7f 100644 --- a/mod/lesson/mediafile.php +++ b/mod/lesson/mediafile.php @@ -39,7 +39,7 @@ $lesson = new lesson($DB->get_record('lesson', array('id' => $cm->instance), '*' require_login($course, false, $cm); -$context = get_context_instance(CONTEXT_MODULE, $cm->id); +$context = context_module::instance($cm->id); $canmanage = has_capability('mod/lesson:manage', $context); $url = new moodle_url('/mod/lesson/mediafile.php', array('id'=>$id)); diff --git a/mod/lesson/pagetypes/branchtable.php b/mod/lesson/pagetypes/branchtable.php index 6f29bb82d6b..93359b8f3c2 100644 --- a/mod/lesson/pagetypes/branchtable.php +++ b/mod/lesson/pagetypes/branchtable.php @@ -176,7 +176,7 @@ class lesson_page_type_branchtable extends lesson_page { $DB->insert_record("lesson_branch", $branch); // this is called when jumping to random from a branch table - $context = get_context_instance(CONTEXT_MODULE, $PAGE->cm->id); + $context = context_module::instance($PAGE->cm->id); if($newpageid == LESSON_UNSEENBRANCHPAGE) { if (has_capability('mod/lesson:manage', $context)) { $newpageid = LESSON_NEXTPAGE; diff --git a/mod/lesson/pagetypes/endofbranch.php b/mod/lesson/pagetypes/endofbranch.php index f328429abb5..38c07a2694a 100644 --- a/mod/lesson/pagetypes/endofbranch.php +++ b/mod/lesson/pagetypes/endofbranch.php @@ -107,7 +107,7 @@ class lesson_page_type_endofbranch extends lesson_page { if (empty($properties->qoption)) { $properties->qoption = '0'; } - $properties = file_postupdate_standard_editor($properties, 'contents', array('noclean'=>true, 'maxfiles'=>EDITOR_UNLIMITED_FILES, 'maxbytes'=>$PAGE->course->maxbytes), get_context_instance(CONTEXT_MODULE, $PAGE->cm->id), 'mod_lesson', 'page_contents', $properties->id); + $properties = file_postupdate_standard_editor($properties, 'contents', array('noclean'=>true, 'maxfiles'=>EDITOR_UNLIMITED_FILES, 'maxbytes'=>$PAGE->course->maxbytes), context_module::instance($PAGE->cm->id), 'mod_lesson', 'page_contents', $properties->id); $DB->update_record("lesson_pages", $properties); $answers = $this->get_answers(); diff --git a/mod/lesson/pagetypes/endofcluster.php b/mod/lesson/pagetypes/endofcluster.php index 05b3f6d6182..edca1fde088 100644 --- a/mod/lesson/pagetypes/endofcluster.php +++ b/mod/lesson/pagetypes/endofcluster.php @@ -76,7 +76,7 @@ class lesson_page_type_endofcluster extends lesson_page { if (empty($properties->qoption)) { $properties->qoption = '0'; } - $properties = file_postupdate_standard_editor($properties, 'contents', array('noclean'=>true, 'maxfiles'=>EDITOR_UNLIMITED_FILES, 'maxbytes'=>$PAGE->course->maxbytes), get_context_instance(CONTEXT_MODULE, $PAGE->cm->id), 'mod_lesson', 'page_contents', $properties->id); + $properties = file_postupdate_standard_editor($properties, 'contents', array('noclean'=>true, 'maxfiles'=>EDITOR_UNLIMITED_FILES, 'maxbytes'=>$PAGE->course->maxbytes), context_module::instance($PAGE->cm->id), 'mod_lesson', 'page_contents', $properties->id); $DB->update_record("lesson_pages", $properties); $answers = $this->get_answers(); diff --git a/mod/lesson/pagetypes/essay.php b/mod/lesson/pagetypes/essay.php index 78323ec299b..9e475a58549 100644 --- a/mod/lesson/pagetypes/essay.php +++ b/mod/lesson/pagetypes/essay.php @@ -131,7 +131,7 @@ class lesson_page_type_essay extends lesson_page { $answers = $this->get_answers(); $properties->id = $this->properties->id; $properties->lessonid = $this->lesson->id; - $properties = file_postupdate_standard_editor($properties, 'contents', array('noclean'=>true, 'maxfiles'=>EDITOR_UNLIMITED_FILES, 'maxbytes'=>$PAGE->course->maxbytes), get_context_instance(CONTEXT_MODULE, $PAGE->cm->id), 'mod_lesson', 'page_contents', $properties->id); + $properties = file_postupdate_standard_editor($properties, 'contents', array('noclean'=>true, 'maxfiles'=>EDITOR_UNLIMITED_FILES, 'maxbytes'=>$PAGE->course->maxbytes), context_module::instance($PAGE->cm->id), 'mod_lesson', 'page_contents', $properties->id); $DB->update_record("lesson_pages", $properties); if (!array_key_exists(0, $this->answers)) { diff --git a/mod/lesson/pagetypes/matching.php b/mod/lesson/pagetypes/matching.php index 057297828d7..b5780f99ac1 100644 --- a/mod/lesson/pagetypes/matching.php +++ b/mod/lesson/pagetypes/matching.php @@ -298,7 +298,7 @@ class lesson_page_type_matching extends lesson_page { $answers = $this->get_answers(); $properties->id = $this->properties->id; $properties->lessonid = $this->lesson->id; - $properties = file_postupdate_standard_editor($properties, 'contents', array('noclean'=>true, 'maxfiles'=>EDITOR_UNLIMITED_FILES, 'maxbytes'=>$PAGE->course->maxbytes), get_context_instance(CONTEXT_MODULE, $PAGE->cm->id), 'mod_lesson', 'page_contents', $properties->id); + $properties = file_postupdate_standard_editor($properties, 'contents', array('noclean'=>true, 'maxfiles'=>EDITOR_UNLIMITED_FILES, 'maxbytes'=>$PAGE->course->maxbytes), context_module::instance($PAGE->cm->id), 'mod_lesson', 'page_contents', $properties->id); $DB->update_record("lesson_pages", $properties); // need to add two to offset correct response and wrong response diff --git a/mod/lesson/pagetypes/truefalse.php b/mod/lesson/pagetypes/truefalse.php index 8566244a3ef..2c016de528a 100644 --- a/mod/lesson/pagetypes/truefalse.php +++ b/mod/lesson/pagetypes/truefalse.php @@ -158,7 +158,7 @@ class lesson_page_type_truefalse extends lesson_page { $answers = $this->get_answers(); $properties->id = $this->properties->id; $properties->lessonid = $this->lesson->id; - $properties = file_postupdate_standard_editor($properties, 'contents', array('noclean'=>true, 'maxfiles'=>EDITOR_UNLIMITED_FILES, 'maxbytes'=>$PAGE->course->maxbytes), get_context_instance(CONTEXT_MODULE, $PAGE->cm->id), 'mod_lesson', 'page_contents', $properties->id); + $properties = file_postupdate_standard_editor($properties, 'contents', array('noclean'=>true, 'maxfiles'=>EDITOR_UNLIMITED_FILES, 'maxbytes'=>$PAGE->course->maxbytes), context_module::instance($PAGE->cm->id), 'mod_lesson', 'page_contents', $properties->id); $DB->update_record("lesson_pages", $properties); // need to reset offset for correct and wrong responses diff --git a/mod/lesson/renderer.php b/mod/lesson/renderer.php index 765b7ca6e07..11e645aee9a 100644 --- a/mod/lesson/renderer.php +++ b/mod/lesson/renderer.php @@ -43,7 +43,7 @@ class mod_lesson_renderer extends plugin_renderer_base { $title = $this->page->course->shortname.": ".$activityname; // Build the buttons - $context = get_context_instance(CONTEXT_MODULE, $cm->id); + $context = context_module::instance($cm->id); /// Header setup $this->page->set_title($title); @@ -215,7 +215,7 @@ class mod_lesson_renderer extends plugin_renderer_base { $table->width = '80%'; $table->data = array(); - $canedit = has_capability('mod/lesson:edit', get_context_instance(CONTEXT_MODULE, $this->page->cm->id)); + $canedit = has_capability('mod/lesson:edit', context_module::instance($this->page->cm->id)); while ($pageid != 0) { $page = $lesson->load_page($pageid); @@ -250,7 +250,7 @@ class mod_lesson_renderer extends plugin_renderer_base { $manager = lesson_page_type_manager::get($lesson); $qtypes = $manager->get_page_type_strings(); $npages = count($lesson->load_all_pages()); - $canedit = has_capability('mod/lesson:edit', get_context_instance(CONTEXT_MODULE, $this->page->cm->id)); + $canedit = has_capability('mod/lesson:edit', context_module::instance($this->page->cm->id)); $content = ''; if ($canedit) { @@ -452,7 +452,7 @@ class mod_lesson_renderer extends plugin_renderer_base { public function ongoing_score(lesson $lesson) { global $USER, $DB; - $context = get_context_instance(CONTEXT_MODULE, $this->page->cm->id); + $context = context_module::instance($this->page->cm->id); if (has_capability('mod/lesson:manage', $context)) { return $this->output->box(get_string('teacherongoingwarning', 'lesson'), "ongoing center"); } else { @@ -483,7 +483,7 @@ class mod_lesson_renderer extends plugin_renderer_base { public function progress_bar(lesson $lesson) { global $CFG, $USER, $DB; - $context = get_context_instance(CONTEXT_MODULE, $this->page->cm->id); + $context = context_module::instance($this->page->cm->id); // lesson setting to turn progress bar on or off if (!$lesson->progressbar) { diff --git a/mod/lesson/report.php b/mod/lesson/report.php index f2d1e059f53..745d725adf4 100644 --- a/mod/lesson/report.php +++ b/mod/lesson/report.php @@ -38,7 +38,7 @@ $lesson = new lesson($DB->get_record('lesson', array('id' => $cm->instance), '*' require_login($course, false, $cm); -$context = get_context_instance(CONTEXT_MODULE, $cm->id); +$context = context_module::instance($cm->id); require_capability('mod/lesson:manage', $context); $ufields = user_picture::fields('u'); // These fields are enough @@ -162,7 +162,7 @@ if ($action === 'delete') { **************************************************************************/ echo $lessonoutput->header($lesson, $cm, $action); - $course_context = get_context_instance(CONTEXT_COURSE, $course->id); + $course_context = context_course::instance($course->id); if (has_capability('gradereport/grader:view', $course_context) && has_capability('moodle/grade:viewall', $course_context)) { $seeallgradeslink = new moodle_url('/grade/report/grader/index.php', array('id'=>$course->id)); $seeallgradeslink = html_writer::link($seeallgradeslink, get_string('seeallcoursegrades', 'grades')); @@ -377,7 +377,7 @@ if ($action === 'delete') { **************************************************************************/ echo $lessonoutput->header($lesson, $cm, $action); - $course_context = get_context_instance(CONTEXT_COURSE, $course->id); + $course_context = context_course::instance($course->id); if (has_capability('gradereport/grader:view', $course_context) && has_capability('moodle/grade:viewall', $course_context)) { $seeallgradeslink = new moodle_url('/grade/report/grader/index.php', array('id'=>$course->id)); $seeallgradeslink = html_writer::link($seeallgradeslink, get_string('seeallcoursegrades', 'grades')); diff --git a/mod/lesson/tabs.php b/mod/lesson/tabs.php index ebdba4fcf61..548ad18e054 100644 --- a/mod/lesson/tabs.php +++ b/mod/lesson/tabs.php @@ -38,7 +38,7 @@ if (!isset($currenttab)) { } if (!isset($cm)) { $cm = get_coursemodule_from_instance('lesson', $lesson->id); - $context = get_context_instance(CONTEXT_MODULE, $cm->id); + $context = context_module::instance($cm->id); } if (!isset($course)) { $course = $DB->get_record('course', array('id' => $lesson->course)); diff --git a/mod/lesson/view.php b/mod/lesson/view.php index 5beec5738eb..3c3346d9f0f 100644 --- a/mod/lesson/view.php +++ b/mod/lesson/view.php @@ -55,7 +55,7 @@ if ($pageid !== null) { } $PAGE->set_url($url); -$context = get_context_instance(CONTEXT_MODULE, $cm->id); +$context = context_module::instance($cm->id); $canmanage = has_capability('mod/lesson:manage', $context); $lessonoutput = $PAGE->get_renderer('mod_lesson'); diff --git a/mod/lti/grade.php b/mod/lti/grade.php index e8c19a1d2a5..14e25c47983 100644 --- a/mod/lti/grade.php +++ b/mod/lti/grade.php @@ -68,7 +68,7 @@ if ($l) { // Two ways to specify the module $course = $DB->get_record('course', array('id' => $cm->course), '*', MUST_EXIST); require_login($course, false, $cm); -$context = get_context_instance(CONTEXT_MODULE, $cm->id); +$context = context_module::instance($cm->id); require_capability('mod/lti:grade', $context); $url = new moodle_url('/mod/lti/grade.php', array('id' => $cm->id)); diff --git a/mod/lti/instructor_edit_tool_type.php b/mod/lti/instructor_edit_tool_type.php index c65b3f40522..3a700512f16 100644 --- a/mod/lti/instructor_edit_tool_type.php +++ b/mod/lti/instructor_edit_tool_type.php @@ -37,7 +37,7 @@ $PAGE->set_pagelayout('popup'); $action = optional_param('action', null, PARAM_TEXT); $typeid = optional_param('typeid', null, PARAM_INT); -require_capability('mod/lti:addcoursetool', get_context_instance(CONTEXT_COURSE, $courseid)); +require_capability('mod/lti:addcoursetool', context_course::instance($courseid)); if (!empty($typeid)) { $type = lti_get_type($typeid); diff --git a/mod/lti/lib.php b/mod/lti/lib.php index 0e154d8482c..fa74bbcd426 100644 --- a/mod/lti/lib.php +++ b/mod/lti/lib.php @@ -395,7 +395,7 @@ function lti_grade_item_delete($basiclti) { function lti_extend_settings_navigation($settings, $parentnode) { global $PAGE; - if (has_capability('mod/lti:grade', get_context_instance(CONTEXT_MODULE, $PAGE->cm->id))) { + if (has_capability('mod/lti:grade', context_module::instance($PAGE->cm->id))) { $keys = $parentnode->get_children_key_list(); $node = navigation_node::create('Submissions', diff --git a/mod/lti/locallib.php b/mod/lti/locallib.php index 0bbe06b85ba..8c9a3ef4d5b 100644 --- a/mod/lti/locallib.php +++ b/mod/lti/locallib.php @@ -462,7 +462,7 @@ function lti_get_ims_role($user, $cmid, $courseid) { //If no cmid is passed, check if the user is a teacher in the course //This allows other modules to programmatically "fake" a launch without //a real LTI instance - $coursecontext = get_context_instance(CONTEXT_COURSE, $courseid); + $coursecontext = context_course::instance($courseid); if (has_capability('moodle/course:manageactivities', $coursecontext)) { array_push($roles, 'Instructor'); @@ -470,7 +470,7 @@ function lti_get_ims_role($user, $cmid, $courseid) { array_push($roles, 'Learner'); } } else { - $context = get_context_instance(CONTEXT_MODULE, $cmid); + $context = context_module::instance($cmid); if (has_capability('mod/lti:manage', $context)) { array_push($roles, 'Instructor'); diff --git a/mod/lti/request_tool.php b/mod/lti/request_tool.php index d5c8c99bd42..daf664c596a 100644 --- a/mod/lti/request_tool.php +++ b/mod/lti/request_tool.php @@ -35,7 +35,7 @@ $course = $DB->get_record('course', array('id' => $lti->course)); require_login($course); -require_capability('mod/lti:requesttooladd', get_context_instance(CONTEXT_COURSE, $lti->course)); +require_capability('mod/lti:requesttooladd', context_course::instance($lti->course)); $baseurl = lti_get_domain_from_url($lti->toolurl); diff --git a/mod/lti/return.php b/mod/lti/return.php index 7b2ed8cb290..1ad5b3c19a7 100644 --- a/mod/lti/return.php +++ b/mod/lti/return.php @@ -61,7 +61,7 @@ if (!empty($errormsg)) { echo htmlspecialchars($errormsg); - $canaddtools = has_capability('mod/lti:addcoursetool', get_context_instance(CONTEXT_COURSE, $courseid)); + $canaddtools = has_capability('mod/lti:addcoursetool', context_course::instance($courseid)); if ($unsigned == 1 && $canaddtools) { echo '

'; diff --git a/mod/lti/service.php b/mod/lti/service.php index f3c9aca3819..fad61e64407 100644 --- a/mod/lti/service.php +++ b/mod/lti/service.php @@ -98,7 +98,7 @@ switch ($messagetype) { $ltiinstance = $DB->get_record('lti', array('id' => $parsed->instanceid)); //Getting the grade requires the context is set - $context = get_context_instance(CONTEXT_COURSE, $ltiinstance->course); + $context = context_course::instance($ltiinstance->course); $PAGE->set_context($context); lti_verify_sourcedid($ltiinstance, $parsed); diff --git a/mod/lti/view.php b/mod/lti/view.php index 7f43092eb14..5399bd72d93 100644 --- a/mod/lti/view.php +++ b/mod/lti/view.php @@ -73,7 +73,7 @@ if ($tool) { } $PAGE->set_cm($cm, $course); // set's up global $COURSE -$context = get_context_instance(CONTEXT_MODULE, $cm->id); +$context = context_module::instance($cm->id); $PAGE->set_context($context); $url = new moodle_url('/mod/lti/view.php', array('id'=>$cm->id)); diff --git a/mod/page/lib.php b/mod/page/lib.php index 3242bd67d87..0f03e2abcfb 100644 --- a/mod/page/lib.php +++ b/mod/page/lib.php @@ -110,7 +110,7 @@ function page_add_instance($data, $mform = null) { // we need to use context now, so we need to make sure all needed info is already in db $DB->set_field('course_modules', 'instance', $data->id, array('id'=>$cmid)); - $context = get_context_instance(CONTEXT_MODULE, $cmid); + $context = context_module::instance($cmid); if ($mform and !empty($data->page['itemid'])) { $draftitemid = $data->page['itemid']; @@ -152,7 +152,7 @@ function page_update_instance($data, $mform) { $DB->update_record('page', $data); - $context = get_context_instance(CONTEXT_MODULE, $cmid); + $context = context_module::instance($cmid); if ($draftitemid) { $data->content = file_save_draft_area_files($draftitemid, $context->id, 'mod_page', 'content', 0, page_get_editor_options($context), $data->content); $DB->update_record('page', $data); @@ -430,7 +430,7 @@ function page_page_type_list($pagetype, $parentcontext, $currentcontext) { function page_export_contents($cm, $baseurl) { global $CFG, $DB; $contents = array(); - $context = get_context_instance(CONTEXT_MODULE, $cm->id); + $context = context_module::instance($cm->id); $page = $DB->get_record('page', array('id'=>$cm->instance), '*', MUST_EXIST); diff --git a/mod/page/view.php b/mod/page/view.php index 6c8c850d27c..e04a2ec3df4 100644 --- a/mod/page/view.php +++ b/mod/page/view.php @@ -48,7 +48,7 @@ if ($p) { $course = $DB->get_record('course', array('id'=>$cm->course), '*', MUST_EXIST); require_course_login($course, true, $cm); -$context = get_context_instance(CONTEXT_MODULE, $cm->id); +$context = context_module::instance($cm->id); require_capability('mod/page:view', $context); add_to_log($course->id, 'page', 'view', 'view.php?id='.$cm->id, $page->id, $cm->id); diff --git a/mod/quiz/attempt.php b/mod/quiz/attempt.php index 162e67262a7..a24245dd215 100644 --- a/mod/quiz/attempt.php +++ b/mod/quiz/attempt.php @@ -41,6 +41,7 @@ $attemptid = required_param('attempt', PARAM_INT); $page = optional_param('page', 0, PARAM_INT); $attemptobj = quiz_attempt::create($attemptid); +$page = $attemptobj->force_page_number_into_range($page); $PAGE->set_url($attemptobj->attempt_url(null, $page)); // Check login. diff --git a/mod/quiz/attemptlib.php b/mod/quiz/attemptlib.php index 78a74a61307..7d6b7965df1 100644 --- a/mod/quiz/attemptlib.php +++ b/mod/quiz/attemptlib.php @@ -555,6 +555,16 @@ class quiz_attempt { } } + /** + * If the given page number is out of range (before the first page, or after + * the last page, chnage it to be within range). + * @param int $page the requested page number. + * @return int a safe page number to use. + */ + public function force_page_number_into_range($page) { + return min(max($page, 0), count($this->pagelayout) - 1); + } + // Simple getters ========================================================== public function get_quiz() { return $this->quizobj->get_quiz(); @@ -1101,7 +1111,7 @@ class quiz_attempt { } /** - * Initialise the JS etc. required all the questions on a page.. + * Initialise the JS etc. required all the questions on a page. * @param mixed $page a page number, or 'all'. */ public function get_html_head_contributions($page = 'all', $showall = false) { diff --git a/mod/quiz/db/upgrade.php b/mod/quiz/db/upgrade.php index b0a4a4f4a95..3bbbb6d4d83 100644 --- a/mod/quiz/db/upgrade.php +++ b/mod/quiz/db/upgrade.php @@ -330,6 +330,16 @@ function xmldb_quiz_upgrade($oldversion) { // Moodle v2.3.0 release upgrade line // Put any upgrade step following this + if ($oldversion < 2012061702) { + + // MDL-32791 somebody reported having nonsense rows in their + // quiz_question_instances which caused various problems. These rows + // are meaningless, hence this upgrade step to clean them up. + $DB->delete_records('quiz_question_instances', array('question' => 0)); + + // Quiz savepoint reached. + upgrade_mod_savepoint(true, 2012061702, 'quiz'); + } return true; } diff --git a/mod/quiz/lib.php b/mod/quiz/lib.php index f704992376e..5b8ff20c530 100644 --- a/mod/quiz/lib.php +++ b/mod/quiz/lib.php @@ -1556,7 +1556,7 @@ function quiz_supports($feature) { case FEATURE_MOD_INTRO: return true; case FEATURE_COMPLETION_TRACKS_VIEWS: return true; case FEATURE_GRADE_HAS_GRADE: return true; - case FEATURE_GRADE_OUTCOMES: return false; + case FEATURE_GRADE_OUTCOMES: return true; case FEATURE_BACKUP_MOODLE2: return true; case FEATURE_SHOW_DESCRIPTION: return true; case FEATURE_CONTROLS_GRADE_VISIBILITY: return true; diff --git a/mod/quiz/processattempt.php b/mod/quiz/processattempt.php index 1757eb5db41..aa4a171f35c 100644 --- a/mod/quiz/processattempt.php +++ b/mod/quiz/processattempt.php @@ -37,13 +37,13 @@ require_once($CFG->dirroot . '/mod/quiz/locallib.php'); $timenow = time(); // Get submitted parameters. -$attemptid = required_param('attempt', PARAM_INT); -$next = optional_param('next', false, PARAM_BOOL); -$thispage = optional_param('thispage', 0, PARAM_INT); -$nextpage = optional_param('nextpage', 0, PARAM_INT); +$attemptid = required_param('attempt', PARAM_INT); +$thispage = optional_param('thispage', 0, PARAM_INT); +$nextpage = optional_param('nextpage', 0, PARAM_INT); +$next = optional_param('next', false, PARAM_BOOL); $finishattempt = optional_param('finishattempt', false, PARAM_BOOL); -$timeup = optional_param('timeup', 0, PARAM_BOOL); // True if form was submitted by timer. -$scrollpos = optional_param('scrollpos', '', PARAM_RAW); +$timeup = optional_param('timeup', 0, PARAM_BOOL); // True if form was submitted by timer. +$scrollpos = optional_param('scrollpos', '', PARAM_RAW); $transaction = $DB->start_delegated_transaction(); $attemptobj = quiz_attempt::create($attemptid); diff --git a/mod/quiz/report/attemptsreport_table.php b/mod/quiz/report/attemptsreport_table.php index 4334256eb18..f119da0b8a4 100644 --- a/mod/quiz/report/attemptsreport_table.php +++ b/mod/quiz/report/attemptsreport_table.php @@ -152,7 +152,11 @@ abstract class quiz_attempts_report_table extends table_sql { * @return string HTML content to go inside the td. */ public function col_state($attempt) { - return quiz_attempt::state_name($attempt->state); + if (!is_null($attempt->attempt)) { + return quiz_attempt::state_name($attempt->state); + } else { + return '-'; + } } /** diff --git a/mod/quiz/report/overview/overviewgraph.php b/mod/quiz/report/overview/overviewgraph.php index c450615d001..6583ef95708 100644 --- a/mod/quiz/report/overview/overviewgraph.php +++ b/mod/quiz/report/overview/overviewgraph.php @@ -89,7 +89,9 @@ while ($bands > 20 || $bands <= 10) { } } -$bands = ceil($bands); +// See MDL-34589. Using doubles as array keys causes problems in PHP 5.4, +// hence the explicit cast to int. +$bands = (int) ceil($bands); $bandwidth = $quiz->grade / $bands; $bandlabels = array(); for ($i = 1; $i <= $bands; $i++) { diff --git a/mod/quiz/report/reportlib.php b/mod/quiz/report/reportlib.php index d3e4e998d14..344513e5afe 100644 --- a/mod/quiz/report/reportlib.php +++ b/mod/quiz/report/reportlib.php @@ -191,6 +191,11 @@ function quiz_report_qm_filter_select($quiz, $quizattemptsalias = 'quiza') { */ function quiz_report_grade_bands($bandwidth, $bands, $quizid, $userids = array()) { global $DB; + if (!is_int($bands)) { + debugging('$bands passed to quiz_report_grade_bands must be an integer. (' . + gettype($bands) . ' passed.)', DEBUG_DEVELOPER); + $bands = (int) $bands; + } if ($userids) { list($usql, $params) = $DB->get_in_or_equal($userids, SQL_PARAMS_NAMED, 'u'); @@ -220,7 +225,7 @@ ORDER BY $data = $DB->get_records_sql_menu($sql, $params); // We need to create array elements with values 0 at indexes where there is no element. - $data = $data + array_fill(0, $bands+1, 0); + $data = $data + array_fill(0, $bands + 1, 0); ksort($data); // Place the maximum (prefect grade) into the last band i.e. make last diff --git a/mod/quiz/review.php b/mod/quiz/review.php index 7bb6335d8fe..c19afaa8970 100644 --- a/mod/quiz/review.php +++ b/mod/quiz/review.php @@ -31,8 +31,8 @@ require_once($CFG->dirroot . '/mod/quiz/locallib.php'); require_once($CFG->dirroot . '/mod/quiz/report/reportlib.php'); $attemptid = required_param('attempt', PARAM_INT); -$page = optional_param('page', 0, PARAM_INT); -$showall = optional_param('showall', 0, PARAM_BOOL); +$page = optional_param('page', 0, PARAM_INT); +$showall = optional_param('showall', 0, PARAM_BOOL); $url = new moodle_url('/mod/quiz/review.php', array('attempt'=>$attemptid)); if ($page !== 0) { @@ -44,6 +44,7 @@ if ($showall !== 0) { $PAGE->set_url($url); $attemptobj = quiz_attempt::create($attemptid); +$page = $attemptobj->force_page_number_into_range($page); // Check login. require_login($attemptobj->get_course(), false, $attemptobj->get_cm()); diff --git a/mod/quiz/version.php b/mod/quiz/version.php index 03f42f1d58f..67ca371213d 100644 --- a/mod/quiz/version.php +++ b/mod/quiz/version.php @@ -25,7 +25,7 @@ defined('MOODLE_INTERNAL') || die(); -$module->version = 2012061701; // The current module version (Date: YYYYMMDDXX). +$module->version = 2012061702; // The current module version (Date: YYYYMMDDXX). $module->requires = 2012061700; // Requires this Moodle version. $module->component = 'mod_quiz'; // Full name of the plugin (used for diagnostics). $module->cron = 60; diff --git a/mod/wiki/renderer.php b/mod/wiki/renderer.php index 26ea0ff49a7..365d5bc1d69 100644 --- a/mod/wiki/renderer.php +++ b/mod/wiki/renderer.php @@ -390,6 +390,9 @@ class mod_wiki_renderer extends plugin_renderer_base { } } else { $group = groups_get_group($subwiki->groupid); + if (!$group) { + return; + } $users = groups_get_members($subwiki->groupid); foreach ($users as $user) { $options[$group->id][$group->name][$group->id . '-' . $user->id] = fullname($user); diff --git a/mod/workshop/mod_form.php b/mod/workshop/mod_form.php index 87ea8002806..2a1103aec0f 100644 --- a/mod/workshop/mod_form.php +++ b/mod/workshop/mod_form.php @@ -197,6 +197,9 @@ class mod_workshop_mod_form extends moodleform_mod { $mform->addElement('date_time_selector', 'assessmentend', $label, array('optional' => true)); $mform->setAdvanced('assessmentend'); + $coursecontext = context_course::instance($this->course->id); + plagiarism_get_form_elements_module($mform, $coursecontext); + // Common module settings, Restrict availability, Activity completion etc. ---- $features = array('groups'=>true, 'groupings'=>true, 'groupmembersonly'=>true, 'outcomes'=>true, 'gradecat'=>false, 'idnumber'=>false); diff --git a/mod/workshop/renderer.php b/mod/workshop/renderer.php index eeee5ad59a9..f6172da4b7d 100644 --- a/mod/workshop/renderer.php +++ b/mod/workshop/renderer.php @@ -82,6 +82,7 @@ class mod_workshop_renderer extends plugin_renderer_base { * @return string HTML */ protected function render_workshop_submission(workshop_submission $submission) { + global $CFG; $o = ''; // output HTML code $anonymous = $submission->is_anonymous(); @@ -134,6 +135,15 @@ class mod_workshop_renderer extends plugin_renderer_base { $content = format_text($submission->content, $submission->contentformat, array('overflowdiv'=>true)); $content = file_rewrite_pluginfile_urls($content, 'pluginfile.php', $this->page->context->id, 'mod_workshop', 'submission_content', $submission->id); + if (!empty($content)) { + if (!empty($CFG->enableplagiarism)) { + require_once($CFG->libdir.'/plagiarismlib.php'); + $content .= plagiarism_get_links(array('userid' => $submission->authorid, + 'content' => $submission->content, + 'cmid' => $this->page->cm->id, + 'course' => $this->page->course)); + } + } $o .= $this->output->container($content, 'content'); $o .= $this->helper_submission_attachments($submission->id, 'html'); @@ -767,6 +777,14 @@ class mod_workshop_renderer extends plugin_renderer_base { } else if ($format == 'text') { $outputfiles .= $linktxt . PHP_EOL; } + + if (!empty($CFG->enableplagiarism)) { + require_once($CFG->libdir.'/plagiarismlib.php'); + $outputfiles .= plagiarism_get_links(array('userid' => $file->get_userid(), + 'file' => $file, + 'cmid' => $this->page->cm->id, + 'course' => $this->page->course->id)); + } } if ($format == 'html') { diff --git a/mod/workshop/submission.php b/mod/workshop/submission.php index e17f13bf824..3d56078d02e 100644 --- a/mod/workshop/submission.php +++ b/mod/workshop/submission.php @@ -207,6 +207,22 @@ if ($edit) { } // store the updated values or re-save the new submission (re-saving needed because URLs are now rewritten) $DB->update_record('workshop_submissions', $formdata); + + // send submitted content for plagiarism detection + $fs = get_file_storage(); + $files = $fs->get_area_files($workshop->context->id, 'mod_workshop', 'submission_attachment', $submission->id); + $eventdata = new stdClass(); + $eventdata->modulename = 'workshop'; + $eventdata->cmid = $cm->id; + $eventdata->itemid = $submission->id; + $eventdata->courseid = $course->id; + $eventdata->userid = $USER->id; + $eventdata->content = $formdata->content; + if ($files) { + $eventdata->pathnamehashes = array_keys($files); + } + events_trigger('assessable_content_uploaded', $eventdata); + redirect($workshop->submission_url($formdata->id)); } } @@ -265,6 +281,10 @@ if (trim($workshop->instructauthors)) { // if in edit mode, display the form to edit the submission if ($edit) { + if (!empty($CFG->enableplagiarism)) { + require_once($CFG->libdir.'/plagiarismlib.php'); + echo plagiarism_print_disclosure($cm->id); + } $mform->display(); echo $output->footer(); die(); diff --git a/question/format/examview/format.php b/question/format/examview/format.php index dc0481a20cd..f1acd3424c8 100644 --- a/question/format/examview/format.php +++ b/question/format/examview/format.php @@ -26,7 +26,7 @@ defined('MOODLE_INTERNAL') || die(); -require_once ($CFG->libdir . '/xmlize.php'); +require_once($CFG->libdir . '/xmlize.php'); /** @@ -46,52 +46,74 @@ class qformat_examview extends qformat_default { 'mtf' => 99, 'nr' => NUMERICAL, 'pr' => 99, - 'es' => 99, + 'es' => ESSAY, 'ca' => 99, 'ot' => 99, - 'sa' => ESSAY + 'sa' => SHORTANSWER ); public $matching_questions = array(); - function provide_import() { + public function provide_import() { return true; } + public function mime_type() { + return 'application/xml'; + } + /** * unxmlise reconstructs part of the xml data structure in order * to identify the actual data therein * @param array $xml section of the xml data structure * @return string data with evrything else removed */ - function unxmlise( $xml ) { - // if it's not an array then it's probably just data + protected function unxmlise( $xml ) { + // If it's not an array then it's probably just data. if (!is_array($xml)) { $text = s($xml); - } - else { - // otherwise parse the array + } else { + // Otherwise parse the array. $text = ''; - foreach ($xml as $tag=>$data) { - // if tag is '@' then it's attributes and we don't care + foreach ($xml as $tag => $data) { + // If tag is '@' then it's attributes and we don't care. if ($tag!=='@') { $text = $text . $this->unxmlise( $data ); } } } - // currently we throw the tags we found + // Currently we throw the tags we found. $text = strip_tags($text); return $text; } + protected function text_field($text) { + return array( + 'text' => htmlspecialchars(trim($text), ENT_NOQUOTES), + 'format' => FORMAT_HTML, + 'files' => array(), + ); + } - function parse_matching_groups($matching_groups) - { + protected function add_blank_combined_feedback($question) { + $question->correctfeedback['text'] = ''; + $question->correctfeedback['format'] = $question->questiontextformat; + $question->correctfeedback['files'] = array(); + $question->partiallycorrectfeedback['text'] = ''; + $question->partiallycorrectfeedback['format'] = $question->questiontextformat; + $question->partiallycorrectfeedback['files'] = array(); + $question->incorrectfeedback['text'] = ''; + $question->incorrectfeedback['format'] = $question->questiontextformat; + $question->incorrectfeedback['files'] = array(); + return $question; + } + + protected function parse_matching_groups($matching_groups) { if (empty($matching_groups)) { return; } - foreach($matching_groups as $match_group) { - $newgroup = NULL; + foreach ($matching_groups as $match_group) { + $newgroup = new stdClass(); $groupname = trim($match_group['@']['name']); $questiontext = $this->unxmlise($match_group['#']['text'][0]['#']); $newgroup->questiontext = trim($questiontext); @@ -99,8 +121,8 @@ class qformat_examview extends qformat_default { $newgroup->subquestions = array(); $newgroup->subanswers = array(); $choices = $match_group['#']['choices']['0']['#']; - foreach($choices as $key => $value) { - if (strpos(trim($key),'choice-') !== FALSE) { + foreach ($choices as $key => $value) { + if (strpos(trim($key), 'choice-') !== false) { $key = strtoupper(trim(str_replace('choice-', '', $key))); $newgroup->subchoices[$key] = trim($value['0']['#']); } @@ -109,8 +131,7 @@ class qformat_examview extends qformat_default { } } - function parse_ma($qrec, $groupname) - { + protected function parse_ma($qrec, $groupname) { $match_group = $this->matching_questions[$groupname]; $phrase = trim($this->unxmlise($qrec['text']['0']['#'])); $answer = trim($this->unxmlise($qrec['answer']['0']['#'])); @@ -118,25 +139,27 @@ class qformat_examview extends qformat_default { $match_group->subquestions[] = $phrase; $match_group->subanswers[] = $match_group->subchoices[$answer]; $this->matching_questions[$groupname] = $match_group; - return NULL; + return null; } - function process_matches(&$questions) - { + protected function process_matches(&$questions) { if (empty($this->matching_questions)) { return; } - foreach($this->matching_questions as $match_group) { + foreach ($this->matching_questions as $match_group) { $question = $this->defaultquestion(); $htmltext = s($match_group->questiontext); $question->questiontext = $htmltext; - $question->name = $question->questiontext; + $question->questiontextformat = FORMAT_HTML; + $question->questiontextfiles = array(); + $question->name = shorten_text( $question->questiontext, 250 ); $question->qtype = MATCH; + $question = $this->add_blank_combined_feedback($question); $question->subquestions = array(); $question->subanswers = array(); - foreach($match_group->subquestions as $key => $value) { + foreach ($match_group->subquestions as $key => $value) { $htmltext = s($value); - $question->subquestions[] = $htmltext; + $question->subquestions[] = $this->text_field($htmltext); $htmltext = s($match_group->subanswers[$key]); $question->subanswers[] = $htmltext; @@ -145,28 +168,28 @@ class qformat_examview extends qformat_default { } } - function cleanUnicode($text) { + protected function cleanunicode($text) { return str_replace('’', "'", $text); } protected function readquestions($lines) { - /// Parses an array of lines into an array of questions, - /// where each item is a question object as defined by - /// readquestion(). + // Parses an array of lines into an array of questions, + // where each item is a question object as defined by + // readquestion(). $questions = array(); $currentquestion = array(); $text = implode($lines, ' '); - $text = $this->cleanUnicode($text); + $text = $this->cleanunicode($text); $xml = xmlize($text, 0); if (!empty($xml['examview']['#']['matching-group'])) { $this->parse_matching_groups($xml['examview']['#']['matching-group']); } - $questionNode = $xml['examview']['#']['question']; - foreach($questionNode as $currentquestion) { + $questionnode = $xml['examview']['#']['question']; + foreach ($questionnode as $currentquestion) { if ($question = $this->readquestion($currentquestion)) { $questions[] = $question; } @@ -175,139 +198,136 @@ class qformat_examview extends qformat_default { $this->process_matches($questions); return $questions; } - // end readquestions - function readquestion($qrec) - { + public function readquestion($qrec) { $type = trim($qrec['@']['type']); $question = $this->defaultquestion(); if (array_key_exists($type, $this->qtypes)) { $question->qtype = $this->qtypes[$type]; - } - else { + } else { $question->qtype = null; } $question->single = 1; - // Only one answer is allowed + // Only one answer is allowed. $htmltext = $this->unxmlise($qrec['#']['text'][0]['#']); $question->questiontext = $htmltext; + $question->questiontextformat = FORMAT_HTML; + $question->questiontextfiles = array(); $question->name = shorten_text( $question->questiontext, 250 ); switch ($question->qtype) { - case MULTICHOICE: - $question = $this->parse_mc($qrec['#'], $question); - break; - case MATCH: - $groupname = trim($qrec['@']['group']); - $question = $this->parse_ma($qrec['#'], $groupname); - break; - case TRUEFALSE: - $question = $this->parse_tf_yn($qrec['#'], $question); - break; - case SHORTANSWER: - $question = $this->parse_co($qrec['#'], $question); - break; - case ESSAY: - $question = $this->parse_sa($qrec['#'], $question); - break; - case NUMERICAL: - $question = $this->parse_nr($qrec['#'], $question); - break; - break; + case MULTICHOICE: + $question = $this->parse_mc($qrec['#'], $question); + break; + case MATCH: + $groupname = trim($qrec['@']['group']); + $question = $this->parse_ma($qrec['#'], $groupname); + break; + case TRUEFALSE: + $question = $this->parse_tf_yn($qrec['#'], $question); + break; + case SHORTANSWER: + $question = $this->parse_co($qrec['#'], $question); + break; + case ESSAY: + $question = $this->parse_es($qrec['#'], $question); + break; + case NUMERICAL: + $question = $this->parse_nr($qrec['#'], $question); + break; + break; default: - print("

Question type ".$type." import not supported for ".$question->questiontext."

"); - $question = NULL; + print("

Question type ".$type." import not supported for ".$question->questiontext."

"); + $question = null; } - // end switch ($question->qtype) return $question; } - // end readquestion - function parse_tf_yn($qrec, $question) - { + protected function parse_tf_yn($qrec, $question) { $choices = array('T' => 1, 'Y' => 1, 'F' => 0, 'N' => 0 ); $answer = trim($qrec['answer'][0]['#']); $question->answer = $choices[$answer]; $question->correctanswer = $question->answer; if ($question->answer == 1) { - $question->feedbacktrue = 'Correct'; - $question->feedbackfalse = 'Incorrect'; + $question->feedbacktrue = $this->text_field('Correct'); + $question->feedbackfalse = $this->text_field('Incorrect'); } else { - $question->feedbacktrue = 'Incorrect'; - $question->feedbackfalse = 'Correct'; + $question->feedbacktrue = $this->text_field('Incorrect'); + $question->feedbackfalse = $this->text_field('Correct'); } return $question; } - function parse_mc($qrec, $question) - { + protected function parse_mc($qrec, $question) { + $question = $this->add_blank_combined_feedback($question); $answer = 'choice-'.strtolower(trim($qrec['answer'][0]['#'])); $choices = $qrec['choices'][0]['#']; - foreach($choices as $key => $value) { - if (strpos(trim($key),'choice-') !== FALSE) { + foreach ($choices as $key => $value) { + if (strpos(trim($key), 'choice-') !== false) { - $question->answer[$key] = s($this->unxmlise($value[0]['#'])); + $question->answer[$key] = $this->text_field(s($this->unxmlise($value[0]['#']))); if (strcmp($key, $answer) == 0) { $question->fraction[$key] = 1; - $question->feedback[$key] = 'Correct'; + $question->feedback[$key] = $this->text_field('Correct'); } else { $question->fraction[$key] = 0; - $question->feedback[$key] = 'Incorrect'; + $question->feedback[$key] = $this->text_field('Incorrect'); } } } return $question; } - function parse_co($qrec, $question) - { + protected function parse_co($qrec, $question) { $question->usecase = 0; $answer = trim($this->unxmlise($qrec['answer'][0]['#'])); $answer = strip_tags( $answer ); - $answers = explode("\n",$answer); + $answers = explode("\n", $answer); - foreach($answers as $key => $value) { + foreach ($answers as $key => $value) { $value = trim($value); if (strlen($value) > 0) { $question->answer[$key] = $value; $question->fraction[$key] = 1; - $question->feedback[$key] = "Correct"; + $question->feedback[$key] = $this->text_field("Correct"); } } return $question; } - function parse_sa($qrec, $question) { + protected function parse_es($qrec, $question) { $feedback = trim($this->unxmlise($qrec['answer'][0]['#'])); + $question->graderinfo = $this->text_field($feedback); $question->feedback = $feedback; + $question->responseformat = 'editor'; + $question->responsefieldlines = 15; + $question->attachments = 0; $question->fraction = 0; return $question; } - function parse_nr($qrec, $question) - { + protected function parse_nr($qrec, $question) { $answer = trim($this->unxmlise($qrec['answer'][0]['#'])); $answer = strip_tags( $answer ); - $answers = explode("\n",$answer); + $answers = explode("\n", $answer); - foreach($answers as $key => $value) { + foreach ($answers as $key => $value) { $value = trim($value); if (is_numeric($value)) { $errormargin = 0; $question->answer[$key] = $value; $question->fraction[$key] = 1; - $question->feedback[$key] = "Correct"; - $question->min[$key] = $question->answer[$key] - $errormargin; - $question->max[$key] = $question->answer[$key] + $errormargin; + $question->feedback[$key] = $this->text_field("Correct"); + $question->tolerance[$key] = $errormargin; } } return $question; } } -// end class +// End class. diff --git a/question/format/examview/tests/fixtures/questions.examview.xml b/question/format/examview/tests/fixtures/questions.examview.xml new file mode 100644 index 00000000000..5abeccd0c19 --- /dev/null +++ b/question/format/examview/tests/fixtures/questions.examview.xml @@ -0,0 +1,164 @@ + + +

+ Moodle Example + A +
+ + + ansi + Times New Roman + variable + roman + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 1 + 13 + + #000000 + + + 1 + 11 + + #000000 + + + 1 + 11 + #000000 + + + 1 + 11 + #000000 + + + 1 + 11 + #000000 + + + Name: ________________________ Class: ___________________ Date: __________ ID: + Name: ________________________ ID: + + + + + True/False +Indicate whether the sentence or statement is true or false. + Modified True/False +Indicate whether the sentence or statement is true or false. If false, change the identified word or phrase to make the sentence or statement true. + Multiple Choice +Identify the letter of the choice that best completes the statement or answers the question. + Yes/No +Indicate whether you agree with the sentence or statement. + Numeric Response + Completion +Complete each sentence or statement. + Matching + Short Answer + Problem + Essay + Case + Other + + This is a T/F question. Tim and Jean-Michael are great people. + Examview allows for this “Rationale” field + T + + + This is an example of a multiple choice question. This is only an ________ + + example + the real thing + a true false question + none of these + + A + + + This is a numeric response question. How much is 12 * 2? + 24 + + -1 + + + + This is a matching question type. + + + Question 1 + Question 2 + Question 3 + Question 4 + + + + This is question 1. + A + + + This is question 2. + B + + + This is question 3. + C + + + This is a short answer question. This is a ___________ answer question. + short + + -1 + + + + This is an essay question. I am not sure if an answer is needed. + This is the answer in Examview. I am curious to see how this shows in Moodle. + + -1 + + + diff --git a/repository/lib.php b/repository/lib.php index dd00d82e353..2093c7d1e4c 100644 --- a/repository/lib.php +++ b/repository/lib.php @@ -899,6 +899,9 @@ abstract class repository { $repositories = array(); if (isset($args['accepted_types'])) { $accepted_types = $args['accepted_types']; + if (is_array($accepted_types) && in_array('*', $accepted_types)) { + $accepted_types = '*'; + } } else { $accepted_types = '*'; } diff --git a/repository/s3/README_MOODLE.txt b/repository/s3/README_MOODLE.txt new file mode 100644 index 00000000000..a6c5f9281f1 --- /dev/null +++ b/repository/s3/README_MOODLE.txt @@ -0,0 +1,10 @@ +- S3.php - + +Amazon S3 PHP Class + +Cloned from git://github.com/tpyo/amazon-s3-php-class.git +Branch master +On July 23rd 2012 + +https://github.com/tpyo/amazon-s3-php-class +http://undesigned.org.za/2007/10/22/amazon-s3-php-class diff --git a/repository/s3/S3.php b/repository/s3/S3.php index dadfb5ab5e3..247d6c382e9 100644 --- a/repository/s3/S3.php +++ b/repository/s3/S3.php @@ -1,7 +1,8 @@ $host, 'type' => $type, 'user' => null, 'pass' => 'null'); + } + + + /** + * Set the error mode to exceptions + * + * @param boolean $enabled Enable exceptions + * @return void + */ + public static function setExceptions($enabled = true) + { + self::$useExceptions = $enabled; + } + + + /** + * Set signing key + * + * @param string $keyPairId AWS Key Pair ID + * @param string $signingKey Private Key + * @param boolean $isFile Load private key from file, set to false to load string + * @return boolean + */ + public static function setSigningKey($keyPairId, $signingKey, $isFile = true) + { + self::$__signingKeyPairId = $keyPairId; + if ((self::$__signingKeyResource = openssl_pkey_get_private($isFile ? + file_get_contents($signingKey) : $signingKey)) !== false) return true; + self::__triggerError('S3::setSigningKey(): Unable to open load private key: '.$signingKey, __FILE__, __LINE__); + return false; + } + + + /** + * Free signing key from memory, MUST be called if you are using setSigningKey() + * + * @return void + */ + public static function freeSigningKey() + { + if (self::$__signingKeyResource !== false) + openssl_free_key(self::$__signingKeyResource); + } + + + /** + * Internal error handler + * + * @internal Internal error handler + * @param string $message Error message + * @param string $file Filename + * @param integer $line Line number + * @param integer $code Error code + * @return void + */ + private static function __triggerError($message, $file, $line, $code = 0) + { + if (self::$useExceptions) + throw new S3Exception($message, $file, $line, $code); + else + trigger_error($message, E_USER_WARNING); + } + + /** * Get a list of buckets * * @param boolean $detailed Returns detailed bucket list when true * @return array | false */ - public static function listBuckets($detailed = false) { - $rest = new S3Request('GET', '', ''); + public static function listBuckets($detailed = false) + { + $rest = new S3Request('GET', '', '', self::$endpoint); $rest = $rest->getResponse(); if ($rest->error === false && $rest->code !== 200) $rest->error = array('code' => $rest->code, 'message' => 'Unexpected HTTP status'); - if ($rest->error !== false) { - trigger_error(sprintf("S3::listBuckets(): [%s] %s", $rest->error['code'], $rest->error['message']), E_USER_WARNING); + if ($rest->error !== false) + { + self::__triggerError(sprintf("S3::listBuckets(): [%s] %s", $rest->error['code'], + $rest->error['message']), __FILE__, __LINE__); return false; } - $results = array(); //var_dump($rest->body); + $results = array(); if (!isset($rest->body->Buckets)) return $results; - if ($detailed) { + if ($detailed) + { if (isset($rest->body->Owner, $rest->body->Owner->ID, $rest->body->Owner->DisplayName)) $results['owner'] = array( 'id' => (string)$rest->body->Owner->ID, 'name' => (string)$rest->body->Owner->ID @@ -118,10 +272,13 @@ class S3 { * @param string $marker Marker (last file listed) * @param string $maxKeys Max keys (maximum number of keys to return) * @param string $delimiter Delimiter + * @param boolean $returnCommonPrefixes Set to true to return CommonPrefixes * @return array | false */ - public static function getBucket($bucket, $prefix = null, $marker = null, $maxKeys = null, $delimiter = null) { - $rest = new S3Request('GET', $bucket, ''); + public static function getBucket($bucket, $prefix = null, $marker = null, $maxKeys = null, $delimiter = null, $returnCommonPrefixes = false) + { + $rest = new S3Request('GET', $bucket, '', self::$endpoint); + if ($maxKeys == 0) $maxKeys = null; if ($prefix !== null && $prefix !== '') $rest->setParameter('prefix', $prefix); if ($marker !== null && $marker !== '') $rest->setParameter('marker', $marker); if ($maxKeys !== null && $maxKeys !== '') $rest->setParameter('max-keys', $maxKeys); @@ -129,49 +286,68 @@ class S3 { $response = $rest->getResponse(); if ($response->error === false && $response->code !== 200) $response->error = array('code' => $response->code, 'message' => 'Unexpected HTTP status'); - if ($response->error !== false) { - trigger_error(sprintf("S3::getBucket(): [%s] %s", $response->error['code'], $response->error['message']), E_USER_WARNING); + if ($response->error !== false) + { + self::__triggerError(sprintf("S3::getBucket(): [%s] %s", + $response->error['code'], $response->error['message']), __FILE__, __LINE__); return false; } $results = array(); - $lastMarker = null; + $nextMarker = null; if (isset($response->body, $response->body->Contents)) - foreach ($response->body->Contents as $c) { + foreach ($response->body->Contents as $c) + { + $results[(string)$c->Key] = array( + 'name' => (string)$c->Key, + 'time' => strtotime((string)$c->LastModified), + 'size' => (int)$c->Size, + 'hash' => substr((string)$c->ETag, 1, -1) + ); + $nextMarker = (string)$c->Key; + } + + if ($returnCommonPrefixes && isset($response->body, $response->body->CommonPrefixes)) + foreach ($response->body->CommonPrefixes as $c) + $results[(string)$c->Prefix] = array('prefix' => (string)$c->Prefix); + + if (isset($response->body, $response->body->IsTruncated) && + (string)$response->body->IsTruncated == 'false') return $results; + + if (isset($response->body, $response->body->NextMarker)) + $nextMarker = (string)$response->body->NextMarker; + + // Loop through truncated results if maxKeys isn't specified + if ($maxKeys == null && $nextMarker !== null && (string)$response->body->IsTruncated == 'true') + do + { + $rest = new S3Request('GET', $bucket, '', self::$endpoint); + if ($prefix !== null && $prefix !== '') $rest->setParameter('prefix', $prefix); + $rest->setParameter('marker', $nextMarker); + if ($delimiter !== null && $delimiter !== '') $rest->setParameter('delimiter', $delimiter); + + if (($response = $rest->getResponse()) == false || $response->code !== 200) break; + + if (isset($response->body, $response->body->Contents)) + foreach ($response->body->Contents as $c) + { $results[(string)$c->Key] = array( 'name' => (string)$c->Key, 'time' => strtotime((string)$c->LastModified), 'size' => (int)$c->Size, 'hash' => substr((string)$c->ETag, 1, -1) ); - $lastMarker = (string)$c->Key; - //$response->body->IsTruncated = 'true'; break; + $nextMarker = (string)$c->Key; } + if ($returnCommonPrefixes && isset($response->body, $response->body->CommonPrefixes)) + foreach ($response->body->CommonPrefixes as $c) + $results[(string)$c->Prefix] = array('prefix' => (string)$c->Prefix); - if (isset($response->body->IsTruncated) && - (string)$response->body->IsTruncated == 'false') return $results; + if (isset($response->body, $response->body->NextMarker)) + $nextMarker = (string)$response->body->NextMarker; - // Loop through truncated results if maxKeys isn't specified - if ($maxKeys == null && $lastMarker !== null && (string)$response->body->IsTruncated == 'true') - do { - $rest = new S3Request('GET', $bucket, ''); - if ($prefix !== null && $prefix !== '') $rest->setParameter('prefix', $prefix); - $rest->setParameter('marker', $lastMarker); - if ($delimiter !== null && $delimiter !== '') $rest->setParameter('delimiter', $delimiter); - - if (($response = $rest->getResponse(true)) == false || $response->code !== 200) break; - if (isset($response->body, $response->body->Contents)) - foreach ($response->body->Contents as $c) { - $results[(string)$c->Key] = array( - 'name' => (string)$c->Key, - 'time' => strtotime((string)$c->LastModified), - 'size' => (int)$c->Size, - 'hash' => substr((string)$c->ETag, 1, -1) - ); - $lastMarker = (string)$c->Key; - } } while ($response !== false && (string)$response->body->IsTruncated == 'true'); return $results; @@ -186,14 +362,16 @@ class S3 { * @param string $location Set as "EU" to create buckets hosted in Europe * @return boolean */ - public static function putBucket($bucket, $acl = self::ACL_PRIVATE, $location = false) { - $rest = new S3Request('PUT', $bucket, ''); + public static function putBucket($bucket, $acl = self::ACL_PRIVATE, $location = false) + { + $rest = new S3Request('PUT', $bucket, '', self::$endpoint); $rest->setAmzHeader('x-amz-acl', $acl); - if ($location !== false) { + if ($location !== false) + { $dom = new DOMDocument; $createBucketConfiguration = $dom->createElement('CreateBucketConfiguration'); - $locationConstraint = $dom->createElement('LocationConstraint', strtoupper($location)); + $locationConstraint = $dom->createElement('LocationConstraint', $location); $createBucketConfiguration->appendChild($locationConstraint); $dom->appendChild($createBucketConfiguration); $rest->data = $dom->saveXML(); @@ -204,9 +382,10 @@ class S3 { if ($rest->error === false && $rest->code !== 200) $rest->error = array('code' => $rest->code, 'message' => 'Unexpected HTTP status'); - if ($rest->error !== false) { - trigger_error(sprintf("S3::putBucket({$bucket}, {$acl}, {$location}): [%s] %s", - $rest->error['code'], $rest->error['message']), E_USER_WARNING); + if ($rest->error !== false) + { + self::__triggerError(sprintf("S3::putBucket({$bucket}, {$acl}, {$location}): [%s] %s", + $rest->error['code'], $rest->error['message']), __FILE__, __LINE__); return false; } return true; @@ -219,14 +398,16 @@ class S3 { * @param string $bucket Bucket name * @return boolean */ - public static function deleteBucket($bucket) { - $rest = new S3Request('DELETE', $bucket); + public static function deleteBucket($bucket) + { + $rest = new S3Request('DELETE', $bucket, '', self::$endpoint); $rest = $rest->getResponse(); if ($rest->error === false && $rest->code !== 204) $rest->error = array('code' => $rest->code, 'message' => 'Unexpected HTTP status'); - if ($rest->error !== false) { - trigger_error(sprintf("S3::deleteBucket({$bucket}): [%s] %s", - $rest->error['code'], $rest->error['message']), E_USER_WARNING); + if ($rest->error !== false) + { + self::__triggerError(sprintf("S3::deleteBucket({$bucket}): [%s] %s", + $rest->error['code'], $rest->error['message']), __FILE__, __LINE__); return false; } return true; @@ -240,14 +421,15 @@ class S3 { * @param mixed $md5sum Use MD5 hash (supply a string if you want to use your own) * @return array | false */ - public static function inputFile($file, $md5sum = true) { - if (!file_exists($file) || !is_file($file) || !is_readable($file)) { - trigger_error('S3::inputFile(): Unable to open input file: '.$file, E_USER_WARNING); + public static function inputFile($file, $md5sum = true) + { + if (!file_exists($file) || !is_file($file) || !is_readable($file)) + { + self::__triggerError('S3::inputFile(): Unable to open input file: '.$file, __FILE__, __LINE__); return false; } - return array('file' => $file, 'size' => filesize($file), - 'md5sum' => $md5sum !== false ? (is_string($md5sum) ? $md5sum : - base64_encode(md5_file($file, true))) : ''); + return array('file' => $file, 'size' => filesize($file), 'md5sum' => $md5sum !== false ? + (is_string($md5sum) ? $md5sum : base64_encode(md5_file($file, true))) : ''); } @@ -259,9 +441,11 @@ class S3 { * @param string $md5sum MD5 hash to send (optional) * @return array | false */ - public static function inputResource(&$resource, $bufferSize, $md5sum = '') { - if (!is_resource($resource) || $bufferSize <= 0) { - trigger_error('S3::inputResource(): Invalid resource or buffer size', E_USER_WARNING); + public static function inputResource(&$resource, $bufferSize, $md5sum = '') + { + if (!is_resource($resource) || $bufferSize < 0) + { + self::__triggerError('S3::inputResource(): Invalid resource or buffer size', __FILE__, __LINE__); return false; } $input = array('size' => $bufferSize, 'md5sum' => $md5sum); @@ -279,13 +463,15 @@ class S3 { * @param constant $acl ACL constant * @param array $metaHeaders Array of x-amz-meta-* headers * @param array $requestHeaders Array of request headers or content type as a string + * @param constant $storageClass Storage class constant * @return boolean */ - public static function putObject($input, $bucket, $uri, $acl = self::ACL_PRIVATE, $metaHeaders = array(), $requestHeaders = array()) { - if ($input == false) return false; - $rest = new S3Request('PUT', $bucket, $uri); + public static function putObject($input, $bucket, $uri, $acl = self::ACL_PRIVATE, $metaHeaders = array(), $requestHeaders = array(), $storageClass = self::STORAGE_CLASS_STANDARD) + { + if ($input === false) return false; + $rest = new S3Request('PUT', $bucket, $uri, self::$endpoint); - if (is_string($input)) $input = array( + if (!is_array($input)) $input = array( 'data' => $input, 'size' => strlen($input), 'md5sum' => base64_encode(md5($input, true)) ); @@ -299,7 +485,7 @@ class S3 { $rest->data = $input['data']; // Content-Length (required) - if (isset($input['size']) && $input['size'] > -1) + if (isset($input['size']) && $input['size'] >= 0) $rest->size = $input['size']; else { if (isset($input['file'])) @@ -315,7 +501,8 @@ class S3 { $input['type'] = $requestHeaders; // Content-Type - if (!isset($input['type'])) { + if (!isset($input['type'])) + { if (isset($requestHeaders['Content-Type'])) $input['type'] =& $requestHeaders['Content-Type']; elseif (isset($input['file'])) @@ -324,8 +511,12 @@ class S3 { $input['type'] = 'application/octet-stream'; } + if ($storageClass !== self::STORAGE_CLASS_STANDARD) // Storage class + $rest->setAmzHeader('x-amz-storage-class', $storageClass); + // We need to post with Content-Length and Content-Type, MD5 is optional - if ($rest->size > 0 && ($rest->fp !== false || $rest->data !== false)) { + if ($rest->size >= 0 && ($rest->fp !== false || $rest->data !== false)) + { $rest->setHeader('Content-Type', $input['type']); if (isset($input['md5sum'])) $rest->setHeader('Content-MD5', $input['md5sum']); @@ -337,8 +528,10 @@ class S3 { if ($rest->response->error === false && $rest->response->code !== 200) $rest->response->error = array('code' => $rest->response->code, 'message' => 'Unexpected HTTP status'); - if ($rest->response->error !== false) { - trigger_error(sprintf("S3::putObject(): [%s] %s", $rest->response->error['code'], $rest->response->error['message']), E_USER_WARNING); + if ($rest->response->error !== false) + { + self::__triggerError(sprintf("S3::putObject(): [%s] %s", + $rest->response->error['code'], $rest->response->error['message']), __FILE__, __LINE__); return false; } return true; @@ -356,7 +549,8 @@ class S3 { * @param string $contentType Content type * @return boolean */ - public static function putObjectFile($file, $bucket, $uri, $acl = self::ACL_PRIVATE, $metaHeaders = array(), $contentType = null) { + public static function putObjectFile($file, $bucket, $uri, $acl = self::ACL_PRIVATE, $metaHeaders = array(), $contentType = null) + { return self::putObject(self::inputFile($file), $bucket, $uri, $acl, $metaHeaders, $contentType); } @@ -372,7 +566,8 @@ class S3 { * @param string $contentType Content type * @return boolean */ - public static function putObjectString($string, $bucket, $uri, $acl = self::ACL_PRIVATE, $metaHeaders = array(), $contentType = 'text/plain') { + public static function putObjectString($string, $bucket, $uri, $acl = self::ACL_PRIVATE, $metaHeaders = array(), $contentType = 'text/plain') + { return self::putObject($string, $bucket, $uri, $acl, $metaHeaders, $contentType); } @@ -385,9 +580,11 @@ class S3 { * @param mixed $saveTo Filename or resource to write to * @return mixed */ - public static function getObject($bucket, $uri, $saveTo = false) { - $rest = new S3Request('GET', $bucket, $uri); - if ($saveTo !== false) { + public static function getObject($bucket, $uri, $saveTo = false) + { + $rest = new S3Request('GET', $bucket, $uri, self::$endpoint); + if ($saveTo !== false) + { if (is_resource($saveTo)) $rest->fp =& $saveTo; else @@ -400,9 +597,10 @@ class S3 { if ($rest->response->error === false && $rest->response->code !== 200) $rest->response->error = array('code' => $rest->response->code, 'message' => 'Unexpected HTTP status'); - if ($rest->response->error !== false) { - trigger_error(sprintf("S3::getObject({$bucket}, {$uri}): [%s] %s", - $rest->response->error['code'], $rest->response->error['message']), E_USER_WARNING); + if ($rest->response->error !== false) + { + self::__triggerError(sprintf("S3::getObject({$bucket}, {$uri}): [%s] %s", + $rest->response->error['code'], $rest->response->error['message']), __FILE__, __LINE__); return false; } return $rest->response; @@ -417,14 +615,16 @@ class S3 { * @param boolean $returnInfo Return response information * @return mixed | false */ - public static function getObjectInfo($bucket, $uri, $returnInfo = true) { - $rest = new S3Request('HEAD', $bucket, $uri); + public static function getObjectInfo($bucket, $uri, $returnInfo = true) + { + $rest = new S3Request('HEAD', $bucket, $uri, self::$endpoint); $rest = $rest->getResponse(); if ($rest->error === false && ($rest->code !== 200 && $rest->code !== 404)) $rest->error = array('code' => $rest->code, 'message' => 'Unexpected HTTP status'); - if ($rest->error !== false) { - trigger_error(sprintf("S3::getObjectInfo({$bucket}, {$uri}): [%s] %s", - $rest->error['code'], $rest->error['message']), E_USER_WARNING); + if ($rest->error !== false) + { + self::__triggerError(sprintf("S3::getObjectInfo({$bucket}, {$uri}): [%s] %s", + $rest->error['code'], $rest->error['message']), __FILE__, __LINE__); return false; } return $rest->code == 200 ? $returnInfo ? $rest->headers : true : false; @@ -439,18 +639,31 @@ class S3 { * @param string $bucket Destination bucket name * @param string $uri Destination object URI * @param constant $acl ACL constant + * @param array $metaHeaders Optional array of x-amz-meta-* headers + * @param array $requestHeaders Optional array of request headers (content type, disposition, etc.) + * @param constant $storageClass Storage class constant * @return mixed | false */ - public static function copyObject($srcBucket, $srcUri, $bucket, $uri, $acl = self::ACL_PRIVATE) { - $rest = new S3Request('PUT', $bucket, $uri); + public static function copyObject($srcBucket, $srcUri, $bucket, $uri, $acl = self::ACL_PRIVATE, $metaHeaders = array(), $requestHeaders = array(), $storageClass = self::STORAGE_CLASS_STANDARD) + { + $rest = new S3Request('PUT', $bucket, $uri, self::$endpoint); + $rest->setHeader('Content-Length', 0); + foreach ($requestHeaders as $h => $v) $rest->setHeader($h, $v); + foreach ($metaHeaders as $h => $v) $rest->setAmzHeader('x-amz-meta-'.$h, $v); + if ($storageClass !== self::STORAGE_CLASS_STANDARD) // Storage class + $rest->setAmzHeader('x-amz-storage-class', $storageClass); $rest->setAmzHeader('x-amz-acl', $acl); - $rest->setAmzHeader('x-amz-copy-source', sprintf('/%s/%s', $srcBucket, $srcUri)); + $rest->setAmzHeader('x-amz-copy-source', sprintf('/%s/%s', $srcBucket, rawurlencode($srcUri))); + if (sizeof($requestHeaders) > 0 || sizeof($metaHeaders) > 0) + $rest->setAmzHeader('x-amz-metadata-directive', 'REPLACE'); + $rest = $rest->getResponse(); if ($rest->error === false && $rest->code !== 200) $rest->error = array('code' => $rest->code, 'message' => 'Unexpected HTTP status'); - if ($rest->error !== false) { - trigger_error(sprintf("S3::copyObject({$srcBucket}, {$srcUri}, {$bucket}, {$uri}): [%s] %s", - $rest->error['code'], $rest->error['message']), E_USER_WARNING); + if ($rest->error !== false) + { + self::__triggerError(sprintf("S3::copyObject({$srcBucket}, {$srcUri}, {$bucket}, {$uri}): [%s] %s", + $rest->error['code'], $rest->error['message']), __FILE__, __LINE__); return false; } return isset($rest->body->LastModified, $rest->body->ETag) ? array( @@ -468,14 +681,17 @@ class S3 { * @param string $targetPrefix Log prefix (e,g; domain.com-) * @return boolean */ - public static function setBucketLogging($bucket, $targetBucket, $targetPrefix = null) { + public static function setBucketLogging($bucket, $targetBucket, $targetPrefix = null) + { // The S3 log delivery group has to be added to the target bucket's ACP - if ($targetBucket !== null && ($acp = self::getAccessControlPolicy($targetBucket, '')) !== false) { + if ($targetBucket !== null && ($acp = self::getAccessControlPolicy($targetBucket, '')) !== false) + { // Only add permissions to the target bucket when they do not exist $aclWriteSet = false; $aclReadSet = false; foreach ($acp['acl'] as $acl) - if ($acl['type'] == 'Group' && $acl['uri'] == 'http://acs.amazonaws.com/groups/s3/LogDelivery') { + if ($acl['type'] == 'Group' && $acl['uri'] == 'http://acs.amazonaws.com/groups/s3/LogDelivery') + { if ($acl['permission'] == 'WRITE') $aclWriteSet = true; elseif ($acl['permission'] == 'READ_ACP') $aclReadSet = true; } @@ -491,7 +707,8 @@ class S3 { $dom = new DOMDocument; $bucketLoggingStatus = $dom->createElement('BucketLoggingStatus'); $bucketLoggingStatus->setAttribute('xmlns', 'http://s3.amazonaws.com/doc/2006-03-01/'); - if ($targetBucket !== null) { + if ($targetBucket !== null) + { if ($targetPrefix == null) $targetPrefix = $bucket . '-'; $loggingEnabled = $dom->createElement('LoggingEnabled'); $loggingEnabled->appendChild($dom->createElement('TargetBucket', $targetBucket)); @@ -501,7 +718,7 @@ class S3 { } $dom->appendChild($bucketLoggingStatus); - $rest = new S3Request('PUT', $bucket, ''); + $rest = new S3Request('PUT', $bucket, '', self::$endpoint); $rest->setParameter('logging', null); $rest->data = $dom->saveXML(); $rest->size = strlen($rest->data); @@ -509,9 +726,10 @@ class S3 { $rest = $rest->getResponse(); if ($rest->error === false && $rest->code !== 200) $rest->error = array('code' => $rest->code, 'message' => 'Unexpected HTTP status'); - if ($rest->error !== false) { - trigger_error(sprintf("S3::setBucketLogging({$bucket}, {$uri}): [%s] %s", - $rest->error['code'], $rest->error['message']), E_USER_WARNING); + if ($rest->error !== false) + { + self::__triggerError(sprintf("S3::setBucketLogging({$bucket}, {$targetBucket}): [%s] %s", + $rest->error['code'], $rest->error['message']), __FILE__, __LINE__); return false; } return true; @@ -527,15 +745,17 @@ class S3 { * @param string $bucket Bucket name * @return array | false */ - public static function getBucketLogging($bucket) { - $rest = new S3Request('GET', $bucket, ''); + public static function getBucketLogging($bucket) + { + $rest = new S3Request('GET', $bucket, '', self::$endpoint); $rest->setParameter('logging', null); $rest = $rest->getResponse(); if ($rest->error === false && $rest->code !== 200) $rest->error = array('code' => $rest->code, 'message' => 'Unexpected HTTP status'); - if ($rest->error !== false) { - trigger_error(sprintf("S3::getBucketLogging({$bucket}): [%s] %s", - $rest->error['code'], $rest->error['message']), E_USER_WARNING); + if ($rest->error !== false) + { + self::__triggerError(sprintf("S3::getBucketLogging({$bucket}): [%s] %s", + $rest->error['code'], $rest->error['message']), __FILE__, __LINE__); return false; } if (!isset($rest->body->LoggingEnabled)) return false; // No logging @@ -552,7 +772,8 @@ class S3 { * @param string $bucket Bucket name * @return boolean */ - public static function disableBucketLogging($bucket) { + public static function disableBucketLogging($bucket) + { return self::setBucketLogging($bucket, null); } @@ -563,15 +784,17 @@ class S3 { * @param string $bucket Bucket name * @return string | false */ - public static function getBucketLocation($bucket) { - $rest = new S3Request('GET', $bucket, ''); + public static function getBucketLocation($bucket) + { + $rest = new S3Request('GET', $bucket, '', self::$endpoint); $rest->setParameter('location', null); $rest = $rest->getResponse(); if ($rest->error === false && $rest->code !== 200) $rest->error = array('code' => $rest->code, 'message' => 'Unexpected HTTP status'); - if ($rest->error !== false) { - trigger_error(sprintf("S3::getBucketLocation({$bucket}): [%s] %s", - $rest->error['code'], $rest->error['message']), E_USER_WARNING); + if ($rest->error !== false) + { + self::__triggerError(sprintf("S3::getBucketLocation({$bucket}): [%s] %s", + $rest->error['code'], $rest->error['message']), __FILE__, __LINE__); return false; } return (isset($rest->body[0]) && (string)$rest->body[0] !== '') ? (string)$rest->body[0] : 'US'; @@ -586,7 +809,8 @@ class S3 { * @param array $acp Access Control Policy Data (same as the data returned from getAccessControlPolicy) * @return boolean */ - public static function setAccessControlPolicy($bucket, $uri = '', $acp = array()) { + public static function setAccessControlPolicy($bucket, $uri = '', $acp = array()) + { $dom = new DOMDocument; $dom->formatOutput = true; $accessControlPolicy = $dom->createElement('AccessControlPolicy'); @@ -598,17 +822,23 @@ class S3 { $owner->appendChild($dom->createElement('DisplayName', $acp['owner']['name'])); $accessControlPolicy->appendChild($owner); - foreach ($acp['acl'] as $g) { + foreach ($acp['acl'] as $g) + { $grant = $dom->createElement('Grant'); $grantee = $dom->createElement('Grantee'); $grantee->setAttribute('xmlns:xsi', 'http://www.w3.org/2001/XMLSchema-instance'); - if (isset($g['id'])) { // CanonicalUser (DisplayName is omitted) + if (isset($g['id'])) + { // CanonicalUser (DisplayName is omitted) $grantee->setAttribute('xsi:type', 'CanonicalUser'); $grantee->appendChild($dom->createElement('ID', $g['id'])); - } elseif (isset($g['email'])) { // AmazonCustomerByEmail + } + elseif (isset($g['email'])) + { // AmazonCustomerByEmail $grantee->setAttribute('xsi:type', 'AmazonCustomerByEmail'); $grantee->appendChild($dom->createElement('EmailAddress', $g['email'])); - } elseif ($g['type'] == 'Group') { // Group + } + elseif ($g['type'] == 'Group') + { // Group $grantee->setAttribute('xsi:type', 'Group'); $grantee->appendChild($dom->createElement('URI', $g['uri'])); } @@ -620,7 +850,7 @@ class S3 { $accessControlPolicy->appendChild($accessControlList); $dom->appendChild($accessControlPolicy); - $rest = new S3Request('PUT', $bucket, $uri); + $rest = new S3Request('PUT', $bucket, $uri, self::$endpoint); $rest->setParameter('acl', null); $rest->data = $dom->saveXML(); $rest->size = strlen($rest->data); @@ -628,9 +858,10 @@ class S3 { $rest = $rest->getResponse(); if ($rest->error === false && $rest->code !== 200) $rest->error = array('code' => $rest->code, 'message' => 'Unexpected HTTP status'); - if ($rest->error !== false) { - trigger_error(sprintf("S3::setAccessControlPolicy({$bucket}, {$uri}): [%s] %s", - $rest->error['code'], $rest->error['message']), E_USER_WARNING); + if ($rest->error !== false) + { + self::__triggerError(sprintf("S3::setAccessControlPolicy({$bucket}, {$uri}): [%s] %s", + $rest->error['code'], $rest->error['message']), __FILE__, __LINE__); return false; } return true; @@ -644,28 +875,33 @@ class S3 { * @param string $uri Object URI * @return mixed | false */ - public static function getAccessControlPolicy($bucket, $uri = '') { - $rest = new S3Request('GET', $bucket, $uri); + public static function getAccessControlPolicy($bucket, $uri = '') + { + $rest = new S3Request('GET', $bucket, $uri, self::$endpoint); $rest->setParameter('acl', null); $rest = $rest->getResponse(); if ($rest->error === false && $rest->code !== 200) $rest->error = array('code' => $rest->code, 'message' => 'Unexpected HTTP status'); - if ($rest->error !== false) { - trigger_error(sprintf("S3::getAccessControlPolicy({$bucket}, {$uri}): [%s] %s", - $rest->error['code'], $rest->error['message']), E_USER_WARNING); + if ($rest->error !== false) + { + self::__triggerError(sprintf("S3::getAccessControlPolicy({$bucket}, {$uri}): [%s] %s", + $rest->error['code'], $rest->error['message']), __FILE__, __LINE__); return false; } $acp = array(); - if (isset($rest->body->Owner, $rest->body->Owner->ID, $rest->body->Owner->DisplayName)) { + if (isset($rest->body->Owner, $rest->body->Owner->ID, $rest->body->Owner->DisplayName)) $acp['owner'] = array( 'id' => (string)$rest->body->Owner->ID, 'name' => (string)$rest->body->Owner->DisplayName ); - } - if (isset($rest->body->AccessControlList)) { + + if (isset($rest->body->AccessControlList)) + { $acp['acl'] = array(); - foreach ($rest->body->AccessControlList->Grant as $grant) { - foreach ($grant->Grantee as $grantee) { + foreach ($rest->body->AccessControlList->Grant as $grant) + { + foreach ($grant->Grantee as $grantee) + { if (isset($grantee->ID, $grantee->DisplayName)) // CanonicalUser $acp['acl'][] = array( 'type' => 'CanonicalUser', @@ -700,14 +936,16 @@ class S3 { * @param string $uri Object URI * @return boolean */ - public static function deleteObject($bucket, $uri) { - $rest = new S3Request('DELETE', $bucket, $uri); + public static function deleteObject($bucket, $uri) + { + $rest = new S3Request('DELETE', $bucket, $uri, self::$endpoint); $rest = $rest->getResponse(); if ($rest->error === false && $rest->code !== 204) $rest->error = array('code' => $rest->code, 'message' => 'Unexpected HTTP status'); - if ($rest->error !== false) { - trigger_error(sprintf("S3::deleteObject(): [%s] %s", - $rest->error['code'], $rest->error['message']), E_USER_WARNING); + if ($rest->error !== false) + { + self::__triggerError(sprintf("S3::deleteObject(): [%s] %s", + $rest->error['code'], $rest->error['message']), __FILE__, __LINE__); return false; } return true; @@ -724,15 +962,122 @@ class S3 { * @param boolean $https Use HTTPS ($hostBucket should be false for SSL verification) * @return string */ - public static function getAuthenticatedURL($bucket, $uri, $lifetime, $hostBucket = false, $https = false) { + public static function getAuthenticatedURL($bucket, $uri, $lifetime, $hostBucket = false, $https = false) + { $expires = time() + $lifetime; - $uri = str_replace('%2F', '/', rawurlencode($uri)); // URI should be encoded (thanks Sean O'Dea) + $uri = str_replace(array('%2F', '%2B'), array('/', '+'), rawurlencode($uri)); return sprintf(($https ? 'https' : 'http').'://%s/%s?AWSAccessKeyId=%s&Expires=%u&Signature=%s', - $hostBucket ? $bucket : $bucket.'.s3.amazonaws.com', $uri, self::$__accessKey, $expires, + // $hostBucket ? $bucket : $bucket.'.s3.amazonaws.com', $uri, self::$__accessKey, $expires, + $hostBucket ? $bucket : 's3.amazonaws.com/'.$bucket, $uri, self::$__accessKey, $expires, urlencode(self::__getHash("GET\n\n\n{$expires}\n/{$bucket}/{$uri}"))); } + /** + * Get a CloudFront signed policy URL + * + * @param array $policy Policy + * @return string + */ + public static function getSignedPolicyURL($policy) + { + $data = json_encode($policy); + $signature = ''; + if (!openssl_sign($data, $signature, self::$__signingKeyResource)) return false; + + $encoded = str_replace(array('+', '='), array('-', '_', '~'), base64_encode($data)); + $signature = str_replace(array('+', '='), array('-', '_', '~'), base64_encode($signature)); + + $url = $policy['Statement'][0]['Resource'] . '?'; + foreach (array('Policy' => $encoded, 'Signature' => $signature, 'Key-Pair-Id' => self::$__signingKeyPairId) as $k => $v) + $url .= $k.'='.str_replace('%2F', '/', rawurlencode($v)).'&'; + return substr($url, 0, -1); + } + + + /** + * Get a CloudFront canned policy URL + * + * @param string $string URL to sign + * @param integer $lifetime URL lifetime + * @return string + */ + public static function getSignedCannedURL($url, $lifetime) + { + return self::getSignedPolicyURL(array( + 'Statement' => array( + array('Resource' => $url, 'Condition' => array( + 'DateLessThan' => array('AWS:EpochTime' => time() + $lifetime) + )) + ) + )); + } + + + /** + * Get upload POST parameters for form uploads + * + * @param string $bucket Bucket name + * @param string $uriPrefix Object URI prefix + * @param constant $acl ACL constant + * @param integer $lifetime Lifetime in seconds + * @param integer $maxFileSize Maximum filesize in bytes (default 5MB) + * @param string $successRedirect Redirect URL or 200 / 201 status code + * @param array $amzHeaders Array of x-amz-meta-* headers + * @param array $headers Array of request headers or content type as a string + * @param boolean $flashVars Includes additional "Filename" variable posted by Flash + * @return object + */ + public static function getHttpUploadPostParams($bucket, $uriPrefix = '', $acl = self::ACL_PRIVATE, $lifetime = 3600, + $maxFileSize = 5242880, $successRedirect = "201", $amzHeaders = array(), $headers = array(), $flashVars = false) + { + // Create policy object + $policy = new stdClass; + $policy->expiration = gmdate('Y-m-d\TH:i:s\Z', (time() + $lifetime)); + $policy->conditions = array(); + $obj = new stdClass; $obj->bucket = $bucket; array_push($policy->conditions, $obj); + $obj = new stdClass; $obj->acl = $acl; array_push($policy->conditions, $obj); + + $obj = new stdClass; // 200 for non-redirect uploads + if (is_numeric($successRedirect) && in_array((int)$successRedirect, array(200, 201))) + $obj->success_action_status = (string)$successRedirect; + else // URL + $obj->success_action_redirect = $successRedirect; + array_push($policy->conditions, $obj); + + if ($acl !== self::ACL_PUBLIC_READ) + array_push($policy->conditions, array('eq', '$acl', $acl)); + + array_push($policy->conditions, array('starts-with', '$key', $uriPrefix)); + if ($flashVars) array_push($policy->conditions, array('starts-with', '$Filename', '')); + foreach (array_keys($headers) as $headerKey) + array_push($policy->conditions, array('starts-with', '$'.$headerKey, '')); + foreach ($amzHeaders as $headerKey => $headerVal) + { + $obj = new stdClass; + $obj->{$headerKey} = (string)$headerVal; + array_push($policy->conditions, $obj); + } + array_push($policy->conditions, array('content-length-range', 0, $maxFileSize)); + $policy = base64_encode(str_replace('\/', '/', json_encode($policy))); + + // Create parameters + $params = new stdClass; + $params->AWSAccessKeyId = self::$__accessKey; + $params->key = $uriPrefix.'${filename}'; + $params->acl = $acl; + $params->policy = $policy; unset($policy); + $params->signature = self::__getHash($params->policy); + if (is_numeric($successRedirect) && in_array((int)$successRedirect, array(200, 201))) + $params->success_action_status = (string)$successRedirect; + else + $params->success_action_redirect = $successRedirect; + foreach ($headers as $headerKey => $headerVal) $params->{$headerKey} = (string)$headerVal; + foreach ($amzHeaders as $headerKey => $headerVal) $params->{$headerKey} = (string)$headerVal; + return $params; + } + + /** * Create a CloudFront distribution * @@ -740,21 +1085,46 @@ class S3 { * @param boolean $enabled Enabled (true/false) * @param array $cnames Array containing CNAME aliases * @param string $comment Use the bucket name as the hostname + * @param string $defaultRootObject Default root object + * @param string $originAccessIdentity Origin access identity + * @param array $trustedSigners Array of trusted signers * @return array | false */ - public static function createDistribution($bucket, $enabled = true, $cnames = array(), $comment = '') { + public static function createDistribution($bucket, $enabled = true, $cnames = array(), $comment = null, $defaultRootObject = null, $originAccessIdentity = null, $trustedSigners = array()) + { + if (!extension_loaded('openssl')) + { + self::__triggerError(sprintf("S3::createDistribution({$bucket}, ".(int)$enabled.", [], '$comment'): %s", + "CloudFront functionality requires SSL"), __FILE__, __LINE__); + return false; + } + $useSSL = self::$useSSL; + self::$useSSL = true; // CloudFront requires SSL - $rest = new S3Request('POST', '', '2008-06-30/distribution', 'cloudfront.amazonaws.com'); - $rest->data = self::__getCloudFrontDistributionConfigXML($bucket.'.s3.amazonaws.com', $enabled, $comment, (string)microtime(true), $cnames); + $rest = new S3Request('POST', '', '2010-11-01/distribution', 'cloudfront.amazonaws.com'); + $rest->data = self::__getCloudFrontDistributionConfigXML( + $bucket.'.s3.amazonaws.com', + $enabled, + (string)$comment, + (string)microtime(true), + $cnames, + $defaultRootObject, + $originAccessIdentity, + $trustedSigners + ); + $rest->size = strlen($rest->data); $rest->setHeader('Content-Type', 'application/xml'); $rest = self::__getCloudFrontResponse($rest); + self::$useSSL = $useSSL; + if ($rest->error === false && $rest->code !== 201) $rest->error = array('code' => $rest->code, 'message' => 'Unexpected HTTP status'); - if ($rest->error !== false) { - trigger_error(sprintf("S3::createDistribution({$bucket}, ".(int)$enabled.", '$comment'): [%s] %s", - $rest->error['code'], $rest->error['message']), E_USER_WARNING); + if ($rest->error !== false) + { + self::__triggerError(sprintf("S3::createDistribution({$bucket}, ".(int)$enabled.", [], '$comment'): [%s] %s", + $rest->error['code'], $rest->error['message']), __FILE__, __LINE__); return false; } elseif ($rest->body instanceof SimpleXMLElement) return self::__parseCloudFrontDistributionConfig($rest->body); @@ -768,20 +1138,35 @@ class S3 { * @param string $distributionId Distribution ID from listDistributions() * @return array | false */ - public static function getDistribution($distributionId) { + public static function getDistribution($distributionId) + { + if (!extension_loaded('openssl')) + { + self::__triggerError(sprintf("S3::getDistribution($distributionId): %s", + "CloudFront functionality requires SSL"), __FILE__, __LINE__); + return false; + } + $useSSL = self::$useSSL; + self::$useSSL = true; // CloudFront requires SSL - $rest = new S3Request('GET', '', '2008-06-30/distribution/'.$distributionId, 'cloudfront.amazonaws.com'); + $rest = new S3Request('GET', '', '2010-11-01/distribution/'.$distributionId, 'cloudfront.amazonaws.com'); $rest = self::__getCloudFrontResponse($rest); + self::$useSSL = $useSSL; + if ($rest->error === false && $rest->code !== 200) $rest->error = array('code' => $rest->code, 'message' => 'Unexpected HTTP status'); - if ($rest->error !== false) { - trigger_error(sprintf("S3::getDistribution($distributionId): [%s] %s", - $rest->error['code'], $rest->error['message']), E_USER_WARNING); + if ($rest->error !== false) + { + self::__triggerError(sprintf("S3::getDistribution($distributionId): [%s] %s", + $rest->error['code'], $rest->error['message']), __FILE__, __LINE__); return false; - } elseif ($rest->body instanceof SimpleXMLElement) { + } + elseif ($rest->body instanceof SimpleXMLElement) + { $dist = self::__parseCloudFrontDistributionConfig($rest->body); $dist['hash'] = $rest->headers['hash']; + $dist['id'] = $distributionId; return $dist; } return false; @@ -794,19 +1179,42 @@ class S3 { * @param array $dist Distribution array info identical to output of getDistribution() * @return array | false */ - public static function updateDistribution($dist) { + public static function updateDistribution($dist) + { + if (!extension_loaded('openssl')) + { + self::__triggerError(sprintf("S3::updateDistribution({$dist['id']}): %s", + "CloudFront functionality requires SSL"), __FILE__, __LINE__); + return false; + } + + $useSSL = self::$useSSL; + self::$useSSL = true; // CloudFront requires SSL - $rest = new S3Request('PUT', '', '2008-06-30/distribution/'.$dist['id'].'/config', 'cloudfront.amazonaws.com'); - $rest->data = self::__getCloudFrontDistributionConfigXML($dist['origin'], $dist['enabled'], $dist['comment'], $dist['callerReference'], $dist['cnames']); + $rest = new S3Request('PUT', '', '2010-11-01/distribution/'.$dist['id'].'/config', 'cloudfront.amazonaws.com'); + $rest->data = self::__getCloudFrontDistributionConfigXML( + $dist['origin'], + $dist['enabled'], + $dist['comment'], + $dist['callerReference'], + $dist['cnames'], + $dist['defaultRootObject'], + $dist['originAccessIdentity'], + $dist['trustedSigners'] + ); + $rest->size = strlen($rest->data); $rest->setHeader('If-Match', $dist['hash']); $rest = self::__getCloudFrontResponse($rest); + self::$useSSL = $useSSL; + if ($rest->error === false && $rest->code !== 200) $rest->error = array('code' => $rest->code, 'message' => 'Unexpected HTTP status'); - if ($rest->error !== false) { - trigger_error(sprintf("S3::updateDistribution({$dist['id']}, ".(int)$enabled.", '$comment'): [%s] %s", - $rest->error['code'], $rest->error['message']), E_USER_WARNING); + if ($rest->error !== false) + { + self::__triggerError(sprintf("S3::updateDistribution({$dist['id']}): [%s] %s", + $rest->error['code'], $rest->error['message']), __FILE__, __LINE__); return false; } else { $dist = self::__parseCloudFrontDistributionConfig($rest->body); @@ -823,17 +1231,30 @@ class S3 { * @param array $dist Distribution array info identical to output of getDistribution() * @return boolean */ - public static function deleteDistribution($dist) { + public static function deleteDistribution($dist) + { + if (!extension_loaded('openssl')) + { + self::__triggerError(sprintf("S3::deleteDistribution({$dist['id']}): %s", + "CloudFront functionality requires SSL"), __FILE__, __LINE__); + return false; + } + + $useSSL = self::$useSSL; + self::$useSSL = true; // CloudFront requires SSL $rest = new S3Request('DELETE', '', '2008-06-30/distribution/'.$dist['id'], 'cloudfront.amazonaws.com'); $rest->setHeader('If-Match', $dist['hash']); $rest = self::__getCloudFrontResponse($rest); + self::$useSSL = $useSSL; + if ($rest->error === false && $rest->code !== 204) $rest->error = array('code' => $rest->code, 'message' => 'Unexpected HTTP status'); - if ($rest->error !== false) { - trigger_error(sprintf("S3::deleteDistribution({$dist['id']}): [%s] %s", - $rest->error['code'], $rest->error['message']), E_USER_WARNING); + if ($rest->error !== false) + { + self::__triggerError(sprintf("S3::deleteDistribution({$dist['id']}): [%s] %s", + $rest->error['code'], $rest->error['message']), __FILE__, __LINE__); return false; } return true; @@ -845,27 +1266,189 @@ class S3 { * * @return array */ - public static function listDistributions() { + public static function listDistributions() + { + if (!extension_loaded('openssl')) + { + self::__triggerError(sprintf("S3::listDistributions(): [%s] %s", + "CloudFront functionality requires SSL"), __FILE__, __LINE__); + return false; + } + + $useSSL = self::$useSSL; self::$useSSL = true; // CloudFront requires SSL - $rest = new S3Request('GET', '', '2008-06-30/distribution', 'cloudfront.amazonaws.com'); + $rest = new S3Request('GET', '', '2010-11-01/distribution', 'cloudfront.amazonaws.com'); $rest = self::__getCloudFrontResponse($rest); + self::$useSSL = $useSSL; if ($rest->error === false && $rest->code !== 200) $rest->error = array('code' => $rest->code, 'message' => 'Unexpected HTTP status'); - if ($rest->error !== false) { - trigger_error(sprintf("S3::listDistributions(): [%s] %s", - $rest->error['code'], $rest->error['message']), E_USER_WARNING); + if ($rest->error !== false) + { + self::__triggerError(sprintf("S3::listDistributions(): [%s] %s", + $rest->error['code'], $rest->error['message']), __FILE__, __LINE__); return false; - } elseif ($rest->body instanceof SimpleXMLElement && isset($rest->body->DistributionSummary)) { + } + elseif ($rest->body instanceof SimpleXMLElement && isset($rest->body->DistributionSummary)) + { $list = array(); - if (isset($rest->body->Marker, $rest->body->MaxItems, $rest->body->IsTruncated)) { + if (isset($rest->body->Marker, $rest->body->MaxItems, $rest->body->IsTruncated)) + { //$info['marker'] = (string)$rest->body->Marker; //$info['maxItems'] = (int)$rest->body->MaxItems; //$info['isTruncated'] = (string)$rest->body->IsTruncated == 'true' ? true : false; } - foreach ($rest->body->DistributionSummary as $summary) { + foreach ($rest->body->DistributionSummary as $summary) $list[(string)$summary->Id] = self::__parseCloudFrontDistributionConfig($summary); - } + + return $list; + } + return array(); + } + + /** + * List CloudFront Origin Access Identities + * + * @return array + */ + public static function listOriginAccessIdentities() + { + if (!extension_loaded('openssl')) + { + self::__triggerError(sprintf("S3::listOriginAccessIdentities(): [%s] %s", + "CloudFront functionality requires SSL"), __FILE__, __LINE__); + return false; + } + + self::$useSSL = true; // CloudFront requires SSL + $rest = new S3Request('GET', '', '2010-11-01/origin-access-identity/cloudfront', 'cloudfront.amazonaws.com'); + $rest = self::__getCloudFrontResponse($rest); + $useSSL = self::$useSSL; + + if ($rest->error === false && $rest->code !== 200) + $rest->error = array('code' => $rest->code, 'message' => 'Unexpected HTTP status'); + if ($rest->error !== false) + { + trigger_error(sprintf("S3::listOriginAccessIdentities(): [%s] %s", + $rest->error['code'], $rest->error['message']), E_USER_WARNING); + return false; + } + + if (isset($rest->body->CloudFrontOriginAccessIdentitySummary)) + { + $identities = array(); + foreach ($rest->body->CloudFrontOriginAccessIdentitySummary as $identity) + if (isset($identity->S3CanonicalUserId)) + $identities[(string)$identity->Id] = array('id' => (string)$identity->Id, 's3CanonicalUserId' => (string)$identity->S3CanonicalUserId); + return $identities; + } + return false; + } + + + /** + * Invalidate objects in a CloudFront distribution + * + * Thanks to Martin Lindkvist for S3::invalidateDistribution() + * + * @param string $distributionId Distribution ID from listDistributions() + * @param array $paths Array of object paths to invalidate + * @return boolean + */ + public static function invalidateDistribution($distributionId, $paths) + { + if (!extension_loaded('openssl')) + { + self::__triggerError(sprintf("S3::invalidateDistribution(): [%s] %s", + "CloudFront functionality requires SSL"), __FILE__, __LINE__); + return false; + } + + $useSSL = self::$useSSL; + self::$useSSL = true; // CloudFront requires SSL + $rest = new S3Request('POST', '', '2010-08-01/distribution/'.$distributionId.'/invalidation', 'cloudfront.amazonaws.com'); + $rest->data = self::__getCloudFrontInvalidationBatchXML($paths, (string)microtime(true)); + $rest->size = strlen($rest->data); + $rest = self::__getCloudFrontResponse($rest); + self::$useSSL = $useSSL; + + if ($rest->error === false && $rest->code !== 201) + $rest->error = array('code' => $rest->code, 'message' => 'Unexpected HTTP status'); + if ($rest->error !== false) + { + trigger_error(sprintf("S3::invalidate('{$distributionId}',{$paths}): [%s] %s", + $rest->error['code'], $rest->error['message']), E_USER_WARNING); + return false; + } + return true; + } + + + /** + * Get a InvalidationBatch DOMDocument + * + * @internal Used to create XML in invalidateDistribution() + * @param array $paths Paths to objects to invalidateDistribution + * @return string + */ + private static function __getCloudFrontInvalidationBatchXML($paths, $callerReference = '0') { + $dom = new DOMDocument('1.0', 'UTF-8'); + $dom->formatOutput = true; + $invalidationBatch = $dom->createElement('InvalidationBatch'); + foreach ($paths as $path) + $invalidationBatch->appendChild($dom->createElement('Path', $path)); + + $invalidationBatch->appendChild($dom->createElement('CallerReference', $callerReference)); + $dom->appendChild($invalidationBatch); + return $dom->saveXML(); + } + + + /** + * List your invalidation batches for invalidateDistribution() in a CloudFront distribution + * + * http://docs.amazonwebservices.com/AmazonCloudFront/latest/APIReference/ListInvalidation.html + * returned array looks like this: + * Array + * ( + * [I31TWB0CN9V6XD] => InProgress + * [IT3TFE31M0IHZ] => Completed + * [I12HK7MPO1UQDA] => Completed + * [I1IA7R6JKTC3L2] => Completed + * ) + * + * @param string $distributionId Distribution ID from listDistributions() + * @return array + */ + public static function getDistributionInvalidationList($distributionId) + { + if (!extension_loaded('openssl')) + { + self::__triggerError(sprintf("S3::getDistributionInvalidationList(): [%s] %s", + "CloudFront functionality requires SSL"), __FILE__, __LINE__); + return false; + } + + $useSSL = self::$useSSL; + self::$useSSL = true; // CloudFront requires SSL + $rest = new S3Request('GET', '', '2010-11-01/distribution/'.$distributionId.'/invalidation', 'cloudfront.amazonaws.com'); + $rest = self::__getCloudFrontResponse($rest); + self::$useSSL = $useSSL; + + if ($rest->error === false && $rest->code !== 200) + $rest->error = array('code' => $rest->code, 'message' => 'Unexpected HTTP status'); + if ($rest->error !== false) + { + trigger_error(sprintf("S3::getDistributionInvalidationList('{$distributionId}'): [%s]", + $rest->error['code'], $rest->error['message']), E_USER_WARNING); + return false; + } + elseif ($rest->body instanceof SimpleXMLElement && isset($rest->body->InvalidationSummary)) + { + $list = array(); + foreach ($rest->body->InvalidationSummary as $summary) + $list[(string)$summary->Id] = (string)$summary->Status; + return $list; } return array(); @@ -875,26 +1458,46 @@ class S3 { /** * Get a DistributionConfig DOMDocument * + * http://docs.amazonwebservices.com/AmazonCloudFront/latest/APIReference/index.html?PutConfig.html + * * @internal Used to create XML in createDistribution() and updateDistribution() - * @param string $bucket Origin bucket + * @param string $bucket S3 Origin bucket * @param boolean $enabled Enabled (true/false) * @param string $comment Comment to append * @param string $callerReference Caller reference * @param array $cnames Array of CNAME aliases + * @param string $defaultRootObject Default root object + * @param string $originAccessIdentity Origin access identity + * @param array $trustedSigners Array of trusted signers * @return string */ - private static function __getCloudFrontDistributionConfigXML($bucket, $enabled, $comment, $callerReference = '0', $cnames = array()) { + private static function __getCloudFrontDistributionConfigXML($bucket, $enabled, $comment, $callerReference = '0', $cnames = array(), $defaultRootObject = null, $originAccessIdentity = null, $trustedSigners = array()) + { $dom = new DOMDocument('1.0', 'UTF-8'); $dom->formatOutput = true; $distributionConfig = $dom->createElement('DistributionConfig'); - $distributionConfig->setAttribute('xmlns', 'http://cloudfront.amazonaws.com/doc/2008-06-30/'); - $distributionConfig->appendChild($dom->createElement('Origin', $bucket)); + $distributionConfig->setAttribute('xmlns', 'http://cloudfront.amazonaws.com/doc/2010-11-01/'); + + $origin = $dom->createElement('S3Origin'); + $origin->appendChild($dom->createElement('DNSName', $bucket)); + if ($originAccessIdentity !== null) $origin->appendChild($dom->createElement('OriginAccessIdentity', $originAccessIdentity)); + $distributionConfig->appendChild($origin); + + if ($defaultRootObject !== null) $distributionConfig->appendChild($dom->createElement('DefaultRootObject', $defaultRootObject)); + $distributionConfig->appendChild($dom->createElement('CallerReference', $callerReference)); foreach ($cnames as $cname) $distributionConfig->appendChild($dom->createElement('CNAME', $cname)); if ($comment !== '') $distributionConfig->appendChild($dom->createElement('Comment', $comment)); $distributionConfig->appendChild($dom->createElement('Enabled', $enabled ? 'true' : 'false')); + + $trusted = $dom->createElement('TrustedSigners'); + foreach ($trustedSigners as $id => $type) + $trusted->appendChild($id !== '' ? $dom->createElement($type, $id) : $dom->createElement($type)); + $distributionConfig->appendChild($trusted); + $dom->appendChild($distributionConfig); + //var_dump($dom->saveXML()); return $dom->saveXML(); } @@ -902,32 +1505,61 @@ class S3 { /** * Parse a CloudFront distribution config * + * See http://docs.amazonwebservices.com/AmazonCloudFront/latest/APIReference/index.html?GetDistribution.html + * * @internal Used to parse the CloudFront DistributionConfig node to an array * @param object &$node DOMNode * @return array */ - private static function __parseCloudFrontDistributionConfig(&$node) { + private static function __parseCloudFrontDistributionConfig(&$node) + { + if (isset($node->DistributionConfig)) + return self::__parseCloudFrontDistributionConfig($node->DistributionConfig); + $dist = array(); - if (isset($node->Id, $node->Status, $node->LastModifiedTime, $node->DomainName)) { + if (isset($node->Id, $node->Status, $node->LastModifiedTime, $node->DomainName)) + { $dist['id'] = (string)$node->Id; $dist['status'] = (string)$node->Status; $dist['time'] = strtotime((string)$node->LastModifiedTime); $dist['domain'] = (string)$node->DomainName; } + if (isset($node->CallerReference)) $dist['callerReference'] = (string)$node->CallerReference; - if (isset($node->Comment)) - $dist['comment'] = (string)$node->Comment; - if (isset($node->Enabled, $node->Origin)) { - $dist['origin'] = (string)$node->Origin; + + if (isset($node->Enabled)) $dist['enabled'] = (string)$node->Enabled == 'true' ? true : false; - } elseif (isset($node->DistributionConfig)) { - $dist = array_merge($dist, self::__parseCloudFrontDistributionConfig($node->DistributionConfig)); - } - if (isset($node->CNAME)) { - $dist['cnames'] = array(); - foreach ($node->CNAME as $cname) $dist['cnames'][(string)$cname] = (string)$cname; + + if (isset($node->S3Origin)) + { + if (isset($node->S3Origin->DNSName)) + $dist['origin'] = (string)$node->S3Origin->DNSName; + + $dist['originAccessIdentity'] = isset($node->S3Origin->OriginAccessIdentity) ? + (string)$node->S3Origin->OriginAccessIdentity : null; } + + $dist['defaultRootObject'] = isset($node->DefaultRootObject) ? (string)$node->DefaultRootObject : null; + + $dist['cnames'] = array(); + if (isset($node->CNAME)) + foreach ($node->CNAME as $cname) + $dist['cnames'][(string)$cname] = (string)$cname; + + $dist['trustedSigners'] = array(); + if (isset($node->TrustedSigners)) + foreach ($node->TrustedSigners as $signer) + { + if (isset($signer->Self)) + $dist['trustedSigners'][''] = 'Self'; + elseif (isset($signer->KeyPairId)) + $dist['trustedSigners'][(string)$signer->KeyPairId] = 'KeyPairId'; + elseif (isset($signer->AwsAccountNumber)) + $dist['trustedSigners'][(string)$signer->AwsAccountNumber] = 'AwsAccountNumber'; + } + + $dist['comment'] = isset($node->Comment) ? (string)$node->Comment : null; return $dist; } @@ -939,14 +1571,17 @@ class S3 { * @param object &$rest S3Request instance * @return object */ - private static function __getCloudFrontResponse(&$rest) { + private static function __getCloudFrontResponse(&$rest) + { $rest->getResponse(); if ($rest->response->error === false && isset($rest->response->body) && - is_string($rest->response->body) && substr($rest->response->body, 0, 5) == 'response->body) && substr($rest->response->body, 0, 5) == 'response->body = simplexml_load_string($rest->response->body); // Grab CloudFront errors if (isset($rest->response->body->Error, $rest->response->body->Error->Code, - $rest->response->body->Error->Message)) { + $rest->response->body->Error->Message)) + { $rest->response->error = array( 'code' => (string)$rest->response->body->Error->Code, 'message' => (string)$rest->response->body->Error->Message @@ -965,13 +1600,16 @@ class S3 { * @param string &$file File path * @return string */ - public static function __getMimeType(&$file) { + public static function __getMimeType(&$file) + { $type = false; // Fileinfo documentation says fileinfo_open() will use the // MAGIC env var for the magic file if (extension_loaded('fileinfo') && isset($_ENV['MAGIC']) && - ($finfo = finfo_open(FILEINFO_MIME, $_ENV['MAGIC'])) !== false) { - if (($type = finfo_file($finfo, $file)) !== false) { + ($finfo = finfo_open(FILEINFO_MIME, $_ENV['MAGIC'])) !== false) + { + if (($type = finfo_file($finfo, $file)) !== false) + { // Remove the charset and grab the last content-type $type = explode(' ', str_replace('; charset=', ';charset=', $type)); $type = array_pop($type); @@ -1001,7 +1639,7 @@ class S3 { 'avi' => 'video/x-msvideo', 'mpg' => 'video/mpeg', 'mpeg' => 'video/mpeg', 'mov' => 'video/quicktime', 'flv' => 'video/x-flv', 'php' => 'text/x-php' ); - $ext = strToLower(pathInfo($file, PATHINFO_EXTENSION)); + $ext = strtolower(pathInfo($file, PATHINFO_EXTENSION)); return isset($exts[$ext]) ? $exts[$ext] : 'application/octet-stream'; } @@ -1013,7 +1651,8 @@ class S3 { * @param string $string String to sign * @return string */ - public static function __getSignature($string) { + public static function __getSignature($string) + { return 'AWS '.self::$__accessKey.':'.self::__getHash($string); } @@ -1027,7 +1666,8 @@ class S3 { * @param string $string String to sign * @return string */ - private static function __getHash($string) { + private static function __getHash($string) + { return base64_encode(extension_loaded('hash') ? hash_hmac('sha1', $string, self::$__secretKey, true) : pack('H*', sha1( (str_pad(self::$__secretKey, 64, chr(0x00)) ^ (str_repeat(chr(0x5c), 64))) . @@ -1037,8 +1677,9 @@ class S3 { } -final class S3Request { - private $verb, $bucket, $uri, $resource = '', $parameters = array(), +final class S3Request +{ + private $endpoint, $verb, $bucket, $uri, $resource = '', $parameters = array(), $amzHeaders = array(), $headers = array( 'Host' => '', 'Date' => '', 'Content-MD5' => '', 'Content-Type' => '' ); @@ -1053,21 +1694,42 @@ final class S3Request { * @param string $uri Object URI * @return mixed */ - function __construct($verb, $bucket = '', $uri = '', $defaultHost = 's3.amazonaws.com') { + function __construct($verb, $bucket = '', $uri = '', $endpoint = 's3.amazonaws.com') + { + $this->endpoint = $endpoint; $this->verb = $verb; - $this->bucket = strtolower($bucket); + $this->bucket = $bucket; $this->uri = $uri !== '' ? '/'.str_replace('%2F', '/', rawurlencode($uri)) : '/'; - if ($this->bucket !== '') { - $this->headers['Host'] = $this->bucket.'.'.$defaultHost; - $this->resource = '/'.$this->bucket.$this->uri; - } else { - $this->headers['Host'] = $defaultHost; - //$this->resource = strlen($this->uri) > 1 ? '/'.$this->bucket.$this->uri : $this->uri; + //if ($this->bucket !== '') + // $this->resource = '/'.$this->bucket.$this->uri; + //else + // $this->resource = $this->uri; + + if ($this->bucket !== '') + { + if ($this->__dnsBucketName($this->bucket)) + { + $this->headers['Host'] = $this->bucket.'.'.$this->endpoint; + $this->resource = '/'.$this->bucket.$this->uri; + } + else + { + $this->headers['Host'] = $this->endpoint; + $this->uri = $this->uri; + if ($this->bucket !== '') $this->uri = '/'.$this->bucket.$this->uri; + $this->bucket = ''; + $this->resource = $this->uri; + } + } + else + { + $this->headers['Host'] = $this->endpoint; $this->resource = $this->uri; } - $this->headers['Date'] = gmdate('D, d M Y H:i:s T'); + + $this->headers['Date'] = gmdate('D, d M Y H:i:s T'); $this->response = new STDClass; $this->response->error = false; } @@ -1080,7 +1742,8 @@ final class S3Request { * @param string $value Value * @return void */ - public function setParameter($key, $value) { + public function setParameter($key, $value) + { $this->parameters[$key] = $value; } @@ -1092,7 +1755,8 @@ final class S3Request { * @param string $value Value * @return void */ - public function setHeader($key, $value) { + public function setHeader($key, $value) + { $this->headers[$key] = $value; } @@ -1104,7 +1768,8 @@ final class S3Request { * @param string $value Value * @return void */ - public function setAmzHeader($key, $value) { + public function setAmzHeader($key, $value) + { $this->amzHeaders[$key] = $value; } @@ -1114,13 +1779,14 @@ final class S3Request { * * @return object | false */ - public function getResponse() { + public function getResponse() + { $query = ''; - if (sizeof($this->parameters) > 0) { + if (sizeof($this->parameters) > 0) + { $query = substr($this->uri, -1) !== '?' ? '?' : '&'; foreach ($this->parameters as $var => $value) if ($value == null || $value == '') $query .= $var.'&'; - // Parameters should be encoded (thanks Sean O'Dea) else $query .= $var.'='.rawurlencode($value).'&'; $query = substr($query, 0, -1); $this->uri .= $query; @@ -1128,24 +1794,39 @@ final class S3Request { if (array_key_exists('acl', $this->parameters) || array_key_exists('location', $this->parameters) || array_key_exists('torrent', $this->parameters) || + array_key_exists('website', $this->parameters) || array_key_exists('logging', $this->parameters)) $this->resource .= $query; } - $url = ((S3::$useSSL && extension_loaded('openssl')) ? - 'https://':'http://').$this->headers['Host'].$this->uri; - //var_dump($this->bucket, $this->uri, $this->resource, $url); + $url = (S3::$useSSL ? 'https://' : 'http://') . ($this->headers['Host'] !== '' ? $this->headers['Host'] : $this->endpoint) . $this->uri; + + //var_dump('bucket: ' . $this->bucket, 'uri: ' . $this->uri, 'resource: ' . $this->resource, 'url: ' . $url); // Basic setup $curl = curl_init(); curl_setopt($curl, CURLOPT_USERAGENT, 'S3/php'); - if (S3::$useSSL) { - curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 1); - curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 1); + if (S3::$useSSL) + { + // SSL Validation can now be optional for those with broken OpenSSL installations + curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, S3::$useSSLValidation ? 1 : 0); + curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, S3::$useSSLValidation ? 1 : 0); + + if (S3::$sslKey !== null) curl_setopt($curl, CURLOPT_SSLKEY, S3::$sslKey); + if (S3::$sslCert !== null) curl_setopt($curl, CURLOPT_SSLCERT, S3::$sslCert); + if (S3::$sslCACert !== null) curl_setopt($curl, CURLOPT_CAINFO, S3::$sslCACert); } curl_setopt($curl, CURLOPT_URL, $url); + if (S3::$proxy != null && isset(S3::$proxy['host'])) + { + curl_setopt($curl, CURLOPT_PROXY, S3::$proxy['host']); + curl_setopt($curl, CURLOPT_PROXYTYPE, S3::$proxy['type']); + if (isset(S3::$proxy['user'], S3::$proxy['pass']) && S3::$proxy['user'] != null && S3::$proxy['pass'] != null) + curl_setopt($curl, CURLOPT_PROXYUSERPWD, sprintf('%s:%s', S3::$proxy['user'], S3::$proxy['pass'])); + } + // Headers $headers = array(); $amz = array(); foreach ($this->amzHeaders as $header => $value) @@ -1155,20 +1836,32 @@ final class S3Request { // Collect AMZ headers for signature foreach ($this->amzHeaders as $header => $value) - if (strlen($value) > 0) $amz[] = strToLower($header).':'.$value; + if (strlen($value) > 0) $amz[] = strtolower($header).':'.$value; // AMZ headers must be sorted - if (sizeof($amz) > 0) { - sort($amz); + if (sizeof($amz) > 0) + { + //sort($amz); + usort($amz, array(&$this, '__sortMetaHeadersCmp')); $amz = "\n".implode("\n", $amz); } else $amz = ''; - // Authorization string (CloudFront stringToSign should only contain a date) - $headers[] = 'Authorization: ' . S3::__getSignature( - $this->headers['Host'] == 'cloudfront.amazonaws.com' ? $this->headers['Date'] : - $this->verb."\n".$this->headers['Content-MD5']."\n". - $this->headers['Content-Type']."\n".$this->headers['Date'].$amz."\n".$this->resource - ); + if (S3::hasAuth()) + { + // Authorization string (CloudFront stringToSign should only contain a date) + if ($this->headers['Host'] == 'cloudfront.amazonaws.com') + $headers[] = 'Authorization: ' . S3::__getSignature($this->headers['Date']); + else + { + $headers[] = 'Authorization: ' . S3::__getSignature( + $this->verb."\n". + $this->headers['Content-MD5']."\n". + $this->headers['Content-Type']."\n". + $this->headers['Date'].$amz."\n". + $this->resource + ); + } + } curl_setopt($curl, CURLOPT_HTTPHEADER, $headers); curl_setopt($curl, CURLOPT_HEADER, false); @@ -1178,20 +1871,23 @@ final class S3Request { curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true); // Request types - switch ($this->verb) { + switch ($this->verb) + { case 'GET': break; case 'PUT': case 'POST': // POST only used for CloudFront - if ($this->fp !== false) { + if ($this->fp !== false) + { curl_setopt($curl, CURLOPT_PUT, true); curl_setopt($curl, CURLOPT_INFILE, $this->fp); - if ($this->size > 0) + if ($this->size >= 0) curl_setopt($curl, CURLOPT_INFILESIZE, $this->size); - } elseif ($this->data !== false) { + } + elseif ($this->data !== false) + { curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $this->verb); curl_setopt($curl, CURLOPT_POSTFIELDS, $this->data); - if ($this->size > 0) - curl_setopt($curl, CURLOPT_BUFFERSIZE, $this->size); - } else + } + else curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $this->verb); break; case 'HEAD': @@ -1218,12 +1914,14 @@ final class S3Request { // Parse body into XML if ($this->response->error === false && isset($this->response->headers['type']) && - $this->response->headers['type'] == 'application/xml' && isset($this->response->body)) { + $this->response->headers['type'] == 'application/xml' && isset($this->response->body)) + { $this->response->body = simplexml_load_string($this->response->body); // Grab S3 errors - if (!in_array($this->response->code, array(200, 204)) && - isset($this->response->body->Code, $this->response->body->Message)) { + if (!in_array($this->response->code, array(200, 204, 206)) && + isset($this->response->body->Code, $this->response->body->Message)) + { $this->response->error = array( 'code' => (string)$this->response->body->Code, 'message' => (string)$this->response->body->Message @@ -1240,6 +1938,24 @@ final class S3Request { return $this->response; } + /** + * Sort compare for meta headers + * + * @internal Used to sort x-amz meta headers + * @param string $a String A + * @param string $b String B + * @return integer + */ + private function __sortMetaHeadersCmp($a, $b) + { + $lenA = strpos($a, ':'); + $lenB = strpos($b, ':'); + $minLen = min($lenA, $lenB); + $ncmp = strncmp($a, $b, $minLen); + if ($lenA == $lenB) return $ncmp; + if (0 == $ncmp) return $lenA < $lenB ? -1 : 1; + return $ncmp; + } /** * CURL write callback @@ -1248,8 +1964,9 @@ final class S3Request { * @param string &$data Data * @return integer */ - private function __responseWriteCallback(&$curl, &$data) { - if ($this->response->code == 200 && $this->fp !== false) + private function __responseWriteCallback(&$curl, &$data) + { + if (in_array($this->response->code, array(200, 206)) && $this->fp !== false) return fwrite($this->fp, $data); else $this->response->body .= $data; @@ -1257,6 +1974,23 @@ final class S3Request { } + /** + * Check DNS conformity + * + * @param string $bucket Bucket name + * @return boolean + */ + private function __dnsBucketName($bucket) + { + if (strlen($bucket) > 63 || !preg_match("/[^a-z0-9\.-]/", $bucket)) return false; + if (strstr($bucket, '-.') !== false) return false; + if (strstr($bucket, '..') !== false) return false; + if (!preg_match("/^[0-9a-z]/", $bucket)) return false; + if (!preg_match("/[0-9a-z]$/", $bucket)) return false; + return true; + } + + /** * CURL header callback * @@ -1264,12 +1998,16 @@ final class S3Request { * @param string &$data Data * @return integer */ - private function __responseHeaderCallback(&$curl, &$data) { + private function __responseHeaderCallback(&$curl, &$data) + { if (($strlen = strlen($data)) <= 2) return $strlen; if (substr($data, 0, 4) == 'HTTP') $this->response->code = (int)substr($data, 9, 3); - else { - list($header, $value) = explode(': ', trim($data), 2); + else + { + $data = trim($data); + if (strpos($data, ': ') === false) return $strlen; + list($header, $value) = explode(': ', $data, 2); if ($header == 'Last-Modified') $this->response->headers['time'] = strtotime($value); elseif ($header == 'Content-Length') @@ -1279,9 +2017,18 @@ final class S3Request { elseif ($header == 'ETag') $this->response->headers['hash'] = $value{0} == '"' ? substr($value, 1, -1) : $value; elseif (preg_match('/^x-amz-meta-.*$/', $header)) - $this->response->headers[$header] = is_numeric($value) ? (int)$value : $value; + $this->response->headers[$header] = $value; } return $strlen; } } + +class S3Exception extends Exception { + function __construct($message, $file, $line, $code = 0) + { + parent::__construct($message, $code); + $this->file = $file; + $this->line = $line; + } +} diff --git a/repository/s3/lib.php b/repository/s3/lib.php index c25dfc6b555..54caa3bbc6c 100644 --- a/repository/s3/lib.php +++ b/repository/s3/lib.php @@ -24,7 +24,7 @@ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ require_once($CFG->dirroot . '/repository/lib.php'); -require_once('S3.php'); +require_once($CFG->dirroot . '/repository/s3/S3.php'); /** * This is a repository class used to browse Amazon S3 content. @@ -49,6 +49,23 @@ class repository_s3 extends repository { $this->s = new S3($this->access_key, $this->secret_key); } + /** + * Extracts the Bucket and URI from the path + * + * @param string $path path in this format 'bucket/path/to/folder/and/file' + * @return array including bucket and uri + */ + protected function explode_path($path) { + $parts = explode('/', $path, 2); + if (isset($parts[1]) && $parts[1] !== '') { + list($bucket, $uri) = $parts; + } else { + $bucket = $parts[0]; + $uri = ''; + } + return array($bucket, $uri); + } + /** * Get S3 file list * @@ -60,8 +77,13 @@ class repository_s3 extends repository { if (empty($this->access_key)) { die(json_encode(array('e'=>get_string('needaccesskey', 'repository_s3')))); } + $list = array(); $list['list'] = array(); + $list['path'] = array( + array('name' => get_string('pluginname', 'repository_s3'), 'path' => '') + ); + // the management interface url $list['manage'] = false; // dynamically loading @@ -71,29 +93,78 @@ class repository_s3 extends repository { $list['nologin'] = true; // set to true, the search button will be removed $list['nosearch'] = true; + $tree = array(); + if (empty($path)) { $buckets = $this->s->listBuckets(); foreach ($buckets as $bucket) { $folder = array( 'title' => $bucket, 'children' => array(), - 'thumbnail'=>$OUTPUT->pix_url(file_folder_icon(90))->out(false), - 'path'=>$bucket + 'thumbnail' => $OUTPUT->pix_url(file_folder_icon(90))->out(false), + 'path' => $bucket ); $tree[] = $folder; } } else { - $contents = $this->s->getBucket($path); - foreach ($contents as $file) { - $info = $this->s->getObjectInfo($path, baseName($file['name'])); - $tree[] = array( - 'title'=>$file['name'], - 'size'=>$file['size'], - 'date'=>userdate($file['time']), - 'source'=>$path.'/'.$file['name'], - 'thumbnail' => $OUTPUT->pix_url(file_extension_icon($file['name'], 90))->out(false) + $files = array(); + $folders = array(); + list($bucket, $uri) = $this->explode_path($path); + + $contents = $this->s->getBucket($bucket, $uri, null, null, '/', true); + foreach ($contents as $object) { + + // If object has a prefix, it is a 'CommonPrefix', which we consider a folder + if (isset($object['prefix'])) { + $title = rtrim($object['prefix'], '/'); + } else { + $title = $object['name']; + } + + // Removes the prefix (folder path) from the title + if (strlen($uri) > 0) { + $title = substr($title, strlen($uri)); + // Check if title is empty and not zero + if (empty($title) && !is_numeric($title)) { + // Amazon returns the prefix itself, we skip it + continue; + } + } + + // This is a so-called CommonPrefix, we consider it as a folder + if (isset($object['prefix'])) { + $folders[] = array( + 'title' => $title, + 'children' => array(), + 'thumbnail'=> $OUTPUT->pix_url(file_folder_icon(90))->out(false), + 'path' => $bucket . '/' . $object['prefix'] ); + } else { + $files[] = array( + 'title' => $title, + 'size' => $object['size'], + 'datemodified' => $object['time'], + 'source' => $bucket . '/' . $object['name'], + 'thumbnail' => $OUTPUT->pix_url(file_extension_icon($title, 90))->out(false) + ); + } + } + $tree = array_merge($folders, $files); + } + + $trail = ''; + if (!empty($path)) { + $parts = explode('/', $path); + if (count($parts) > 1) { + foreach ($parts as $part) { + if (!empty($part)) { + $trail .= $part . '/'; + $list['path'][] = array('name' => $part, 'path' => $trail); + } + } + } else { + $list['path'][] = array('name' => $path, 'path' => $path); } } @@ -110,13 +181,10 @@ class repository_s3 extends repository { * @return array The local stored path */ public function get_file($filepath, $file = '') { - global $CFG; - $arr = explode('/', $filepath); - $bucket = $arr[0]; - $filename = $arr[1]; + list($bucket, $uri) = $this->explode_path($filepath); $path = $this->prepare_file($file); - $this->s->getObject($bucket, $filename, $path); - return array('path'=>$path); + $this->s->getObject($bucket, $uri, $path); + return array('path' => $path); } /** diff --git a/rss/file.php b/rss/file.php index fdc4958e675..b9896db3781 100644 --- a/rss/file.php +++ b/rss/file.php @@ -85,7 +85,7 @@ if ($token==="$inttoken") { foreach ($modinfo->instances[$componentname] as $modinstanceid=>$cm) { if ($modinstanceid==$instanceid) { - $context = get_context_instance(CONTEXT_MODULE, $cm->id); + $context = context_module::instance($cm->id, IGNORE_MISSING); break; } } diff --git a/tag/coursetags_add.php b/tag/coursetags_add.php index 969dda3e3ac..2ad17772202 100644 --- a/tag/coursetags_add.php +++ b/tag/coursetags_add.php @@ -28,7 +28,7 @@ require_once('../config.php'); require_login(); -$systemcontext = get_context_instance(CONTEXT_SYSTEM); +$systemcontext = context_system::instance(); require_capability('moodle/tag:create', $systemcontext); if (empty($CFG->usetags)) { diff --git a/tag/coursetags_edit.php b/tag/coursetags_edit.php index 8dbc285dffa..53e6be65186 100644 --- a/tag/coursetags_edit.php +++ b/tag/coursetags_edit.php @@ -59,7 +59,7 @@ if ($courseid != SITEID) { } // Permissions -$sitecontext = get_context_instance(CONTEXT_SYSTEM); +$sitecontext = context_system::instance(); require_login($course); $canedit = has_capability('moodle/tag:create', $sitecontext); @@ -85,7 +85,7 @@ if ($data = data_submitted()) { // The title and breadcrumb $title = get_string('edittitle', $tagslang); $coursefullname = format_string($course->fullname); -$courseshortname = format_string($course->shortname, true, array('context' => get_context_instance(CONTEXT_COURSE, $course->id))); +$courseshortname = format_string($course->shortname, true, array('context' => context_course::instance($course->id))); $PAGE->navbar->add($title); $PAGE->set_title($title); $PAGE->set_heading($course->fullname); diff --git a/tag/coursetags_more.php b/tag/coursetags_more.php index 60b18207be1..61c3ccd3331 100644 --- a/tag/coursetags_more.php +++ b/tag/coursetags_more.php @@ -65,7 +65,7 @@ if ($courseid) { } if ($courseid) { - $PAGE->set_context(get_context_instance(CONTEXT_COURSE, $courseid)); + $PAGE->set_context(context_course::instance($courseid)); } else { $PAGE->set_context(get_system_context()); } @@ -86,7 +86,7 @@ $welcome = get_string('morewelcome', $tagslang); // The title and breadcrumb if ($courseid) { - $courseshortname = format_string($course->shortname, true, array('context' => get_context_instance(CONTEXT_COURSE, $courseid))); + $courseshortname = format_string($course->shortname, true, array('context' => context_course::instance($courseid))); $PAGE->navbar->add($courseshortname, new moodle_url('/course/view.php', array('id'=>$courseid))); } $PAGE->navbar->add($title); @@ -183,7 +183,7 @@ if ($loggedin) { } } if ($courseid) { - $fullname = format_string($course->fullname, true, array('context' => get_context_instance(CONTEXT_COURSE, $course->id))); + $fullname = format_string($course->fullname, true, array('context' => context_course::instance($course->id))); if ($show == 'course') { $link1 .= ' | '.get_string('moreshowcoursetags', $tagslang, $fullname).''; } else { diff --git a/tag/coursetagslib.php b/tag/coursetagslib.php index 5b5557aa5e4..7d36b473642 100644 --- a/tag/coursetagslib.php +++ b/tag/coursetagslib.php @@ -232,7 +232,7 @@ function coursetag_print_cloud($tagcloud, $return=false, $max_size=180, $min_siz $step = ($max_size - $min_size)/($spread); - $systemcontext = get_context_instance(CONTEXT_SYSTEM); + $systemcontext = context_system::instance(); $can_manage_tags = has_capability('moodle/tag:manage', $systemcontext); //prints the tag cloud diff --git a/tag/edit.php b/tag/edit.php index b71c72f2be0..3629ed0315c 100644 --- a/tag/edit.php +++ b/tag/edit.php @@ -36,7 +36,7 @@ if (empty($CFG->usetags)) { } //Editing a tag requires moodle/tag:edit capability -$systemcontext = get_context_instance(CONTEXT_SYSTEM); +$systemcontext = context_system::instance(); require_capability('moodle/tag:edit', $systemcontext); if ($tag_name) { diff --git a/tag/edit_form.php b/tag/edit_form.php index 972836755a7..9c62a4a6d05 100644 --- a/tag/edit_form.php +++ b/tag/edit_form.php @@ -51,7 +51,7 @@ class tag_edit_form extends moodleform { $mform->addElement('hidden', 'id'); $mform->setType('id', PARAM_INT); - $systemcontext = get_context_instance(CONTEXT_SYSTEM); + $systemcontext = context_system::instance(); if (has_capability('moodle/tag:manage', $systemcontext)) { $mform->addElement('text', 'rawname', get_string('name', 'tag'), diff --git a/tag/index.php b/tag/index.php index 7e957826964..dbf3009a9c1 100644 --- a/tag/index.php +++ b/tag/index.php @@ -41,7 +41,7 @@ $edit = optional_param('edit', -1, PARAM_BOOL); $userpage = optional_param('userpage', 0, PARAM_INT); // which page to show $perpage = optional_param('perpage', 24, PARAM_INT); -$systemcontext = get_context_instance(CONTEXT_SYSTEM); +$systemcontext = context_system::instance(); if ($tagname) { $tag = tag_get('name', $tagname, '*'); diff --git a/tag/lib.php b/tag/lib.php index cdbe37fb904..d2a6f66500e 100644 --- a/tag/lib.php +++ b/tag/lib.php @@ -600,7 +600,7 @@ function tag_delete($tagids) { } $success = true; - $context = get_context_instance(CONTEXT_SYSTEM); + $context = context_system::instance(); foreach ($tagids as $tagid) { if (is_null($tagid)) { // can happen if tag doesn't exists continue; diff --git a/tag/locallib.php b/tag/locallib.php index fb7f9a9f730..81afc01928f 100644 --- a/tag/locallib.php +++ b/tag/locallib.php @@ -39,7 +39,7 @@ require_once($CFG->libdir.'/filelib.php'); function tag_print_cloud($nr_of_tags=150, $return=false) { global $CFG, $DB; - $can_manage_tags = has_capability('moodle/tag:manage', get_context_instance(CONTEXT_SYSTEM)); + $can_manage_tags = has_capability('moodle/tag:manage', context_system::instance()); if ( !$tagsincloud = $DB->get_records_sql('SELECT tg.rawname, tg.id, tg.name, tg.tagtype, COUNT(ti.id) AS count, tg.flag FROM {tag_instance} ti JOIN {tag} tg ON tg.id = ti.tagid @@ -146,7 +146,7 @@ function tag_print_description_box($tag_object, $return=false) { $options = new stdClass(); $options->para = false; $options->overflowdiv = true; - $tag_object->description = file_rewrite_pluginfile_urls($tag_object->description, 'pluginfile.php', get_context_instance(CONTEXT_SYSTEM)->id, 'tag', 'description', $tag_object->id); + $tag_object->description = file_rewrite_pluginfile_urls($tag_object->description, 'pluginfile.php', context_system::instance()->id, 'tag', 'description', $tag_object->id); $output .= format_text($tag_object->description, $tag_object->descriptionformat, $options); } @@ -190,7 +190,7 @@ function tag_print_management_box($tag_object, $return=false) { if (!isguestuser()) { $output .= $OUTPUT->box_start('box','tag-management-box'); - $systemcontext = get_context_instance(CONTEXT_SYSTEM); + $systemcontext = context_system::instance(); $links = array(); // Add a link for users to add/remove this from their interests @@ -356,7 +356,7 @@ function tag_print_tagged_users_table($tag_object, $limitfrom='', $limitnum='', function tag_print_user_box($user, $return=false) { global $CFG, $OUTPUT; - $usercontext = get_context_instance(CONTEXT_USER, $user->id); + $usercontext = context_user::instance($user->id); $profilelink = ''; if ($usercontext and (has_capability('moodle/user:viewdetails', $usercontext) || has_coursecontact_role($user->id))) { diff --git a/tag/manage.php b/tag/manage.php index e0edeb94bf5..2a886d3c7aa 100644 --- a/tag/manage.php +++ b/tag/manage.php @@ -41,7 +41,7 @@ if (empty($CFG->usetags)) { print_error('tagsaredisabled', 'tag'); } -$systemcontext = get_context_instance(CONTEXT_SYSTEM); +$systemcontext = context_system::instance(); require_capability('moodle/tag:manage', $systemcontext); $params = array(); @@ -151,7 +151,7 @@ switch($action) { // tag exists, change the type tag_type_set($new_otag_id, 'official'); } else { - require_capability('moodle/tag:create', get_context_instance(CONTEXT_SYSTEM)); + require_capability('moodle/tag:create', context_system::instance()); tag_add($new_otag, 'official'); } $notice .= get_string('addedotag', 'tag', $new_otag) .' '; diff --git a/tag/search.php b/tag/search.php index 7ebcfbf3e99..422d4e1bc7c 100644 --- a/tag/search.php +++ b/tag/search.php @@ -47,10 +47,10 @@ if ($perpage !== 18) { $params['perpage'] = $perpage; } $PAGE->set_url(new moodle_url('/tag/search.php', $params)); -$PAGE->set_context(get_context_instance(CONTEXT_SYSTEM)); +$PAGE->set_context(context_system::instance()); $PAGE->set_pagelayout('standard'); -$systemcontext = get_context_instance(CONTEXT_SYSTEM); +$systemcontext = context_system::instance(); $manage_link = ' '; $PAGE->set_title(get_string('tags', 'tag')); diff --git a/theme/base/style/admin.css b/theme/base/style/admin.css index 049a2a88d87..8c0ce47fc5c 100644 --- a/theme/base/style/admin.css +++ b/theme/base/style/admin.css @@ -68,6 +68,7 @@ .path-admin-roles .capabilitysearchui {text-align: left;margin-left: auto;margin-right: auto;} #page-admin-roles-define .topfields {margin: 1em 0 2em;} #page-admin-roles-define .mform {width: 100%;} +#page-admin-roles-define .capdefault {background-color: #eee; border: 1px solid #cecece;} #page-filter-manage .backlink, .path-admin-roles .backlink {margin-top: 1em} #page-admin-roles-explain #chooseuser h3, diff --git a/theme/canvas/config.php b/theme/canvas/config.php index 925a72b0701..70d1790a21d 100644 --- a/theme/canvas/config.php +++ b/theme/canvas/config.php @@ -40,9 +40,7 @@ $THEME->name = 'canvas'; // the directory in which this file resides. //////////////////////////////////////////////////// -$THEME->parents = array( - 'base', -); +$THEME->parents = array('base'); ///////////////////////////////////////////////////// // Which existing theme(s) in the /theme/ directory @@ -73,12 +71,7 @@ $THEME->sheets = array( // this theme's /styles/ directory. //////////////////////////////////////////////////// -$THEME->parents_exclude_sheets = array( - 'base'=>array( - 'navigation', - 'browser', - ), -); +$THEME->parents_exclude_sheets = array(); //////////////////////////////////////////////////// // An array of stylesheets not to inherit from the @@ -194,16 +187,13 @@ $THEME->hidefromselector = true; // switched on. ///////////////////////////////////////////////////// - - -// $THEME->enable_dock = false; +$THEME->enable_dock = true; //////////////////////////////////////////////////// // Do you want to use the new navigation dock? //////////////////////////////////////////////////// - -// $THEME->editor_sheets +$THEME->editor_sheets = array('editor'); //////////////////////////////////////////////////// // An array of stylesheets to include within the @@ -265,5 +255,3 @@ $THEME->hidefromselector = true; // Sets a custom render factory to use with the // theme, used when working with custom renderers. //////////////////////////////////////////////////// - -$THEME->editor_sheets = array('editor'); \ No newline at end of file diff --git a/theme/canvas/layout/frontpage.php b/theme/canvas/layout/frontpage.php index a8b573d1f0a..3c3b0f66d9c 100644 --- a/theme/canvas/layout/frontpage.php +++ b/theme/canvas/layout/frontpage.php @@ -1,19 +1,24 @@ heading); -$hasnavbar = (empty($PAGE->layout_options['nonavbar']) && $PAGE->has_navbar()); -$hasfooter = (empty($PAGE->layout_options['nofooter'])); $hassidepre = $PAGE->blocks->region_has_content('side-pre', $OUTPUT); $hassidepost = $PAGE->blocks->region_has_content('side-post', $OUTPUT); +$showsidepre = $hassidepre && !$PAGE->blocks->region_completely_docked('side-pre', $OUTPUT); +$showsidepost = $hassidepost && !$PAGE->blocks->region_completely_docked('side-post', $OUTPUT); + +$custommenu = $OUTPUT->custom_menu(); +$hascustommenu = (empty($PAGE->layout_options['nocustommenu']) && !empty($custommenu)); $bodyclasses = array(); -if ($hassidepre && !$hassidepost) { +if ($showsidepre && !$showsidepost) { $bodyclasses[] = 'side-pre-only'; -} else if ($hassidepost && !$hassidepre) { +} else if ($showsidepost && !$showsidepre) { $bodyclasses[] = 'side-post-only'; -} else if (!$hassidepost && !$hassidepre) { +} else if (!$showsidepost && !$showsidepre) { $bodyclasses[] = 'content-only'; } +if ($hascustommenu) { + $bodyclasses[] = 'has_custom_menu'; +} echo $OUTPUT->doctype() ?> htmlattributes() ?>> @@ -30,20 +35,24 @@ echo $OUTPUT->doctype() ?> -
+
- + + + +
+
@@ -51,57 +60,57 @@ echo $OUTPUT->doctype() ?> -
-
-
-
+
+
+
+
-
-
-
- main_content() ?> -
-
-
+
+
+
+ main_content() ?> +
+
+
- -
-
- blocks_for_region('side-pre') ?> -
-
- + +
+
+ blocks_for_region('side-pre') ?> +
+
+ - -
-
- blocks_for_region('side-post') ?> -
-
- + +
+
+ blocks_for_region('side-post') ?> +
+
+ -
-
-
-
+
+
+
+
- -
+
diff --git a/theme/canvas/layout/general.php b/theme/canvas/layout/general.php index cda6005acd4..09261f02e69 100644 --- a/theme/canvas/layout/general.php +++ b/theme/canvas/layout/general.php @@ -3,17 +3,27 @@ $hasheading = ($PAGE->heading); $hasnavbar = (empty($PAGE->layout_options['nonavbar']) && $PAGE->has_navbar()); $hasfooter = (empty($PAGE->layout_options['nofooter'])); -$hassidepre = $PAGE->blocks->region_has_content('side-pre', $OUTPUT); -$hassidepost = $PAGE->blocks->region_has_content('side-post', $OUTPUT); +$hassidepre = (empty($PAGE->layout_options['noblocks']) && $PAGE->blocks->region_has_content('side-pre', $OUTPUT)); +$hassidepost = (empty($PAGE->layout_options['noblocks']) && $PAGE->blocks->region_has_content('side-post', $OUTPUT)); +$haslogininfo = (empty($PAGE->layout_options['nologininfo'])); + +$showsidepre = ($hassidepre && !$PAGE->blocks->region_completely_docked('side-pre', $OUTPUT)); +$showsidepost = ($hassidepost && !$PAGE->blocks->region_completely_docked('side-post', $OUTPUT)); + +$custommenu = $OUTPUT->custom_menu(); +$hascustommenu = (empty($PAGE->layout_options['nocustommenu']) && !empty($custommenu)); $bodyclasses = array(); -if ($hassidepre && !$hassidepost) { +if ($showsidepre && !$showsidepost) { $bodyclasses[] = 'side-pre-only'; -} else if ($hassidepost && !$hassidepre) { +} else if ($showsidepost && !$showsidepre) { $bodyclasses[] = 'side-post-only'; -} else if (!$hassidepost && !$hassidepre) { +} else if (!$showsidepost && !$showsidepre) { $bodyclasses[] = 'content-only'; } +if ($hascustommenu) { + $bodyclasses[] = 'has_custom_menu'; +} echo $OUTPUT->doctype() ?> htmlattributes() ?>> @@ -49,6 +59,10 @@ echo $OUTPUT->doctype() ?> + +
+ + -
+
blocks_for_region('side-pre') ?>
@@ -84,7 +98,7 @@ echo $OUTPUT->doctype() ?> -
+
blocks_for_region('side-post') ?>
diff --git a/theme/canvas/layout/report.php b/theme/canvas/layout/report.php index fce6e89e427..9141174123d 100644 --- a/theme/canvas/layout/report.php +++ b/theme/canvas/layout/report.php @@ -3,17 +3,23 @@ $hasheading = ($PAGE->heading); $hasnavbar = (empty($PAGE->layout_options['nonavbar']) && $PAGE->has_navbar()); $hasfooter = (empty($PAGE->layout_options['nofooter'])); -$hassidepre = $PAGE->blocks->region_has_content('side-pre', $OUTPUT); -$hassidepost = $PAGE->blocks->region_has_content('side-post', $OUTPUT); +$hassidepre = (empty($PAGE->layout_options['noblocks']) && $PAGE->blocks->region_has_content('side-pre', $OUTPUT)); +$haslogininfo = (empty($PAGE->layout_options['nologininfo'])); + +$showsidepre = ($hassidepre && !$PAGE->blocks->region_completely_docked('side-pre', $OUTPUT)); + +$custommenu = $OUTPUT->custom_menu(); +$hascustommenu = (empty($PAGE->layout_options['nocustommenu']) && !empty($custommenu)); $bodyclasses = array(); -if ($hassidepre && !$hassidepost) { +if ($showsidepre ) { $bodyclasses[] = 'side-pre-only'; -} else if ($hassidepost && !$hassidepre) { - $bodyclasses[] = 'side-post-only'; -} else if (!$hassidepost && !$hassidepre) { +} else { $bodyclasses[] = 'content-only'; } +if ($hascustommenu) { + $bodyclasses[] = 'has_custom_menu'; +} echo $OUTPUT->doctype() ?> htmlattributes() ?>> @@ -49,6 +55,10 @@ echo $OUTPUT->doctype() ?>
+ +
+ + '; @@ -405,7 +405,7 @@ class theme_mymobile_core_renderer extends core_renderer { // $course->id is not defined during installation return ''; } else if (isloggedin()) { - $context = get_context_instance(CONTEXT_COURSE, $course->id); + $context = context_course::instance($course->id); $fullname = fullname($USER, true); // Since Moodle 2.0 this link always goes to the public profile page (not the course profile page) @@ -447,7 +447,7 @@ class theme_mymobile_core_renderer extends core_renderer { } else { $loggedinas .= get_string('failedloginattemptsall', '', $count); } - if (has_capability('report/log:view', get_context_instance(CONTEXT_SYSTEM))) { + if (has_capability('report/log:view', context_system::instance())) { $loggedinas .= ' ('.get_string('logs').')'; } $loggedinas .= '
'; diff --git a/theme/mymobile/style/jmobile11_rtl.css b/theme/mymobile/style/jmobile11_rtl.css new file mode 100644 index 00000000000..7d2ba26d8e6 --- /dev/null +++ b/theme/mymobile/style/jmobile11_rtl.css @@ -0,0 +1,54 @@ +.dir-rtl .ui-collapsible-heading a {text-align: right} + +.dir-rtl .ui-li, .ui-li.ui-field-contain {text-align: right;} + +.dir-rtl .ui-li-thumb, .dir-rtl .ui-listview .ui-li-icon, .dir-rtl .ui-li-content { + float: right; + margin-left: 27px; +} +.dir-rtl .ui-li, .dir-rtl .ui-li.ui-field-contain { + text-align: right; +} +.dir-rtl .ui-listview .ui-li-icon {right:27px; left:auto;} + +.dir-rtl .mod-indent-1 { margin-right: 0px;} + +.dir-rtl .ui-icon-arrow-r { + background-position: -108px 0%; +} + +.dir-rtl .ui-field-contain div.ui-slider-switch { + width: 10.5em; +} + +.dir-rtl .coursebox h3 a .ui-btn-inner, .dir-rtl .category a .ui-btn-inner { + padding-right: .8em; + padding-left: 8px; +} + +.dir-rtl .mform .fitem .felement { + margin-right: auto; + margin-left: 16%; + text-align: right; +} + +.dir-rtl .has-myblocks .content-secondary { + text-align: right; +} + +.dir-rtl .forumheaderlist thead .ui-btn-inner, .dir-rtl .topic .ui-btn { + text-align: right !important; + padding-right: 7px; +} + +.dir-rtl .ui-li-count { left:38px; right:auto;} + +.dir-rtl .ui-checkbox .ui-btn, .dir-rtl .ui-radio .ui-btn { + text-align: right; +} + +.dir-rtl .mform .fitemtitle { text-align: right !important; } + +.path-mod-quiz.dir-rtl .que .control { + width: 75%; +} \ No newline at end of file diff --git a/theme/standard/style/core.css b/theme/standard/style/core.css index cb7311557f0..d3410e7b28a 100644 --- a/theme/standard/style/core.css +++ b/theme/standard/style/core.css @@ -453,3 +453,4 @@ table#tag-management-list {margin: 10px auto;width: 80%;} #page-message-edit table.generaltable th.c0 {text-align: left;} #page-message-edit table.generaltable td.c0 {text-align: right;} #page-message-edit table.generaltable td.disallowed {text-align: center;vertical-align:middle;} +#messagewarning {font-style:italic;} diff --git a/user/addnote.php b/user/addnote.php index 1b899822686..e64957b4ecc 100644 --- a/user/addnote.php +++ b/user/addnote.php @@ -37,7 +37,7 @@ if (! $course = $DB->get_record('course', array('id'=>$id))) { print_error('invalidcourseid'); } -$context = get_context_instance(CONTEXT_COURSE, $id); +$context = context_course::instance($id); require_login($course); // to create notes the current user needs a capability diff --git a/user/edit.php b/user/edit.php index aa88131d5fa..207093c23dd 100644 --- a/user/edit.php +++ b/user/edit.php @@ -97,12 +97,12 @@ if ($editurl = $userauth->edit_profile_url()) { } if ($course->id == SITEID) { - $coursecontext = get_context_instance(CONTEXT_SYSTEM); // SYSTEM context + $coursecontext = context_system::instance(); // SYSTEM context } else { - $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id); // Course context + $coursecontext = context_course::instance($course->id); // Course context } -$systemcontext = get_context_instance(CONTEXT_SYSTEM); -$personalcontext = get_context_instance(CONTEXT_USER, $user->id); +$systemcontext = context_system::instance(); +$personalcontext = context_user::instance($user->id); // check access control if ($user->id == $USER->id) { @@ -244,7 +244,7 @@ if ($usernew = $userform->get_data()) { $a = new stdClass(); $a->url = $CFG->wwwroot . '/user/emailupdate.php?key=' . $usernew->preference_newemailkey . '&id=' . $user->id; - $a->site = format_string($SITE->fullname, true, array('context' => get_context_instance(CONTEXT_COURSE, SITEID))); + $a->site = format_string($SITE->fullname, true, array('context' => context_course::instance(SITEID))); $a->fullname = fullname($user, true); $emailupdatemessage = get_string('emailupdatemessage', 'auth', $a); diff --git a/user/edit_form.php b/user/edit_form.php index b077a0c2143..cec4d5dfd68 100644 --- a/user/edit_form.php +++ b/user/edit_form.php @@ -83,7 +83,7 @@ class user_edit_form extends moodleform { // print picture if (!empty($CFG->gdversion)) { - $context = get_context_instance(CONTEXT_USER, $user->id, MUST_EXIST); + $context = context_user::instance($user->id, MUST_EXIST); $fs = get_file_storage(); $hasuploadedpicture = ($fs->file_exists($context->id, 'user', 'icon', 0, '/', 'f2.png') || $fs->file_exists($context->id, 'user', 'icon', 0, '/', 'f2.jpg')); if (!empty($user->picture) && $hasuploadedpicture) { @@ -147,7 +147,7 @@ class user_edit_form extends moodleform { $errors['email'] = get_string('toomanybounces'); } - if (isset($usernew->email) and !empty($CFG->verifychangedemail) and !isset($errors['email']) and !has_capability('moodle/user:update', get_context_instance(CONTEXT_SYSTEM))) { + if (isset($usernew->email) and !empty($CFG->verifychangedemail) and !isset($errors['email']) and !has_capability('moodle/user:update', context_system::instance())) { $errorstr = email_is_not_allowed($usernew->email); if ($errorstr !== false) { $errors['email'] = $errorstr; diff --git a/user/editadvanced.php b/user/editadvanced.php index cdf03bd86e7..10c0faa0b48 100644 --- a/user/editadvanced.php +++ b/user/editadvanced.php @@ -49,11 +49,11 @@ if (!empty($USER->newadminuser)) { } if ($course->id == SITEID) { - $coursecontext = get_context_instance(CONTEXT_SYSTEM); // SYSTEM context + $coursecontext = context_system::instance(); // SYSTEM context } else { - $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id); // Course context + $coursecontext = context_course::instance($course->id); // Course context } -$systemcontext = get_context_instance(CONTEXT_SYSTEM); +$systemcontext = context_system::instance(); if ($id == -1) { // creating new user @@ -68,7 +68,7 @@ if ($id == -1) { // editing existing user require_capability('moodle/user:update', $systemcontext); $user = $DB->get_record('user', array('id'=>$id), '*', MUST_EXIST); - $PAGE->set_context(get_context_instance(CONTEXT_USER, $user->id)); + $PAGE->set_context(context_user::instance($user->id)); if ($user->id == $USER->id) { if ($course->id != SITEID && $node = $PAGE->navigation->find($course->id, navigation_node::TYPE_COURSE)) { $node->make_active(); @@ -112,7 +112,7 @@ if (!empty($CFG->usetags)) { } if ($user->id !== -1) { - $usercontext = get_context_instance(CONTEXT_USER, $user->id); + $usercontext = context_user::instance($user->id); $editoroptions = array( 'maxfiles' => EDITOR_UNLIMITED_FILES, 'maxbytes' => $CFG->maxbytes, @@ -203,7 +203,7 @@ if ($usernew = $userform->get_data()) { $usercreated = false; } - $usercontext = get_context_instance(CONTEXT_USER, $usernew->id); + $usercontext = context_user::instance($usernew->id); //update preferences useredit_update_user_preference($usernew); diff --git a/user/editadvanced_form.php b/user/editadvanced_form.php index dbe6d829cab..04a63d718e0 100644 --- a/user/editadvanced_form.php +++ b/user/editadvanced_form.php @@ -130,7 +130,7 @@ class user_editadvanced_form extends moodleform { // print picture if (!empty($CFG->gdversion) and empty($USER->newadminuser)) { if ($user) { - $context = get_context_instance(CONTEXT_USER, $user->id, MUST_EXIST); + $context = context_user::instance($user->id, MUST_EXIST); $fs = get_file_storage(); $hasuploadedpicture = ($fs->file_exists($context->id, 'user', 'icon', 0, '/', 'f2.png') || $fs->file_exists($context->id, 'user', 'icon', 0, '/', 'f2.jpg')); if (!empty($user->picture) && $hasuploadedpicture) { diff --git a/user/editlib.php b/user/editlib.php index 4c2a317fa34..d2250fbbfc3 100644 --- a/user/editlib.php +++ b/user/editlib.php @@ -46,7 +46,7 @@ function useredit_update_picture(stdClass $usernew, moodleform $userform, $filem global $CFG, $DB; require_once("$CFG->libdir/gdlib.php"); - $context = get_context_instance(CONTEXT_USER, $usernew->id, MUST_EXIST); + $context = context_user::instance($usernew->id, MUST_EXIST); $user = $DB->get_record('user', array('id'=>$usernew->id), 'id, picture', MUST_EXIST); $newpicture = $user->picture; diff --git a/user/emailupdate.php b/user/emailupdate.php index 602aa164017..0aee6c87584 100644 --- a/user/emailupdate.php +++ b/user/emailupdate.php @@ -31,7 +31,7 @@ $key = required_param('key', PARAM_ALPHANUM); $id = required_param('id', PARAM_INT); $PAGE->set_url('/user/emailupdate.php', array('id'=>$id, 'key'=>$key)); -$PAGE->set_context(get_context_instance(CONTEXT_SYSTEM)); +$PAGE->set_context(context_system::instance()); if (!$user = $DB->get_record('user', array('id' => $id))) { print_error('invaliduserid'); diff --git a/user/externallib.php b/user/externallib.php index 47b2663a663..4ea18553c22 100644 --- a/user/externallib.php +++ b/user/externallib.php @@ -100,7 +100,7 @@ class core_user_external extends external_api { require_once($CFG->dirroot."/user/profile/lib.php"); //required for customfields related function // Ensure the current user is allowed to run this function - $context = get_context_instance(CONTEXT_SYSTEM); + $context = context_system::instance(); self::validate_context($context); require_capability('moodle/user:create', $context); @@ -226,7 +226,7 @@ class core_user_external extends external_api { require_once($CFG->dirroot."/user/lib.php"); // Ensure the current user is allowed to run this function - $context = get_context_instance(CONTEXT_SYSTEM); + $context = context_system::instance(); require_capability('moodle/user:delete', $context); self::validate_context($context); @@ -324,7 +324,7 @@ class core_user_external extends external_api { require_once($CFG->dirroot."/user/profile/lib.php"); //required for customfields related function // Ensure the current user is allowed to run this function - $context = get_context_instance(CONTEXT_SYSTEM); + $context = context_system::instance(); require_capability('moodle/user:update', $context); self::validate_context($context); @@ -413,7 +413,7 @@ class core_user_external extends external_api { continue; } context_instance_preload($user); - $usercontext = get_context_instance(CONTEXT_USER, $user->id); + $usercontext = context_user::instance($user->id, IGNORE_MISSING); self::validate_context($usercontext); $currentuser = ($user->id == $USER->id); @@ -576,7 +576,7 @@ class core_user_external extends external_api { } context_instance_preload($user); $course = $courses[$courseids[$user->id]]; - $context = get_context_instance(CONTEXT_COURSE, $courseids[$user->id]); + $context = context_course::instance($courseids[$user->id], IGNORE_MISSING); self::validate_context($context); if ($userarray = user_get_user_details($user, $course)) { $result[] = $userarray; @@ -614,6 +614,7 @@ class core_user_external extends external_api { 'msn' => new external_value(PARAM_NOTAGS, 'msn number', VALUE_OPTIONAL), 'department' => new external_value(PARAM_TEXT, 'department', VALUE_OPTIONAL), 'institution' => new external_value(PARAM_TEXT, 'institution', VALUE_OPTIONAL), + 'idnumber' => new external_value(PARAM_RAW, 'An arbitrary ID code number perhaps from the institution', VALUE_OPTIONAL), 'interests' => new external_value(PARAM_TEXT, 'user interests (separated by commas)', VALUE_OPTIONAL), 'firstaccess' => new external_value(PARAM_INT, 'first access to the site (0 if never)', VALUE_OPTIONAL), 'lastaccess' => new external_value(PARAM_INT, 'last access to the site (0 if never)', VALUE_OPTIONAL), diff --git a/user/files.php b/user/files.php index 54f7962c75a..973bbf5773c 100644 --- a/user/files.php +++ b/user/files.php @@ -38,7 +38,7 @@ if (empty($returnurl)) { $returnurl = new moodle_url('/user/files.php'); } -$context = get_context_instance(CONTEXT_USER, $USER->id); +$context = context_user::instance($USER->id); require_capability('moodle/user:manageownfiles', $context); $title = get_string('myfiles'); diff --git a/user/filters/courserole.php b/user/filters/courserole.php index a38fe415c6f..0247bcc4f99 100644 --- a/user/filters/courserole.php +++ b/user/filters/courserole.php @@ -21,7 +21,7 @@ class user_filter_courserole extends user_filter_type { * @return array of availble roles */ function get_roles() { - $context = get_context_instance(CONTEXT_SYSTEM); + $context = context_system::instance(); $roles = array(0=> get_string('anyrole','filters')) + get_default_enrol_roles($context); return $roles; } diff --git a/user/filters/globalrole.php b/user/filters/globalrole.php index 2721fdb9a0b..2e9635ecbe2 100644 --- a/user/filters/globalrole.php +++ b/user/filters/globalrole.php @@ -22,7 +22,7 @@ class user_filter_globalrole extends user_filter_type { * @return array of availble roles */ function get_roles() { - $context = get_context_instance(CONTEXT_SYSTEM); + $context = context_system::instance(); $roles = array(0=> get_string('anyrole','filters')) + get_assignable_roles($context); return $roles; } diff --git a/user/groupaddnote.php b/user/groupaddnote.php index 26649da10ba..67dc9b39c2c 100644 --- a/user/groupaddnote.php +++ b/user/groupaddnote.php @@ -44,7 +44,7 @@ if (! $course = $DB->get_record('course', array('id'=>$id))) { print_error('invalidcourseid'); } -$context = get_context_instance(CONTEXT_COURSE, $id); +$context = context_course::instance($id); require_login($course); // to create notes the current user needs a capability diff --git a/user/index.php b/user/index.php index c73e42b02a6..e850bdc9a90 100644 --- a/user/index.php +++ b/user/index.php @@ -41,7 +41,7 @@ $course = $DB->get_record('course', array('id'=>$context->instanceid), '*', MUST_EXIST); } else { $course = $DB->get_record('course', array('id'=>$courseid), '*', MUST_EXIST); - $context = get_context_instance(CONTEXT_COURSE, $course->id, MUST_EXIST); + $context = context_course::instance($course->id, MUST_EXIST); } // not needed anymore unset($contextid); @@ -49,10 +49,10 @@ require_login($course); - $systemcontext = get_context_instance(CONTEXT_SYSTEM); + $systemcontext = context_system::instance(); $isfrontpage = ($course->id == SITEID); - $frontpagectx = get_context_instance(CONTEXT_COURSE, SITEID); + $frontpagectx = context_course::instance(SITEID); if ($isfrontpage) { $PAGE->set_pagelayout('admin'); @@ -190,7 +190,7 @@ $courselist = array(); $popupurl = new moodle_url('/user/index.php?roleid='.$roleid.'&sifirst=&silast='); foreach ($mycourses as $mycourse) { - $coursecontext = get_context_instance(CONTEXT_COURSE, $mycourse->id); + $coursecontext = context_course::instance($mycourse->id); $courselist[$mycourse->id] = format_string($mycourse->shortname, true, array('context' => $coursecontext)); } if (has_capability('moodle/site:viewparticipants', $systemcontext)) { @@ -579,8 +579,8 @@ context_instance_preload($user); - $context = get_context_instance(CONTEXT_COURSE, $course->id); - $usercontext = get_context_instance(CONTEXT_USER, $user->id); + $context = context_course::instance($course->id); + $usercontext = context_user::instance($user->id); $countries = get_string_manager()->get_list_of_countries(); @@ -719,7 +719,7 @@ } } - $usercontext = get_context_instance(CONTEXT_USER, $user->id); + $usercontext = context_user::instance($user->id); if ($piclink = ($USER->id == $user->id || has_capability('moodle/user:viewdetails', $context) || has_capability('moodle/user:viewdetails', $usercontext))) { $profilelink = ''.fullname($user).''; diff --git a/user/lib.php b/user/lib.php index 9a497d2b9f2..72998b8c3a7 100644 --- a/user/lib.php +++ b/user/lib.php @@ -70,7 +70,7 @@ function user_create_user($user) { $newuser = $DB->get_record('user', array('id' => $newuserid)); // create USER context for this user - get_context_instance(CONTEXT_USER, $newuserid); + context_user::instance($newuserid); // update user password if necessary if (isset($userpassword)) { @@ -225,11 +225,11 @@ function user_get_user_details($user, $course = null, array $userfields = array( } if (!empty($course)) { - $context = get_context_instance(CONTEXT_COURSE, $course->id); - $usercontext = get_context_instance(CONTEXT_USER, $user->id); + $context = context_course::instance($course->id); + $usercontext = context_user::instance($user->id); $canviewdetailscap = (has_capability('moodle/user:viewdetails', $context) || has_capability('moodle/user:viewdetails', $usercontext)); } else { - $context = get_context_instance(CONTEXT_USER, $user->id); + $context = context_user::instance($user->id); $usercontext = $context; $canviewdetailscap = has_capability('moodle/user:viewdetails', $usercontext); } @@ -237,6 +237,8 @@ function user_get_user_details($user, $course = null, array $userfields = array( $currentuser = ($user->id == $USER->id); $isadmin = is_siteadmin($USER); + $showuseridentityfields = get_extra_user_fields($context); + if (!empty($course)) { $canviewhiddenuserfields = has_capability('moodle/course:viewhiddenuserfields', $context); } else { @@ -319,16 +321,19 @@ function user_get_user_details($user, $course = null, array $userfields = array( if ($user->address && in_array('address', $userfields)) { $userdetails['address'] = $user->address; } - if ($user->phone1 && in_array('phone1', $userfields)) { - $userdetails['phone1'] = $user->phone1; - } - if ($user->phone2 && in_array('phone2', $userfields)) { - $userdetails['phone2'] = $user->phone2; - } } else { $hiddenfields = array_flip(explode(',', $CFG->hiddenuserfields)); } + if ($user->phone1 && in_array('phone1', $userfields) && + (isset($showuseridentityfields['phone1']) or $canviewhiddenuserfields)) { + $userdetails['phone1'] = $user->phone1; + } + if ($user->phone2 && in_array('phone2', $userfields) && + (isset($showuseridentityfields['phone2']) or $canviewhiddenuserfields)) { + $userdetails['phone2'] = $user->phone2; + } + if (isset($user->description) && (!isset($hiddenfields['description']) or $isadmin)) { if (!$cannotviewdescription) { @@ -393,6 +398,7 @@ function user_get_user_details($user, $course = null, array $userfields = array( if (in_array('email', $userfields) && ($isadmin // The admin is allowed the users email or $currentuser // Of course the current user is as well or $canviewuseremail // this is a capability in course context, it will be false in usercontext + or isset($showuseridentityfields['email']) or $user->maildisplay == 1 or ($user->maildisplay == 2 and enrol_sharing_course($user, $USER)))) { $userdetails['email'] = $user->email; @@ -405,11 +411,18 @@ function user_get_user_details($user, $course = null, array $userfields = array( } } - //Departement/Institution are not displayed on any profile, however you can get them from editing profile. - if ($isadmin or $currentuser) { + //Departement/Institution/Idnumber are not displayed on any profile, however you can get them from editing profile. + if ($isadmin or $currentuser or isset($showuseridentityfields['idnumber'])) { + if (in_array('idnumber', $userfields) && $user->idnumber) { + $userdetails['idnumber'] = $user->idnumber; + } + } + if ($isadmin or $currentuser or isset($showuseridentityfields['institution'])) { if (in_array('institution', $userfields) && $user->institution) { $userdetails['institution'] = $user->institution; } + } + if ($isadmin or $currentuser or isset($showuseridentityfields['department'])) { if (in_array('department', $userfields) && isset($user->department)) { //isset because it's ok to have department 0 $userdetails['department'] = $user->department; } @@ -448,10 +461,10 @@ function user_get_user_details($user, $course = null, array $userfields = array( if ($mycourses = enrol_get_users_courses($user->id, true)) { foreach ($mycourses as $mycourse) { if ($mycourse->category) { - $coursecontext = get_context_instance(CONTEXT_COURSE, $mycourse->id); + $coursecontext = context_course::instance($mycourse->id); $enrolledcourse = array(); $enrolledcourse['id'] = $mycourse->id; - $enrolledcourse['fullname'] = format_string($mycourse->fullname, true, array('context' => get_context_instance(CONTEXT_COURSE, $mycourse->id))); + $enrolledcourse['fullname'] = format_string($mycourse->fullname, true, array('context' => $coursecontext)); $enrolledcourse['shortname'] = format_string($mycourse->shortname, true, array('context' => $coursecontext)); $enrolledcourses[] = $enrolledcourse; } diff --git a/user/managetoken.php b/user/managetoken.php index c8f47b2af88..1342f129d48 100644 --- a/user/managetoken.php +++ b/user/managetoken.php @@ -29,7 +29,7 @@ require('../config.php'); require_login(); require_sesskey(); -$usercontext = get_context_instance(CONTEXT_USER, $USER->id); +$usercontext = context_user::instance($USER->id); $PAGE->set_context($usercontext); $PAGE->set_url('/user/managetoken.php'); diff --git a/user/messageselect.php b/user/messageselect.php index d54d26d4133..db354bf965d 100644 --- a/user/messageselect.php +++ b/user/messageselect.php @@ -58,7 +58,7 @@ if ($deluser !== 0) { $url->param('deluser', $deluser); } $PAGE->set_url($url); -$PAGE->set_context(get_context_instance(CONTEXT_SYSTEM)); +$PAGE->set_context(context_system::instance()); if (!$course = $DB->get_record('course', array('id'=>$id))) { print_error('invalidcourseid'); @@ -66,8 +66,8 @@ if (!$course = $DB->get_record('course', array('id'=>$id))) { require_login(); -$coursecontext = get_context_instance(CONTEXT_COURSE, $id); // Course context -$systemcontext = get_context_instance(CONTEXT_SYSTEM); // SYSTEM context +$coursecontext = context_course::instance($id); // Course context +$systemcontext = context_system::instance(); // SYSTEM context require_capability('moodle/course:bulkmessaging', $coursecontext); if (empty($SESSION->emailto)) { diff --git a/user/pix.php b/user/pix.php index b4b4cc1100b..1e354ed0c65 100644 --- a/user/pix.php +++ b/user/pix.php @@ -42,7 +42,7 @@ if (count($args) == 2) { } else { $image = 'f2'; } - if ($usercontext = get_context_instance(CONTEXT_USER, $userid)) { + if ($usercontext = context_user::instance($userid, IGNORE_MISSING)) { $url = moodle_url::make_pluginfile_url($usercontext->id, 'user', 'icon', NULL, '/', $image); redirect($url); } diff --git a/user/policy.php b/user/policy.php index 46a2f2bb20f..0f5168fe352 100644 --- a/user/policy.php +++ b/user/policy.php @@ -66,7 +66,7 @@ $strpolicyagree = get_string('policyagree'); $strpolicyagreement = get_string('policyagreement'); $strpolicyagreementclick = get_string('policyagreementclick'); -$PAGE->set_context(get_context_instance(CONTEXT_SYSTEM)); +$PAGE->set_context(context_system::instance()); $PAGE->set_title($strpolicyagreement); $PAGE->set_heading($SITE->fullname); $PAGE->navbar->add($strpolicyagreement); diff --git a/user/portfolio.php b/user/portfolio.php index c91e04e628d..653131e365d 100644 --- a/user/portfolio.php +++ b/user/portfolio.php @@ -58,7 +58,7 @@ $display = true; // set this to false in the conditions to stop processing require_login($course, false); $PAGE->set_url($url); -$PAGE->set_context(get_context_instance(CONTEXT_USER, $user->id)); +$PAGE->set_context(context_user::instance($user->id)); $PAGE->set_title("$course->fullname: $fullname: $strportfolios"); $PAGE->set_heading($course->fullname); $PAGE->set_pagelayout('standard'); diff --git a/user/portfoliologs.php b/user/portfoliologs.php index 1690b1f6381..d9f60355ebd 100644 --- a/user/portfoliologs.php +++ b/user/portfoliologs.php @@ -60,7 +60,7 @@ if ($perpage !== 0) { $PAGE->set_url($url); $PAGE->set_title("$course->fullname: $fullname: $strportfolios"); $PAGE->set_heading($course->fullname); -$PAGE->set_context(get_context_instance(CONTEXT_USER, $user->id)); +$PAGE->set_context(context_user::instance($user->id)); $PAGE->set_pagelayout('standard'); echo $OUTPUT->header(); diff --git a/user/profile.php b/user/profile.php index 9dafdd9d35a..979319dcd88 100644 --- a/user/profile.php +++ b/user/profile.php @@ -59,7 +59,7 @@ $userid = $userid ? $userid : $USER->id; // Owner of the page $user = $DB->get_record('user', array('id' => $userid)); if ($user->deleted) { - $PAGE->set_context(get_context_instance(CONTEXT_SYSTEM)); + $PAGE->set_context(context_system::instance()); echo $OUTPUT->header(); echo $OUTPUT->heading(get_string('userdeleted')); echo $OUTPUT->footer(); @@ -67,7 +67,7 @@ if ($user->deleted) { } $currentuser = ($user->id == $USER->id); -$context = $usercontext = get_context_instance(CONTEXT_USER, $userid, MUST_EXIST); +$context = $usercontext = context_user::instance($userid, MUST_EXIST); if (!$currentuser && !empty($CFG->forceloginforprofiles) && @@ -76,7 +76,7 @@ if (!$currentuser && // Course managers can be browsed at site level. If not forceloginforprofiles, allow access (bug #4366) $struser = get_string('user'); - $PAGE->set_context(get_context_instance(CONTEXT_SYSTEM)); + $PAGE->set_context(context_system::instance()); $PAGE->set_title("$SITE->shortname: $struser"); // Do not leak the name $PAGE->set_heading("$SITE->shortname: $struser"); $PAGE->set_url('/user/profile.php', array('id'=>$userid)); @@ -93,7 +93,7 @@ if (!$currentpage = my_get_page($userid, MY_PAGE_PUBLIC)) { } if (!$currentpage->userid) { - $context = get_context_instance(CONTEXT_SYSTEM); // A trick so that we even see non-sticky blocks + $context = context_system::instance(); // A trick so that we even see non-sticky blocks } $PAGE->set_context($context); @@ -306,7 +306,7 @@ if (!isset($hiddenfields['mycourses'])) { if ($mycourse->category) { $class = ''; if ($mycourse->visible == 0) { - $ccontext = get_context_instance(CONTEXT_COURSE, $mycourse->id); + $ccontext = context_course::instance($mycourse->id); if (!has_capability('moodle/course:viewhiddencourses', $ccontext)) { continue; } diff --git a/user/profile/field/checkbox/field.class.php b/user/profile/field/checkbox/field.class.php index 6602556d029..142ce254842 100644 --- a/user/profile/field/checkbox/field.class.php +++ b/user/profile/field/checkbox/field.class.php @@ -29,7 +29,7 @@ class profile_field_checkbox extends profile_field_base { $checkbox->setChecked(true); } $mform->setType($this->inputname, PARAM_BOOL); - if ($this->is_required() and !has_capability('moodle/user:update', get_context_instance(CONTEXT_SYSTEM))) { + if ($this->is_required() and !has_capability('moodle/user:update', context_system::instance())) { $mform->addRule($this->inputname, get_string('required'), 'nonzero', null, 'client'); } } diff --git a/user/profile/field/menu/field.class.php b/user/profile/field/menu/field.class.php index 36b711acc8f..c0b8694134b 100644 --- a/user/profile/field/menu/field.class.php +++ b/user/profile/field/menu/field.class.php @@ -80,7 +80,7 @@ class profile_field_menu extends profile_field_base { if (!$mform->elementExists($this->inputname)) { return; } - if ($this->is_locked() and !has_capability('moodle/user:update', get_context_instance(CONTEXT_SYSTEM))) { + if ($this->is_locked() and !has_capability('moodle/user:update', context_system::instance())) { $mform->hardFreeze($this->inputname); $mform->setConstant($this->inputname, $this->datakey); } diff --git a/user/profile/lib.php b/user/profile/lib.php index fd30d581180..4c193e4131d 100644 --- a/user/profile/lib.php +++ b/user/profile/lib.php @@ -67,7 +67,7 @@ class profile_field_base { function edit_field($mform) { if ($this->field->visible != PROFILE_VISIBLE_NONE - or has_capability('moodle/user:update', get_context_instance(CONTEXT_SYSTEM))) { + or has_capability('moodle/user:update', context_system::instance())) { $this->edit_field_add($mform); $this->edit_field_set_default($mform); @@ -85,7 +85,7 @@ class profile_field_base { function edit_after_data($mform) { if ($this->field->visible != PROFILE_VISIBLE_NONE - or has_capability('moodle/user:update', get_context_instance(CONTEXT_SYSTEM))) { + or has_capability('moodle/user:update', context_system::instance())) { $this->edit_field_set_locked($mform); return true; } @@ -183,7 +183,7 @@ class profile_field_base { if (!$mform->elementExists($this->inputname)) { return; } - if ($this->is_locked() and !has_capability('moodle/user:update', get_context_instance(CONTEXT_SYSTEM))) { + if ($this->is_locked() and !has_capability('moodle/user:update', context_system::instance())) { $mform->hardFreeze($this->inputname); $mform->setConstant($this->inputname, $this->data); } @@ -283,11 +283,11 @@ class profile_field_base { return true; } else { return has_capability('moodle/user:viewalldetails', - get_context_instance(CONTEXT_USER, $this->userid)); + context_user::instance($this->userid)); } default: return has_capability('moodle/user:viewalldetails', - get_context_instance(CONTEXT_USER, $this->userid)); + context_user::instance($this->userid)); } } @@ -359,7 +359,7 @@ function profile_definition($mform, $userid = 0) { global $CFG, $DB; // if user is "admin" fields are displayed regardless - $update = has_capability('moodle/user:update', get_context_instance(CONTEXT_SYSTEM)); + $update = has_capability('moodle/user:update', context_system::instance()); if ($categories = $DB->get_records('user_info_category', null, 'sortorder ASC')) { foreach ($categories as $category) { diff --git a/user/profilesys.php b/user/profilesys.php index 79740ef311e..fc3e467346e 100644 --- a/user/profilesys.php +++ b/user/profilesys.php @@ -37,7 +37,7 @@ $edit = optional_param('edit', null, PARAM_BOOL); // Turn editing on and of require_login(); -$context = get_context_instance(CONTEXT_SYSTEM); +$context = context_system::instance(); require_capability('moodle/my:configsyspages', $context); $PAGE->set_blocks_editing_capability('moodle/my:configsyspages'); $header = "$SITE->shortname: ".get_string('publicprofile')." (".get_string('myprofile', 'admin').")"; diff --git a/user/renderer.php b/user/renderer.php index 09f30d73895..70319c630b7 100644 --- a/user/renderer.php +++ b/user/renderer.php @@ -84,7 +84,7 @@ class user_files_tree implements renderable { public $dir; public function __construct() { global $USER; - $this->context = get_context_instance(CONTEXT_USER, $USER->id); + $this->context = context_user::instance($USER->id); $fs = get_file_storage(); $this->dir = $fs->get_area_tree($this->context->id, 'user', 'private', 0); } diff --git a/user/repository.php b/user/repository.php index 23ed84f160b..daa6de058f4 100644 --- a/user/repository.php +++ b/user/repository.php @@ -46,7 +46,7 @@ $configstr = get_string('manageuserrepository', 'repository'); $pluginstr = get_string('plugin', 'repository'); require_login($course, false); -$coursecontext = get_context_instance(CONTEXT_COURSE, $course->id, MUST_EXIST); +$coursecontext = context_course::instance($course->id, MUST_EXIST); $link = new moodle_url('/user/view.php', array('id'=>$user->id)); $PAGE->navbar->add($fullname, $link); diff --git a/user/selector/lib.php b/user/selector/lib.php index 35f40658d77..9aa40edf03f 100644 --- a/user/selector/lib.php +++ b/user/selector/lib.php @@ -98,7 +98,7 @@ abstract class user_selector_base { if (isset($options['accesscontext'])) { $this->accesscontext = $options['accesscontext']; } else { - $this->accesscontext = get_context_instance(CONTEXT_SYSTEM); + $this->accesscontext = context_system::instance(); } if (isset($options['extrafields'])) { @@ -676,7 +676,7 @@ abstract class groups_user_selector_base extends user_selector_base { */ public function __construct($name, $options) { global $CFG; - $options['accesscontext'] = get_context_instance(CONTEXT_COURSE, $options['courseid']); + $options['accesscontext'] = context_course::instance($options['courseid']); parent::__construct($name, $options); $this->groupid = $options['groupid']; $this->courseid = $options['courseid']; @@ -809,7 +809,7 @@ class group_non_members_selector extends groups_user_selector_base { global $DB; // Get list of allowed roles. - $context = get_context_instance(CONTEXT_COURSE, $this->courseid); + $context = context_course::instance($this->courseid); if ($validroleids = groups_get_possible_roles($context)) { list($roleids, $roleparams) = $DB->get_in_or_equal($validroleids, SQL_PARAMS_NAMED, 'r'); } else { diff --git a/user/selector/search.php b/user/selector/search.php index fcaf74ec3bb..341ebf5b226 100644 --- a/user/selector/search.php +++ b/user/selector/search.php @@ -26,7 +26,7 @@ require_once(dirname(__FILE__) . '/../../config.php'); require_once($CFG->dirroot . '/user/selector/lib.php'); -$PAGE->set_context(get_context_instance(CONTEXT_SYSTEM)); +$PAGE->set_context(context_system::instance()); $PAGE->set_url('/user/selector/search.php'); // In developer debug mode, when there is a debug=1 in the URL send as plain text diff --git a/user/view.php b/user/view.php index 68d36ac33cf..4c4c8da2b99 100644 --- a/user/view.php +++ b/user/view.php @@ -46,9 +46,9 @@ $user = $DB->get_record('user', array('id'=>$id), '*', MUST_EXIST); $course = $DB->get_record('course', array('id'=>$courseid), '*', MUST_EXIST); $currentuser = ($user->id == $USER->id); -$systemcontext = get_context_instance(CONTEXT_SYSTEM); -$coursecontext = get_context_instance(CONTEXT_COURSE, $course->id); -$usercontext = get_context_instance(CONTEXT_USER, $user->id, IGNORE_MISSING); +$systemcontext = context_system::instance(); +$coursecontext = context_course::instance($course->id); +$usercontext = context_user::instance($user->id, IGNORE_MISSING); // Require login first if (isguestuser($user)) { @@ -288,7 +288,7 @@ if (!isset($hiddenfields['mycourses'])) { $courselisting = ''; foreach ($mycourses as $mycourse) { if ($mycourse->category) { - $ccontext = get_context_instance(CONTEXT_COURSE, $mycourse->id);; + $ccontext = context_course::instance($mycourse->id);; $cfullname = format_string($mycourse->fullname, true, array('context' => $ccontext)); if ($mycourse->id != $course->id){ $class = ''; diff --git a/userpix/index.php b/userpix/index.php index 652df70401f..515957116ad 100644 --- a/userpix/index.php +++ b/userpix/index.php @@ -13,7 +13,7 @@ $PAGE->set_url('/userpix/index.php'); require_login(); /// Remove the following three lines if you want everyone to access it -$syscontext = get_context_instance(CONTEXT_SYSTEM); +$syscontext = context_system::instance(); require_capability('moodle/site:config', $syscontext); $title = get_string("users"); diff --git a/version.php b/version.php index 4d207bc7e59..6f790c025fb 100644 --- a/version.php +++ b/version.php @@ -30,11 +30,11 @@ defined('MOODLE_INTERNAL') || die(); -$version = 2012072600.00; // YYYYMMDD = weekly release date of this DEV branch +$version = 2012080200.01; // YYYYMMDD = weekly release date of this DEV branch // RR = release increments - 00 in DEV branches // .XX = incremental changes -$release = '2.4dev (Build: 20120726)'; // Human-friendly version name +$release = '2.4dev (Build: 20120802)'; // Human-friendly version name $branch = '24'; // this version's branch $maturity = MATURITY_ALPHA; // this version's maturity level diff --git a/webservice/externallib.php b/webservice/externallib.php index 7b006d6e1b1..4effcde1d49 100644 --- a/webservice/externallib.php +++ b/webservice/externallib.php @@ -71,7 +71,7 @@ class core_webservice_external extends external_api { array('serviceshortnames'=>$serviceshortnames)); $profileimageurl = moodle_url::make_pluginfile_url( - get_context_instance(CONTEXT_USER, $USER->id)->id, 'user', 'icon', NULL, '/', 'f1'); + context_user::instance($USER->id)->id, 'user', 'icon', NULL, '/', 'f1'); //site information $siteinfo = array( diff --git a/webservice/lib.php b/webservice/lib.php index 4fac2e9722a..66ed91f8f8e 100644 --- a/webservice/lib.php +++ b/webservice/lib.php @@ -102,7 +102,7 @@ class webservice { } //Non admin can not authenticate if maintenance mode - $hassiteconfig = has_capability('moodle/site:config', get_context_instance(CONTEXT_SYSTEM), $user); + $hassiteconfig = has_capability('moodle/site:config', context_system::instance(), $user); if (!empty($CFG->maintenance_enabled) and !$hassiteconfig) { //this is usually temporary, client want to implement code logic => moodle_exception throw new moodle_exception('sitemaintenance', 'admin'); @@ -116,7 +116,7 @@ class webservice { } //check if there is any required system capability - if ($service->requiredcapability and !has_capability($service->requiredcapability, get_context_instance(CONTEXT_SYSTEM), $user)) { + if ($service->requiredcapability and !has_capability($service->requiredcapability, context_system::instance(), $user)) { throw new webservice_access_exception('The capability ' . $service->requiredcapability . ' is required.'); } @@ -262,7 +262,7 @@ class webservice { global $CFG, $DB; // generate a token for non admin if web service are enable and the user has the capability to create a token - if (!is_siteadmin() && has_capability('moodle/webservice:createtoken', get_context_instance(CONTEXT_SYSTEM), $userid) && !empty($CFG->enablewebservices)) { + if (!is_siteadmin() && has_capability('moodle/webservice:createtoken', context_system::instance(), $userid) && !empty($CFG->enablewebservices)) { // for every service than the user is authorised on, create a token (if it doesn't already exist) // get all services which are set to all user (no restricted to specific users) @@ -298,7 +298,7 @@ class webservice { $newtoken->userid = $userid; $newtoken->externalserviceid = $serviceid; // TODO MDL-31190 find a way to get the context - UPDATE FOLLOWING LINE - $newtoken->contextid = get_context_instance(CONTEXT_SYSTEM)->id; + $newtoken->contextid = context_system::instance()->id; $newtoken->creatorid = $userid; $newtoken->timecreated = time(); @@ -835,7 +835,7 @@ abstract class webservice_server implements webservice_server_interface { throw new webservice_access_exception('The web service authentication plugin is missing.'); } - $this->restricted_context = get_context_instance(CONTEXT_SYSTEM); + $this->restricted_context = context_system::instance(); if (!$this->username) { throw new moodle_exception('missingusername', 'webservice'); @@ -860,7 +860,7 @@ abstract class webservice_server implements webservice_server_interface { } //Non admin can not authenticate if maintenance mode - $hassiteconfig = has_capability('moodle/site:config', get_context_instance(CONTEXT_SYSTEM), $user); + $hassiteconfig = has_capability('moodle/site:config', context_system::instance(), $user); if (!empty($CFG->maintenance_enabled) and !$hassiteconfig) { throw new moodle_exception('sitemaintenance', 'admin'); } @@ -1110,7 +1110,7 @@ abstract class webservice_zend_server extends webservice_server { FROM {external_services} s JOIN {external_services_functions} sf ON (sf.externalserviceid = s.id AND s.restrictedusers = 1) JOIN {external_services_users} su ON (su.externalserviceid = s.id AND su.userid = :userid) - WHERE s.enabled = 1 AND su.validuntil IS NULL OR su.validuntil < :now $wscond2"; + WHERE s.enabled = 1 AND (su.validuntil IS NULL OR su.validuntil < :now) $wscond2"; $params = array_merge($params, array('userid'=>$USER->id, 'now'=>time())); @@ -1612,7 +1612,7 @@ abstract class webservice_base_server extends webservice_server { FROM {external_services} s JOIN {external_services_functions} sf ON (sf.externalserviceid = s.id AND s.restrictedusers = 1 AND sf.functionname = :name2) JOIN {external_services_users} su ON (su.externalserviceid = s.id AND su.userid = :userid) - WHERE s.enabled = 1 AND su.validuntil IS NULL OR su.validuntil < :now $wscond2"; + WHERE s.enabled = 1 AND (su.validuntil IS NULL OR su.validuntil < :now) $wscond2"; $params = array_merge($params, array('userid'=>$USER->id, 'name1'=>$function->name, 'name2'=>$function->name, 'now'=>time())); $rs = $DB->get_recordset_sql($sql, $params); diff --git a/webservice/upload.php b/webservice/upload.php index 5e2f6cc0f2f..9c01869e004 100644 --- a/webservice/upload.php +++ b/webservice/upload.php @@ -51,7 +51,7 @@ $webservicelib = new webservice(); $authenticationinfo = $webservicelib->authenticate_user($token); // check the user can manage his own files (can upload) -$context = get_context_instance(CONTEXT_USER, $USER->id); +$context = context_user::instance($USER->id); require_capability('moodle/user:manageownfiles', $context); $fs = get_file_storage(); diff --git a/webservice/wsdoc.php b/webservice/wsdoc.php index a0206c2dbae..01b71c034c9 100644 --- a/webservice/wsdoc.php +++ b/webservice/wsdoc.php @@ -29,7 +29,7 @@ require($CFG->dirroot . '/webservice/lib.php'); require_login(); require_sesskey(); -$usercontext = get_context_instance(CONTEXT_USER, $USER->id); +$usercontext = context_user::instance($USER->id); $tokenid = required_param('id', PARAM_INT); // PAGE settings