MDL-82322 course: Coding style fixes

This commit is contained in:
Andrew Nicols
2025-08-25 15:09:50 +08:00
parent 5b98b99c59
commit bb78066b8f
9 changed files with 311 additions and 206 deletions
+58 -41
View File
@@ -33,6 +33,7 @@ use stdClass;
* Please note we do not allow embedded images here because there is no context
* to store them with proper access control.
*
* @package core_course
* @copyright 2009 Sam Hemelryk
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
* @since Moodle 2.0
@@ -47,7 +48,6 @@ use stdClass;
* @property-read int $requester
*/
class course_request {
/**
* This is the stdClass that stores the properties for the course request
* and is externally accessed through the __get magic method
@@ -57,26 +57,24 @@ class course_request {
/**
* An array of options for the summary editor used by course request forms.
* This is initially set by {@link summary_editor_options()}
*
* This is initially set by {@see summary_editor_options()}
* @var array
* @static
*/
protected static $summaryeditoroptions;
/**
* Static function to prepare the summary editor for working with a course
* request.
* Static function to prepare the summary editor for working with a course request.
*
* @static
* @param null|stdClass $data Optional, an object containing the default values
* for the form, these may be modified when preparing the
* editor so this should be called before creating the form
* @return stdClass An object that can be used to set the default values for
* an mforms form
*/
public static function prepare($data=null) {
public static function prepare($data = null) {
if ($data === null) {
$data = new stdClass;
$data = new stdClass();
}
$data = file_prepare_standard_editor($data, 'summary', self::summary_editor_options());
return $data;
@@ -88,7 +86,6 @@ class course_request {
*
* This function also handles saving any files that may have been used in the editor
*
* @static
* @param stdClass $data
* @return course_request The newly created course request
*/
@@ -101,19 +98,18 @@ class course_request {
$data->category = $CFG->defaultrequestcategory;
}
// Summary is a required field so copy the text over
// Summary is a required field so copy the text over.
$data->summary = $data->summary_editor['text'];
$data->summaryformat = $data->summary_editor['format'];
$data->id = $DB->insert_record('course_request', $data);
// Create a new course_request object and return it
// Create a new course_request object and return it.
$request = new course_request($data);
// Notify the admin if required.
if ($users = get_users_from_config($CFG->courserequestnotify, 'moodle/site:approvecourse')) {
$a = new stdClass;
$a = new stdClass();
$a->link = "$CFG->wwwroot/course/pending.php";
$a->user = fullname($USER);
$a->shortname = s($data->shortname) ?? '';
@@ -139,7 +135,7 @@ class course_request {
public static function summary_editor_options() {
global $CFG;
if (self::$summaryeditoroptions === null) {
self::$summaryeditoroptions = array('maxfiles' => 0, 'maxbytes'=>0);
self::$summaryeditoroptions = ['maxfiles' => 0, 'maxbytes' => 0];
}
return self::$summaryeditoroptions;
}
@@ -158,12 +154,12 @@ class course_request {
throw new coding_exception('You must provide a course request id when creating a course_request object');
}
$id = $properties;
$properties = new stdClass;
$properties = new stdClass();
$properties->id = (int)$id;
unset($id);
}
if (empty($properties->requester)) {
if (!($this->properties = $DB->get_record('course_request', array('id' => $properties->id)))) {
if (!($this->properties = $DB->get_record('course_request', ['id' => $properties->id]))) {
throw new moodle_exception('unknowncourserequest');
}
} else {
@@ -195,18 +191,17 @@ class course_request {
}
/**
* Returns the user who requested this course
* Returns the user who requested this course.
*
* Uses a static var to cache the results and cut down the number of db queries
*
* @staticvar array $requesters An array of cached users
* @return stdClass The user who requested the course
*/
public function get_requester() {
global $DB;
static $requesters= array();
static $requesters = [];
if (!array_key_exists($this->properties->requester, $requesters)) {
$requesters[$this->properties->requester] = $DB->get_record('user', array('id'=>$this->properties->requester));
$requesters[$this->properties->requester] = $DB->get_record('user', ['id' => $this->properties->requester]);
}
return $requesters[$this->properties->requester];
}
@@ -229,9 +224,9 @@ class course_request {
if (empty($this->properties->shortname)) {
debugging('Attempting to check a course request shortname before it has been set', DEBUG_DEVELOPER);
$this->properties->collision = false;
} else if ($DB->record_exists('course', array('shortname' => $this->properties->shortname))) {
} else if ($DB->record_exists('course', ['shortname' => $this->properties->shortname])) {
if (!empty($shortnamemark)) {
$this->properties->shortname .= ' '.$shortnamemark;
$this->properties->shortname .= ' ' . $shortnamemark;
}
$this->properties->collision = true;
} else {
@@ -276,10 +271,15 @@ class course_request {
*/
public function get_category() {
global $CFG;
if ($this->properties->category && ($category = core_course_category::get($this->properties->category, IGNORE_MISSING))) {
if (
$this->properties->category
&& ($category = core_course_category::get($this->properties->category, IGNORE_MISSING))
) {
return $category;
} else if ($CFG->defaultrequestcategory &&
($category = core_course_category::get($CFG->defaultrequestcategory, IGNORE_MISSING))) {
} else if (
$CFG->defaultrequestcategory
&& ($category = core_course_category::get($CFG->defaultrequestcategory, IGNORE_MISSING))
) {
return $category;
} else {
return core_course_category::get_default();
@@ -300,23 +300,24 @@ class course_request {
require_once($CFG->dirroot . '/backup/util/includes/restore_includes.php');
$user = $DB->get_record('user', array('id' => $this->properties->requester, 'deleted'=>0), '*', MUST_EXIST);
$user = $DB->get_record('user', ['id' => $this->properties->requester, 'deleted' => 0], '*', MUST_EXIST);
$courseconfig = get_config('moodlecourse');
// Transfer appropriate settings
// Transfer appropriate settings.
$data = clone($this->properties);
unset($data->id);
unset($data->reason);
unset($data->requester);
// Set category
// Set category.
$category = $this->get_category();
$data->category = $category->id;
// Set misc settings
// Set misc settings.
$data->requested = 1;
// Apply course default settings
// Apply course default settings.
$data->format = $courseconfig->format;
$data->newsitems = $courseconfig->newsitems;
$data->showgrades = $courseconfig->showgrades;
@@ -334,20 +335,24 @@ class course_request {
$data->enddate = usergetmidnight(time()) + $courseconfig->courseduration;
}
list($data->fullname, $data->shortname) = restore_dbops::calculate_course_names(0, $data->fullname, $data->shortname);
[$data->fullname, $data->shortname] = restore_dbops::calculate_course_names(0, $data->fullname, $data->shortname);
$course = create_course($data);
$context = context_course::instance($course->id, MUST_EXIST);
// add enrol instances
if (!$DB->record_exists('enrol', array('courseid'=>$course->id, 'enrol'=>'manual'))) {
// Add enrol instances.
if (!$DB->record_exists('enrol', ['courseid' => $course->id, 'enrol' => 'manual'])) {
if ($manual = enrol_get_plugin('manual')) {
$manual->add_default_instance($course);
}
}
// enrol the requester as teacher if necessary
if (!empty($CFG->creatornewroleid) and !is_viewing($context, $user, 'moodle/role:assign') and !is_enrolled($context, $user, 'moodle/role:assign')) {
// Enrol the requester as teacher if necessary.
if (
!empty($CFG->creatornewroleid)
&& !is_viewing($context, $user, 'moodle/role:assign')
&& !is_enrolled($context, $user, 'moodle/role:assign')
) {
enrol_try_internal_enrol($course->id, $user->id, $CFG->creatornewroleid);
}
@@ -362,7 +367,14 @@ class course_request {
$a->{$field} = $value;
}
$this->notify($user, $USER, 'courserequestapproved', get_string('courseapprovedsubject'), get_string('courseapprovedemail2', 'moodle', $a), $course->id);
$this->notify(
touser: $user,
fromuser: $USER,
name: 'courserequestapproved',
subject: get_string('courseapprovedsubject'),
message: get_string('courseapprovedemail2', 'moodle', $a),
courseid: $course->id,
);
return $course->id;
}
@@ -377,8 +389,14 @@ class course_request {
*/
public function reject($notice) {
global $USER, $DB;
$user = $DB->get_record('user', array('id' => $this->properties->requester), '*', MUST_EXIST);
$this->notify($user, $USER, 'courserequestrejected', get_string('courserejectsubject'), get_string('courserejectemail', 'moodle', $notice));
$user = $DB->get_record('user', ['id' => $this->properties->requester], '*', MUST_EXIST);
$this->notify(
touser: $user,
fromuser: $USER,
name: 'courserequestrejected',
subject: get_string('courserejectsubject'),
message: get_string('courserejectemail', 'moodle', $notice),
);
$this->delete();
}
@@ -387,7 +405,7 @@ class course_request {
*/
public function delete() {
global $DB;
$DB->delete_records('course_request', array('id' => $this->properties->id));
$DB->delete_records('course_request', ['id' => $this->properties->id]);
}
/**
@@ -433,8 +451,7 @@ class course_request {
if ($context instanceof context_system) {
$defaultcontext = context_coursecat::instance($CFG->defaultrequestcategory, IGNORE_MISSING);
return $defaultcontext &&
has_capability('moodle/course:request', $defaultcontext);
return $defaultcontext && has_capability('moodle/course:request', $defaultcontext);
} else if ($context instanceof context_coursecat) {
if (!$CFG->lockrequestcategory || $CFG->defaultrequestcategory == $context->instanceid) {
return has_capability('moodle/course:request', $context);
@@ -34,9 +34,8 @@ use stdClass;
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class dndupload_ajax_processor {
/** Returned when no error has occurred */
const ERROR_OK = 0;
public const ERROR_OK = 0;
/** @var object The course that we are uploading to */
protected $course = null;
@@ -51,7 +50,7 @@ class dndupload_ajax_processor {
protected $type = null;
/** @var object The details of the module type that will be created */
protected $module= null;
protected $module = null;
/** @var object The course module that has been created */
protected $cm = null;
@@ -77,7 +76,7 @@ class dndupload_ajax_processor {
throw new coding_exception('dndupload_ajax_processor should only be used within AJAX requests');
}
$this->course = $DB->get_record('course', array('id' => $courseid), '*', MUST_EXIST);
$this->course = $DB->get_record('course', ['id' => $courseid], '*', MUST_EXIST);
require_login($this->course, false);
$this->context = context_course::instance($this->course->id);
@@ -88,7 +87,7 @@ class dndupload_ajax_processor {
$this->section = $section;
$this->type = $type;
if (!$this->module = $DB->get_record('modules', array('name' => $modulename))) {
if (!$this->module = $DB->get_record('modules', ['name' => $modulename])) {
throw new coding_exception("Module $modulename does not exist");
}
@@ -146,7 +145,7 @@ class dndupload_ajax_processor {
$draftitemid = file_get_unused_draft_itemid();
$maxbytes = get_user_max_upload_file_size($this->context, $CFG->maxbytes, $this->course->maxbytes);
$types = $this->dnduploadhandler->get_handled_file_types($this->module->name);
$repo = repository::get_instances(array('type' => 'upload', 'currentcontext' => $this->context));
$repo = repository::get_instances(['type' => 'upload', 'currentcontext' => $this->context]);
if (empty($repo)) {
throw new moodle_exception('errornouploadrepo', 'moodle');
}
@@ -163,9 +162,13 @@ class dndupload_ajax_processor {
// Ask the module to set itself up.
$moduledata = $this->prepare_module_data($draftitemid);
$instanceid = plugin_callback('mod', $this->module->name, 'dndupload', 'handle', array($moduledata), 'invalidfunction');
$instanceid = plugin_callback('mod', $this->module->name, 'dndupload', 'handle', [$moduledata], 'invalidfunction');
if ($instanceid === 'invalidfunction') {
throw new coding_exception("{$this->module->name} does not support drag and drop upload (missing {$this->module->name}_dndupload_handle function");
throw new coding_exception(sprintf(
"%s does not support drag and drop upload (missing %s_dndupload_handle function",
$this->module->name,
$this->module->name,
));
}
// Finish setting up the course module.
@@ -179,9 +182,9 @@ class dndupload_ajax_processor {
* @param string $content the content uploaded to the browser
*/
protected function handle_other_upload($content) {
// Check this plugin is registered to handle this type of upload
// Check this plugin is registered to handle this type of upload.
if (!$this->dnduploadhandler->has_type_handler($this->module->name, $this->type)) {
$info = (object)array('modname' => $this->module->name, 'type' => $this->type);
$info = (object)['modname' => $this->module->name, 'type' => $this->type];
throw new moodle_exception('moddoesnotsupporttype', 'moodle', $info);
}
@@ -190,9 +193,13 @@ class dndupload_ajax_processor {
// Ask the module to set itself up.
$moduledata = $this->prepare_module_data(null, $content);
$instanceid = plugin_callback('mod', $this->module->name, 'dndupload', 'handle', array($moduledata), 'invalidfunction');
$instanceid = plugin_callback('mod', $this->module->name, 'dndupload', 'handle', [$moduledata], 'invalidfunction');
if ($instanceid === 'invalidfunction') {
throw new coding_exception("{$this->module->name} does not support drag and drop upload (missing {$this->module->name}_dndupload_handle function");
throw new coding_exception(sprintf(
"%s does not support drag and drop upload (missing %s_dndupload_handle function",
$this->module->name,
$this->module->name,
));
}
// Finish setting up the course module.
@@ -219,8 +226,8 @@ class dndupload_ajax_processor {
*/
protected function create_course_module() {
global $CFG;
require_once($CFG->dirroot.'/course/modlib.php');
list($module, $context, $cw, $cm, $data) = prepare_new_moduleinfo_data($this->course, $this->module->name, $this->section);
require_once($CFG->dirroot . '/course/modlib.php');
[$module, $context, $cw, $cm, $data] = prepare_new_moduleinfo_data($this->course, $this->module->name, $this->section);
$data->coursemodule = $data->id = add_course_module($data);
$this->cm = $data;
@@ -268,23 +275,23 @@ class dndupload_ajax_processor {
throw new moodle_exception('errorcreatingactivity', 'moodle', '', $this->module->name);
}
// Note the section visibility
// Note the section visibility.
$visible = get_fast_modinfo($this->course)->get_section_info($this->section)->visible;
$DB->set_field('course_modules', 'instance', $instanceid, array('id' => $this->cm->id));
$DB->set_field('course_modules', 'instance', $instanceid, ['id' => $this->cm->id]);
course_modinfo::purge_course_module_cache($this->course->id, $this->cm->id);
// Rebuild the course cache after update action
// Rebuild the course cache after update action.
rebuild_course_cache($this->course->id, true, true);
$sectionid = course_add_cm_to_section($this->course, $this->cm->id, $this->section, modname: $this->module->name);
set_coursemodule_visible($this->cm->id, $visible);
if (!$visible) {
$DB->set_field('course_modules', 'visibleold', 1, array('id' => $this->cm->id));
$DB->set_field('course_modules', 'visibleold', 1, ['id' => $this->cm->id]);
}
// retrieve the final info about this module.
// Retrieve the final info about this module.
$info = get_fast_modinfo($this->course);
if (!isset($info->cms[$this->cm->id])) {
// The course module has not been properly created in the course - undo everything.
+65 -39
View File
@@ -27,21 +27,20 @@ use stdClass;
*
* @package core
* @copyright 2012 Davo Smith
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
* @license https://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class dndupload_handler {
/**
* @var array A list of all registered mime types that can be dropped onto a course
* along with the modules that will handle them.
*/
protected $types = array();
protected $types = [];
/**
* @var array A list of the different file types (extensions) that different modules
* will handle.
*/
protected $filehandlers = array();
protected $filehandlers = [];
/**
* @var context_course|null
@@ -52,6 +51,7 @@ class dndupload_handler {
* Gather a list of dndupload handlers from the different mods
*
* @param object $course The course this is being added to (to check course_allowed_module() )
* @param array|null $modnames An array of module names that are allowed in this course.
*/
public function __construct($course, $modnames = null) {
global $CFG, $PAGE;
@@ -59,19 +59,37 @@ class dndupload_handler {
// Add some default types to handle.
// Note: 'Files' type is hard-coded into the Javascript as this needs to be ...
// ... treated a little differently.
$this->register_type('url', array('url', 'text/uri-list', 'text/x-moz-url'), get_string('addlinkhere', 'moodle'),
get_string('nameforlink', 'moodle'), get_string('whatforlink', 'moodle'), 10);
$this->register_type('text/html', array('text/html'), get_string('addpagehere', 'moodle'),
get_string('nameforpage', 'moodle'), get_string('whatforpage', 'moodle'), 20);
$this->register_type('text', array('text', 'text/plain'), get_string('addpagehere', 'moodle'),
get_string('nameforpage', 'moodle'), get_string('whatforpage', 'moodle'), 30);
$this->register_type(
identifier: 'url',
datatransfertypes: ['url', 'text/uri-list', 'text/x-moz-url'],
addmessage: get_string('addlinkhere', 'moodle'),
namemessage: get_string('nameforlink', 'moodle'),
handlermessage: get_string('whatforlink', 'moodle'),
priority: 10,
);
$this->register_type(
identifier: 'text/html',
datatransfertypes: ['text/html'],
addmessage: get_string('addpagehere', 'moodle'),
namemessage: get_string('nameforpage', 'moodle'),
handlermessage: get_string('whatforpage', 'moodle'),
priority: 20,
);
$this->register_type(
identifier: 'text',
datatransfertypes: ['text', 'text/plain'],
addmessage: get_string('addpagehere', 'moodle'),
namemessage: get_string('nameforpage', 'moodle'),
handlermessage: get_string('whatforpage', 'moodle'),
priority: 30,
);
$this->context = context_course::instance($course->id);
// Loop through all modules to find handlers.
$mods = get_plugin_list_with_function('mod', 'dndupload_register');
foreach ($mods as $component => $funcname) {
list($modtype, $modname) = component::normalize_component($component);
[$modtype, $modname] = component::normalize_component($component);
if ($modnames && !array_key_exists($modname, $modnames)) {
continue; // Module is deactivated (hidden) at the site level.
}
@@ -97,8 +115,14 @@ class dndupload_handler {
if (!isset($type['handlermessage'])) {
$type['handlermessage'] = '';
}
$this->register_type($type['identifier'], $type['datatransfertypes'],
$type['addmessage'], $type['namemessage'], $type['handlermessage'], $priority);
$this->register_type(
identifier: $type['identifier'],
datatransfertypes: $type['datatransfertypes'],
addmessage: $type['addmessage'],
namemessage: $type['namemessage'],
handlermessage: $type['handlermessage'],
priority: $priority,
);
}
}
if (isset($resp['types'])) {
@@ -126,19 +150,20 @@ class dndupload_handler {
* @param int $priority Controls the order in which types are checked by the browser (mainly
* needed to check for 'text' last as that is usually given as fallback)
*/
protected function register_type($identifier, $datatransfertypes, $addmessage, $namemessage, $handlermessage, $priority=100) {
protected function register_type($identifier, $datatransfertypes, $addmessage, $namemessage, $handlermessage, $priority = 100) {
if ($this->is_known_type($identifier)) {
throw new coding_exception("Type $identifier is already registered");
}
$add = new stdClass;
$add->identifier = $identifier;
$add->datatransfertypes = $datatransfertypes;
$add->addmessage = $addmessage;
$add->namemessage = $namemessage;
$add->handlermessage = $handlermessage;
$add->priority = $priority;
$add->handlers = array();
$add = (object) [
'identifier' => $identifier,
'datatransfertypes' => $datatransfertypes,
'addmessage' => $addmessage,
'namemessage' => $namemessage,
'handlermessage' => $handlermessage,
'priority' => $priority,
'handlers' => [],
];
$this->types[$identifier] = $add;
}
@@ -159,11 +184,12 @@ class dndupload_handler {
throw new coding_exception("Trying to add handler for unknown type $type");
}
$add = new stdClass;
$add->type = $type;
$add->module = $module;
$add->message = $message;
$add->noname = $noname ? 1 : 0;
$add = (object) [
'type' => $type,
'module' => $module,
'message' => $message,
'noname' => $noname ? 1 : 0,
];
$this->types[$type]->handlers[] = $add;
}
@@ -180,10 +206,11 @@ class dndupload_handler {
protected function register_file_handler($extension, $module, $message) {
$extension = strtolower($extension);
$add = new stdClass;
$add->extension = $extension;
$add->module = $module;
$add->message = $message;
$add = (object) [
'extension' => $extension,
'module' => $module,
'message' => $message,
];
$this->filehandlers[] = $add;
}
@@ -245,14 +272,14 @@ class dndupload_handler {
* @return array of file extensions or string '*'
*/
public function get_handled_file_types($module) {
$types = array();
$types = [];
foreach ($this->filehandlers as $handler) {
if ($handler->module == $module) {
if ($handler->extension == '*') {
return '*';
} else {
// Prepending '.' as otherwise mimeinfo fails.
$types[] = '.'.$handler->extension;
$types[] = '.' . $handler->extension;
}
}
}
@@ -268,12 +295,12 @@ class dndupload_handler {
public function get_js_data() {
global $CFG;
$ret = new stdClass;
$ret = new stdClass();
// Sort the types by priority.
uasort($this->types, array($this, 'type_compare'));
uasort($this->types, [$this, 'type_compare']);
$ret->types = array();
$ret->types = [];
if (!empty($CFG->dndallowtextandlinks)) {
foreach ($this->types as $type) {
if (empty($type->handlers)) {
@@ -284,9 +311,9 @@ class dndupload_handler {
}
$ret->filehandlers = $this->filehandlers;
$uploadrepo = repository::get_instances(array('type' => 'upload', 'currentcontext' => $this->context));
$uploadrepo = repository::get_instances(['type' => 'upload', 'currentcontext' => $this->context]);
if (empty($uploadrepo)) {
$ret->filehandlers = array(); // No upload repo => no file handlers.
$ret->filehandlers = []; // No upload repo => no file handlers.
}
return $ret;
@@ -307,7 +334,6 @@ class dndupload_handler {
}
return 0;
}
}
// Alias this class to the old name.
@@ -30,15 +30,21 @@ require_once("{$CFG->libdir}/formslib.php");
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class reject_course_request extends moodleform {
function definition() {
#[\Override]
public function definition() {
$mform =& $this->_form;
$mform->addElement('hidden', 'reject', 0);
$mform->setType('reject', PARAM_INT);
$mform->addElement('header','coursedetails', get_string('coursereasonforrejecting'));
$mform->addElement('header', 'coursedetails', get_string('coursereasonforrejecting'));
$mform->addElement('textarea', 'rejectnotice', get_string('coursereasonforrejectingemail'), array('rows'=>'15', 'cols'=>'50'));
$mform->addElement(
'textarea',
'rejectnotice',
get_string('coursereasonforrejectingemail'),
['rows' => '15', 'cols' => '50'],
);
$mform->addRule('rejectnotice', get_string('missingreqreason'), 'required', null, 'client');
$mform->setType('rejectnotice', PARAM_TEXT);
+35 -15
View File
@@ -33,14 +33,14 @@ require_once("{$CFG->libdir}/formslib.php");
*/
class request_course extends moodleform {
#[\Override]
function definition() {
public function definition() {
global $CFG, $DB, $USER;
$mform =& $this->_form;
if ($pending = $DB->get_records('course_request', array('requester' => $USER->id))) {
if ($pending = $DB->get_records('course_request', ['requester' => $USER->id])) {
$mform->addElement('header', 'pendinglist', get_string('coursespending'));
$list = array();
$list = [];
foreach ($pending as $cp) {
$list[] = format_string($cp->fullname);
}
@@ -48,16 +48,24 @@ class request_course extends moodleform {
$mform->addElement('static', 'pendingcourses', get_string('courses'), $list);
}
$mform->addElement('header','coursedetails', get_string('courserequestdetails'));
$mform->addElement('header', 'coursedetails', get_string('courserequestdetails'));
$mform->addElement('text', 'fullname', get_string('fullnamecourse'),
['maxlength' => \core_course\constants::FULLNAME_MAXIMUM_LENGTH, 'size' => 50]);
$mform->addElement(
'text',
'fullname',
get_string('fullnamecourse'),
['maxlength' => \core_course\constants::FULLNAME_MAXIMUM_LENGTH, 'size' => 50],
);
$mform->addHelpButton('fullname', 'fullnamecourse');
$mform->addRule('fullname', get_string('missingfullname'), 'required', null, 'client');
$mform->setType('fullname', PARAM_TEXT);
$mform->addElement('text', 'shortname', get_string('shortnamecourse'),
['maxlength' => \core_course\constants::SHORTNAME_MAXIMUM_LENGTH, 'size' => 20]);
$mform->addElement(
'text',
'shortname',
get_string('shortnamecourse'),
['maxlength' => \core_course\constants::SHORTNAME_MAXIMUM_LENGTH, 'size' => 20],
);
$mform->addHelpButton('shortname', 'shortnamecourse');
$mform->addRule('shortname', get_string('missingshortname'), 'required', null, 'client');
$mform->setType('shortname', PARAM_TEXT);
@@ -70,20 +78,32 @@ class request_course extends moodleform {
$mform->addHelpButton('category', 'coursecategory');
}
$mform->addElement('editor', 'summary_editor', get_string('summary'), null, course_request::summary_editor_options());
$mform->addElement(
'editor',
'summary_editor',
get_string('summary'),
null,
course_request::summary_editor_options(),
);
$mform->addHelpButton('summary_editor', 'coursesummary');
$mform->setType('summary_editor', PARAM_RAW);
$mform->addElement('header','requestreason', get_string('courserequestreason'));
$mform->addElement('header', 'requestreason', get_string('courserequestreason'));
$mform->addElement('textarea', 'reason', get_string('courserequestsupport'), array('rows'=>'15', 'cols'=>'50'));
$mform->addElement(
'textarea',
'reason',
get_string('courserequestsupport'),
['rows' => '15', 'cols' => '50'],
);
$mform->addRule('reason', get_string('missingreqreason'), 'required', null, 'client');
$mform->setType('reason', PARAM_TEXT);
$this->add_action_buttons(true, get_string('requestcourse'));
}
function validation($data, $files) {
#[\Override]
public function validation($data, $files) {
global $DB;
$errors = parent::validation($data, $files);
@@ -91,8 +111,8 @@ class request_course extends moodleform {
$foundreqcourses = null;
if (!empty($data['shortname'])) {
$foundcourses = $DB->get_records('course', array('shortname'=>$data['shortname']));
$foundreqcourses = $DB->get_records('course_request', array('shortname'=>$data['shortname']));
$foundcourses = $DB->get_records('course', ['shortname' => $data['shortname']]);
$foundreqcourses = $DB->get_records('course_request', ['shortname' => $data['shortname']]);
}
if (!empty($foundreqcourses)) {
if (!empty($foundcourses)) {
@@ -106,7 +126,7 @@ class request_course extends moodleform {
foreach ($foundcourses as $foundcourse) {
if (!empty($foundcourse->requester)) {
$pending = 1;
$foundcoursenames[] = $foundcourse->fullname.' [*]';
$foundcoursenames[] = $foundcourse->fullname . ' [*]';
} else {
$foundcoursenames[] = $foundcourse->fullname;
}
-1
View File
@@ -26,7 +26,6 @@ defined('MOODLE_INTERNAL') || die;
use core\di;
use core\hook;
use core_course\external\course_summary_exporter;
use core_courseformat\base as course_format;
use core_courseformat\formatactions;
use core_courseformat\sectiondelegate;
+69 -62
View File
@@ -1,33 +1,25 @@
<?php
///////////////////////////////////////////////////////////////////////////
// //
// NOTICE OF COPYRIGHT //
// //
// Moodle - Modular Object-Oriented Dynamic Learning Environment //
// http://moodle.org //
// //
// Copyright (C) 1999 onwards Martin Dougiamas http://dougiamas.com //
// //
// This program is free software; you can redistribute it and/or modify //
// it under the terms of the GNU General Public License as published by //
// the Free Software Foundation; either version 2 of the License, or //
// (at your option) any later version. //
// //
// This program is distributed in the hope that it will be useful, //
// but WITHOUT ANY WARRANTY; without even the implied warranty of //
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //
// GNU General Public License for more details: //
// //
// http://www.gnu.org/copyleft/gpl.html //
// //
///////////////////////////////////////////////////////////////////////////
// This file is part of Moodle - https://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <https://www.gnu.org/licenses/>.
/**
* Allow the administrator to look through a list of course requests and approve or reject them.
*
* @license http://www.gnu.org/copyleft/gpl.html GNU Public License
* @license https://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
* @package course
* @copyright Moodle Pty Ltd
*/
use core\context\course as context_course;
@@ -57,27 +49,27 @@ if (has_capability('moodle/site:approvecourse', $context)) {
require_capability('moodle/site:approvecourse', $context);
}
$PAGE->set_context($context);
$PAGE->set_url(new moodle_url('/course/pending.php'));
$PAGE->set_url(new url('/course/pending.php'));
}
/// Process approval of a course.
if (!empty($approve) and confirm_sesskey()) {
/// Load the request.
// Process approval of a course.
if (!empty($approve) && confirm_sesskey()) {
// Load the request.
$course = new course_request($approve);
$courseid = $course->approve();
if ($courseid !== false) {
if (has_capability('moodle/course:update', context_course::instance($courseid))) {
redirect(new moodle_url('/course/edit.php', ['id' => $courseid, 'returnto' => 'pending']));
redirect(new url('/course/edit.php', ['id' => $courseid, 'returnto' => 'pending']));
} else {
redirect(new moodle_url('/course/view.php', ['id' => $courseid]));
redirect(new url('/course/view.php', ['id' => $courseid]));
}
} else {
throw new \moodle_exception('courseapprovedfailed');
throw new moodle_exception('courseapprovedfailed');
}
}
/// Process rejection of a course.
// Process rejection of a course.
if (!empty($reject)) {
// Load the request.
$course = new course_request($reject);
@@ -88,27 +80,25 @@ if (!empty($reject)) {
$default->reject = $course->id;
$rejectform->set_data($default);
/// Standard form processing if statement.
if ($rejectform->is_cancelled()){
// Standard form processing if statement.
if ($rejectform->is_cancelled()) {
redirect($baseurl);
} else if ($data = $rejectform->get_data()) {
/// Reject the request
// Reject the request.
$course->reject($data->rejectnotice);
/// Redirect back to the course listing.
// Redirect back to the course listing.
redirect($baseurl, get_string('courserejected'));
}
/// Display the form for giving a reason for rejecting the request.
// Display the form for giving a reason for rejecting the request.
echo $OUTPUT->header($rejectform->focus());
$rejectform->display();
echo $OUTPUT->footer();
exit;
}
/// Print a list of all the pending requests.
// Print a list of all the pending requests.
echo $OUTPUT->header();
$pending = $DB->get_records('course_request');
@@ -121,16 +111,16 @@ if (empty($pending)) {
if ($role) {
echo $OUTPUT->notification(get_string('courserequestwarning', 'core', role_get_name($role)), 'notifyproblem');
} else {
$userpoliciesurl = new moodle_url('/admin/settings.php', ['section' => 'userpolicies']);
$userpoliciesurl = new url('/admin/settings.php', ['section' => 'userpolicies']);
echo $OUTPUT->notification(get_string('courserequestroleerror', 'core', (string) $userpoliciesurl), 'notifyerror');
}
/// Build a table of all the requests.
// Build a table of all the requests.
$table = new html_table();
$table->attributes['class'] = 'pendingcourserequests table generaltable';
$table->align = array('center', 'center', 'center', 'center', 'center', 'center');
$table->head = array(get_string('requestedby'), get_string('shortnamecourse'), get_string('fullnamecourse'),
get_string('summary'), get_string('category'), get_string('requestreason'), get_string('action'));
$table->align = ['center', 'center', 'center', 'center', 'center', 'center'];
$table->head = [get_string('requestedby'), get_string('shortnamecourse'), get_string('fullnamecourse'),
get_string('summary'), get_string('category'), get_string('requestreason'), get_string('action')];
foreach ($pending as $course) {
$course = new course_request($course);
@@ -144,34 +134,51 @@ if (empty($pending)) {
$category = $course->get_category();
// Fullname of the user who requested the course (with link to profile if current user can view it).
$requesterfullname = $OUTPUT->user_picture($course->get_requester(), [
'includefullname' => true,
'link' => user_can_view_profile($course->get_requester()),
]);
$requesterfullname = $OUTPUT->user_picture(
$course->get_requester(),
[
'includefullname' => true,
'link' => user_can_view_profile($course->get_requester()),
],
);
$row = array();
$row[] = $requesterfullname;
$row[] = format_string($course->shortname);
$row[] = format_string($course->fullname);
$row[] = format_text($course->summary, $course->summaryformat);
$row[] = $category->get_formatted_name();
$row[] = format_string($course->reason);
$row[] = $OUTPUT->single_button(new moodle_url($baseurl, array('approve' => $course->id, 'sesskey' => sesskey())), get_string('approve'), 'get') .
$OUTPUT->single_button(new moodle_url($baseurl, array('reject' => $course->id)), get_string('rejectdots'), 'get');
$row = [
$requesterfullname,
format_string($course->shortname),
format_string($course->fullname),
format_text($course->summary, $course->summaryformat),
$category->get_formatted_name(),
format_string($course->reason),
];
/// Add the row to the table.
$controls = [
$OUTPUT->single_button(
new url($baseurl, ['approve' => $course->id, 'sesskey' => sesskey()]),
get_string('approve'),
'get',
),
$OUTPUT->single_button(
new url($baseurl, ['reject' => $course->id]),
get_string('rejectdots'),
'get',
),
];
$row[] = implode(' ', $controls);
// Add the row to the table.
$table->data[] = $row;
}
/// Display the table.
// Display the table.
echo html_writer::table($table);
/// Message about name collisions, if necessary.
// Message about name collisions, if necessary.
if (!empty($collision)) {
print_string('shortnamecollisionwarning');
}
}
/// Finish off the page.
// Finish off the page.
echo $OUTPUT->single_button($CFG->wwwroot . '/course/index.php', get_string('backtocourselisting'));
echo $OUTPUT->footer();
+13 -12
View File
@@ -1,5 +1,4 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
@@ -15,6 +14,12 @@
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
use core\context\coursecat as context_coursecat;
use core\exception\moodle_exception;
use core\url;
use core_course\course_request;
use core_course\form\request_course as request_course_form;
/**
* Allows a user to request a course be created for them.
*
@@ -23,21 +28,18 @@
* @package course
*/
use core_course\course_request;
use core_course\form\request_course as request_course_form;
require_once(__DIR__ . '/../config.php');
require_once($CFG->dirroot . '/course/lib.php');
// Where we came from. Used in a number of redirects.
$url = new moodle_url('/course/request.php');
$url = new url('/course/request.php');
$return = optional_param('return', null, PARAM_ALPHANUMEXT);
$categoryid = optional_param('category', null, PARAM_INT);
if ($return === 'management') {
$url->param('return', $return);
$returnurl = new moodle_url('/course/management.php', array('categoryid' => $CFG->defaultrequestcategory));
$returnurl = new url('/course/management.php', ['categoryid' => $CFG->defaultrequestcategory]);
} else {
$returnurl = new moodle_url('/course/index.php');
$returnurl = new url('/course/index.php');
}
$PAGE->set_url($url);
@@ -45,10 +47,10 @@ $PAGE->set_url($url);
// Check permissions.
require_login(null, false);
if (isguestuser()) {
throw new \moodle_exception('guestsarenotallowed', '', $returnurl);
throw new moodle_exception('guestsarenotallowed', '', $returnurl);
}
if (empty($CFG->enablecourserequests)) {
throw new \moodle_exception('courserequestdisabled', '', $returnurl);
throw new moodle_exception('courserequestdisabled', '', $returnurl);
}
if ($CFG->lockrequestcategory) {
@@ -78,9 +80,8 @@ $PAGE->set_heading($coursecategory->get_formatted_name());
$PAGE->set_primary_active_tab('home');
// Standard form processing if statement.
if ($requestform->is_cancelled()){
if ($requestform->is_cancelled()) {
redirect($returnurl);
} else if ($data = $requestform->get_data()) {
$request = course_request::create($data);
@@ -88,7 +89,7 @@ if ($requestform->is_cancelled()){
notice(get_string('courserequestsuccess'), $returnurl);
}
$categoryurl = new moodle_url('/course/index.php');
$categoryurl = new url('/course/index.php');
if ($categoryid) {
$categoryurl->param('categoryid', $categoryid);
}
+36 -14
View File
@@ -92,8 +92,12 @@ final class course_request_test extends \advanced_testcase {
// Create a user and allow course requests for him.
$requester = $this->getDataGenerator()->create_user();
$roleid = create_role('Course requestor role', 'courserequestor', '');
assign_capability('moodle/course:request', CAP_ALLOW, $roleid,
\context_system::instance()->id);
assign_capability(
'moodle/course:request',
CAP_ALLOW,
$roleid,
\context_system::instance()->id
);
role_assign($roleid, $requester->id, \context_system::instance()->id);
accesslib_clear_all_caches_for_unit_testing();
@@ -112,7 +116,7 @@ final class course_request_test extends \advanced_testcase {
$id = $cr->approve();
$this->assertCount(1, $sink->get_messages_by_component_and_type('core', 'courserequestapproved'));
$sink->close();
$course = $DB->get_record('course', array('id' => $id));
$course = $DB->get_record('course', ['id' => $id]);
$this->assertEquals($data->fullname, $course->fullname);
$this->assertEquals($data->shortname, $course->shortname);
$this->assertEquals($data->summary_editor['text'], $course->summary);
@@ -132,7 +136,7 @@ final class course_request_test extends \advanced_testcase {
$id = $cr->approve();
$this->assertCount(1, $sink->get_messages_by_component_and_type('core', 'courserequestapproved'));
$sink->close();
$course = $DB->get_record('course', array('id' => $id));
$course = $DB->get_record('course', ['id' => $id]);
$this->assertEquals($data->category, $course->category);
}
@@ -149,8 +153,12 @@ final class course_request_test extends \advanced_testcase {
// Create a user and allow course requests for him.
$requester = $this->getDataGenerator()->create_user();
$roleid = create_role('Course requestor role', 'courserequestor', '');
assign_capability('moodle/course:request', CAP_ALLOW, $roleid,
\context_system::instance()->id);
assign_capability(
'moodle/course:request',
CAP_ALLOW,
$roleid,
\context_system::instance()->id
);
role_assign($roleid, $requester->id, \context_system::instance()->id);
accesslib_clear_all_caches_for_unit_testing();
@@ -163,12 +171,12 @@ final class course_request_test extends \advanced_testcase {
$this->setUser($requester);
$cr = course_request::create($data);
$this->assertTrue($DB->record_exists('course_request', array('id' => $cr->id)));
$this->assertTrue($DB->record_exists('course_request', ['id' => $cr->id]));
$this->setAdminUser();
$sink = $this->redirectMessages();
$cr->reject('Sorry!');
$this->assertFalse($DB->record_exists('course_request', array('id' => $cr->id)));
$this->assertFalse($DB->record_exists('course_request', ['id' => $cr->id]));
$this->assertCount(1, $sink->get_messages());
$sink->close();
}
@@ -197,8 +205,12 @@ final class course_request_test extends \advanced_testcase {
// Allow for the 'user' role the capability to request courses.
$userroleid = $DB->get_field('role', 'id', ['shortname' => 'user']);
assign_capability('moodle/course:request', CAP_ALLOW, $userroleid,
context_system::instance()->id);
assign_capability(
'moodle/course:request',
CAP_ALLOW,
$userroleid,
context_system::instance()->id
);
accesslib_clear_all_caches_for_unit_testing();
// Lock category selection.
@@ -219,8 +231,13 @@ final class course_request_test extends \advanced_testcase {
// Remove cap from cat2.
$roleid = create_role('Test role', 'testrole', 'Test role description');
assign_capability('moodle/course:request', CAP_PROHIBIT, $roleid,
$context2->id, true);
assign_capability(
'moodle/course:request',
CAP_PROHIBIT,
$roleid,
$context2->id,
true
);
role_assign($roleid, $user->id, $context2->id);
accesslib_clear_all_caches_for_unit_testing();
@@ -262,8 +279,13 @@ final class course_request_test extends \advanced_testcase {
$this->setUser($user);
// Add capability to approve courses.
$roleid = create_role('Test role', 'testrole', 'Test role description');
assign_capability('moodle/site:approvecourse', CAP_ALLOW, $roleid,
context_system::instance()->id, true);
assign_capability(
'moodle/site:approvecourse',
CAP_ALLOW,
$roleid,
context_system::instance()->id,
true
);
role_assign($roleid, $user->id, context_coursecat::instance($cat2)->id);
accesslib_clear_all_caches_for_unit_testing();